Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 59 additions & 43 deletions crates/buzz-db/src/store/group_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,98 +28,113 @@ pub struct ChannelMissingDiscovery {
pub channel_id: Uuid,
/// When the channel was created; with `channel_id`, the scan's cursor.
pub created_at: DateTime<Utc>,
/// The kinds it lacks, ascending and never empty.
pub missing_kinds: Vec<i32>,
}

// One probe per kind on `idx_events_addressable`. A channel's discovery
// The kinds of `$kinds` that channel `ch` lacks, as `missing.missing_kinds`:
// ascending, or NULL when it lacks none. One probe per kind on
// `idx_events_addressable`. The probe is a scalar subquery tested with
// `IS NULL` rather than `NOT EXISTS`: PostgreSQL pulls a `NOT EXISTS` up into
// an anti join, which can walk the channel's whole history on the
// channel/time index instead of probing each kind. A channel's discovery
// events are written after its row, so `created_at` bounds them from below
// and, at run time, prunes the monthly `events` partitions to the ones since
// the channel was created. The hour of slack covers a relay clock behind the
// database's: events carry the relay's time, the channel row the database's.
// `$also` adds further conditions on `e`, such as a constant floor the
// planner can prune with whatever join it picks.
// the channel was created.
// The hour of slack covers a relay clock behind the database's: events carry
// the relay's time, the channel row the database's. `$also` adds further
// conditions on `e`, such as a constant floor the planner can prune with
// whatever join it picks.
//
// Expands to the probe as a string literal, with the kinds array and relay
// pubkey as the given bind parameters, so each query stays static SQL.
macro_rules! missing_kind_probe {
// Expands to a `CROSS JOIN LATERAL` as a string literal, with the kinds
// array and relay pubkey as the given bind parameters, so each query stays
// static SQL.
macro_rules! missing_kinds_join {
($kinds:literal, $relay:literal, $also:literal) => {
concat!(
"SELECT 1 FROM unnest(",
"CROSS JOIN LATERAL (
SELECT array_agg(wanted.kind ORDER BY wanted.kind) AS missing_kinds
FROM unnest(",
$kinds,
"::int[]) AS wanted(kind)
WHERE NOT EXISTS (
SELECT 1 FROM events e
WHERE e.community_id = ch.community_id
AND e.kind = wanted.kind
AND e.pubkey = ",
WHERE (
SELECT 1 FROM events e
WHERE e.community_id = ch.community_id
AND e.kind = wanted.kind
AND e.pubkey = ",
$relay,
"
AND e.channel_id = ch.id
AND e.deleted_at IS NULL
AND e.created_at >= ch.created_at - INTERVAL '1 hour'
",
AND e.channel_id = ch.id
AND e.deleted_at IS NULL
AND e.created_at >= ch.created_at - INTERVAL '1 hour'
",
$also,
"
)"
LIMIT 1
) IS NULL
) missing"
)
};
}

const CHANNEL_MISSING_DISCOVERY_SQL: &str = concat!(
"SELECT EXISTS (
SELECT 1 FROM channels ch
WHERE ch.community_id = $1 AND ch.id = $2 AND ch.deleted_at IS NULL
AND EXISTS (",
missing_kind_probe!("$4", "$3", ""),
"))"
"SELECT missing.missing_kinds
FROM channels ch
",
missing_kinds_join!("$4", "$3", ""),
"
WHERE ch.community_id = $1 AND ch.id = $2 AND ch.deleted_at IS NULL"
);

const LIST_CHANNELS_MISSING_DISCOVERY_SQL: &str = concat!(
"SELECT ch.community_id, community.host, ch.id, ch.created_at
"SELECT ch.community_id, community.host, ch.id, ch.created_at, missing.missing_kinds
FROM channels ch
JOIN communities community
ON community.id = ch.community_id
AND community.archived_at IS NULL
AND community.deleted_at IS NULL
AND community.deletion_state = 'active'
WHERE ch.deleted_at IS NULL
AND ch.created_at >= $1
AND ch.created_at < $2
AND (ch.created_at, ch.id) > ($3, $4)
AND EXISTS (",
missing_kind_probe!(
",
missing_kinds_join!(
"$6",
"$5",
"AND e.created_at >= $1::timestamptz - INTERVAL '1 hour'"
),
")
"
WHERE ch.deleted_at IS NULL
AND ch.created_at >= $1
AND ch.created_at < $2
AND (ch.created_at, ch.id) > ($3, $4)
AND missing.missing_kinds IS NOT NULL
ORDER BY ch.created_at, ch.id
LIMIT $7"
);

/// Whether the live channel `channel_id` lacks a live relay-signed event of
/// any of [`GROUP_DISCOVERY_KINDS`]. A deleted or unknown channel lacks
/// The [`GROUP_DISCOVERY_KINDS`] the live channel `channel_id` lacks a live
/// relay-signed event of, ascending. A deleted or unknown channel lacks
/// nothing.
pub async fn channel_missing_discovery(
pool: &PgPool,
community_id: CommunityId,
channel_id: Uuid,
relay_pubkey: &[u8],
) -> Result<bool> {
) -> Result<Vec<i32>> {
let mut connection =
observability::acquire_writer(pool, observability::WriterOperation::EventWrite).await?;
let missing: bool = sqlx::query_scalar(CHANNEL_MISSING_DISCOVERY_SQL)
let missing: Option<Option<Vec<i32>>> = sqlx::query_scalar(CHANNEL_MISSING_DISCOVERY_SQL)
.bind(community_id.as_uuid())
.bind(channel_id)
.bind(relay_pubkey)
.bind(GROUP_DISCOVERY_KINDS.as_slice())
.fetch_one(&mut *connection)
.fetch_optional(&mut *connection)
.await?;
Ok(missing)
Ok(missing.flatten().unwrap_or_default())
}

/// One page, in `(created_at, id)` order, of live channels in active
/// communities created from `created_since` until `created_before` that
/// lack a live relay-signed event of any of [`GROUP_DISCOVERY_KINDS`].
/// lack a live relay-signed event of any of [`GROUP_DISCOVERY_KINDS`], each
/// with the kinds it lacks.
///
/// `after` is the previous page's last `(created_at, channel_id)`. A page
/// shorter than `limit` is the last one. This is an internal
Expand Down Expand Up @@ -153,21 +168,22 @@ pub async fn list_channels_missing_discovery(
host: row.try_get("host")?,
channel_id: row.try_get("id")?,
created_at: row.try_get("created_at")?,
missing_kinds: row.try_get("missing_kinds")?,
})
})
.collect()
}

