referrerpolicy=no-referrer-when-downgrade

sc_statement_store/
subscription.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Subscription logic for statement store.
20//!
21//! Manages subscriptions to statement topics and notifies subscribers when new statements arrive.
22//! Uses multiple matcher tasks to handle subscriptions concurrently, each responsible for a subset
23//! of subscriptions. Each matcher task maintains its own list of subscriptions and matches incoming
24//! statements against them. When a new statement is submitted, it is sent to all matcher tasks for
25//! processing. If a statement matches a subscription's filter, it is sent to the subscriber via an
26//! async channel.
27//!
28//! This design allows for efficient handling of a large number of subscriptions and statements and
29//! can be scaled by adjusting the number of matcher tasks.
30
31// Buffer size for the matcher task channels, to backpressure the submission senders.
32// This value is generous to allow for bursts of statements without dropping any or backpressuring
33// too early.
34const MATCHERS_TASK_CHANNEL_BUFFER_SIZE: usize = 80_000;
35
36// Buffer size for individual subscriptions.
37const SUBSCRIPTION_BUFFER_SIZE: usize = 128;
38const STOP_RESERVE_CHANNEL_SLOTS: usize = 1;
39
40/// Maximum number of active filters attached to one statement subscription.
41///
42/// Keeps one subscription useful for multiplexing, while bounding internal per-event filter-id
43/// metadata to 128 `u64`s, i.e. 1 KiB before `Vec` overhead.
44pub const MAX_FILTERS_PER_SUBSCRIPTION: usize = 128;
45// Keep replay batches bounded by raw statement bytes. The JSON response is roughly twice this size
46// because statements are hex-encoded.
47pub(crate) const REPLAY_CHUNK_RAW_BYTES: usize = 4 * 1024 * 1024;
48use futures::{Stream, StreamExt};
49use itertools::Itertools;
50use parking_lot::Mutex;
51
52use crate::LOG_TARGET;
53use sc_utils::id_sequence::SeqID;
54use sp_core::{traits::SpawnNamed, Bytes, Encode};
55pub use sp_statement_store::StatementStore;
56use sp_statement_store::{
57	FilterId, LiveStatementEvent, OptimizedTopicFilter, Result, Statement, StatementEvent, Topic,
58	MAX_TOPICS,
59};
60use std::{
61	collections::{hash_map::Entry, HashMap, HashSet, VecDeque},
62	sync::{atomic::AtomicU64, Arc},
63};
64
65/// Error returned when attaching a filter to a multi-filter subscription fails
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum AddFilterError {
68	/// The subscription already has the maximum number of active filters
69	LimitReached,
70	/// The filter could not be registered: the store or the matcher is gone, or the subscription
71	/// is no longer active
72	Stopped,
73}
74
75/// Trait for initiating statement store subscriptions from the RPC module.
76pub trait StatementStoreSubscriptionApi: Send + Sync {
77	/// Subscribe to statements matching the topic filter.
78	///
79	/// Returns existing matching statements, a sender channel to send matched statements and a
80	/// stream for receiving matched statements when they arrive.
81	fn subscribe_statement(
82		&self,
83		topic_filter: OptimizedTopicFilter,
84	) -> Result<(Vec<Vec<u8>>, async_channel::Sender<StatementEvent>, SubscriptionStatementsStream)>;
85}
86
87/// Creates multi-filter subscriptions for the RPC module
88pub trait MultiFilterSubscriptionApi: Send + Sync {
89	/// Creates an empty subscription that can receive filters dynamically
90	fn create_subscription(&self) -> (SubscriptionHandle, MultiFilterEventStream);
91}
92
93/// Provides cursor-based replay for dynamically attached filters.
94pub(crate) trait ReplaySnapshotProvider: Send + Sync {
95	/// Capture the committed admission watermark and enqueue filter registration atomically with
96	/// respect to submit.
97	/// Returns the registered watermark, or `None` when registration could not be enqueued.
98	///
99	/// `enqueue` is called at most once, with the submit lock held: it must not block or call
100	/// back into the store.
101	fn register_replay(&self, enqueue: &mut dyn FnMut(u64) -> bool) -> Result<Option<u64>>;
102
103	/// Read the next replay batch from the persisted admission sequence.
104	fn replay_batch(
105		&self,
106		filter: &OptimizedTopicFilter,
107		cursor: u64,
108		watermark: u64,
109	) -> Result<ReplayBatch>;
110}
111
112pub(crate) struct ReplayBatch {
113	pub(crate) statements: Vec<Vec<u8>>,
114	pub(crate) cursor: u64,
115	pub(crate) done: bool,
116}
117
118/// A handle that attaches, removes, and inspects filters for one multi-filter subscription
119#[derive(Clone)]
120pub struct SubscriptionHandle {
121	pub(crate) sub_id: SeqID,
122	pub(crate) inner: Arc<Mutex<SubscriptionHandleInner>>,
123	pub(crate) matchers: SubscriptionsMatchersHandlers,
124	pub(crate) snapshot_provider: Arc<dyn ReplaySnapshotProvider>,
125}
126
127pub(crate) struct SubscriptionHandleInner {
128	active_filter_ids: HashSet<FilterId>,
129	next_filter_id: u64,
130}
131
132impl SubscriptionHandleInner {
133	pub(crate) fn new() -> Self {
134		Self { active_filter_ids: HashSet::new(), next_filter_id: 0 }
135	}
136}
137
138impl SubscriptionHandle {
139	/// Attaches a filter and returns its id
140	pub fn add_filter(
141		&self,
142		filter: OptimizedTopicFilter,
143	) -> std::result::Result<FilterId, AddFilterError> {
144		let mut inner = self.inner.lock();
145		if inner.active_filter_ids.len() >= MAX_FILTERS_PER_SUBSCRIPTION {
146			return Err(AddFilterError::LimitReached);
147		}
148
149		let filter_id = FilterId::new(inner.next_filter_id);
150		let sub_id = self.sub_id;
151
152		let (result_tx, result_rx) = async_channel::bounded(1);
153		let mut result_tx = Some(result_tx);
154		let Some(_watermark) = self
155			.snapshot_provider
156			.register_replay(&mut |watermark| {
157				let result_tx =
158					result_tx.take().expect("register_replay invokes enqueue at most once; qed");
159				self.matchers
160					.try_send_by_seq_id(
161						sub_id,
162						MatcherMessage::RegisterFilter {
163							sub_id,
164							filter_id,
165							filter: filter.clone(),
166							watermark,
167							result_tx,
168						},
169					)
170					.is_ok()
171			})
172			.map_err(|_| AddFilterError::Stopped)?
173		else {
174			return Err(AddFilterError::Stopped);
175		};
176		match result_rx.recv_blocking() {
177			Ok(result) => result?,
178			Err(_) => return Err(AddFilterError::Stopped),
179		}
180		inner.next_filter_id = inner.next_filter_id.wrapping_add(1);
181		inner.active_filter_ids.insert(filter_id);
182		Ok(filter_id)
183	}
184
185	/// Removes a filter from this subscription
186	pub fn remove_filter(&self, filter_id: FilterId) -> bool {
187		let mut inner = self.inner.lock();
188		if !inner.active_filter_ids.remove(&filter_id) {
189			return false;
190		}
191		self.matchers.send_by_seq_id(
192			self.sub_id,
193			MatcherMessage::RemoveFilter { sub_id: self.sub_id, filter_id },
194		);
195		true
196	}
197}
198
199struct PendingReplay {
200	filter_id: FilterId,
201	filter: OptimizedTopicFilter,
202	cursor: u64,
203	watermark: u64,
204}
205
206pub(crate) struct MultiFilterSubscriptionState {
207	pending_replays: VecDeque<PendingReplay>,
208	stopped: bool,
209	stop_emitted: bool,
210}
211
212impl MultiFilterSubscriptionState {
213	pub(crate) fn new() -> Self {
214		Self { pending_replays: VecDeque::new(), stopped: false, stop_emitted: false }
215	}
216
217	fn record_filter_added(
218		&mut self,
219		filter_id: FilterId,
220		filter: OptimizedTopicFilter,
221		watermark: u64,
222	) {
223		self.pending_replays
224			.push_back(PendingReplay { filter_id, filter, cursor: 0, watermark });
225	}
226
227	fn record_filter_removed(&mut self, filter_id: FilterId) {
228		self.pending_replays.retain(|replay| replay.filter_id != filter_id);
229	}
230
231	fn next_event(
232		&mut self,
233		snapshot_provider: &dyn ReplaySnapshotProvider,
234	) -> Option<MultiFilterSubscriptionEvent> {
235		if !self.stopped {
236			if let Some(event) = self.next_replay_event(snapshot_provider) {
237				return Some(event);
238			}
239		}
240
241		if self.stopped && !self.stop_emitted {
242			self.stop_emitted = true;
243			return Some(MultiFilterSubscriptionEvent::Stop);
244		}
245		None
246	}
247
248	fn next_replay_event(
249		&mut self,
250		snapshot_provider: &dyn ReplaySnapshotProvider,
251	) -> Option<MultiFilterSubscriptionEvent> {
252		let replay = self.pending_replays.front_mut()?;
253		let filter_id = replay.filter_id;
254		if replay.cursor >= replay.watermark {
255			self.pending_replays.pop_front();
256			return Some(MultiFilterSubscriptionEvent::ReplayDone { filter_id });
257		}
258		let batch =
259			match snapshot_provider.replay_batch(&replay.filter, replay.cursor, replay.watermark) {
260				Ok(batch) => batch,
261				Err(e) => {
262					log::error!(
263						target: LOG_TARGET,
264						"Stopping subscription: replaying filter {:?} from {} failed: {:?}",
265						filter_id,
266						replay.cursor,
267						e
268					);
269					self.stopped = true;
270					return None;
271				},
272			};
273		replay.cursor = batch.cursor;
274		if batch.done && batch.statements.is_empty() {
275			self.pending_replays.pop_front();
276			return Some(MultiFilterSubscriptionEvent::ReplayDone { filter_id });
277		}
278		Some(MultiFilterSubscriptionEvent::ReplayStatements {
279			filter_id,
280			statements: batch.statements,
281		})
282	}
283
284	fn new_statement_event(
285		&mut self,
286		hash: sp_statement_store::Hash,
287		encoded: Vec<u8>,
288		filter_ids: &HashSet<FilterId>,
289	) -> Option<MultiFilterSubscriptionEvent> {
290		let matched_filter_ids: Vec<FilterId> = filter_ids.iter().copied().collect();
291
292		if matched_filter_ids.is_empty() {
293			return None;
294		}
295
296		Some(MultiFilterSubscriptionEvent::NewStatement(LiveStatementEvent {
297			hash,
298			encoded,
299			matched_filter_ids,
300		}))
301	}
302}
303
304/// Event emitted by a multi-filter subscription
305#[derive(Debug, Clone)]
306pub enum MultiFilterSubscriptionEvent {
307	/// Replay statements for a newly attached filter
308	ReplayStatements {
309		/// Filter that produced this replay batch
310		filter_id: FilterId,
311		/// SCALE-encoded statements included in this replay batch
312		statements: Vec<Vec<u8>>,
313	},
314	/// Replay completed for a newly attached filter
315	ReplayDone {
316		/// Filter whose replay completed
317		filter_id: FilterId,
318	},
319	/// Live statement event matched one or more active filters
320	NewStatement(LiveStatementEvent),
321	/// Subscription stopped: the subscriber fell behind its buffer, or replaying a filter failed
322	Stop,
323}
324
325/// Stream of multi-filter subscription events
326pub struct MultiFilterEventStream {
327	sub_id: SeqID,
328	matchers: SubscriptionsMatchersHandlers,
329	rx: async_channel::Receiver<MultiFilterSubscriptionEvent>,
330}
331
332impl Stream for MultiFilterEventStream {
333	type Item = MultiFilterSubscriptionEvent;
334
335	fn poll_next(
336		self: std::pin::Pin<&mut Self>,
337		cx: &mut std::task::Context<'_>,
338	) -> std::task::Poll<Option<Self::Item>> {
339		self.get_mut().rx.poll_next_unpin(cx)
340	}
341}
342
343impl Drop for MultiFilterEventStream {
344	fn drop(&mut self) {
345		self.matchers
346			.send_by_seq_id(self.sub_id, MatcherMessage::Unsubscribe(self.sub_id));
347	}
348}
349
350/// Messages sent to matcher tasks.
351enum MatcherMessage {
352	/// A new statement has been submitted, tagged with the store sequence number.
353	NewStatement(u64, Statement),
354	/// A new subscription has been created.
355	Subscribe { info: IndexedSubscription, tx: async_channel::Sender<StatementEvent> },
356	/// A new multi-filter subscription has been created
357	SubscribeEmpty {
358		seq_id: SeqID,
359		snapshot_provider: Arc<dyn ReplaySnapshotProvider>,
360		tx: async_channel::Sender<MultiFilterSubscriptionEvent>,
361	},
362	/// Register a filter at a store watermark. The matcher drains its cursor replay before
363	/// processing later live-statement messages from this channel.
364	RegisterFilter {
365		sub_id: SeqID,
366		filter_id: FilterId,
367		filter: OptimizedTopicFilter,
368		watermark: u64,
369		result_tx: async_channel::Sender<std::result::Result<(), AddFilterError>>,
370	},
371	/// Remove a filter from an existing multi-filter subscription
372	RemoveFilter { sub_id: SeqID, filter_id: FilterId },
373
374	/// Unsubscribe the subscription with the given ID.
375	Unsubscribe(SeqID),
376}
377
378// Topics each live subscription holds.
379#[derive(Clone, Default)]
380struct SubscriptionTopics {
381	by_sub_id: Arc<Mutex<HashMap<SeqID, Vec<Topic>>>>,
382}
383
384impl SubscriptionTopics {
385	// The concrete topics a filter references.
386	fn filter_topics(filter: &OptimizedTopicFilter) -> Vec<Topic> {
387		match filter {
388			OptimizedTopicFilter::Any => Vec::new(), // matches everything and so names no topic.
389			OptimizedTopicFilter::MatchAll(topics) | OptimizedTopicFilter::MatchAny(topics) => {
390				topics.iter().copied().collect()
391			},
392		}
393	}
394
395	fn insert(&self, sub_id: SeqID, filter: &OptimizedTopicFilter) {
396		let topics = Self::filter_topics(filter);
397		if !topics.is_empty() {
398			self.by_sub_id.lock().insert(sub_id, topics);
399		}
400	}
401
402	fn remove(&self, sub_id: SeqID) {
403		self.by_sub_id.lock().remove(&sub_id);
404	}
405
406	fn snapshot(&self) -> HashSet<Topic> {
407		self.by_sub_id.lock().values().flatten().copied().collect()
408	}
409}
410
411// Handle to manage all subscriptions.
412pub struct SubscriptionsHandle {
413	// Sequence generator for subscription IDs, atomic for thread safety.
414	// Subscription creation is expensive enough that we don't worry about overflow here.
415	id_sequence: AtomicU64,
416	//  Subscriptions matchers handlers.
417	matchers: SubscriptionsMatchersHandlers,
418	// Topics of all live subscriptions.
419	topics: SubscriptionTopics,
420}
421
422impl SubscriptionsHandle {
423	/// Create a new SubscriptionsHandle with the given task spawner and number of filter workers.
424	pub(crate) fn new(
425		task_spawner: Box<dyn SpawnNamed>,
426		num_matcher_workers: usize,
427	) -> SubscriptionsHandle {
428		let mut subscriptions_matchers_senders = Vec::with_capacity(num_matcher_workers);
429
430		for task in 0..num_matcher_workers {
431			let (subscription_matcher_sender, subscription_matcher_receiver) =
432				async_channel::bounded(MATCHERS_TASK_CHANNEL_BUFFER_SIZE);
433			subscriptions_matchers_senders.push(subscription_matcher_sender);
434			task_spawner.spawn_blocking(
435				"statement-store-subscription-filters",
436				Some("statement-store"),
437				Box::pin(async move {
438					let mut subscriptions = SubscriptionsInfo::new();
439					log::debug!(
440						target: LOG_TARGET,
441						"Started statement subscription matcher task: {task}"
442					);
443					loop {
444						let res = subscription_matcher_receiver.recv().await;
445						match res {
446							Ok(MatcherMessage::NewStatement(seq, statement)) => {
447								subscriptions.notify_matching_filters(seq, &statement);
448							},
449							Ok(MatcherMessage::Subscribe { info, tx }) => {
450								subscriptions.subscribe(info, tx);
451							},
452							Ok(MatcherMessage::SubscribeEmpty {
453								seq_id,
454								snapshot_provider,
455								tx,
456							}) => {
457								subscriptions.subscribe_empty(seq_id, snapshot_provider, tx);
458							},
459							Ok(MatcherMessage::RegisterFilter {
460								sub_id,
461								filter_id,
462								filter,
463								watermark,
464								result_tx,
465							}) => {
466								let result = subscriptions
467									.register_filter(sub_id, filter_id, filter, watermark);
468								let registered = result.is_ok();
469								let _ = result_tx.try_send(result);
470								if registered {
471									subscriptions.drain_ready_events(sub_id);
472								}
473							},
474							Ok(MatcherMessage::RemoveFilter { sub_id, filter_id }) => {
475								subscriptions.remove_filter(sub_id, filter_id);
476							},
477							Ok(MatcherMessage::Unsubscribe(seq_id)) => {
478								subscriptions.unsubscribe(seq_id);
479							},
480							Err(_) => {
481								// Expected when the subscription manager is dropped at shutdown.
482								log::debug!(
483									target: LOG_TARGET,
484									"Statement subscription matcher channel closed: {task}"
485								);
486								break;
487							},
488						};
489					}
490				}),
491			);
492		}
493		SubscriptionsHandle {
494			id_sequence: AtomicU64::new(0),
495			matchers: SubscriptionsMatchersHandlers::new(subscriptions_matchers_senders),
496			topics: SubscriptionTopics::default(),
497		}
498	}
499
500	// Generate the next unique subscription ID.
501	fn next_id(&self) -> SeqID {
502		let id = self.id_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
503		SeqID::from(id)
504	}
505
506	/// Subscribe to statements matching the topic filter.
507	pub(crate) fn subscribe(
508		&self,
509		topic_filter: OptimizedTopicFilter,
510		watermark: u64,
511	) -> (async_channel::Sender<StatementEvent>, SubscriptionStatementsStream) {
512		let next_id = self.next_id();
513		let (tx, rx) = async_channel::bounded(SUBSCRIPTION_BUFFER_SIZE);
514		let subscription_info = IndexedSubscription {
515			topic_filter: topic_filter.clone(),
516			seq_id: next_id,
517			filter_key: SubscriptionFilterKey::Fixed,
518			watermark,
519		};
520		let subscription_tx = tx.clone();
521
522		self.topics.insert(subscription_info.seq_id, &topic_filter);
523
524		let result = (
525			tx,
526			SubscriptionStatementsStream {
527				rx,
528				sub_id: subscription_info.seq_id,
529				matchers: self.matchers.clone(),
530				topics: self.topics.clone(),
531			},
532		);
533
534		self.matchers.send_by_seq_id(
535			subscription_info.seq_id,
536			MatcherMessage::Subscribe { info: subscription_info, tx: subscription_tx },
537		);
538		result
539	}
540
541	pub(crate) fn subscribe_empty(
542		&self,
543		snapshot_provider: Arc<dyn ReplaySnapshotProvider>,
544	) -> (SeqID, MultiFilterEventStream) {
545		let sub_id = self.next_id();
546		let (tx, rx) =
547			async_channel::bounded(SUBSCRIPTION_BUFFER_SIZE + STOP_RESERVE_CHANNEL_SLOTS);
548		self.matchers.send_by_seq_id(
549			sub_id,
550			MatcherMessage::SubscribeEmpty { seq_id: sub_id, snapshot_provider, tx },
551		);
552
553		let stream = MultiFilterEventStream { sub_id, matchers: self.matchers.clone(), rx };
554		(sub_id, stream)
555	}
556
557	pub(crate) fn notify(&self, seq: u64, statement: Statement) {
558		self.matchers.send_all(seq, statement);
559	}
560
561	pub(crate) fn matchers(&self) -> SubscriptionsMatchersHandlers {
562		self.matchers.clone()
563	}
564
565	/// The topics across all live subscriptions, for advertising topic affinity.
566	pub(crate) fn subscription_topics(&self) -> HashSet<Topic> {
567		self.topics.snapshot()
568	}
569}
570
571#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
572enum SubscriptionFilterKey {
573	Fixed,
574	Dynamic(FilterId),
575}
576
577enum SubscriptionRecord {
578	SingleFilter {
579		tx: async_channel::Sender<StatementEvent>,
580		filter: OptimizedTopicFilter,
581	},
582	MultiFilter {
583		filters: HashMap<FilterId, OptimizedTopicFilter>,
584		state: MultiFilterSubscriptionState,
585		tx: async_channel::Sender<MultiFilterSubscriptionEvent>,
586		snapshot_provider: Arc<dyn ReplaySnapshotProvider>,
587	},
588}
589
590enum MatchedSubscription {
591	Statements,
592	Live(HashSet<FilterId>),
593}
594
595enum ReadyEventDelivery {
596	Continue,
597	Stopped,
598	Closed,
599}
600
601enum PostLiveSendAction {
602	None,
603	Unsubscribe,
604}
605
606type IndexedSubscriptionKey = (SeqID, SubscriptionFilterKey);
607
608// Information about all subscriptions.
609// Each matcher task will have its own instance of this struct.
610struct SubscriptionsInfo {
611	// Subscriptions organized by topic for MatchAll filters.
612	//
613	// Maps each topic to an array of HashMaps, where the array is indexed by
614	// `(number_of_topics_in_filter - 1)`. For example, a subscription requiring
615	// topics [A, B] (2 topics) will be stored at index 1 under both topic A and B.
616	//
617	// This structure allows efficient matching: when a statement arrives with N topics,
618	// we only need to check subscriptions that require exactly N or fewer topics.
619	subscriptions_match_all_by_topic:
620		HashMap<Topic, [HashMap<IndexedSubscriptionKey, IndexedSubscription>; MAX_TOPICS]>,
621	// Subscriptions organized by topic for MatchAny filters.
622	subscriptions_match_any_by_topic:
623		HashMap<Topic, HashMap<IndexedSubscriptionKey, IndexedSubscription>>,
624	// Subscriptions that listen with Any filter (i.e., no topic filtering).
625	subscriptions_any: HashMap<IndexedSubscriptionKey, IndexedSubscription>,
626	// Mapping from subscription ID to subscription state.
627	by_sub_id: HashMap<SeqID, SubscriptionRecord>,
628}
629
630// Information about one indexed subscription filter.
631#[derive(Clone, Debug)]
632struct IndexedSubscription {
633	// The filter used for this subscription.
634	topic_filter: OptimizedTopicFilter,
635	// The unique ID of this subscription.
636	seq_id: SeqID,
637	// The filter key within the subscription.
638	filter_key: SubscriptionFilterKey,
639	// Store sequence-number boundary captured when this entry was registered: at subscription
640	// creation for a fixed filter, at `add_filter` for a dynamic one.
641	watermark: u64,
642}
643
644impl SubscriptionsInfo {
645	fn new() -> SubscriptionsInfo {
646		SubscriptionsInfo {
647			subscriptions_match_all_by_topic: HashMap::new(),
648			subscriptions_match_any_by_topic: HashMap::new(),
649			subscriptions_any: HashMap::new(),
650			by_sub_id: HashMap::new(),
651		}
652	}
653
654	// Subscribe a new subscription.
655	fn subscribe(
656		&mut self,
657		subscription_info: IndexedSubscription,
658		tx: async_channel::Sender<StatementEvent>,
659	) {
660		self.by_sub_id.insert(
661			subscription_info.seq_id,
662			SubscriptionRecord::SingleFilter { tx, filter: subscription_info.topic_filter.clone() },
663		);
664		self.index_filter(subscription_info);
665	}
666
667	fn subscribe_empty(
668		&mut self,
669		seq_id: SeqID,
670		snapshot_provider: Arc<dyn ReplaySnapshotProvider>,
671		tx: async_channel::Sender<MultiFilterSubscriptionEvent>,
672	) {
673		self.by_sub_id.insert(
674			seq_id,
675			SubscriptionRecord::MultiFilter {
676				filters: HashMap::new(),
677				state: MultiFilterSubscriptionState::new(),
678				tx,
679				snapshot_provider,
680			},
681		);
682	}
683
684	#[cfg(test)]
685	fn add_filter(
686		&mut self,
687		sub_id: SeqID,
688		filter_id: FilterId,
689		filter: OptimizedTopicFilter,
690		snapshot_hashes: Vec<sp_statement_store::Hash>,
691	) {
692		self.add_filter_with_cursor(sub_id, filter_id, filter, snapshot_hashes.len() as u64);
693		self.drain_ready_events(sub_id);
694	}
695
696	fn register_filter(
697		&mut self,
698		sub_id: SeqID,
699		filter_id: FilterId,
700		filter: OptimizedTopicFilter,
701		watermark: u64,
702	) -> std::result::Result<(), AddFilterError> {
703		let Some(SubscriptionRecord::MultiFilter { filters, .. }) = self.by_sub_id.get(&sub_id)
704		else {
705			return Err(AddFilterError::Stopped);
706		};
707		if filters.contains_key(&filter_id) {
708			return Err(AddFilterError::Stopped);
709		}
710		let output_closed = matches!(
711			self.by_sub_id.get(&sub_id),
712			Some(SubscriptionRecord::MultiFilter { tx, .. }) if tx.is_closed()
713		);
714		if output_closed {
715			self.unsubscribe(sub_id);
716			return Err(AddFilterError::Stopped);
717		}
718		self.add_filter_with_cursor(sub_id, filter_id, filter, watermark);
719		Ok(())
720	}
721
722	fn add_filter_with_cursor(
723		&mut self,
724		sub_id: SeqID,
725		filter_id: FilterId,
726		filter: OptimizedTopicFilter,
727		watermark: u64,
728	) {
729		let filter_key = SubscriptionFilterKey::Dynamic(filter_id);
730		{
731			let Some(SubscriptionRecord::MultiFilter { filters, state, .. }) =
732				self.by_sub_id.get_mut(&sub_id)
733			else {
734				return;
735			};
736
737			let Entry::Vacant(entry) = filters.entry(filter_id) else {
738				return;
739			};
740			entry.insert(filter.clone());
741			state.record_filter_added(filter_id, filter.clone(), watermark);
742		}
743		self.index_filter(IndexedSubscription {
744			topic_filter: filter,
745			seq_id: sub_id,
746			filter_key,
747			watermark,
748		});
749	}
750
751	fn remove_filter(&mut self, sub_id: SeqID, filter_id: FilterId) {
752		let Some(record) = self.by_sub_id.get_mut(&sub_id) else {
753			return;
754		};
755		let SubscriptionRecord::MultiFilter { filters, state, .. } = record else {
756			return;
757		};
758		let Some(filter) = filters.remove(&filter_id) else {
759			return;
760		};
761		state.record_filter_removed(filter_id);
762		self.remove_indexed_filter(sub_id, SubscriptionFilterKey::Dynamic(filter_id), &filter);
763		self.drain_ready_events(sub_id);
764	}
765
766	fn send_stop(tx: &async_channel::Sender<MultiFilterSubscriptionEvent>) {
767		let _ = tx.try_send(MultiFilterSubscriptionEvent::Stop);
768		tx.close();
769	}
770
771	fn send_ready_event(
772		state: &mut MultiFilterSubscriptionState,
773		tx: &async_channel::Sender<MultiFilterSubscriptionEvent>,
774		event: MultiFilterSubscriptionEvent,
775	) -> ReadyEventDelivery {
776		if tx.is_closed() {
777			return ReadyEventDelivery::Closed;
778		}
779		if matches!(event, MultiFilterSubscriptionEvent::Stop) {
780			Self::send_stop(tx);
781			return ReadyEventDelivery::Stopped;
782		}
783		if tx.len() >= SUBSCRIPTION_BUFFER_SIZE {
784			state.stopped = true;
785			Self::send_stop(tx);
786			return ReadyEventDelivery::Stopped;
787		}
788		match tx.try_send(event) {
789			Ok(()) => ReadyEventDelivery::Continue,
790			Err(async_channel::TrySendError::Full(_)) => {
791				state.stopped = true;
792				Self::send_stop(tx);
793				ReadyEventDelivery::Stopped
794			},
795			Err(async_channel::TrySendError::Closed(_)) => ReadyEventDelivery::Closed,
796		}
797	}
798
799	fn drain_ready_events(&mut self, sub_id: SeqID) {
800		loop {
801			let result = {
802				let Some(record) = self.by_sub_id.get_mut(&sub_id) else {
803					return;
804				};
805				let SubscriptionRecord::MultiFilter { state, tx, snapshot_provider, .. } = record
806				else {
807					return;
808				};
809				let Some(event) = state.next_event(snapshot_provider.as_ref()) else {
810					return;
811				};
812				match Self::send_ready_event(state, tx, event) {
813					ReadyEventDelivery::Continue => Ok(()),
814					ReadyEventDelivery::Stopped => return,
815					ReadyEventDelivery::Closed => Err(()),
816				}
817			};
818			if result.is_err() {
819				self.unsubscribe(sub_id);
820				return;
821			}
822		}
823	}
824
825	/// Emit a live statement matched for a multi-filter subscription.
826	fn deliver_live_statement(
827		&mut self,
828		sub_id: SeqID,
829		hash: sp_statement_store::Hash,
830		encoded: Vec<u8>,
831		matched_filter_ids: HashSet<FilterId>,
832	) {
833		let action = {
834			let Some(SubscriptionRecord::MultiFilter { state, tx, .. }) =
835				self.by_sub_id.get_mut(&sub_id)
836			else {
837				return;
838			};
839
840			match state.new_statement_event(hash, encoded, &matched_filter_ids) {
841				Some(event) => match Self::send_ready_event(state, tx, event) {
842					ReadyEventDelivery::Closed => PostLiveSendAction::Unsubscribe,
843					ReadyEventDelivery::Continue | ReadyEventDelivery::Stopped => {
844						PostLiveSendAction::None
845					},
846				},
847				None => PostLiveSendAction::None,
848			}
849		};
850
851		match action {
852			PostLiveSendAction::Unsubscribe => self.unsubscribe(sub_id),
853			PostLiveSendAction::None => {},
854		}
855	}
856
857	fn index_filter(&mut self, subscription_info: IndexedSubscription) {
858		let index_key = (subscription_info.seq_id, subscription_info.filter_key);
859		match &subscription_info.topic_filter {
860			OptimizedTopicFilter::Any => {
861				self.subscriptions_any.insert(index_key, subscription_info);
862			},
863			OptimizedTopicFilter::MatchAll(topics) => {
864				for topic in topics {
865					self.subscriptions_match_all_by_topic.entry(*topic).or_default()
866						[topics.len() - 1]
867						.insert(index_key, subscription_info.clone());
868				}
869			},
870			OptimizedTopicFilter::MatchAny(topics) => {
871				for topic in topics {
872					self.subscriptions_match_any_by_topic
873						.entry(*topic)
874						.or_default()
875						.insert(index_key, subscription_info.clone());
876				}
877			},
878		};
879	}
880
881	// Deliver the statement at store sequence number `seq` to every matching subscription.
882	// Subscriptions and filters registered above `seq` are skipped: the statement predates them, so
883	// it is covered by the subscribe-time snapshot
884	// (`StatementStoreSubscriptionApi::subscribe_statement`) for a fixed filter, or by the
885	// admission-cursor replay (`ReplaySnapshotProvider::replay_batch`) for a dynamic one.
886	fn notify_matching_filters(&mut self, seq: u64, statement: &Statement) {
887		let mut matches = HashMap::new();
888		self.collect_match_all_subscribers(seq, statement, &mut matches);
889		self.collect_match_any_subscribers(seq, statement, &mut matches);
890		self.collect_any_subscribers(seq, &mut matches);
891
892		let encoded = statement.encode();
893		let bytes_to_send: Bytes = encoded.clone().into();
894		let mut needs_unsubscribing = HashSet::new();
895
896		for (sub_id, matched) in matches {
897			match matched {
898				MatchedSubscription::Statements => {
899					let Some(SubscriptionRecord::SingleFilter { tx, .. }) =
900						self.by_sub_id.get(&sub_id)
901					else {
902						continue;
903					};
904					if let Err(err) = tx.try_send(StatementEvent::NewStatements {
905						statements: vec![bytes_to_send.clone()],
906						remaining: None,
907					}) {
908						log::debug!(
909							target: LOG_TARGET,
910							"Failed to send statement to subscriber {:?}: {:?} unsubscribing it", sub_id, err
911						);
912						needs_unsubscribing.insert(sub_id);
913					}
914				},
915				MatchedSubscription::Live(filter_ids) if !filter_ids.is_empty() => {
916					self.deliver_live_statement(
917						sub_id,
918						statement.hash(),
919						encoded.clone(),
920						filter_ids,
921					);
922				},
923				_ => {},
924			}
925		}
926
927		for sub_id in needs_unsubscribing {
928			self.unsubscribe(sub_id);
929		}
930	}
931
932	// Record a subscription filter as matched, unless the statement's sequence number is below the
933	// watermark captured when it was registered (exactly-once delivery: such statements are covered
934	// by the subscribe-time snapshot or the admission-cursor replay instead).
935	fn record_match(
936		matches: &mut HashMap<SeqID, MatchedSubscription>,
937		subscription: &IndexedSubscription,
938		seq: u64,
939	) {
940		if seq < subscription.watermark {
941			return;
942		}
943		match subscription.filter_key {
944			SubscriptionFilterKey::Fixed => {
945				matches.entry(subscription.seq_id).or_insert(MatchedSubscription::Statements);
946			},
947			SubscriptionFilterKey::Dynamic(filter_id) => {
948				let entry = matches
949					.entry(subscription.seq_id)
950					.or_insert_with(|| MatchedSubscription::Live(HashSet::new()));
951				if let MatchedSubscription::Live(filter_ids) = entry {
952					filter_ids.insert(filter_id);
953				}
954			},
955		}
956	}
957
958	// Collect all subscribers with MatchAny filters that match the given statement.
959	fn collect_match_any_subscribers(
960		&self,
961		seq: u64,
962		statement: &Statement,
963		matches: &mut HashMap<SeqID, MatchedSubscription>,
964	) {
965		for statement_topic in statement.topics() {
966			if let Some(subscriptions) = self.subscriptions_match_any_by_topic.get(statement_topic)
967			{
968				for subscription in subscriptions.values() {
969					Self::record_match(matches, subscription, seq);
970				}
971			}
972		}
973	}
974
975	// Collect all subscribers with MatchAll filters that match the given statement.
976	fn collect_match_all_subscribers(
977		&self,
978		seq: u64,
979		statement: &Statement,
980		matches: &mut HashMap<SeqID, MatchedSubscription>,
981	) {
982		let num_topics = statement.topics().len();
983
984		// Check all combinations of topics in the statement to find matching subscriptions.
985		// This works well because the maximum allowed topics is small (MAX_TOPICS = 4).
986		for num_topics_to_check in 1..=num_topics {
987			for topics_combination in statement.topics().iter().combinations(num_topics_to_check) {
988				// Find the topic with the fewest subscriptions to minimize the number of checks.
989				let Some(Some(topic_with_fewest)) = topics_combination
990					.iter()
991					.map(|topic| self.subscriptions_match_all_by_topic.get(*topic))
992					.min_by_key(|subscriptions| {
993						subscriptions.map_or(0, |subscriptions_by_length| {
994							subscriptions_by_length[num_topics_to_check - 1].len()
995						})
996					})
997				else {
998					continue;
999				};
1000
1001				for subscription in topic_with_fewest[num_topics_to_check - 1]
1002					.values()
1003					.filter(|subscription| subscription.topic_filter.matches(statement))
1004				{
1005					Self::record_match(matches, subscription, seq);
1006				}
1007			}
1008		}
1009	}
1010
1011	// Collect all subscribers that don't filter by topic and want to receive all statements.
1012	fn collect_any_subscribers(&self, seq: u64, matches: &mut HashMap<SeqID, MatchedSubscription>) {
1013		for subscription in self.subscriptions_any.values() {
1014			Self::record_match(matches, subscription, seq);
1015		}
1016	}
1017
1018	// Unsubscribe a subscription by its ID.
1019	fn unsubscribe(&mut self, id: SeqID) {
1020		let Some(entry) = self.by_sub_id.remove(&id) else {
1021			return;
1022		};
1023
1024		match entry {
1025			SubscriptionRecord::SingleFilter { filter, .. } => {
1026				self.remove_indexed_filter(id, SubscriptionFilterKey::Fixed, &filter);
1027			},
1028			SubscriptionRecord::MultiFilter { filters, .. } => {
1029				for (filter_id, filter) in filters {
1030					self.remove_indexed_filter(
1031						id,
1032						SubscriptionFilterKey::Dynamic(filter_id),
1033						&filter,
1034					);
1035				}
1036			},
1037		}
1038	}
1039
1040	fn remove_indexed_filter(
1041		&mut self,
1042		id: SeqID,
1043		filter_key: SubscriptionFilterKey,
1044		filter: &OptimizedTopicFilter,
1045	) {
1046		let topics = match filter {
1047			OptimizedTopicFilter::Any => {
1048				self.subscriptions_any.remove(&(id, filter_key));
1049				return;
1050			},
1051			OptimizedTopicFilter::MatchAll(topics) => topics,
1052			OptimizedTopicFilter::MatchAny(topics) => topics,
1053		};
1054
1055		// Remove subscription from relevant maps.
1056		for topic in topics {
1057			// Check MatchAny map.
1058			if let Entry::Occupied(mut entry) = self.subscriptions_match_any_by_topic.entry(*topic)
1059			{
1060				entry.get_mut().remove(&(id, filter_key));
1061				if entry.get().is_empty() {
1062					entry.remove();
1063				}
1064			}
1065			// Check MatchAll map.
1066			if let Entry::Occupied(mut entry) = self.subscriptions_match_all_by_topic.entry(*topic)
1067			{
1068				for subscriptions in entry.get_mut().iter_mut() {
1069					if subscriptions.remove(&(id, filter_key)).is_some() {
1070						break;
1071					}
1072				}
1073				if entry.get().iter().all(|s| s.is_empty()) {
1074					entry.remove();
1075				}
1076			}
1077		}
1078	}
1079}
1080
1081// Handlers to communicate with subscription matcher tasks.
1082#[derive(Clone)]
1083pub struct SubscriptionsMatchersHandlers {
1084	// Channels to send messages to matcher tasks.
1085	matchers: Vec<async_channel::Sender<MatcherMessage>>,
1086}
1087
1088impl SubscriptionsMatchersHandlers {
1089	/// Create new SubscriptionsMatchersHandlers with the given matcher task senders.
1090	fn new(matchers: Vec<async_channel::Sender<MatcherMessage>>) -> SubscriptionsMatchersHandlers {
1091		SubscriptionsMatchersHandlers { matchers }
1092	}
1093
1094	// Send a message to the matcher task responsible for the given subscription ID.
1095	fn send_by_seq_id(&self, id: SeqID, message: MatcherMessage) {
1096		// If matchers channels are full we backpressure the sender, in this case it will be the
1097		// processing of new statements.
1098		if let Err(err) = self.try_send_by_seq_id(id, message) {
1099			log::error!(
1100				target: LOG_TARGET,
1101				"Failed to send statement to matcher task: {:?}", err
1102			);
1103		}
1104	}
1105
1106	fn try_send_by_seq_id(
1107		&self,
1108		id: SeqID,
1109		message: MatcherMessage,
1110	) -> std::result::Result<(), async_channel::TrySendError<MatcherMessage>> {
1111		self.sender_by_seq_id(id).try_send(message)
1112	}
1113
1114	fn sender_by_seq_id(&self, id: SeqID) -> async_channel::Sender<MatcherMessage> {
1115		let index: u64 = id.into();
1116		self.matchers[index as usize % self.matchers.len()].clone()
1117	}
1118
1119	// Send a new statement, tagged with its store sequence number, to all matcher tasks.
1120	fn send_all(&self, seq: u64, statement: Statement) {
1121		for sender in &self.matchers {
1122			if let Err(err) =
1123				sender.send_blocking(MatcherMessage::NewStatement(seq, statement.clone()))
1124			{
1125				log::error!(
1126					target: LOG_TARGET,
1127					"Failed to send message to matcher task: {:?}", err
1128				);
1129			}
1130		}
1131	}
1132}
1133
1134// Stream of statements for a subscription.
1135pub struct SubscriptionStatementsStream {
1136	// Channel to receive statements.
1137	pub rx: async_channel::Receiver<StatementEvent>,
1138	// Subscription ID, used for cleanup on drop.
1139	sub_id: SeqID,
1140	// Reference to the matchers for cleanup.
1141	matchers: SubscriptionsMatchersHandlers,
1142	// Shared affinity map.
1143	topics: SubscriptionTopics,
1144}
1145
1146// When the stream is dropped, unsubscribe from the matchers.
1147impl Drop for SubscriptionStatementsStream {
1148	fn drop(&mut self) {
1149		self.matchers
1150			.send_by_seq_id(self.sub_id, MatcherMessage::Unsubscribe(self.sub_id));
1151		self.topics.remove(self.sub_id);
1152	}
1153}
1154
1155impl Stream for SubscriptionStatementsStream {
1156	type Item = StatementEvent;
1157
1158	fn poll_next(
1159		mut self: std::pin::Pin<&mut Self>,
1160		cx: &mut std::task::Context<'_>,
1161	) -> std::task::Poll<Option<Self::Item>> {
1162		self.rx.poll_next_unpin(cx)
1163	}
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168
1169	use crate::tests::signed_statement;
1170
1171	use super::*;
1172	use sp_core::Decode;
1173	use sp_statement_store::Topic;
1174	use std::{
1175		sync::{mpsc, Mutex as StdMutex},
1176		thread,
1177		time::{Duration, Instant},
1178	};
1179
1180	fn unwrap_statement(item: StatementEvent) -> Bytes {
1181		match item {
1182			StatementEvent::NewStatements { mut statements, .. } => {
1183				assert_eq!(statements.len(), 1, "Expected exactly one statement in batch");
1184				statements.remove(0)
1185			},
1186		}
1187	}
1188
1189	fn fixed_subscription(seq_id: u64, topic_filter: OptimizedTopicFilter) -> IndexedSubscription {
1190		IndexedSubscription {
1191			topic_filter,
1192			seq_id: SeqID::from(seq_id),
1193			filter_key: SubscriptionFilterKey::Fixed,
1194			watermark: 0,
1195		}
1196	}
1197
1198	fn live_event_for(statement: &Statement, filter_ids: Vec<FilterId>) -> LiveStatementEvent {
1199		LiveStatementEvent {
1200			hash: statement.hash(),
1201			encoded: statement.encode(),
1202			matched_filter_ids: filter_ids,
1203		}
1204	}
1205
1206	struct TestReplaySnapshotProvider {
1207		statements: HashMap<sp_statement_store::Hash, Vec<u8>>,
1208		snapshot_hashes: Vec<sp_statement_store::Hash>,
1209		batch_len: u64,
1210	}
1211
1212	impl TestReplaySnapshotProvider {
1213		fn with_snapshot(snapshot: &[Statement], statements: &[Statement]) -> Self {
1214			Self {
1215				statements: statements
1216					.iter()
1217					.map(|statement| (statement.hash(), statement.encode()))
1218					.collect(),
1219				snapshot_hashes: snapshot.iter().map(Statement::hash).collect(),
1220				batch_len: snapshot.len() as u64,
1221			}
1222		}
1223	}
1224
1225	impl ReplaySnapshotProvider for TestReplaySnapshotProvider {
1226		fn register_replay(&self, enqueue: &mut dyn FnMut(u64) -> bool) -> Result<Option<u64>> {
1227			let watermark = self.snapshot_hashes.len() as u64;
1228			Ok(enqueue(watermark).then_some(watermark))
1229		}
1230
1231		fn replay_batch(
1232			&self,
1233			_filter: &OptimizedTopicFilter,
1234			cursor: u64,
1235			watermark: u64,
1236		) -> Result<ReplayBatch> {
1237			let end = watermark.min(self.snapshot_hashes.len() as u64).min(cursor + self.batch_len);
1238			let statements = self.snapshot_hashes[cursor as usize..end as usize]
1239				.iter()
1240				.filter_map(|hash| self.statements.get(hash).cloned())
1241				.collect();
1242			Ok(ReplayBatch { statements, cursor: end, done: end >= watermark })
1243		}
1244	}
1245
1246	struct BlockingReplaySnapshotProvider {
1247		statements: HashMap<sp_statement_store::Hash, Vec<u8>>,
1248		snapshot_hashes: Vec<sp_statement_store::Hash>,
1249		scan_started: mpsc::SyncSender<()>,
1250		continue_scan: StdMutex<mpsc::Receiver<()>>,
1251	}
1252
1253	impl ReplaySnapshotProvider for BlockingReplaySnapshotProvider {
1254		fn register_replay(&self, enqueue: &mut dyn FnMut(u64) -> bool) -> Result<Option<u64>> {
1255			let watermark = self.snapshot_hashes.len() as u64;
1256			Ok(enqueue(watermark).then_some(watermark))
1257		}
1258
1259		fn replay_batch(
1260			&self,
1261			_filter: &OptimizedTopicFilter,
1262			cursor: u64,
1263			watermark: u64,
1264		) -> Result<ReplayBatch> {
1265			self.scan_started.send(()).expect("test receiver remains open");
1266			self.continue_scan
1267				.lock()
1268				.expect("test mutex is not poisoned")
1269				.recv()
1270				.expect("test sender remains open");
1271			let end = watermark.min(self.snapshot_hashes.len() as u64);
1272			let statements = self.snapshot_hashes[cursor as usize..end as usize]
1273				.iter()
1274				.filter_map(|hash| self.statements.get(hash).cloned())
1275				.collect();
1276			Ok(ReplayBatch { statements, cursor: end, done: end >= watermark })
1277		}
1278	}
1279
1280	struct ReplayLoadBlockingProvider {
1281		body: Vec<u8>,
1282		load_started: mpsc::SyncSender<()>,
1283		continue_load: StdMutex<mpsc::Receiver<()>>,
1284	}
1285
1286	impl ReplaySnapshotProvider for ReplayLoadBlockingProvider {
1287		fn register_replay(&self, enqueue: &mut dyn FnMut(u64) -> bool) -> Result<Option<u64>> {
1288			Ok(enqueue(1).then_some(1))
1289		}
1290
1291		fn replay_batch(
1292			&self,
1293			_filter: &OptimizedTopicFilter,
1294			cursor: u64,
1295			watermark: u64,
1296		) -> Result<ReplayBatch> {
1297			assert_eq!(cursor, 0);
1298			assert_eq!(watermark, 1);
1299			self.load_started.send(()).expect("test receiver remains open");
1300			self.continue_load
1301				.lock()
1302				.expect("test mutex is not poisoned")
1303				.recv()
1304				.expect("test sender remains open");
1305			Ok(ReplayBatch { statements: vec![self.body.clone()], cursor: 1, done: true })
1306		}
1307	}
1308
1309	fn recv_multi_filter_event(
1310		stream: &MultiFilterEventStream,
1311		timeout: Duration,
1312	) -> Option<MultiFilterSubscriptionEvent> {
1313		let deadline = Instant::now() + timeout;
1314		loop {
1315			match stream.rx.try_recv() {
1316				Ok(event) => return Some(event),
1317				Err(async_channel::TryRecvError::Closed) => return None,
1318				Err(async_channel::TryRecvError::Empty) if Instant::now() < deadline => {
1319					thread::sleep(Duration::from_millis(1));
1320				},
1321				Err(async_channel::TryRecvError::Empty) => return None,
1322			}
1323		}
1324	}
1325
1326	#[test]
1327	fn multi_filter_replays_before_live_submissions_committed_during_snapshot() {
1328		let subscriptions =
1329			SubscriptionsHandle::new(Box::new(sp_core::testing::TaskExecutor::new()), 1);
1330		let filter_id = FilterId::new(0);
1331		let replayed = signed_statement(41);
1332		let delayed = signed_statement(40);
1333		let delayed_hash = delayed.hash();
1334		let live = signed_statement(42);
1335		let (scan_started_tx, scan_started_rx) = mpsc::sync_channel(1);
1336		let (continue_scan_tx, continue_scan_rx) = mpsc::sync_channel(1);
1337		let provider = Arc::new(BlockingReplaySnapshotProvider {
1338			statements: [(replayed.hash(), replayed.encode())].into_iter().collect(),
1339			snapshot_hashes: vec![replayed.hash()],
1340			scan_started: scan_started_tx,
1341			continue_scan: StdMutex::new(continue_scan_rx),
1342		});
1343		let (sub_id, stream) = subscriptions.subscribe_empty(provider.clone());
1344		let handle = SubscriptionHandle {
1345			sub_id,
1346			inner: Arc::new(Mutex::new(SubscriptionHandleInner::new())),
1347			matchers: subscriptions.matchers(),
1348			snapshot_provider: provider,
1349		};
1350
1351		let add_filter = thread::spawn(move || handle.add_filter(OptimizedTopicFilter::Any));
1352		scan_started_rx.recv().expect("snapshot scan starts");
1353
1354		// Both post-watermark live events wait behind replay.
1355		subscriptions.notify(0, replayed.clone());
1356		subscriptions.notify(1, delayed);
1357		subscriptions.notify(2, live.clone());
1358		continue_scan_tx.send(()).expect("snapshot scan is still waiting");
1359		assert_eq!(add_filter.join().expect("add-filter thread does not panic"), Ok(filter_id));
1360
1361		assert!(matches!(
1362			recv_multi_filter_event(&stream, Duration::from_secs(1)),
1363			Some(MultiFilterSubscriptionEvent::ReplayStatements { statements, .. })
1364				if statements == vec![replayed.encode()]
1365		));
1366		assert!(matches!(
1367			recv_multi_filter_event(&stream, Duration::from_secs(1)),
1368			Some(MultiFilterSubscriptionEvent::ReplayDone { filter_id: done }) if done == filter_id
1369		));
1370		assert!(matches!(
1371			recv_multi_filter_event(&stream, Duration::from_secs(1)),
1372			Some(MultiFilterSubscriptionEvent::NewStatement(event))
1373				if event.hash == delayed_hash && event.matched_filter_ids == vec![filter_id]
1374		));
1375		assert!(matches!(
1376			recv_multi_filter_event(&stream, Duration::from_secs(1)),
1377			Some(MultiFilterSubscriptionEvent::NewStatement(event))
1378				if event.hash == live.hash() && event.matched_filter_ids == vec![filter_id]
1379		));
1380		assert!(recv_multi_filter_event(&stream, Duration::from_millis(10)).is_none());
1381	}
1382
1383	#[test]
1384	fn add_filter_returns_before_matcher_drains_replay() {
1385		let subscriptions =
1386			SubscriptionsHandle::new(Box::new(sp_core::testing::TaskExecutor::new()), 1);
1387		let statement = signed_statement(43);
1388		let (load_started_tx, load_started_rx) = mpsc::sync_channel(1);
1389		let (continue_load_tx, continue_load_rx) = mpsc::sync_channel(1);
1390		let provider = Arc::new(ReplayLoadBlockingProvider {
1391			body: statement.encode(),
1392			load_started: load_started_tx,
1393			continue_load: StdMutex::new(continue_load_rx),
1394		});
1395		let (sub_id, _stream) = subscriptions.subscribe_empty(provider.clone());
1396		let handle = SubscriptionHandle {
1397			sub_id,
1398			inner: Arc::new(Mutex::new(SubscriptionHandleInner::new())),
1399			matchers: subscriptions.matchers(),
1400			snapshot_provider: provider,
1401		};
1402		let (result_tx, result_rx) = mpsc::sync_channel(1);
1403		let add_filter = thread::spawn(move || {
1404			result_tx
1405				.send(handle.add_filter(OptimizedTopicFilter::Any))
1406				.expect("test receiver remains open");
1407		});
1408
1409		load_started_rx.recv().expect("matcher starts loading replay");
1410		let result = result_rx.recv_timeout(Duration::from_secs(1));
1411		continue_load_tx.send(()).expect("replay load is still waiting");
1412		add_filter.join().expect("add-filter thread does not panic");
1413		assert_eq!(result, Ok(Ok(FilterId::new(0))));
1414	}
1415
1416	#[test]
1417	fn multi_filter_delivers_re_admitted_hash_skipped_during_replay() {
1418		let mut subscriptions = SubscriptionsInfo::new();
1419		let sub_id = SeqID::from(12);
1420		let filter_id = FilterId::new(1);
1421		let topic = Topic::from([9u8; 32]);
1422		let filter = OptimizedTopicFilter::MatchAny(vec![topic].into_iter().collect());
1423		let (tx, rx) = async_channel::bounded::<MultiFilterSubscriptionEvent>(10);
1424		let mut statement = signed_statement(42);
1425		statement.set_topic(0, topic);
1426		// The statement has an admission entry inside the replay range, but its body is no longer
1427		// retrievable, so the replay skips that sequence number.
1428		let provider = Arc::new(TestReplaySnapshotProvider::with_snapshot(
1429			std::slice::from_ref(&statement),
1430			&[],
1431		));
1432
1433		subscriptions.subscribe_empty(sub_id, provider, tx);
1434		subscriptions.add_filter(sub_id, filter_id, filter, vec![statement.hash()]);
1435
1436		// The body could not be loaded, so the replay finishes without emitting it.
1437		assert!(matches!(
1438			rx.try_recv(),
1439			Ok(MultiFilterSubscriptionEvent::ReplayDone { filter_id: done }) if done == filter_id
1440		));
1441
1442		// The statement is re-admitted at a new sequence. It was never delivered through replay,
1443		// so it must reach the subscriber as a live event.
1444		subscriptions.notify_matching_filters(1, &statement);
1445
1446		match rx.try_recv() {
1447			Ok(MultiFilterSubscriptionEvent::NewStatement(event)) => {
1448				assert_eq!(event.hash, statement.hash());
1449				assert_eq!(event.matched_filter_ids, vec![filter_id]);
1450			},
1451			other => {
1452				panic!("statement skipped during replay must be delivered live, got {other:?}")
1453			},
1454		}
1455
1456		subscriptions.notify_matching_filters(2, &statement);
1457		assert!(matches!(
1458			rx.try_recv(),
1459			Ok(MultiFilterSubscriptionEvent::NewStatement(event))
1460				if event.hash == statement.hash() && event.matched_filter_ids == vec![filter_id]
1461		));
1462	}
1463
1464	#[test]
1465	fn multi_filter_replay_resumes_from_the_returned_cursor() {
1466		let mut subscriptions = SubscriptionsInfo::new();
1467		let sub_id = SeqID::from(11);
1468		let filter_id = FilterId::new(1);
1469		let topic = Topic::from([9u8; 32]);
1470		let filter = OptimizedTopicFilter::MatchAny(vec![topic].into_iter().collect());
1471		let (tx, rx) = async_channel::bounded::<MultiFilterSubscriptionEvent>(10);
1472		let replayed: Vec<Statement> = (0..3u8)
1473			.map(|seed| {
1474				let mut statement = signed_statement(seed);
1475				statement.set_topic(0, topic);
1476				statement
1477			})
1478			.collect();
1479		let mut provider = TestReplaySnapshotProvider::with_snapshot(&replayed, &replayed);
1480		provider.batch_len = 1;
1481
1482		subscriptions.subscribe_empty(sub_id, Arc::new(provider), tx);
1483		subscriptions.add_filter(
1484			sub_id,
1485			filter_id,
1486			filter,
1487			replayed.iter().map(Statement::hash).collect(),
1488		);
1489
1490		let mut delivered = Vec::new();
1491		let mut replay_done = 0;
1492		while let Ok(event) = rx.try_recv() {
1493			match event {
1494				MultiFilterSubscriptionEvent::ReplayStatements { filter_id: id, statements } => {
1495					assert_eq!(id, filter_id);
1496					delivered.extend(statements);
1497				},
1498				MultiFilterSubscriptionEvent::ReplayDone { filter_id: id } => {
1499					assert_eq!(id, filter_id);
1500					replay_done += 1;
1501				},
1502				other => panic!("expected replay events, got {other:?}"),
1503			}
1504		}
1505		assert_eq!(delivered, replayed.iter().map(Statement::encode).collect::<Vec<_>>());
1506		assert_eq!(replay_done, 1);
1507	}
1508
1509	#[test]
1510	fn multi_filter_pushes_ready_live_events_without_request_next() {
1511		let mut subscriptions = SubscriptionsInfo::new();
1512		let sub_id = SeqID::from(7);
1513		let filter_id = FilterId::new(1);
1514		let topic = Topic::from([9u8; 32]);
1515		let filter = OptimizedTopicFilter::MatchAny(vec![topic].into_iter().collect());
1516		let (tx, rx) = async_channel::bounded::<MultiFilterSubscriptionEvent>(10);
1517		let mut statement = signed_statement(42);
1518		statement.set_topic(0, topic);
1519		let provider = Arc::new(TestReplaySnapshotProvider::with_snapshot(
1520			&[],
1521			std::slice::from_ref(&statement),
1522		));
1523
1524		subscriptions.subscribe_empty(sub_id, provider, tx);
1525		subscriptions.add_filter(sub_id, filter_id, filter, vec![]);
1526		assert!(matches!(
1527			rx.try_recv(),
1528			Ok(MultiFilterSubscriptionEvent::ReplayDone { filter_id: done_filter })
1529				if done_filter == filter_id
1530		));
1531
1532		subscriptions.notify_matching_filters(0, &statement);
1533
1534		match rx.try_recv() {
1535			Ok(MultiFilterSubscriptionEvent::NewStatement(event)) => {
1536				assert_eq!(event.hash, statement.hash());
1537				assert_eq!(event.matched_filter_ids, vec![filter_id]);
1538			},
1539			other => panic!("expected pushed live statement, got {other:?}"),
1540		}
1541	}
1542
1543	#[test]
1544	fn multi_filter_reserves_output_slot_for_stop() {
1545		let mut subscriptions = SubscriptionsInfo::new();
1546		let sub_id = SeqID::from(8);
1547		let filter_id = FilterId::new(1);
1548		let topic = Topic::from([9u8; 32]);
1549		let filter = OptimizedTopicFilter::MatchAny(vec![topic].into_iter().collect());
1550		let mut statements =
1551			Vec::with_capacity(SUBSCRIPTION_BUFFER_SIZE + STOP_RESERVE_CHANNEL_SLOTS);
1552		for seed in 0..=SUBSCRIPTION_BUFFER_SIZE as u64 {
1553			let mut statement = signed_statement(seed as u8);
1554			statement.set_topic(0, topic);
1555			statements.push(statement);
1556		}
1557		let provider = Arc::new(TestReplaySnapshotProvider::with_snapshot(&[], &statements));
1558		let (tx, rx) = async_channel::bounded::<MultiFilterSubscriptionEvent>(
1559			SUBSCRIPTION_BUFFER_SIZE + STOP_RESERVE_CHANNEL_SLOTS,
1560		);
1561
1562		subscriptions.subscribe_empty(sub_id, provider, tx);
1563		subscriptions.add_filter(sub_id, filter_id, filter, vec![]);
1564		assert!(matches!(
1565			rx.try_recv(),
1566			Ok(MultiFilterSubscriptionEvent::ReplayDone { filter_id: done_filter })
1567				if done_filter == filter_id
1568		));
1569
1570		for statement in statements.iter().take(SUBSCRIPTION_BUFFER_SIZE) {
1571			subscriptions.notify_matching_filters(0, statement);
1572		}
1573		assert_eq!(rx.len(), SUBSCRIPTION_BUFFER_SIZE);
1574
1575		subscriptions.notify_matching_filters(0, &statements[SUBSCRIPTION_BUFFER_SIZE]);
1576		assert_eq!(rx.len(), SUBSCRIPTION_BUFFER_SIZE + STOP_RESERVE_CHANNEL_SLOTS);
1577
1578		for _ in 0..SUBSCRIPTION_BUFFER_SIZE {
1579			assert!(matches!(rx.try_recv(), Ok(MultiFilterSubscriptionEvent::NewStatement(_))));
1580		}
1581		assert!(matches!(rx.try_recv(), Ok(MultiFilterSubscriptionEvent::Stop)));
1582		assert!(rx.is_closed());
1583	}
1584
1585	#[test]
1586	fn multi_filter_closed_channel_is_reported_as_closed_before_buffer_limit() {
1587		let mut state = MultiFilterSubscriptionState::new();
1588		let (tx, rx) = async_channel::bounded::<MultiFilterSubscriptionEvent>(
1589			SUBSCRIPTION_BUFFER_SIZE + STOP_RESERVE_CHANNEL_SLOTS,
1590		);
1591		for seed in 0..SUBSCRIPTION_BUFFER_SIZE {
1592			tx.try_send(MultiFilterSubscriptionEvent::NewStatement(live_event_for(
1593				&signed_statement(seed as u8),
1594				vec![FilterId::new(1)],
1595			)))
1596			.expect("channel capacity exceeds subscription buffer size; qed");
1597		}
1598		drop(rx);
1599
1600		assert!(matches!(
1601			SubscriptionsInfo::send_ready_event(
1602				&mut state,
1603				&tx,
1604				MultiFilterSubscriptionEvent::NewStatement(live_event_for(
1605					&signed_statement(42),
1606					vec![FilterId::new(1)],
1607				)),
1608			),
1609			ReadyEventDelivery::Closed
1610		));
1611		assert!(matches!(
1612			SubscriptionsInfo::send_ready_event(
1613				&mut state,
1614				&tx,
1615				MultiFilterSubscriptionEvent::Stop,
1616			),
1617			ReadyEventDelivery::Closed
1618		));
1619		assert!(!state.stopped);
1620	}
1621
1622	#[test]
1623	fn filter_topics_maps_each_variant() {
1624		let t1 = Topic::from([1u8; 32]);
1625		let t2 = Topic::from([2u8; 32]);
1626		assert!(SubscriptionTopics::filter_topics(&OptimizedTopicFilter::Any).is_empty());
1627		assert_eq!(
1628			SubscriptionTopics::filter_topics(&OptimizedTopicFilter::MatchAll(
1629				[t1, t2].into_iter().collect()
1630			))
1631			.into_iter()
1632			.collect::<HashSet<_>>(),
1633			HashSet::from([t1, t2])
1634		);
1635		assert_eq!(
1636			SubscriptionTopics::filter_topics(&OptimizedTopicFilter::MatchAny(
1637				[t1].into_iter().collect()
1638			)),
1639			vec![t1]
1640		);
1641	}
1642
1643	#[test]
1644	fn handle_tracks_live_subscription_topics() {
1645		let handle = SubscriptionsHandle::new(Box::new(sp_core::testing::TaskExecutor::new()), 1);
1646		let t1 = Topic::from([1u8; 32]);
1647		let t2 = Topic::from([2u8; 32]);
1648
1649		let (_tx1, stream1) =
1650			handle.subscribe(OptimizedTopicFilter::MatchAny([t1, t2].into_iter().collect()), 0);
1651		assert_eq!(handle.subscription_topics(), HashSet::from([t1, t2]));
1652
1653		// A second subscription on t1 keeps it after the first drops.
1654		let (_tx2, stream2) =
1655			handle.subscribe(OptimizedTopicFilter::MatchAny([t1].into_iter().collect()), 0);
1656		drop(stream1);
1657		assert_eq!(handle.subscription_topics(), HashSet::from([t1]));
1658
1659		// An `Any` subscription contributes no topics.
1660		let (_tx3, stream3) = handle.subscribe(OptimizedTopicFilter::Any, 0);
1661		assert_eq!(handle.subscription_topics(), HashSet::from([t1]));
1662
1663		drop(stream2);
1664		drop(stream3);
1665		assert!(handle.subscription_topics().is_empty());
1666	}
1667
1668	#[test]
1669	fn test_subscribe_unsubscribe() {
1670		let mut subscriptions = SubscriptionsInfo::new();
1671
1672		let (tx1, _rx1) = async_channel::bounded::<StatementEvent>(10);
1673		let topic1 = Topic::from([8u8; 32]);
1674		let topic2 = Topic::from([9u8; 32]);
1675		let sub_info1 = fixed_subscription(
1676			1,
1677			OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
1678		);
1679		subscriptions.subscribe(sub_info1.clone(), tx1);
1680		assert!(subscriptions.subscriptions_match_all_by_topic.contains_key(&topic1));
1681		assert!(subscriptions.subscriptions_match_all_by_topic.contains_key(&topic2));
1682		assert!(subscriptions.by_sub_id.contains_key(&sub_info1.seq_id));
1683		assert!(!subscriptions
1684			.subscriptions_any
1685			.contains_key(&(sub_info1.seq_id, sub_info1.filter_key)));
1686
1687		subscriptions.unsubscribe(sub_info1.seq_id);
1688		assert!(!subscriptions.subscriptions_match_all_by_topic.contains_key(&topic1));
1689		assert!(!subscriptions.subscriptions_match_all_by_topic.contains_key(&topic2));
1690	}
1691
1692	#[test]
1693	fn test_subscribe_any() {
1694		let mut subscriptions = SubscriptionsInfo::new();
1695		let (tx1, _rx1) = async_channel::bounded::<StatementEvent>(10);
1696		let sub_info1 = fixed_subscription(1, OptimizedTopicFilter::Any);
1697		subscriptions.subscribe(sub_info1.clone(), tx1);
1698		assert!(subscriptions
1699			.subscriptions_any
1700			.contains_key(&(sub_info1.seq_id, sub_info1.filter_key)));
1701		assert!(subscriptions.by_sub_id.contains_key(&sub_info1.seq_id));
1702		subscriptions.unsubscribe(sub_info1.seq_id);
1703		assert!(!subscriptions
1704			.subscriptions_any
1705			.contains_key(&(sub_info1.seq_id, sub_info1.filter_key)));
1706	}
1707
1708	#[test]
1709	fn test_subscribe_match_any() {
1710		let mut subscriptions = SubscriptionsInfo::new();
1711
1712		let (tx1, _rx1) = async_channel::bounded::<StatementEvent>(10);
1713		let topic1 = Topic::from([8u8; 32]);
1714		let topic2 = Topic::from([9u8; 32]);
1715		let sub_info1 = fixed_subscription(
1716			1,
1717			OptimizedTopicFilter::MatchAny(vec![topic1, topic2].into_iter().collect()),
1718		);
1719		subscriptions.subscribe(sub_info1.clone(), tx1);
1720		assert!(subscriptions.subscriptions_match_any_by_topic.contains_key(&topic1));
1721		assert!(subscriptions.subscriptions_match_any_by_topic.contains_key(&topic2));
1722		assert!(subscriptions.by_sub_id.contains_key(&sub_info1.seq_id));
1723		assert!(!subscriptions
1724			.subscriptions_any
1725			.contains_key(&(sub_info1.seq_id, sub_info1.filter_key)));
1726
1727		subscriptions.unsubscribe(sub_info1.seq_id);
1728		assert!(!subscriptions.subscriptions_match_all_by_topic.contains_key(&topic1));
1729		assert!(!subscriptions.subscriptions_match_all_by_topic.contains_key(&topic2));
1730	}
1731
1732	#[test]
1733	fn test_notify_matching_filters_any() {
1734		let mut subscriptions = SubscriptionsInfo::new();
1735
1736		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
1737		let sub_info1 = fixed_subscription(1, OptimizedTopicFilter::Any);
1738		subscriptions.subscribe(sub_info1.clone(), tx1);
1739
1740		let statement = signed_statement(1);
1741		subscriptions.notify_matching_filters(0, &statement);
1742
1743		let received = unwrap_statement(rx1.try_recv().expect("Should receive statement"));
1744		let decoded_statement: Statement =
1745			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
1746		assert_eq!(decoded_statement, statement);
1747	}
1748
1749	#[test]
1750	fn test_notify_matching_filters_match_all() {
1751		let mut subscriptions = SubscriptionsInfo::new();
1752
1753		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
1754		let topic1 = Topic::from([8u8; 32]);
1755		let topic2 = Topic::from([9u8; 32]);
1756		let sub_info1 = fixed_subscription(
1757			1,
1758			OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
1759		);
1760		subscriptions.subscribe(sub_info1.clone(), tx1);
1761
1762		let mut statement = signed_statement(1);
1763		statement.set_topic(0, topic2);
1764		subscriptions.notify_matching_filters(0, &statement);
1765
1766		// Should not receive yet, only one topic matched.
1767		assert!(rx1.try_recv().is_err());
1768
1769		statement.set_topic(1, topic1);
1770		subscriptions.notify_matching_filters(1, &statement);
1771
1772		let received = unwrap_statement(rx1.try_recv().expect("Should receive statement"));
1773		let decoded_statement: Statement =
1774			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
1775		assert_eq!(decoded_statement, statement);
1776	}
1777
1778	#[test]
1779	fn test_notify_matching_filters_match_any() {
1780		let mut subscriptions = SubscriptionsInfo::new();
1781		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
1782		let (tx2, rx2) = async_channel::bounded::<StatementEvent>(10);
1783
1784		let topic1 = Topic::from([8u8; 32]);
1785		let topic2 = Topic::from([9u8; 32]);
1786		let sub_info1 = fixed_subscription(
1787			1,
1788			OptimizedTopicFilter::MatchAny(vec![topic1, topic2].into_iter().collect()),
1789		);
1790
1791		let sub_info2 = fixed_subscription(
1792			2,
1793			OptimizedTopicFilter::MatchAny(vec![topic2].into_iter().collect()),
1794		);
1795
1796		subscriptions.subscribe(sub_info1.clone(), tx1);
1797		subscriptions.subscribe(sub_info2.clone(), tx2);
1798
1799		let mut statement = signed_statement(1);
1800		statement.set_topic(0, topic1);
1801		statement.set_topic(1, topic2);
1802		subscriptions.notify_matching_filters(0, &statement);
1803
1804		let received = unwrap_statement(rx1.try_recv().expect("Should receive statement"));
1805		let decoded_statement: Statement =
1806			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
1807		assert_eq!(decoded_statement, statement);
1808
1809		let received = unwrap_statement(rx2.try_recv().expect("Should receive statement"));
1810		let decoded_statement: Statement =
1811			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
1812		assert_eq!(decoded_statement, statement);
1813	}
1814
1815	#[tokio::test]
1816	async fn test_subscription_handle_with_different_workers_number() {
1817		for num_workers in 1..5 {
1818			let subscriptions_handle = SubscriptionsHandle::new(
1819				Box::new(sp_core::testing::TaskExecutor::new()),
1820				num_workers,
1821			);
1822
1823			let topic1 = Topic::from([8u8; 32]);
1824			let topic2 = Topic::from([9u8; 32]);
1825
1826			let streams = (0..5)
1827				.into_iter()
1828				.map(|_| {
1829					subscriptions_handle.subscribe(
1830						OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
1831						0,
1832					)
1833				})
1834				.collect::<Vec<_>>();
1835
1836			let mut statement = signed_statement(1);
1837			statement.set_topic(0, topic2);
1838			subscriptions_handle.notify(0, statement.clone());
1839
1840			statement.set_topic(1, topic1);
1841			subscriptions_handle.notify(1, statement.clone());
1842
1843			for (_tx, mut stream) in streams {
1844				let received =
1845					unwrap_statement(stream.next().await.expect("Should receive statement"));
1846				let decoded_statement: Statement =
1847					Statement::decode(&mut &received.0[..]).expect("Should decode statement");
1848				assert_eq!(decoded_statement, statement);
1849			}
1850		}
1851	}
1852
1853	#[tokio::test]
1854	async fn test_handle_unsubscribe() {
1855		let subscriptions_handle =
1856			SubscriptionsHandle::new(Box::new(sp_core::testing::TaskExecutor::new()), 2);
1857
1858		let topic1 = Topic::from([8u8; 32]);
1859		let topic2 = Topic::from([9u8; 32]);
1860
1861		let (tx, mut stream) = subscriptions_handle.subscribe(
1862			OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
1863			0,
1864		);
1865
1866		let mut statement = signed_statement(1);
1867		statement.set_topic(0, topic1);
1868		statement.set_topic(1, topic2);
1869
1870		// Send a statement and verify it's received.
1871		subscriptions_handle.notify(0, statement.clone());
1872
1873		let received = unwrap_statement(stream.next().await.expect("Should receive statement"));
1874		let decoded_statement: Statement =
1875			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
1876		assert_eq!(decoded_statement, statement);
1877
1878		// Drop the stream to trigger unsubscribe.
1879		drop(stream);
1880
1881		// Give some time for the unsubscribe message to be processed.
1882		tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
1883
1884		// Send another statement after unsubscribe.
1885		let mut statement2 = signed_statement(2);
1886		statement2.set_topic(0, topic1);
1887		statement2.set_topic(1, topic2);
1888		subscriptions_handle.notify(1, statement2.clone());
1889
1890		// The tx channel should be closed/disconnected since the subscription was removed.
1891		// Give some time for the notification to potentially arrive (it shouldn't).
1892		tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
1893
1894		// The sender should fail to send since the subscription is gone.
1895		// We verify by checking that the tx channel is disconnected.
1896		assert!(tx.is_closed(), "Sender should be closed after unsubscribe");
1897	}
1898
1899	#[test]
1900	fn test_unsubscribe_nonexistent() {
1901		let mut subscriptions = SubscriptionsInfo::new();
1902		// Unsubscribing a non-existent subscription should not panic.
1903		subscriptions.unsubscribe(SeqID::from(999));
1904		// Verify internal state is still valid.
1905		assert!(subscriptions.by_sub_id.is_empty());
1906		assert!(subscriptions.subscriptions_any.is_empty());
1907		assert!(subscriptions.subscriptions_match_all_by_topic.is_empty());
1908		assert!(subscriptions.subscriptions_match_any_by_topic.is_empty());
1909	}
1910
1911	#[test]
1912	fn test_multiple_subscriptions_same_topic() {
1913		let mut subscriptions = SubscriptionsInfo::new();
1914
1915		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
1916		let (tx2, rx2) = async_channel::bounded::<StatementEvent>(10);
1917		let topic1 = Topic::from([8u8; 32]);
1918		let topic2 = Topic::from([9u8; 32]);
1919
1920		let sub_info1 = fixed_subscription(
1921			1,
1922			OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
1923		);
1924		let sub_info2 = fixed_subscription(
1925			2,
1926			OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
1927		);
1928
1929		subscriptions.subscribe(sub_info1.clone(), tx1);
1930		subscriptions.subscribe(sub_info2.clone(), tx2);
1931
1932		// Both subscriptions should be registered under each topic.
1933		assert_eq!(
1934			subscriptions
1935				.subscriptions_match_all_by_topic
1936				.get(&topic1)
1937				.unwrap()
1938				.iter()
1939				.map(|s| s.len())
1940				.sum::<usize>(),
1941			2
1942		);
1943		assert_eq!(
1944			subscriptions
1945				.subscriptions_match_all_by_topic
1946				.get(&topic2)
1947				.unwrap()
1948				.iter()
1949				.map(|s| s.len())
1950				.sum::<usize>(),
1951			2
1952		);
1953
1954		// Send a matching statement.
1955		let mut statement = signed_statement(1);
1956		statement.set_topic(0, topic1);
1957		statement.set_topic(1, topic2);
1958		subscriptions.notify_matching_filters(0, &statement);
1959
1960		// Both should receive.
1961		assert!(rx1.try_recv().is_ok());
1962		assert!(rx2.try_recv().is_ok());
1963
1964		// Unsubscribe one.
1965		subscriptions.unsubscribe(sub_info1.seq_id);
1966
1967		// Only one subscription should remain.
1968		assert_eq!(
1969			subscriptions
1970				.subscriptions_match_all_by_topic
1971				.get(&topic1)
1972				.unwrap()
1973				.iter()
1974				.map(|s| s.len())
1975				.sum::<usize>(),
1976			1
1977		);
1978		assert_eq!(
1979			subscriptions
1980				.subscriptions_match_all_by_topic
1981				.get(&topic2)
1982				.unwrap()
1983				.iter()
1984				.map(|s| s.len())
1985				.sum::<usize>(),
1986			1
1987		);
1988		assert!(!subscriptions.by_sub_id.contains_key(&sub_info1.seq_id));
1989		assert!(subscriptions.by_sub_id.contains_key(&sub_info2.seq_id));
1990
1991		// Send another statement.
1992		subscriptions.notify_matching_filters(1, &statement);
1993
1994		// Only sub2 should receive.
1995		assert!(rx2.try_recv().is_ok());
1996		assert!(rx1.try_recv().is_err());
1997	}
1998
1999	#[test]
2000	fn test_subscriber_auto_unsubscribe_on_channel_full() {
2001		let mut subscriptions = SubscriptionsInfo::new();
2002
2003		// Create a channel with capacity 1.
2004		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(1);
2005		let topic1 = Topic::from([8u8; 32]);
2006
2007		let sub_info1 = fixed_subscription(
2008			1,
2009			OptimizedTopicFilter::MatchAny(vec![topic1].into_iter().collect()),
2010		);
2011		subscriptions.subscribe(sub_info1.clone(), tx1);
2012
2013		let mut statement = signed_statement(1);
2014		statement.set_topic(0, topic1);
2015
2016		// First notification should succeed.
2017		subscriptions.notify_matching_filters(0, &statement);
2018		assert!(rx1.try_recv().is_ok());
2019
2020		// Fill the channel.
2021		subscriptions.notify_matching_filters(1, &statement);
2022		// Channel is now full.
2023
2024		// Next notification should trigger auto-unsubscribe.
2025		subscriptions.notify_matching_filters(2, &statement);
2026
2027		// Subscription should be removed.
2028		assert!(!subscriptions.by_sub_id.contains_key(&sub_info1.seq_id));
2029		assert!(!subscriptions.subscriptions_match_any_by_topic.contains_key(&topic1));
2030	}
2031
2032	#[test]
2033	fn test_match_any_receives_once_per_statement() {
2034		let mut subscriptions = SubscriptionsInfo::new();
2035
2036		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
2037		let topic1 = Topic::from([8u8; 32]);
2038		let topic2 = Topic::from([9u8; 32]);
2039
2040		// Subscribe to MatchAny with both topics.
2041		let sub_info1 = fixed_subscription(
2042			1,
2043			OptimizedTopicFilter::MatchAny(vec![topic1, topic2].into_iter().collect()),
2044		);
2045		subscriptions.subscribe(sub_info1.clone(), tx1);
2046
2047		// Create a statement that matches BOTH topics.
2048		let mut statement = signed_statement(1);
2049		statement.set_topic(0, topic1);
2050		statement.set_topic(1, topic2);
2051
2052		subscriptions.notify_matching_filters(0, &statement);
2053
2054		// Should receive exactly once, not twice.
2055		let received = unwrap_statement(rx1.try_recv().expect("Should receive statement"));
2056		let decoded_statement: Statement =
2057			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
2058		assert_eq!(decoded_statement, statement);
2059
2060		// No more messages.
2061		assert!(rx1.try_recv().is_err());
2062	}
2063
2064	#[test]
2065	fn test_match_all_receives_once_per_statement() {
2066		// A `MatchAll` subscriber must receive each matching statement exactly once, even when it
2067		// is registered under several of the statement's topics and the matcher therefore
2068		// encounters it across multiple topic combinations.
2069		let mut subscriptions = SubscriptionsInfo::new();
2070
2071		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
2072		let (tx2, _rx2) = async_channel::bounded::<StatementEvent>(10);
2073		let (tx3, _rx3) = async_channel::bounded::<StatementEvent>(10);
2074
2075		let topic1 = Topic::from([1u8; 32]);
2076		let topic2 = Topic::from([2u8; 32]);
2077		let topic3 = Topic::from([3u8; 32]);
2078		let topic4 = Topic::from([4u8; 32]);
2079
2080		// The subscription under test: MatchAll on topic1 AND topic2 (stored under both topics).
2081		let sub_info1 = fixed_subscription(
2082			1,
2083			OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
2084		);
2085		subscriptions.subscribe(sub_info1, tx1);
2086
2087		// Extra MatchAll subscriptions on topic3 so the matcher encounters sub_info1 across
2088		// several topic combinations of the statement below. They do not match the statement
2089		// themselves (topic4 is absent).
2090		let sub_info2 = fixed_subscription(
2091			2,
2092			OptimizedTopicFilter::MatchAll(vec![topic3, topic4].into_iter().collect()),
2093		);
2094		let sub_info3 = fixed_subscription(
2095			3,
2096			OptimizedTopicFilter::MatchAll(vec![topic3, topic4].into_iter().collect()),
2097		);
2098		subscriptions.subscribe(sub_info2, tx2);
2099		subscriptions.subscribe(sub_info3, tx3);
2100
2101		// Statement carrying topic1, topic2 and topic3.
2102		let mut statement = signed_statement(1);
2103		statement.set_topic(0, topic1);
2104		statement.set_topic(1, topic2);
2105		statement.set_topic(2, topic3);
2106
2107		subscriptions.notify_matching_filters(0, &statement);
2108
2109		// sub_info1 must receive the statement exactly once.
2110		let received = unwrap_statement(rx1.try_recv().expect("Should receive statement"));
2111		let decoded_statement: Statement =
2112			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
2113		assert_eq!(decoded_statement, statement);
2114
2115		assert!(
2116			rx1.try_recv().is_err(),
2117			"MatchAll subscriber must receive each statement only once"
2118		);
2119	}
2120
2121	#[test]
2122	fn test_match_all_with_single_topic_matches_statement_with_two_topics() {
2123		let mut subscriptions = SubscriptionsInfo::new();
2124
2125		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
2126		let topic1 = Topic::from([8u8; 32]);
2127		let topic2 = Topic::from([9u8; 32]);
2128
2129		// Subscribe with MatchAll on only topic1.
2130		let sub_info1 = fixed_subscription(
2131			1,
2132			OptimizedTopicFilter::MatchAll(vec![topic1].into_iter().collect()),
2133		);
2134		subscriptions.subscribe(sub_info1.clone(), tx1);
2135
2136		// Create a statement that has BOTH topic1 and topic2.
2137		let mut statement = signed_statement(1);
2138		statement.set_topic(0, topic1);
2139		statement.set_topic(1, topic2);
2140
2141		subscriptions.notify_matching_filters(0, &statement);
2142
2143		// Should receive because the statement contains topic1 (which is the only required topic).
2144		let received = unwrap_statement(rx1.try_recv().expect("Should receive statement"));
2145		let decoded_statement: Statement =
2146			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
2147		assert_eq!(decoded_statement, statement);
2148
2149		// No more messages.
2150		assert!(rx1.try_recv().is_err());
2151	}
2152
2153	#[test]
2154	fn test_match_all_no_matching_topics() {
2155		let mut subscriptions = SubscriptionsInfo::new();
2156
2157		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
2158		let topic1 = Topic::from([8u8; 32]);
2159		let topic2 = Topic::from([9u8; 32]);
2160		let topic3 = Topic::from([10u8; 32]);
2161
2162		let sub_info1 = fixed_subscription(
2163			1,
2164			OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
2165		);
2166		subscriptions.subscribe(sub_info1.clone(), tx1);
2167
2168		// Statement with completely different topics.
2169		let mut statement = signed_statement(1);
2170		statement.set_topic(0, topic3);
2171
2172		subscriptions.notify_matching_filters(0, &statement);
2173
2174		// Should not receive anything.
2175		assert!(rx1.try_recv().is_err());
2176	}
2177
2178	#[test]
2179	fn test_match_all_with_unsubscribed_topic_first_in_statement() {
2180		// This test guards against returning early when one statement topic has no subscriptions.
2181		// The matcher must still check later topic combinations that can match.
2182		let mut subscriptions = SubscriptionsInfo::new();
2183
2184		let (tx1, rx1) = async_channel::bounded::<StatementEvent>(10);
2185		// topic1 will have NO subscriptions
2186		let topic1 = Topic::from([1u8; 32]);
2187		// topic2 WILL have a subscription
2188		let topic2 = Topic::from([2u8; 32]);
2189
2190		// Subscribe only to topic2 with MatchAll filter.
2191		let sub_info1 = fixed_subscription(
2192			1,
2193			OptimizedTopicFilter::MatchAll(vec![topic2].into_iter().collect()),
2194		);
2195		subscriptions.subscribe(sub_info1, tx1);
2196
2197		// Create a statement with BOTH topics. topic1 comes first (lower bytes).
2198		// When iterating combinations(1), [topic1] is checked before [topic2].
2199		// Since topic1 has no subscriptions, the buggy `return` exits early,
2200		// preventing the [topic2] combination from being checked.
2201		let mut statement = signed_statement(1);
2202		statement.set_topic(0, topic1);
2203		statement.set_topic(1, topic2);
2204
2205		subscriptions.notify_matching_filters(0, &statement);
2206
2207		// The receive succeeds only if the matcher checks the [topic2] combination.
2208		let received = unwrap_statement(
2209			rx1.try_recv()
2210				.expect("Should receive statement from a later matching topic combination"),
2211		);
2212		let decoded_statement: Statement =
2213			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
2214		assert_eq!(decoded_statement, statement);
2215	}
2216
2217	#[tokio::test]
2218	async fn test_handle_with_match_any_filter() {
2219		let subscriptions_handle =
2220			SubscriptionsHandle::new(Box::new(sp_core::testing::TaskExecutor::new()), 2);
2221
2222		let topic1 = Topic::from([8u8; 32]);
2223		let topic2 = Topic::from([9u8; 32]);
2224
2225		let (_tx, mut stream) = subscriptions_handle.subscribe(
2226			OptimizedTopicFilter::MatchAny(vec![topic1, topic2].into_iter().collect()),
2227			0,
2228		);
2229
2230		// Statement matching only topic1.
2231		let mut statement1 = signed_statement(1);
2232		statement1.set_topic(0, topic1);
2233		subscriptions_handle.notify(0, statement1.clone());
2234
2235		let received = unwrap_statement(stream.next().await.expect("Should receive statement"));
2236		let decoded_statement: Statement =
2237			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
2238		assert_eq!(decoded_statement, statement1);
2239
2240		// Statement matching only topic2.
2241		let mut statement2 = signed_statement(2);
2242		statement2.set_topic(0, topic2);
2243		subscriptions_handle.notify(1, statement2.clone());
2244
2245		let received = unwrap_statement(stream.next().await.expect("Should receive statement"));
2246		let decoded_statement: Statement =
2247			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
2248		assert_eq!(decoded_statement, statement2);
2249	}
2250
2251	#[tokio::test]
2252	async fn test_handle_with_any_filter() {
2253		let subscriptions_handle =
2254			SubscriptionsHandle::new(Box::new(sp_core::testing::TaskExecutor::new()), 2);
2255
2256		let (_tx, mut stream) = subscriptions_handle.subscribe(OptimizedTopicFilter::Any, 0);
2257
2258		// Send statements with various topics.
2259		let statement1 = signed_statement(1);
2260		subscriptions_handle.notify(0, statement1.clone());
2261
2262		let received = unwrap_statement(stream.next().await.expect("Should receive statement"));
2263		let decoded_statement: Statement =
2264			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
2265		assert_eq!(decoded_statement, statement1);
2266
2267		let mut statement2 = signed_statement(2);
2268		statement2.set_topic(0, Topic::from([99u8; 32]));
2269		subscriptions_handle.notify(1, statement2.clone());
2270
2271		let received = unwrap_statement(stream.next().await.expect("Should receive statement"));
2272		let decoded_statement: Statement =
2273			Statement::decode(&mut &received.0[..]).expect("Should decode statement");
2274		assert_eq!(decoded_statement, statement2);
2275	}
2276
2277	#[tokio::test]
2278	async fn test_handle_multiple_subscribers_different_filters() {
2279		let subscriptions_handle =
2280			SubscriptionsHandle::new(Box::new(sp_core::testing::TaskExecutor::new()), 2);
2281
2282		let topic1 = Topic::from([8u8; 32]);
2283		let topic2 = Topic::from([9u8; 32]);
2284
2285		// Subscriber 1: MatchAll on topic1 and topic2.
2286		let (_tx1, mut stream1) = subscriptions_handle.subscribe(
2287			OptimizedTopicFilter::MatchAll(vec![topic1, topic2].into_iter().collect()),
2288			0,
2289		);
2290
2291		// Subscriber 2: MatchAny on topic1.
2292		let (_tx2, mut stream2) = subscriptions_handle
2293			.subscribe(OptimizedTopicFilter::MatchAny(vec![topic1].into_iter().collect()), 0);
2294
2295		// Subscriber 3: Any.
2296		let (_tx3, mut stream3) = subscriptions_handle.subscribe(OptimizedTopicFilter::Any, 0);
2297
2298		// Statement matching only topic1.
2299		let mut statement1 = signed_statement(1);
2300		statement1.set_topic(0, topic1);
2301		subscriptions_handle.notify(0, statement1.clone());
2302
2303		// stream1 should NOT receive (needs both topics).
2304		// stream2 should receive (MatchAny topic1).
2305		// stream3 should receive (Any).
2306
2307		let received2 = unwrap_statement(stream2.next().await.expect("stream2 should receive"));
2308		let decoded2: Statement = Statement::decode(&mut &received2.0[..]).unwrap();
2309		assert_eq!(decoded2, statement1);
2310
2311		let received3 = unwrap_statement(stream3.next().await.expect("stream3 should receive"));
2312		let decoded3: Statement = Statement::decode(&mut &received3.0[..]).unwrap();
2313		assert_eq!(decoded3, statement1);
2314
2315		// Statement matching both topics.
2316		let mut statement2 = signed_statement(2);
2317		statement2.set_topic(0, topic1);
2318		statement2.set_topic(1, topic2);
2319		subscriptions_handle.notify(1, statement2.clone());
2320
2321		// All should receive.
2322		let received1 = unwrap_statement(stream1.next().await.expect("stream1 should receive"));
2323		let decoded1: Statement = Statement::decode(&mut &received1.0[..]).unwrap();
2324		assert_eq!(decoded1, statement2);
2325
2326		let received2 = unwrap_statement(stream2.next().await.expect("stream2 should receive"));
2327		let decoded2: Statement = Statement::decode(&mut &received2.0[..]).unwrap();
2328		assert_eq!(decoded2, statement2);
2329
2330		let received3 = unwrap_statement(stream3.next().await.expect("stream3 should receive"));
2331		let decoded3: Statement = Statement::decode(&mut &received3.0[..]).unwrap();
2332		assert_eq!(decoded3, statement2);
2333	}
2334}