Skip to main content

happenstance_sync_testkit/
write_group_suite.rs

1//! The write-group family (#420): a store reads its log back in the writes
2//! that made it (SY-39).
3//!
4//! Mounted with [`write_group_store_conformance!`](crate::write_group_store_conformance)
5//! on the same [`IngestFixture`](crate::IngestFixture) the ingest family takes,
6//! whose store must also implement
7//! [`WriteGroupStore`](happenstance_sync::WriteGroupStore). No new fixture
8//! trait and no bound added to `IngestFixture::Store`, so an adapter that has
9//! not implemented the port yet still mounts the ingest family unchanged.
10
11/// The write-group rules. See the [crate documentation](crate) for what each
12/// covers.
13///
14/// Each rule is an async function taking `impl AsyncFn() -> F`, how to make a
15/// fixture, and returning `Result<RuleOutcome, Violation>`, as the ingest
16/// family's do.
17///
18/// # What no rule here does
19///
20/// **Assert a local position it did not read back.** Every `first` compared
21/// is the position the store assigned to the group's first event, read through
22/// [`EventStore::read`](happenstance_core::EventStore::read). The literal
23/// positions below are **origin** positions: facts a peer supplies.
24///
25/// **Decode a payload** (SY-35). Groups are told apart by their opaque bytes.
26pub mod write_group_rules {
27    use alloc::format;
28    use alloc::string::String;
29    use alloc::vec::Vec;
30    use core::num::NonZeroUsize;
31
32    use happenstance_core::{
33        AppendCondition, Event, EventId, EventStore, EventType, Query, QueryItem, ReadOptions,
34        RecordedAt, SequencePosition, StoreId, collect,
35    };
36    use happenstance_sync::{
37        GroupPage, IngestGroup, IngestStore, ReplicatedEvent, Waiting, WriteGroup, WriteGroupStore,
38    };
39    use happenstance_testkit::RuleOutcome;
40
41    use crate::IngestFixture;
42    use crate::violation::{Violation, ensure};
43
44    /// Every rule's clause.
45    const CLAUSE: &str = "SY-39";
46
47    /// A page large enough for every arrangement here: 64 events.
48    const WHOLE_LOG: NonZeroUsize = NonZeroUsize::MIN.saturating_add(63);
49
50    /// The most pages the chaining rule reads before it decides the store will
51    /// never reach the end (H-13).
52    const MAX_PAGES: usize = 64;
53
54    const APPENDED: EventType = EventType::from_static("GroupAppended");
55    const SHIPPED: EventType = EventType::from_static("GroupShipped");
56    const REVERSED: EventType = EventType::from_static("GroupReversed");
57
58    /// The origin of every foreign group here.
59    const ORIGIN: StoreId = StoreId::from_bytes([0x79; 16]);
60
61    /// SY-39: one `append` reads back as one write group, named by the position
62    /// the store gave its first event, carrying no guard.
63    ///
64    /// Two appends, of three events and of one, then one page of the whole log:
65    /// two groups, `[3, 1]`, in order, each `first` equal to the position the
66    /// store assigned that append's first event.
67    ///
68    /// # Rejects
69    ///
70    /// A store that records no groups, so every row reads as its own, and one
71    /// that merges adjacent appends into one group. Both are in
72    /// `tests/wrong_write_group_stores.rs`.
73    ///
74    /// # Errors
75    ///
76    /// A [`Violation`] of SY-39 if the store refuses a write or a read, or
77    /// reads back other groups.
78    pub async fn an_append_reads_back_as_one_group<F>(
79        open: impl AsyncFn() -> F,
80    ) -> Result<RuleOutcome, Violation>
81    where
82        F: IngestFixture,
83        F::Store: WriteGroupStore,
84    {
85        let fixture = open().await;
86        let store = fixture.connect().await;
87        append(&store, &["append-a1", "append-a2", "append-a3"]).await?;
88        append(&store, &["append-b1"]).await?;
89
90        let page = read(&store, None, WHOLE_LOG).await?;
91
92        expect_shape(
93            &page,
94            &[&["append-a1", "append-a2", "append-a3"], &["append-b1"]],
95        )?;
96        let expected = [
97            position_of(&store, "append-a1").await?,
98            position_of(&store, "append-b1").await?,
99        ];
100        let firsts: Vec<SequencePosition> = page.groups.iter().map(WriteGroup::first).collect();
101        ensure(firsts == expected, CLAUSE, || {
102            format!(
103                "the store named its two appends {firsts:?}; the positions it gave their first \
104                 events are {expected:?}"
105            )
106        })?;
107        ensure(
108            page.groups.iter().all(|g| g.guard().is_none()),
109            CLAUSE,
110            || String::from("a local append read back with a guard; a local append records none"),
111        )?;
112        Ok(RuleOutcome::Ran)
113    }
114
115    /// SY-39: an ingested group keeps its boundary, the origin's identities,
116    /// and the guard it arrived with.
117    ///
118    /// One `ingest` of two groups, `[x1, x2]` under a position-free guard and
119    /// `[y1]` under none, read back as two groups, with the origin's
120    /// identities and the guards `[Some(guard), None]`.
121    ///
122    /// # Rejects
123    ///
124    /// A store that drops the guard, and one that merges what one call
125    /// ingested into one group.
126    ///
127    /// # Errors
128    ///
129    /// A [`Violation`] of SY-39 if the store refuses the ingest or a read, or
130    /// reads back other groups, identities or guards.
131    pub async fn an_ingested_group_keeps_its_boundary_and_guard<F>(
132        open: impl AsyncFn() -> F,
133    ) -> Result<RuleOutcome, Violation>
134    where
135        F: IngestFixture,
136        F::Store: WriteGroupStore,
137    {
138        let fixture = open().await;
139        let store = fixture.connect().await;
140        ensure_foreign(&store).await?;
141        let guard = guard()?;
142        let x = [shipped(4, "ingest-x1")?, shipped(5, "ingest-x2")?];
143        let y = [shipped(6, "ingest-y1")?];
144
145        ingest(
146            &store,
147            &[
148                IngestGroup::new(&x, &[]).with_guard(Some(&guard)),
149                IngestGroup::new(&y, &[]),
150            ],
151        )
152        .await?;
153        let page = read(&store, None, WHOLE_LOG).await?;
154
155        expect_shape(&page, &[&["ingest-x1", "ingest-x2"], &["ingest-y1"]])?;
156        let ids: Vec<EventId> = events(&page).map(|event| event.id).collect();
157        let sent: Vec<EventId> = x.iter().chain(&y).map(|event| event.id).collect();
158        ensure(ids == sent, CLAUSE, || {
159            format!("the store read back identities {ids:?} for the origin's {sent:?}")
160        })?;
161        let guards: Vec<Option<&AppendCondition>> =
162            page.groups.iter().map(WriteGroup::guard).collect();
163        ensure(guards == [Some(&guard), None], CLAUSE, || {
164            format!(
165                "the store read back guards {guards:?}; the first group arrived under \
166                 {guard:?} and the second under none"
167            )
168        })?;
169        Ok(RuleOutcome::Ran)
170    }
171
172    /// SY-39, with SY-2: a compensation is one write group with the ingested
173    /// group it answers, after it.
174    ///
175    /// One `ingest` of `[losing]` answered by `[reversal]`: one group holding
176    /// both, the losing event first.
177    ///
178    /// # Rejects
179    ///
180    /// A store that records the compensation as a group of its own, which a
181    /// relay would forward in a separate atomic unit (SY-2).
182    ///
183    /// # Errors
184    ///
185    /// A [`Violation`] of SY-39 if the store refuses the ingest or a read, or
186    /// reads back other groups.
187    pub async fn compensation_joins_its_group<F>(
188        open: impl AsyncFn() -> F,
189    ) -> Result<RuleOutcome, Violation>
190    where
191        F: IngestFixture,
192        F::Store: WriteGroupStore,
193    {
194        let fixture = open().await;
195        let store = fixture.connect().await;
196        ensure_foreign(&store).await?;
197        let losing = [shipped(9, "compensated-losing")?];
198        let reversal = [opaque(REVERSED, "compensated-reversal")?];
199
200        ingest(&store, &[IngestGroup::new(&losing, &reversal)]).await?;
201        let page = read(&store, None, WHOLE_LOG).await?;
202
203        expect_shape(&page, &[&["compensated-losing", "compensated-reversal"]])?;
204        Ok(RuleOutcome::Ran)
205    }
206
207    /// SY-39, with SY-11: a group whose first event is a re-delivery is named
208    /// by the first row it **landed**, and keeps its guard.
209    ///
210    /// `[held]` is ingested alone, then a local append of two, then `[held,
211    /// new1, new2]` under a position-free guard. The re-delivered `held` is
212    /// skipped, so the third write lands two rows: three groups,
213    /// `[held]`, `[local1, local2]` and `[new1, new2]`, the last carrying the
214    /// guard, with `first` equal to the position the store gave `new1`.
215    ///
216    /// # Rejects
217    ///
218    /// A store that names a group by the first position it **allocated** for
219    /// it rather than the first row it wrote. On a store whose sequence burns
220    /// a value for each skipped re-delivery, as a Postgres sequence and
221    /// SQLite's `AUTOINCREMENT` both do, that position belongs to no row of
222    /// the group. Only the in-memory stores burn nothing and cannot make the
223    /// mistake. The wrong store is in
224    /// `tests/wrong_write_group_stores.rs`.
225    ///
226    /// # Errors
227    ///
228    /// A [`Violation`] of SY-39 if the store refuses a write or a read, reads
229    /// back other groups, names the guarded group by another position, or
230    /// drops its guard.
231    pub async fn a_group_after_a_redelivery_is_named_by_its_first_landed_row<F>(
232        open: impl AsyncFn() -> F,
233    ) -> Result<RuleOutcome, Violation>
234    where
235        F: IngestFixture,
236        F::Store: WriteGroupStore,
237    {
238        let fixture = open().await;
239        let store = fixture.connect().await;
240        ensure_foreign(&store).await?;
241        let guard = guard()?;
242        let held = [shipped(21, "redelivered-held")?];
243        let redelivered = [
244            shipped(21, "redelivered-held")?,
245            shipped(22, "redelivered-new1")?,
246            shipped(23, "redelivered-new2")?,
247        ];
248
249        ingest(&store, &[IngestGroup::new(&held, &[])]).await?;
250        append(&store, &["redelivered-local1", "redelivered-local2"]).await?;
251        ingest(
252            &store,
253            &[IngestGroup::new(&redelivered, &[]).with_guard(Some(&guard))],
254        )
255        .await?;
256        let page = read(&store, None, WHOLE_LOG).await?;
257
258        expect_shape(
259            &page,
260            &[
261                &["redelivered-held"],
262                &["redelivered-local1", "redelivered-local2"],
263                &["redelivered-new1", "redelivered-new2"],
264            ],
265        )?;
266        let landed = position_of(&store, "redelivered-new1").await?;
267        let named = page.groups.last().map(WriteGroup::first);
268        ensure(named == Some(landed), CLAUSE, || {
269            format!(
270                "the store named the group that landed after a re-delivery {named:?}; the first \
271                 row it wrote is at {landed}"
272            )
273        })?;
274        let kept = page.groups.last().and_then(WriteGroup::guard);
275        ensure(kept == Some(&guard), CLAUSE, || {
276            format!(
277                "the group that landed after a re-delivery read back with the guard {kept:?}; \
278                 it arrived under {guard:?}"
279            )
280        })?;
281        Ok(RuleOutcome::Ran)
282    }
283
284    /// SY-39: a read never returns part of a group. It stops before the group
285    /// that would take the page past `max_events`, and returns a first group
286    /// whole however large it is.
287    ///
288    /// Appends of two, three and two events. `read_groups(None, 4)` returns the
289    /// first group alone, because the second would take the page to five; then
290    /// `read_groups(after = its first, 1)` returns the three-event group whole.
291    ///
292    /// # Rejects
293    ///
294    /// A store that fills a page by event and cuts the group that crosses it,
295    /// one that skips a first group larger than the page, and one that resumes
296    /// above a row position rather than a group's first, which hands back a
297    /// group's tail as if it were a group.
298    ///
299    /// # Errors
300    ///
301    /// A [`Violation`] of SY-39 if the store refuses a write or a read, or a
302    /// page carries other groups.
303    pub async fn a_read_never_cuts_a_group<F>(
304        open: impl AsyncFn() -> F,
305    ) -> Result<RuleOutcome, Violation>
306    where
307        F: IngestFixture,
308        F::Store: WriteGroupStore,
309    {
310        let fixture = open().await;
311        let store = fixture.connect().await;
312        append(&store, &["cut-a1", "cut-a2"]).await?;
313        append(&store, &["cut-b1", "cut-b2", "cut-b3"]).await?;
314        append(&store, &["cut-c1", "cut-c2"]).await?;
315
316        let head = read(&store, None, budget(4)?).await?;
317        expect_shape(&head, &[&["cut-a1", "cut-a2"]])?;
318
319        let after = head.groups.first().map(WriteGroup::first);
320        let oversized = read(&store, after, budget(1)?).await?;
321        expect_shape(&oversized, &[&["cut-b1", "cut-b2", "cut-b3"]])?;
322        Ok(RuleOutcome::Ran)
323    }
324
325    /// SY-39: pages chained on `after = last.first()` return every group
326    /// exactly once, in order, and only the read that reached the end says
327    /// [`Waiting::Nothing`].
328    ///
329    /// Appends of two, one, two and one events, read two events at a time:
330    /// each page stops before a group that would overflow it, so every page
331    /// but the last ends at a group boundary with the log going on.
332    ///
333    /// # Rejects
334    ///
335    /// A store that says nothing is waiting on a page its budget cut, one that
336    /// resumes above a row position, and one that cuts a group to fill a page.
337    ///
338    /// # Errors
339    ///
340    /// A [`Violation`] of SY-39 if the store refuses a write or a read, hands
341    /// back a group twice or never, or says [`Waiting::Nothing`] before the end
342    /// or not at it.
343    pub async fn pages_chain_on_first_and_end_with_nothing<F>(
344        open: impl AsyncFn() -> F,
345    ) -> Result<RuleOutcome, Violation>
346    where
347        F: IngestFixture,
348        F::Store: WriteGroupStore,
349    {
350        let fixture = open().await;
351        let store = fixture.connect().await;
352        let written: [&[&str]; 4] = [
353            &["chain-a1", "chain-a2"],
354            &["chain-b1"],
355            &["chain-c1", "chain-c2"],
356            &["chain-d1"],
357        ];
358        for group in written {
359            append(&store, group).await?;
360        }
361
362        let pages = chain(&store, budget(2)?).await?;
363
364        let read: Vec<Vec<String>> = pages.iter().flat_map(shape).collect();
365        let expected: Vec<Vec<String>> = written.iter().map(|group| owned(group)).collect();
366        ensure(read == expected, CLAUSE, || {
367            format!("chained pages read back groups {read:?}; the log holds {expected:?}")
368        })?;
369        let waiting: Vec<Waiting> = pages.iter().map(|page| page.waiting).collect();
370        let Some((last, before)) = waiting.split_last() else {
371            return Err(Violation::new(CLAUSE, "the store returned no page at all"));
372        };
373        ensure(
374            *last == Waiting::Nothing && !before.contains(&Waiting::Nothing),
375            CLAUSE,
376            || {
377                format!(
378                    "the pages said {waiting:?}; only the last, which reached the end of the \
379                     log, may say Nothing, and it must"
380                )
381            },
382        )?;
383        Ok(RuleOutcome::Ran)
384    }
385
386    /// Every non-empty page from the start, each read above the last group's
387    /// first; stops at the first empty page.
388    async fn chain<S>(store: &S, max: NonZeroUsize) -> Result<Vec<GroupPage>, Violation>
389    where
390        S: WriteGroupStore,
391    {
392        let mut pages = Vec::new();
393        let mut after = None;
394        for _ in 0..MAX_PAGES {
395            let page = read(store, after, max).await?;
396            let Some(last) = page.groups.last() else {
397                return Ok(pages);
398            };
399            after = Some(last.first());
400            pages.push(page);
401        }
402        Err(Violation::new(
403            CLAUSE,
404            format!("the store was still handing back groups after {MAX_PAGES} pages"),
405        ))
406    }
407
408    /// The page's groups match `expected`, payload by payload.
409    fn expect_shape(page: &GroupPage, expected: &[&[&str]]) -> Result<(), Violation> {
410        let read = shape(page);
411        let expected: Vec<Vec<String>> = expected.iter().map(|group| owned(group)).collect();
412        ensure(read == expected, CLAUSE, || {
413            format!("the store read back groups {read:?} where it wrote {expected:?}")
414        })
415    }
416
417    /// Each group's payloads, as text: every payload here is ASCII.
418    fn shape(page: &GroupPage) -> Vec<Vec<String>> {
419        page.groups
420            .iter()
421            .map(|group| {
422                group
423                    .events()
424                    .iter()
425                    .map(|event| String::from_utf8_lossy(event.event.data()).into_owned())
426                    .collect()
427            })
428            .collect()
429    }
430
431    fn owned(group: &[&str]) -> Vec<String> {
432        group.iter().map(|payload| String::from(*payload)).collect()
433    }
434
435    fn events(page: &GroupPage) -> impl Iterator<Item = &ReplicatedEvent> + '_ {
436        page.groups.iter().flat_map(|group| group.events().iter())
437    }
438
439    fn budget(events: usize) -> Result<NonZeroUsize, Violation> {
440        NonZeroUsize::new(events).ok_or_else(|| Violation::new(CLAUSE, "a page budget of zero"))
441    }
442
443    /// One `append` of an event per payload.
444    async fn append<S: EventStore>(store: &S, payloads: &[&str]) -> Result<(), Violation> {
445        let events = payloads
446            .iter()
447            .map(|payload| opaque(APPENDED, payload))
448            .collect::<Result<Vec<Event>, Violation>>()?;
449        EventStore::append(store, &events, None)
450            .await
451            .map(|_| ())
452            .map_err(|error| {
453                Violation::new(CLAUSE, format!("the store refused an append: {error}"))
454            })
455    }
456
457    async fn ingest<S: IngestStore>(
458        store: &S,
459        groups: &[IngestGroup<'_>],
460    ) -> Result<(), Violation> {
461        IngestStore::ingest(store, groups)
462            .await
463            .map(|_| ())
464            .map_err(|error| {
465                Violation::new(CLAUSE, format!("the store refused an ingest: {error}"))
466            })
467    }
468
469    async fn read<S: WriteGroupStore>(
470        store: &S,
471        after: Option<SequencePosition>,
472        max: NonZeroUsize,
473    ) -> Result<GroupPage, Violation> {
474        WriteGroupStore::read_groups(store, after, max)
475            .await
476            .map_err(|error| {
477                Violation::new(CLAUSE, format!("the store refused a group read: {error}"))
478            })
479    }
480
481    /// The position the store gave the event carrying `payload`.
482    async fn position_of<S: EventStore>(
483        store: &S,
484        payload: &str,
485    ) -> Result<SequencePosition, Violation> {
486        let log = collect(EventStore::read(store, &Query::all(), ReadOptions::new()))
487            .await
488            .map_err(|error| {
489                Violation::new(
490                    CLAUSE,
491                    format!("the store refused a read of its log: {error}"),
492                )
493            })?;
494        log.iter()
495            .find(|row| row.event.data().as_ref() == payload.as_bytes())
496            .map(|row| row.position)
497            .ok_or_else(|| Violation::new(CLAUSE, format!("{payload} is not in the log")))
498    }
499
500    /// Fails a fixture whose store has the rules' origin as its own identity.
501    async fn ensure_foreign<S: IngestStore>(store: &S) -> Result<(), Violation> {
502        let own = IngestStore::store_id(store).await.map_err(|error| {
503            Violation::new(CLAUSE, format!("the store refused its identity: {error}"))
504        })?;
505        ensure(own != ORIGIN, CLAUSE, || {
506            format!("the fixture's store has the incarnation {own}, the rules' foreign origin")
507        })
508    }
509
510    /// A position-free guard: evidence that travels, never refused (SY-6).
511    fn guard() -> Result<AppendCondition, Violation> {
512        let item = QueryItem::of_types([SHIPPED]).map_err(|error| {
513            Violation::new(CLAUSE, format!("the rule's own query is invalid: {error}"))
514        })?;
515        Ok(AppendCondition::new(Query::from_item(item)))
516    }
517
518    fn shipped(position: u64, payload: &str) -> Result<ReplicatedEvent, Violation> {
519        let at = SequencePosition::new(position)
520            .ok_or_else(|| Violation::new(CLAUSE, "the rule's origin position is zero"))?;
521        Ok(ReplicatedEvent::new(
522            EventId::new(ORIGIN, at),
523            RecordedAt::from_millis(1_800_000_000_000),
524            opaque(SHIPPED, payload)?,
525        ))
526    }
527
528    fn opaque(event_type: EventType, payload: &str) -> Result<Event, Violation> {
529        Event::new(event_type, payload.as_bytes().to_vec()).map_err(|error| {
530            Violation::new(CLAUSE, format!("the rule's own event is invalid: {error}"))
531        })
532    }
533}
534
535/// Hands the complete write-group rule set to `$callback`.
536///
537/// This family's single enumeration: `$callback` is the path of a macro that
538/// accepts a comma-separated list of identifiers, invoked once with every rule
539/// in [`write_group_rules`].
540///
541/// # Examples
542///
543/// ```
544/// macro_rules! rule_names {
545///     ($($name:ident),* $(,)?) => { [ $( stringify!($name) ),* ] };
546/// }
547///
548/// let names = happenstance_sync_testkit::for_each_write_group_rule!(rule_names);
549/// assert!(names.contains(&"a_read_never_cuts_a_group"));
550/// ```
551#[macro_export]
552macro_rules! for_each_write_group_rule {
553    // Raw token trees rather than `$cb:path`, for the reason the event-store
554    // family's enumeration records.
555    ($($callback:tt)+) => {
556        $($callback)+! {
557            // --- One write reads back as one group (SY-39) ------------------
558            an_append_reads_back_as_one_group,
559            an_ingested_group_keeps_its_boundary_and_guard,
560            compensation_joins_its_group,
561            a_group_after_a_redelivery_is_named_by_its_first_landed_row,
562
563            // --- A page never cuts a group, and pages chain (SY-39) ---------
564            a_read_never_cuts_a_group,
565            pages_chain_on_first_and_end_with_nothing,
566        }
567    };
568}
569
570/// Emits one `#[tokio::test]` per write-group rule.
571///
572/// The caller's crate needs `tokio` with `macros` and `rt` in its
573/// `dev-dependencies`. The default emitter of
574/// [`write_group_store_conformance!`](crate::write_group_store_conformance).
575#[macro_export]
576macro_rules! emit_write_group_tokio {
577    ($($name:ident),* $(,)?) => {
578        $(
579            #[tokio::test]
580            async fn $name() -> ::core::result::Result<(), $crate::Violation> {
581                $crate::__private::write_group_rules::$name(__write_group_fixture)
582                    .await?
583                    .report(::core::stringify!($name));
584                Ok(())
585            }
586        )*
587    };
588}
589
590/// Emits one plain `#[test]` per write-group rule, driven by
591/// [`happenstance_testkit::block_on`]: no runtime and no `Send` bound.
592#[macro_export]
593macro_rules! emit_write_group_blocking {
594    ($($name:ident),* $(,)?) => {
595        $(
596            #[test]
597            fn $name() -> ::core::result::Result<(), $crate::Violation> {
598                $crate::__private::block_on(
599                    $crate::__private::write_group_rules::$name(__write_group_fixture),
600                )?
601                .report(::core::stringify!($name));
602                Ok(())
603            }
604        )*
605    };
606}
607
608/// Emits one `#[wasm_bindgen_test]` per write-group rule.
609///
610/// The caller's crate needs `wasm-bindgen-test` in its `dev-dependencies`,
611/// gated on `cfg(target_arch = "wasm32")`. A skip is logged through
612/// `console_log!` rather than reported on stdout, which writes nowhere on that
613/// target: [`emit_ingest_wasm!`](crate::emit_ingest_wasm)'s twin, and the
614/// harness the Durable Object's ingest store runs this family under.
615#[macro_export]
616macro_rules! emit_write_group_wasm {
617    ($($name:ident),* $(,)?) => {
618        $(
619            #[::wasm_bindgen_test::wasm_bindgen_test]
620            async fn $name() -> ::core::result::Result<(), $crate::Violation> {
621                let __outcome =
622                    $crate::__private::write_group_rules::$name(__write_group_fixture).await?;
623                if let Some(__line) = __outcome.skip_line(::core::stringify!($name)) {
624                    ::wasm_bindgen_test::console_log!("{}", __line);
625                }
626                Ok(())
627            }
628        )*
629    };
630}
631
632/// Expands to a `[&str; N]` of the rule names, for the orphan meta-test.
633///
634/// Not an emitter and not promised; exported only because `macro_rules!` has no
635/// other way to reach another crate's tests.
636#[doc(hidden)]
637#[macro_export]
638macro_rules! __write_group_rule_names {
639    ($($name:ident),* $(,)?) => { [ $( ::core::stringify!($name) ),* ] };
640}
641
642/// No rule exists without appearing in the enumeration, and none is
643/// enumerated without existing: `no_orphan_ingest_rules`, one family over.
644#[cfg(test)]
645#[test]
646fn no_orphan_write_group_rules() {
647    const SOURCE: &str = include_str!("write_group_suite.rs");
648    const PREFIX: &str = "    pub async fn ";
649
650    let registered = crate::for_each_write_group_rule!(crate::__write_group_rule_names);
651    let mut declared: Vec<&str> = SOURCE
652        .lines()
653        .filter_map(|line| line.strip_prefix(PREFIX))
654        .filter_map(|rest| {
655            rest.split(|c: char| !c.is_alphanumeric() && c != '_')
656                .next()
657        })
658        .collect();
659
660    assert!(
661        !declared.is_empty(),
662        "the source scan matched no rule at all"
663    );
664    declared.sort_unstable();
665    let mut registered_sorted = registered.to_vec();
666    registered_sorted.sort_unstable();
667    assert_eq!(
668        declared, registered_sorted,
669        "`for_each_write_group_rule!` and the rules declared in `write_group_suite.rs` disagree"
670    );
671}