impl Db {
/// Whether a live channel lacks any of its relay-signed discovery events.
/// See [`channel_missing_discovery`].
/// The relay-signed discovery kinds a live channel lacks. See
/// [`channel_missing_discovery`].
#[datastore_span(name = "channel_missing_discovery", system = "postgresql")]
pub async fn channel_missing_discovery(
&self,
community_id: CommunityId,
channel_id: Uuid,
relay_pubkey: &[u8],
) -> Result<bool> {
) -> Result<Vec<i32>> {
channel_missing_discovery(&self.pool, community_id, channel_id, relay_pubkey).await
}

Expand Down
33 changes: 21 additions & 12 deletions crates/buzz-relay/src/handlers/discovery_repair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use chrono::{DateTime, Utc};
use tracing::{info, warn};
use uuid::Uuid;

use super::side_effects::{emit_group_discovery_events, ReconcileSummary};
use super::side_effects::{emit_group_discovery_kinds, ReconcileSummary};
use crate::state::AppState;

/// Channels the startup sweep reads per statement.
Expand All @@ -25,31 +25,33 @@ const SWEEP_PAGE: i64 = 200;
/// publishing.
const IN_FLIGHT_GRACE: chrono::Duration = chrono::Duration::minutes(1);

/// Publish `channel_id`'s discovery events again if any of them is missing.
/// Returns whether it published. Healthy channels cost one indexed read and
/// no writes. `path` names the caller in the republish metric.
/// Publish whichever of `channel_id`'s discovery events are missing, and
/// only those: the live ones keep their `created_at`. Returns whether it
/// published. Healthy channels cost one indexed read and no writes. `path`
/// names the caller in the republish metric.
pub async fn republish_missing_discovery(
tenant: &TenantContext,
state: &Arc<AppState>,
channel_id: Uuid,
path: &'static str,
) -> anyhow::Result<bool> {
let relay_pubkey = state.relay_keypair.public_key().to_bytes();
if !state
let missing = state
.db
.channel_missing_discovery(tenant.community(), channel_id, &relay_pubkey)
.await?
{
.await?;
if missing.is_empty() {
return Ok(false);
}
emit_group_discovery_events(tenant, state, channel_id).await?;
emit_group_discovery_kinds(tenant, state, channel_id, &missing).await?;
metrics::counter!("buzz_channel_discovery_republished_total", "path" => path).increment(1);
info!(channel = %channel_id, path, "republished missing channel discovery events");
info!(channel = %channel_id, path, kinds = ?missing, "republished missing channel discovery events");
Ok(true)
}

/// Republish discovery events for live channels in active communities that
/// were created in the `lookback` before now and lack any of them.
/// Republish the missing discovery events of live channels in active
/// communities that were created in the `lookback` before now, as
/// [`republish_missing_discovery`] does.
///
/// The scan reads [`SWEEP_PAGE`] channels per statement and moves past a
/// channel whose repair fails, so it ends after one pass over the window.
Expand Down Expand Up @@ -87,7 +89,14 @@ pub(crate) async fn reconcile_missing_channel_discovery_paged(
.await?;
for channel in &page {
let tenant = TenantContext::resolved(channel.community_id, channel.host.clone());
match emit_group_discovery_events(&tenant, state, channel.channel_id).await {
match emit_group_discovery_kinds(
&tenant,
state,
channel.channel_id,
&channel.missing_kinds,
)
.await
{
Ok(()) => summary.repaired += 1,
Err(error) => {
summary.failed += 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,11 @@ async fn open_dm(
}

/// Reopening a DM whose roster is missing publishes it again, with both
/// people, and a reopen of a healthy DM publishes nothing.
/// people, and leaves its live metadata and admins as they were; a reopen
/// of a healthy DM publishes nothing.
/// Mutations: drop the reopen repair → no live kind:39002 → RED; republish
/// unconditionally → the healthy reopen replaces kind:39000 → RED.
/// unconditionally → the healthy reopen replaces kind:39000 → RED; republish
/// every kind when one is missing → the repair replaces kind:39000 → RED.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn reopening_a_dm_republishes_its_missing_roster() {
Expand Down Expand Up @@ -171,14 +173,18 @@ async fn reopening_a_dm_republishes_its_missing_roster() {
.get(&39002)
.expect("the reopen republishes the roster");
assert_eq!(members, &people, "the roster names both people");
assert!(repaired.contains_key(&39000) && repaired.contains_key(&39001));
for kind in [39000, 39001] {
assert_eq!(repaired[&kind], healthy[&kind], "kind:{kind} is untouched");
}
}

/// The sweep republishes every channel in its window that lacks any
/// discovery kind, across pages, and leaves healthy, too-old and in-flight
/// channels alone.
/// The sweep republishes the missing discovery kinds of every channel in its
/// window, across pages, keeps their live ones, and leaves healthy, too-old
/// and in-flight channels alone.
/// Mutations: check only kind:39000, or count deleted events as live → the
/// partial channel stays without a roster → RED; stop after the first page →
/// partial channel stays without a roster → RED; republish every kind of a
/// partial channel → its kind:39000 is replaced → RED; stop after the first
/// page →
/// a later channel stays broken → RED; start the scan before the lookback or
/// drop the grace bound → the old or the in-flight channel is republished →
/// RED.
Expand All @@ -204,6 +210,7 @@ async fn the_sweep_republishes_recent_channels_missing_any_discovery_kind() {
drop_discovery(&state, &tenant, bare, &[39000, 39001, 39002]).await;
drop_discovery(&state, &tenant, too_old, &[39002]).await;
drop_discovery(&state, &tenant, in_flight, &[39002]).await;
let partial_metadata = live_discovery(&state, &tenant, partial).await[&39000].clone();
let healthy_before = live_discovery(&state, &tenant, healthy).await;

// One channel per page, so each repaired channel is on its own page.
Expand All @@ -223,6 +230,11 @@ async fn the_sweep_republishes_recent_channels_missing_any_discovery_kind() {
"the roster names the owner"
);
}
assert_eq!(
live_discovery(&state, &tenant, partial).await[&39000],
partial_metadata,
"the partial channel keeps its live metadata"
);
assert_eq!(
live_discovery(&state, &tenant, healthy).await,
healthy_before
Expand Down
Loading
Loading