fix(relay): fence pending subscriptions on close or replacement (#2382)

## Summary

A REQ handler runs as a spawned task and can pause in its access checks.
Before this change it took its subscription ID only when it registered.
So:

- `REQ x`, then `CLOSE x` while the REQ was still in its access checks:
the relay sent `CLOSED x`, and then the REQ registered `x` anyway and
sent events and `EOSE` under an ID the client had closed.
- `REQ x` (A), then a newer `REQ x` (B): if A finished its checks after
B registered, A replaced B, or A's refusal retired B and sent a `CLOSED`
the client could not tell from B failing.

Now the read loop admits each REQ and sync REQ, in arrival order, before
it spawns the handler: the newest request owns the ID from the moment it
arrives. A `CLOSE` or a newer same-ID request fences an older one that
is still pending. A fenced request does not register, and does not send
`NOTICE`, `CLOSED`, `EVENT` or `EOSE` for the ID.

This builds on the owner token and lifecycle lock that #8522 added. That
PR fenced output after registration; this one moves the token to
admission, so the same fence also covers the time before registration.

The pubsub retain no longer waits on a full subscriber command queue.
Callers hold a connection's lifecycle lock while they retain. A retain
past a full queue now leaves a coalesced wake-up, and the subscriber
subscribes every retained topic it is missing. A retain that fits in the
queue leaves no wake-up, so first retains do not each make the
subscriber rescan the map.

## Behavior

- `close::admit` runs in the read loop before spawn. It records the
request's token in the connection's subscription map, with a flag that
says whether the request has claimed yet. It also applies the
subscription limit, which moves there from the handlers.
- Claims (`claim_admitted_live`, `claim_admitted_search`, the sync
claim) register only while the request still owns its token.
- Refusals after admission go through `close_if_owner`. The two REQ
refusals that also send a `NOTICE` send it in the same critical section.
- Refusals before admission (rate limit, admission quota) still retire
the old holder, as before.
- The old holder stays registered until the newer request claims or is
refused, as before.
- A channel-access eviction that removes an old holder while a newer
same-ID request is still pending retires only the old holder. It sends
no `CLOSED` for the ID, because the client already replaced that holder,
and the newer request still claims.

Client-visible changes to the subscription limit:

- The limit is checked on arrival, before scope, auth and filter checks.
On a full connection, a REQ for a new ID that would also fail those
checks now gets `CLOSED "error: too many subscriptions"` instead of the
other refusal.
- Requests still in their access checks count toward the limit.

## Scope

Live fan-out does not check the token. A same-ID request that has
arrived but not yet claimed does not stop live events to the old holder.
That path is unchanged here.

If a handler panics before it claims, its token stays in the map until a
`CLOSE`, a same-ID REQ, or the disconnect removes it. Until then it
counts toward the subscription limit.

## Testing

- `close_fences_a_req_whose_handler_has_not_run` (REQ and sync REQ):
`REQ x` then `CLOSE x` before the handler runs gives only `CLOSED x` and
no registration.
- `only_the_newest_same_id_req_answers`: of two same-ID REQs, only the
newer one answers.
- `superseded_or_closed_requests_cannot_claim`: an older request cannot
claim after a newer one, and a closed request cannot claim or close.
- `revoke_of_a_replaced_holder_spares_the_pending_replacement`: a revoke
of the old holder sends no `CLOSED`, keeps the pending request's token,
and the pending request then claims its own channel.
- `queue_full_retain_does_not_wait_and_schedules_reconciliation`
(pubsub).
- `live_subscriber_recovers_a_dropped_subscribe_hint` (pubsub, requires
Redis): it runs the real subscriber on a live link and drops a topic's
subscribe hint with a full queue. The topic is still delivered without a
reconnect and without `Confirm`. The same holds after the topic is
released, unsubscribed and retained again.
- Mutations: with no owner check in `close_owned`, both connection tests
fail. With no owner check in `claim_admitted_live`, the claim test
fails. With no `replaced` check in the eviction, the revoke test fails.
With no reconcile arm in the subscriber, or no `notify_one` in
`retain_topic`, the Redis subscriber test fails.
- CI: the four new relay tests and the full-queue pubsub test are added
to `just test-unit` and `scripts/run-tests.sh`. The Redis subscriber
test runs in a new Redis-backed backend-integration step.
- `cargo test -p buzz-relay --lib` (with `--skip config::tests`, which
hangs locally when run in one process), `cargo test -p buzz-pubsub --
--include-ignored` against a local Redis, `cargo clippy -p buzz-relay -p
buzz-pubsub --all-targets -- -D warnings`, `cargo fmt --all -- --check`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Logan Johnson
2026-11-10 14:16:48 -05:00
committed by GitHub
parent dd2d3cf4ea
commit 30e1fa47fb
12 changed files with 953 additions and 160 deletions

View File

@@ -56,7 +56,7 @@ use std::time::Duration;
use buzz_core::TenantContext;
use nostr::PublicKey;
use tokio::sync::{broadcast, mpsc, oneshot, watch, Mutex};
use tokio::sync::{broadcast, mpsc, oneshot, watch, Mutex, Notify};
use crate::cache_invalidation::{
cache_invalidation_channel, CacheInvalidation, ScopedCacheInvalidation,
@@ -119,6 +119,10 @@ impl PubSubConfig {
}
}
/// Capacity of the subscriber command queue. A full queue loses only a
/// subscribe hint: the desired-topic map is reconciled separately.
const SUBSCRIPTION_COMMAND_CAPACITY: usize = 4096;
/// Central pub/sub manager for a Buzz relay instance.
pub struct PubSubManager {
pool: crate::RedisConnection,
@@ -130,6 +134,8 @@ pub struct PubSubManager {
desired_topics: subscriber::DesiredTopics,
subscription_tx: mpsc::Sender<subscriber::SubscriptionCommand>,
subscription_rx: Mutex<Option<mpsc::Receiver<subscriber::SubscriptionCommand>>>,
/// Coalesced wake-up: reconcile desired topics with the live Redis link.
subscription_changed: Arc<Notify>,
broadcast_tx: broadcast::Sender<ChannelEvent>,
cache_invalidation_tx: broadcast::Sender<ScopedCacheInvalidation>,
conn_control_tx: broadcast::Sender<ScopedConnControl>,
@@ -152,7 +158,7 @@ impl PubSubManager {
let (cache_invalidation_tx, _) = broadcast::channel(4096);
let (conn_control_tx, _) = broadcast::channel(4096);
let (nip_fi_disconnect_tx, _) = broadcast::channel(4096);
let (subscription_tx, subscription_rx) = mpsc::channel(4096);
let (subscription_tx, subscription_rx) = mpsc::channel(SUBSCRIPTION_COMMAND_CAPACITY);
Ok(Self {
pool,
@@ -161,6 +167,7 @@ impl PubSubManager {
desired_topics: Arc::new(Mutex::new(HashMap::new())),
subscription_tx,
subscription_rx: Mutex::new(Some(subscription_rx)),
subscription_changed: Arc::new(Notify::new()),
broadcast_tx,
cache_invalidation_tx,
conn_control_tx,
@@ -184,6 +191,7 @@ impl PubSubManager {
self.broadcast_tx.clone(),
self.desired_topics.clone(),
subscription_rx,
self.subscription_changed.clone(),
self.link.clone(),
)
.await;
@@ -235,7 +243,8 @@ impl PubSubManager {
/// Retain local interest in a scoped Redis event topic.
///
/// The first retain for a topic asks the subscriber task to `SUBSCRIBE`.
/// Additional retains only increment the local desired refcount.
/// Additional retains only increment the local desired refcount. It never
/// waits on the subscriber: callers hold a connection's lifecycle lock.
pub async fn retain_topic(&self, ctx: &TenantContext, topic: EventTopic) {
let topic_key = EventTopicKey::from_context(ctx, topic);
let should_subscribe = {
@@ -247,10 +256,25 @@ impl PubSubManager {
};
if should_subscribe {
let _ = self
match self
.subscription_tx
.send(subscriber::SubscriptionCommand::Subscribe(topic_key))
.await;
.try_send(subscriber::SubscriptionCommand::Subscribe(topic_key))
{
// A queued command subscribes in order; a closed queue means
// the subscriber is gone, and a restart re-subscribes the
// whole desired-topic map.
Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {}
Err(mpsc::error::TrySendError::Full(_)) => {
// The wake-up is lossless and coalesced: the subscriber
// reconciles the desired-topic map on the live link
// instead of waiting for a Redis reconnect.
self.subscription_changed.notify_one();
tracing::warn!(
?topic_key,
"pubsub subscription command queue full; reconciliation scheduled"
);
}
}
}
}
@@ -703,6 +727,185 @@ mod tests {
assert_eq!(manager.topic_refcount(&ctx_b, topic).await, 0);
}
/// A retain past a full command queue neither waits for the subscriber
/// (callers hold a lifecycle lock) nor loses the topic: it leaves a
/// reconciliation wake-up, and the topic is in the desired map the
/// subscriber re-reads. Retains that fit in the queue leave no wake-up,
/// so first retains do not each make the subscriber rescan the map.
/// Mutation: `send().await` instead of `try_send` hangs at the timeout
/// below; no `notify_one` fails the wake-up check; `notify_one` on every
/// first retain fails the no-wake-up check.
#[tokio::test]
async fn queue_full_retain_does_not_wait_and_schedules_reconciliation() {
let manager = make_manager().await;
let filler = ctx(0xaaaa, "a.example");
for id in 0..SUBSCRIPTION_COMMAND_CAPACITY {
manager
.retain_topic(&filler, EventTopic::Channel(Uuid::from_u128(id as u128)))
.await;
}
// Retains that fit in the queue leave no reconciliation wake-up.
assert!(
tokio::time::timeout(
Duration::from_millis(10),
manager.subscription_changed.notified()
)
.await
.is_err(),
"a queued subscribe needs no reconciliation"
);
let dropped_ctx = ctx(0xbbbb, "b.example");
let dropped = EventTopic::Channel(Uuid::from_u128(0xcccc));
tokio::time::timeout(
Duration::from_secs(1),
manager.retain_topic(&dropped_ctx, dropped),
)
.await
.expect("a retain must not wait on a full command queue");
assert_eq!(manager.topic_refcount(&dropped_ctx, dropped).await, 1);
tokio::time::timeout(
Duration::from_millis(10),
manager.subscription_changed.notified(),
)
.await
.expect("a queue-full retain must leave a reconciliation wake-up");
let missing = subscriber::missing_desired_topics(
&manager.desired_topics,
&std::collections::HashSet::new(),
)
.await;
assert!(missing.contains(&EventTopicKey::from_context(&dropped_ctx, dropped)));
}
/// Fill the command queue with first retains of fresh topics, then retain
/// `topic`, without yielding: on this single-threaded runtime the
/// subscriber cannot drain the queue in between, so `topic`'s subscribe
/// hint is dropped.
async fn retain_with_dropped_hint(
manager: &PubSubManager,
filler: &TenantContext,
first_filler: u128,
target: &TenantContext,
topic: EventTopic,
) {
tokio::task::unconstrained(async {
let mut id = first_filler;
while manager.subscription_tx.capacity() > 0 {
manager
.retain_topic(filler, EventTopic::Channel(Uuid::from_u128(id)))
.await;
id += 1;
}
manager.retain_topic(target, topic).await;
})
.await;
}
/// Publish to `topic` until the live link delivers it.
async fn delivered(
manager: &PubSubManager,
rx: &mut broadcast::Receiver<ChannelEvent>,
ctx: &TenantContext,
topic: EventTopic,
) -> bool {
let event = EventBuilder::new(Kind::TextNote, "reconciled")
.sign_with_keys(&Keys::generate())
.expect("sign");
tokio::time::timeout(Duration::from_secs(10), async {
loop {
manager
.publish_event(ctx, topic, &event)
.await
.expect("publish");
let wait = tokio::time::sleep(Duration::from_millis(100));
tokio::pin!(wait);
loop {
tokio::select! {
() = &mut wait => break,
received = rx.recv() => match received {
Ok(received) if received.event.id == event.id => return,
Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
Err(broadcast::error::RecvError::Closed) => panic!("closed"),
},
}
}
}
})
.await
.is_ok()
}
/// A subscribe hint lost to a full command queue is recovered by the
/// running subscriber on the same Redis link: first for a new topic, then
/// for one released, unsubscribed, and retained again. The link never
/// reconnects and nothing sends `Confirm` for the topic, so only the
/// reconciliation wake-up can subscribe it. Mutation: drop the
/// subscriber's `subscription_changed` arm, or the `notify_one` in
/// `retain_topic` → the topic is never delivered → RED.
#[tokio::test]
#[ignore = "requires Redis"]
async fn live_subscriber_recovers_a_dropped_subscribe_hint() {
let manager = Arc::new(
PubSubManager::with_config(
PubSubConfig::new("redis://127.0.0.1:6379")
.with_unsubscribe_debounce(Duration::from_millis(1)),
make_test_pool(),
)
.await
.unwrap(),
);
let mut rx = manager.subscribe_local();
let mut link = manager.link_state();
let subscriber = tokio::spawn(Arc::clone(&manager).run_subscriber());
link.wait_for(|state| state.up).await.expect("link up");
let epoch = link.borrow().epoch;
let filler = ctx(Uuid::new_v4().as_u128(), "filler.example");
let target = ctx(Uuid::new_v4().as_u128(), "target.example");
let topic = EventTopic::Channel(Uuid::new_v4());
retain_with_dropped_hint(&manager, &filler, 0, &target, topic).await;
assert!(
delivered(&manager, &mut rx, &target, topic).await,
"a dropped hint for a new topic must be reconciled"
);
manager.release_topic(&target, topic).await;
// Wait until Redis shows the debounced unsubscribe took effect, so
// the re-retain below starts from an unsubscribed topic.
let channel = EventTopicKey::from_context(&target, topic).redis_channel();
let mut redis = redis::Client::open("redis://127.0.0.1:6379")
.unwrap()
.get_multiplexed_async_connection()
.await
.expect("redis");
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let (_, subscribers): (String, i64) = redis::cmd("PUBSUB")
.arg("NUMSUB")
.arg(&channel)
.query_async(&mut redis)
.await
.expect("numsub");
if subscribers == 0 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the released topic must be unsubscribed");
retain_with_dropped_hint(&manager, &filler, 1 << 32, &target, topic).await;
assert!(
delivered(&manager, &mut rx, &target, topic).await,
"a dropped hint after an unsubscribe must be reconciled"
);
assert_eq!(link.borrow().epoch, epoch, "the link must not reconnect");
subscriber.abort();
}
#[tokio::test]
async fn retain_release_refcounts_and_debounces_last_release() {
let pool = make_test_pool();

View File

@@ -6,7 +6,7 @@ use std::time::Duration;
use futures_util::StreamExt;
use nostr::JsonUtil;
use tokio::sync::{broadcast, mpsc, oneshot, watch, Mutex};
use tokio::sync::{broadcast, mpsc, oneshot, watch, Mutex, Notify};
use crate::topic::EventTopicKey;
use crate::{ChannelEvent, LinkState};
@@ -51,6 +51,7 @@ pub(crate) async fn run_subscriber(
broadcast_tx: broadcast::Sender<ChannelEvent>,
desired_topics: DesiredTopics,
mut subscription_rx: mpsc::Receiver<SubscriptionCommand>,
subscription_changed: Arc<Notify>,
link: watch::Sender<LinkState>,
) {
let mut backoff_secs = BACKOFF_INITIAL_SECS;
@@ -61,6 +62,7 @@ pub(crate) async fn run_subscriber(
&broadcast_tx,
desired_topics.clone(),
&mut subscription_rx,
&subscription_changed,
&link,
)
.await;
@@ -95,6 +97,7 @@ async fn connect_and_subscribe(
broadcast_tx: &broadcast::Sender<ChannelEvent>,
desired_topics: DesiredTopics,
subscription_rx: &mut mpsc::Receiver<SubscriptionCommand>,
subscription_changed: &Notify,
link: &watch::Sender<LinkState>,
) -> Result<(), redis::RedisError> {
let client = redis::Client::open(redis_url)?;
@@ -124,6 +127,16 @@ async fn connect_and_subscribe(
loop {
tokio::select! {
() = subscription_changed.notified() => {
// Retains signal this besides their best-effort queue hint.
// Re-read the source of truth so a hint lost to a full queue
// cannot leave the live connection missing a topic.
for topic in missing_desired_topics(&desired_topics, &active_topics).await {
let channel = topic.redis_channel();
sink.subscribe(&channel).await?;
active_topics.insert(channel);
}
}
Some(command) = subscription_rx.recv() => {
match command {
SubscriptionCommand::Subscribe(topic) => {
@@ -201,6 +214,21 @@ async fn connect_and_subscribe(
}
}
/// Retained topics the live connection has not subscribed yet.
pub(crate) async fn missing_desired_topics(
desired_topics: &DesiredTopics,
active_topics: &HashSet<String>,
) -> Vec<EventTopicKey> {
desired_topics
.lock()
.await
.iter()
.filter_map(|(topic, count)| {
(*count > 0 && !active_topics.contains(&topic.redis_channel())).then_some(*topic)
})
.collect()
}
async fn desired_refcount(desired_topics: &DesiredTopics, topic: EventTopicKey) -> usize {
desired_topics
.lock()