happenstance_core/store.rs
1//! The event store port, in two flavours.
2//!
3//! # Why there are two traits
4//!
5//! `async fn` in a trait produces an anonymous future whose `Send`-ness is fixed
6//! by the trait definition. Two of happenstance's targets disagree about that:
7//!
8//! * **native / tokio** needs `Send` futures, or `tokio::spawn` rejects them;
9//! * **`wasm32` / Cloudflare Workers** is single-threaded and its futures are
10//! `!Send`, so a `Send` bound cannot be satisfied there at all.
11//!
12//! Rather than duplicate the trait, [`EventStore`] is written without any `Send`
13//! requirement and `trait_variant` derives [`SendEventStore`] from it. The two
14//! are related in exactly one direction, which is the sound one:
15//!
16//! ```text
17//! impl SendEventStore ==> EventStore comes free
18//! impl EventStore =/=> SendEventStore (cannot conjure Send)
19//! ```
20//!
21//! ## What that means in practice
22//!
23//! * **Writing an adapter?** Implement [`SendEventStore`] if your store can be
24//! shared across threads — which is every native adapter. Implement
25//! [`EventStore`] only when you genuinely cannot, as on wasm.
26//! * **Writing code that takes a store?** Bound on [`EventStore`]. It is the
27//! weaker requirement, so it accepts both kinds. Reach for
28//! [`SendEventStore`] only where you actually need to cross a thread
29//! boundary.
30//!
31//! ## Import one flavour, not both
32//!
33//! Because a `SendEventStore` is also an `EventStore`, bringing **both** names
34//! into scope makes method-call syntax ambiguous:
35//!
36//! ```text
37//! error[E0034]: multiple applicable items in scope
38//! --> src/lib.rs:6:19
39//! |
40//! 6 | let _ = store.read(&query, options);
41//! | ^^^^ multiple `read` found
42//! |
43//! = note: candidate #1 is defined in an impl of the trait `SendEventStore` for the type `MemoryEventStore`
44//! = note: candidate #2 is defined in an impl of the trait `EventStore` for the type `TraitVariantBlanketType`
45//! help: disambiguate the method for candidate #2
46//! |
47//! 6 - let _ = store.read(&query, options);
48//! 6 + let _ = EventStore::read(&store, &query, options);
49//! |
50//! ```
51//!
52//! In words, because a caret does not survive a search hit or a screen reader:
53//! `store.read(…)` is ambiguous because both [`EventStore`] and
54//! [`SendEventStore`] are in scope and each of them supplies a `read`.
55//!
56//! Import only the one you are binding on — [`EventStore`] in almost every
57//! case. If you genuinely need both in one module, disambiguate with
58//! fully-qualified syntax: `SendEventStore::read(&store, &query, options)`.
59//!
60//! The block above is a `text` fence and nothing compiles it. The error *code*
61//! is asserted by the compiled `rust,compile_fail,E0034` examples in
62//! `standards/rust/20-two-flavour-ports.md` and `standards/rust/00-prime-directives.md`;
63//! the notes' wording and `TraitVariantBlanketType` are rustc 1.97.1's, asserted by nothing.
64//!
65//! For why there are two flavours at all, and what an adapter looks like once
66//! you accept them, the adapter reading order at `docs/adapter-reading-order.md`
67//! sequences what is already written. Named, not linked: it is a page, not an item.
68//!
69//! ## Naming
70//!
71//! The names carry the distinction deliberately. `trait_variant`'s own
72//! convention would call the `!Send` flavour `LocalEventStore`, but "local"
73//! already means something else here — a local-first application's on-device
74//! store — and conflating the two would be a permanent source of confusion.
75
76use alloc::vec::Vec;
77
78use futures_core::Stream;
79
80use crate::append::AppendCondition;
81use crate::error::AppendError;
82use crate::event::{Event, SequencePosition, SequencedEvent};
83use crate::identity::EventId;
84use crate::query::{Query, ReadOptions};
85
86/// A DCB-compliant event store.
87///
88/// Two traits, one set of doc attributes. `trait_variant` derives
89/// [`SendEventStore`] from [`EventStore`] and copies this block onto it, so
90/// every sentence here is written to hold on whichever of the two pages you
91/// opened. [`EventStore`] states no `Send` requirement and is what generic code
92/// binds; [`SendEventStore`] adds it and hands back [`EventStore`] free. The
93/// [module documentation](self) has the reason the split exists.
94///
95/// # Implementing this trait
96///
97/// Implement [`SendEventStore`] where the store can be shared across threads,
98/// which is every native adapter; implement [`EventStore`] only where `Send`
99/// cannot be had at all, as on `wasm32`.
100///
101/// The specification's requirements are obligations on the implementer, and
102/// [`happenstance-testkit`](https://docs.rs/happenstance-testkit) checks every one of
103/// them. An adapter is not finished until it passes that suite.
104///
105/// For a runnable end-to-end example see `MemoryEventStore`, which the `memory`
106/// feature provides. It is not linked because this item exists without that
107/// feature and the link would not resolve (D13).
108///
109/// # Deletion is outside the port
110///
111/// This port has no delete, truncate, compact, redact or tombstone method, and
112/// no 1.x release adds one. A store that has lost events by some means outside
113/// the port still owes every promise about the events it holds. It never
114/// reuses a position, and [`Query::all`] means every event it holds
115/// (specification ES-38). What a condition over removed history does is on
116/// [`AppendCondition`]: it passes vacuously (ES-40). Nothing here reports what
117/// a store no longer holds.
118///
119/// # Writing generic code over a store
120///
121/// Bound on [`EventStore`], not [`SendEventStore`], unless you need to cross a
122/// thread boundary:
123///
124/// ```
125/// use happenstance_core::{EventStore, Query, ReadOptions, collect};
126///
127/// async fn count_all<S: EventStore>(store: &S) -> Result<usize, S::Error> {
128/// let events = collect(store.read(&Query::all(), ReadOptions::new())).await?;
129/// Ok(events.len())
130/// }
131/// ```
132// The workspace's first `#[doc(alias)]`, so the rule it is added under is
133// written here rather than left to be inferred. An alias is a *search key* and
134// not a pointer: it moves a reader who is already searching and does nothing
135// for the reader who is reading, so it never substitutes for the cross-reference
136// at the stall in this module's documentation. It is permitted only where the
137// string a reader types is one that rustc, the specification, or a recorded
138// reader question actually emits, and is not the item's own name or a substring
139// of it. Both strings below are rustc's, from the diagnostic reproduced above.
140// Rejected: synonym farming (`eventstore`, `es`, `event-store`), and aliases for
141// concepts rather than for strings. No pointer-register row is filed: an
142// attribute cannot rot independently of the item it sits on, because deleting
143// the item deletes the alias.
144//
145// Two attributes, not the three the design projected, and the reason is
146// mechanical rather than editorial. `SendEventStore` is *derived* — the
147// `trait_variant` expansion builds it with `..tr.clone()`
148// (`trait-variant-0.1.3/src/variant.rs:115-123`), which copies the trait's
149// attributes verbatim — so there is no item on which to write a variant-only
150// alias, and every alias written here lands on both flavours. Two written is
151// four in the search index, which is the coverage the criterion asked for.
152//
153// Residual risk, named: `TraitVariantBlanketType` is an *internal* name of that
154// expansion. If it is renamed upstream the string here goes stale and nothing
155// in this repository catches it.
156#[doc(alias = "E0034")]
157#[doc(alias = "TraitVariantBlanketType")]
158#[trait_variant::make(SendEventStore: Send)]
159pub trait EventStore {
160 /// How this adapter fails for its own reasons.
161 ///
162 /// Append-condition violations do **not** belong here — they are reported
163 /// through [`AppendError::ConditionViolated`], so that callers can tell
164 /// "retry the decision" from "something broke" without knowing which
165 /// adapter they hold.
166 type Error: core::error::Error + 'static;
167
168 /// Reads the events matching `query`, in the order `options` asks for.
169 ///
170 /// Evaluated against one state **sampled no later than the first poll**; laziness
171 /// is permitted, never required. An adapter issuing more than one statement per
172 /// `read` must capture a position ceiling no later than that poll and bound every
173 /// later statement by it. Failures surface as `Err` items rather than up front.
174 /// This method is not `async` because putting the stream at the top level of the
175 /// return type is what allows [`SendEventStore`] to mark the *stream* `Send`, not
176 /// merely the future that produces it, and it is what lets an adapter stream a
177 /// million-event replay without buffering it. Use [`collect`] for a `Vec`.
178 ///
179 /// # Ordering
180 ///
181 /// Ascending by [`SequencePosition`] unless
182 /// [`ReadOptions::backwards`](crate::ReadOptions::backwards) is set.
183 /// [`ReadOptions::from`](crate::ReadOptions::from) is **inclusive**.
184 fn read(
185 &self,
186 query: &Query,
187 options: ReadOptions,
188 ) -> impl Stream<Item = Result<SequencedEvent, Self::Error>>;
189
190 /// Atomically appends `events`, rejecting the write if `condition` matches.
191 ///
192 /// Returns the position assigned to the **last** appended event. The
193 /// specification does not require this, but it is what checkpointing and
194 /// reporting need, and only the store knows it.
195 ///
196 /// **It is not a sound `after` for a follow-up condition** unless the
197 /// caller has already read up to it. Positions may have gaps and another
198 /// writer may hold one *below* this value that this caller never saw, so a
199 /// condition anchored here silently excludes exactly the events a condition
200 /// exists to catch. The sound `after` comes from a read:
201 /// [`read_decision_model`] returns the last position actually observed,
202 /// which is what
203 /// [`AppendCondition::after_every_guard_opt`](crate::AppendCondition::after_every_guard_opt)
204 /// expects.
205 ///
206 /// # Atomicity
207 ///
208 /// Either every event lands or none does. A rejected append must leave the
209 /// store byte-identical.
210 ///
211 /// # Cancellation
212 ///
213 /// **Dropping this future does not cancel the append.** An adapter MAY
214 /// commit a batch whose future was dropped, and a caller MUST NOT read a
215 /// dropped future as evidence that nothing landed. There is deliberately no
216 /// error value for it — a dropped future produces no `Result` at all, so
217 /// the outcome has nowhere to go, and the contract states the absence of a
218 /// promise rather than inventing a variant that could never be delivered.
219 ///
220 /// What *is* promised is `# Atomicity`, which bounds what the silence can
221 /// cost: whichever the adapter does, the batch is applied in full or not at
222 /// all and never in part. Each adapter MUST state which of the two it does.
223 ///
224 /// At the edge this is the ordinary termination path rather than an exotic
225 /// one — a client disconnect, a CPU limit, a Durable Object or pod
226 /// eviction. The shape that looks cancellation-safe and is not: a pooled
227 /// `rusqlite` adapter doing its work in `spawn_blocking`. Dropping the
228 /// `JoinHandle` does not cancel the closure, the `COMMIT` runs, the caller
229 /// is told nothing, and an operator retries a payment that already went
230 /// out.
231 ///
232 /// # Resolving an unknown outcome
233 ///
234 /// **A conditional append is at-most-once under verbatim reissue.** Where
235 /// the events being appended are themselves matched by the condition's
236 /// query, reissuing the identical batch resolves what a dropped future left
237 /// unknown: [`AppendError::ConditionViolated`] means the first attempt
238 /// landed, `Ok` means it had not and now has. Either way the store holds
239 /// exactly one copy. No identity, no idempotency key and no extra operation
240 /// — the guarantee falls out of the condition the caller already wrote.
241 ///
242 /// It has three limits, stated here because a guarantee whose limits are
243 /// unstated gets read as universal:
244 ///
245 /// * An **unconditional** append has no such property. Reissuing it appends
246 /// a second copy, and nothing in this port can prevent that.
247 /// * A **conditional** append whose query does not match its own events has
248 /// none either: conditioning on `CourseCapacityChanged` while appending
249 /// `StudentSubscribed` leaves the reissue indistinguishable from a first
250 /// attempt. That is the *common* shape, not a corner — it is what a
251 /// decision that reads one thing and writes another looks like.
252 /// * The reissue must be **verbatim**. This is not the
253 /// [`ConditionViolated`](AppendError::ConditionViolated) re-decide path,
254 /// where the correct response is to re-read, rebuild the decision model
255 /// and produce *different* events. The two arrive as the same error value
256 /// and mean opposite things — one says "your write already happened", the
257 /// other says "the world moved, decide again" — and collapsing them is
258 /// the mistake this section exists to prevent.
259 ///
260 /// A caller needing at-most-once for the second and third shapes supplies
261 /// its own dedup in the domain. A natural key in the tags is the mechanism,
262 /// and it is queryable; an identity buried in
263 /// [`Event::metadata`](crate::Event::metadata) is not, because a query
264 /// matches on type and tags only.
265 ///
266 /// # Errors
267 ///
268 /// * [`AppendError::NoEvents`] when `events` is empty. The specification
269 /// defines a batch as non-empty, so there is no position to return. This
270 /// check MUST precede the condition check: an empty batch is the caller's
271 /// own bug and retrying cannot fix it, whereas `ConditionViolated` means
272 /// "retry", so reporting the violation for an empty batch puts a correct
273 /// client into a loop that never terminates.
274 /// * [`AppendError::ConditionViolated`] when the store already holds an
275 /// event matching `condition`. This is routine under contention: rebuild
276 /// the decision model and retry.
277 /// * [`AppendError::Busy`] when the store refused for a transient reason
278 /// before the batch took any effect. Nothing was written, so taking the
279 /// decision again is safe. An adapter that cannot vouch for that reports
280 /// `Store` instead.
281 /// * [`AppendError::Store`] for adapter-specific failures, including any
282 /// outcome the adapter cannot vouch for.
283 async fn append(
284 &self,
285 events: &[Event],
286 condition: Option<&AppendCondition>,
287 ) -> Result<SequencePosition, AppendError<Self::Error>>;
288
289 /// The highest position currently visible in the store, or `None` when it
290 /// holds nothing.
291 ///
292 /// # Why this is required rather than provided
293 ///
294 /// A provided body would have to be
295 /// `read(&Query::all(), backwards().limit(1))`, which is a scan on any store
296 /// that cannot push the ordering down, and a blanket implementation cannot
297 /// be overridden per adapter. A SQLite adapter wants `SELECT max(position)`.
298 /// The cost of `required` is a body in every implementation; the cost of
299 /// `provided` is a fast path no adapter can install.
300 ///
301 /// There is a second reason, and it is the one that settles it: the only
302 /// provided form holds `&self` across an `await`, which needs
303 /// `where Self: Sync` — and the `!Send` edge adapter that the bare flavour
304 /// exists for is not `Sync`, so the convenience body would fail to compile
305 /// for exactly the adapter it was meant to spare.
306 ///
307 /// # What it is for
308 ///
309 /// Answering "am I caught up?" — a projection runner compares its checkpoint
310 /// with this for **equality or ordering**. Do not subtract two positions and
311 /// read the difference as a count of outstanding events: positions are an
312 /// opaque ordering key and the specification permits gaps, so the difference
313 /// is not a number of anything.
314 ///
315 /// # Errors
316 ///
317 /// Returns the adapter's error if the head cannot be determined.
318 async fn head(&self) -> Result<Option<SequencePosition>, Self::Error>;
319
320 /// Whether this store holds an event with `id`.
321 ///
322 /// The membership question a replicating peer must be able to ask without
323 /// constructing a [`Query`] and without parsing any payload — which is why
324 /// [`EventId`] is deliberately outside the query language.
325 ///
326 /// # Why every store can answer this cheaply
327 ///
328 /// Every store already holds at most one event per `EventId`, so the index
329 /// that answers this exists wherever the contract is honoured, and no
330 /// adapter is taxed with a new one. A store that has never ingested anything
331 /// can answer without an index at all: if the identifier's store half is not
332 /// its own incarnation the answer is `false`, and if it is, the question
333 /// reduces to whether that position exists.
334 ///
335 /// `false` means this store does not hold the event. It does not say
336 /// whether the store never held it or no longer does.
337 ///
338 /// # Errors
339 ///
340 /// Returns the adapter's error if the lookup fails.
341 async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error>;
342}
343
344// =====================================================================
345// ES-13's regression pin, and the guard that keeps it where cargo looks
346// =====================================================================
347
348/// ES-13's regression pin: the query must outlive the stream.
349///
350/// A carrier, not an API — the two fences below are the artefact, and a doc
351/// comment needs an item to sit on. It sits in `src/` because rustdoc collects
352/// doctests from the **lib target only**. It lived in
353/// `crates/happenstance-core/tests/frozen_signatures.rs` from phase 4 until
354/// F1-04, where nothing ever compiled it; the guard below is what stops it
355/// drifting back there.
356///
357/// ES-13 freezes [`EventStore::read`] on `&Query` and names taking the query
358/// **by value** as the wrong fix. What the reference costs is that the opaque
359/// return type captures the query's lifetime, so the query has to be owned by
360/// something that outlives the stream: a *parameter* is, and a local never can
361/// be. The diagnostic depends on how the return type is spelled, which is why
362/// ES-13 states the defect rather than pinning a code:
363///
364/// | Arrangement | Diagnostic |
365/// |---|---|
366/// | `store.read(&Query::all(), ..)` bound to a `let` | `error[E0716]` |
367/// | returned, bare `-> impl Stream<..>` | `error[E0597]` |
368/// | returned, `+ '_` or `+ 'a` | `error[E0515]` |
369/// | returned inside a struct, bare | `error[E0597]` |
370///
371/// All four are the same defect reported from two ends. Without a lifetime bound
372/// the compiler reasons from the *borrow* — `&query` must outlive the return and
373/// `query` drops at the end of the function. With one, the opaque type is
374/// required to live for `'a`, so it reasons from the *value* instead. The cause
375/// either way is that the opaque type captures the query's lifetime.
376///
377/// # The control
378///
379/// Paired per RS-62-1, and it carries the half of the check the refusal cannot:
380/// it is the one thing here that goes red when `read`, `Query` or `ReadOptions`
381/// is renamed or moved behind a feature, which a lone `compile_fail` fence
382/// reports as passing.
383///
384/// ```
385/// use futures_core::Stream;
386/// use happenstance_core::{EventStore, Query, ReadOptions, SequencedEvent};
387///
388/// // The query comes from the caller, so it outlives the returned stream.
389/// fn replay<'a, S: EventStore>(
390/// store: &'a S,
391/// query: &'a Query,
392/// ) -> impl Stream<Item = Result<SequencedEvent, S::Error>> + 'a {
393/// store.read(query, ReadOptions::new())
394/// }
395/// # fn main() {}
396/// ```
397///
398/// # The refusal
399///
400/// The same function over a **local** query. The fence carries no error code:
401/// the table above has four of them, and rustdoc 1.97.1 compares an annotated
402/// code, finds no match, and reports the fence as passing anyway (RS-62-1).
403///
404/// ```compile_fail
405/// use futures_core::Stream;
406/// use happenstance_core::{EventStore, Query, ReadOptions, SequencedEvent};
407///
408/// fn escapes<S: EventStore>(store: &S) -> impl Stream<Item = Result<SequencedEvent, S::Error>> {
409/// let query = Query::all();
410/// store.read(&query, ReadOptions::new())
411/// }
412/// # fn main() {}
413/// ```
414#[doc(hidden)]
415#[expect(dead_code, reason = "a doc carrier: the fence above is the item")]
416fn es_13_the_query_must_outlive_the_stream() {}
417
418/// A doc fence inside an integration test target is never handed to a compiler.
419///
420/// rustdoc collects doctests from the **lib target only**, so a fence in a
421/// `tests/` file is compiled as prose: it cannot fail, and it cannot be told
422/// apart from one that has stopped being Rust. Measured rather than reasoned
423/// about — `crates/happenstance-core/tests/frozen_signatures.rs` carried a
424/// `compile_fail` fence claiming to pin ES-13 from phase 4 until F1-04, and with
425/// that fence's body replaced by a line of English both
426/// `cargo test -p happenstance-core --doc` and
427/// `cargo test -p happenstance-core --test frozen_signatures` still exit `0`.
428///
429/// So the pin moved to `es_13_the_query_must_outlive_the_stream` above, and this
430/// is the standing guard on the move: it fails if that file opens a doc fence
431/// again. It reads the file rather than reasoning about it, the way
432/// `mod module_doc` below reads this one.
433///
434/// ```
435/// // Anchored on the package root rather than on relative depth, per RS-62-5:
436/// // the path a packaged `.crate` resolves is then the path checked here.
437/// const ARTEFACT: &str = include_str!(concat!(
438/// env!("CARGO_MANIFEST_DIR"),
439/// "/tests/frozen_signatures.rs"
440/// ));
441///
442/// // Spelled with escapes on purpose. A literal fence inside a doctest inside a
443/// // doc comment is three nested parsers deep, and the needle is the one thing
444/// // here that must not be guessed at by any of them.
445/// const FENCE: &str = "\u{60}\u{60}\u{60}";
446///
447/// fn main() {
448/// let opened: Vec<usize> = ARTEFACT
449/// .lines()
450/// .enumerate()
451/// .filter(|(_, line)| {
452/// let text = line.trim_start();
453/// text.strip_prefix("//!")
454/// .or_else(|| text.strip_prefix("///"))
455/// .is_some_and(|body| body.trim_start().starts_with(FENCE))
456/// })
457/// .map(|(index, _)| index + 1)
458/// .collect();
459///
460/// assert!(
461/// opened.is_empty(),
462/// "tests/frozen_signatures.rs opens a doc fence at line(s) {opened:?}. \
463/// cargo hands a doc fence to a compiler from the lib target only, so \
464/// whatever that one claims to pin is decorative. Move it beside \
465/// `es_13_the_query_must_outlive_the_stream` in src/store.rs."
466/// );
467///
468/// // The other direction, and it is the half a reader would not think to
469/// // ask for: an empty `tests/` file satisfies everything above, so on its
470/// // own this guard stays green the day the pin it points at is deleted.
471/// const HERE: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/store.rs"));
472/// const CARRIER: &str = "fn es_13_the_query_must_outlive_the_stream() {}";
473///
474/// // Matched as a whole *line*, not as a substring. `contains` is satisfied
475/// // by the `const` two lines up — this doctest is inside the file it is
476/// // reading — and passed unchanged with the item renamed, measured.
477/// assert!(
478/// HERE.lines().any(|line| line.trim_start() == CARRIER),
479/// "ES-13's pin has left src/store.rs, where cargo compiles its fence"
480/// );
481/// assert!(
482/// HERE.contains(&[FENCE, "compile_fail"].concat()),
483/// "src/store.rs opens no `compile_fail` fence, so nothing rejects the \
484/// escaping arrangement ES-13's `Rejects:` line forbids"
485/// );
486/// }
487/// ```
488#[doc(hidden)]
489#[expect(dead_code, reason = "a doc carrier: the fence above is the item")]
490fn a_doc_fence_in_an_integration_test_target_is_never_compiled() {}
491
492/// Drains a [`read`](EventStore::read) stream into a `Vec`, stopping at the
493/// first error.
494///
495/// Convenient for tests, small reads, and rebuilding a decision model that fits
496/// in memory. Do not use it to replay an entire log.
497///
498/// Implemented by hand rather than pulling in `futures-util`, so that the
499/// contract crate's dependency graph stays as small as its semver surface is
500/// stable.
501///
502/// # Errors
503///
504/// Returns the first error the stream yields, discarding any events already
505/// collected.
506pub async fn collect<S, T, E>(stream: S) -> Result<Vec<T>, E>
507where
508 S: Stream<Item = Result<T, E>>,
509{
510 use core::task::Poll;
511
512 let mut stream = core::pin::pin!(stream);
513 let mut collected = Vec::new();
514
515 core::future::poll_fn(|cx| {
516 loop {
517 match stream.as_mut().poll_next(cx) {
518 Poll::Ready(Some(Ok(item))) => collected.push(item),
519 Poll::Ready(Some(Err(err))) => return Poll::Ready(Err(err)),
520 Poll::Ready(None) => return Poll::Ready(Ok(())),
521 Poll::Pending => return Poll::Pending,
522 }
523 }
524 })
525 .await?;
526
527 Ok(collected)
528}
529
530/// Reads `query` and reports both the matching events and the position to use
531/// in a follow-up [`AppendCondition`].
532///
533/// This is the read half of the DCB command loop: build a decision model from
534/// what you can see, then append conditioned on nothing new having appeared.
535/// The returned position is the last one observed, or `None` when nothing
536/// matched — which is exactly what
537/// [`AppendCondition::after_every_guard_opt`](crate::AppendCondition::after_every_guard_opt) expects.
538///
539/// # Errors
540///
541/// Returns the adapter's error if the read fails.
542pub async fn read_decision_model<S>(
543 store: &S,
544 query: &Query,
545) -> Result<(Vec<SequencedEvent>, Option<SequencePosition>), S::Error>
546where
547 S: EventStore,
548{
549 let events = collect(store.read(query, ReadOptions::new())).await?;
550 let last = events.last().map(|event| event.position);
551 Ok((events, last))
552}
553
554// Gated on `memory` because the assertion below has to be *instantiated* at a
555// concrete store to mean anything, and `MemoryEventStore` is the only one the
556// contract crate has. An uninstantiated generic proves nothing: the projections
557// stay opaque and the coercion is never checked.
558#[cfg(all(test, feature = "memory"))]
559mod tests {
560 // Both flavours are in scope here, which the module documentation warns
561 // against — but the warning is about *method-call* syntax, and nothing below
562 // calls a method. These are type-level assertions only.
563 use super::{EventStore, SendEventStore};
564
565 /// ES-5. The two flavours' `Error` projections are the *same type*, not
566 /// merely two types that happen to carry the same bounds.
567 ///
568 /// The assertion is the identity function's body: returning an
569 /// `<S as SendEventStore>::Error` where an `<S as EventStore>::Error` is
570 /// demanded type-checks only if the compiler can normalise both projections
571 /// to one type. Today it can, via the blanket impl `trait_variant` emits
572 /// (`type Error = <Self as SendEventStore>::Error`).
573 ///
574 /// This is deliberately *not* spelled as a bounds check —
575 /// `fn f<S: SendEventStore>() where S::Error: core::error::Error` would pass
576 /// trivially, since both traits state the same bound and the compiler would
577 /// simply believe it. Equality is the property with content: it is what
578 /// forbids ES-5's "Rejects" case, abandoning the derivation for two
579 /// hand-written traits whose associated types are independent. Under that
580 /// shape this fails with `error[E0308]: mismatched types`.
581 fn error_projections_are_one_type<S: SendEventStore>(
582 error: <S as SendEventStore>::Error,
583 ) -> <S as EventStore>::Error {
584 error
585 }
586
587 #[test]
588 fn error_bound_is_identical_on_both_flavours() {
589 // Naming the function is what instantiates the coercion check above;
590 // the body is where the assertion lives, so there is nothing to run.
591 let _ = error_projections_are_one_type::<crate::MemoryEventStore>;
592 }
593}
594
595/// The module documentation, read as a deliverable rather than as decoration.
596///
597/// Everything here reads this file's own `//!` comment. That is unusual and it is
598/// deliberate: the section `## Import one flavour, not both` exists so that an
599/// adapter author whose build just failed with `error[E0034]` finds rustc's own
600/// words in the file they already have open, and every part of that claim — the
601/// transcript being verbatim, the diagnosis surviving without the caret, the fix
602/// arriving before the pointer — is a property of the *text*, invisible to every
603/// other instrument this workspace owns. A doc comment nothing checks is exactly
604/// the rot the section was rewritten to repair.
605///
606/// It is `cfg(test)` with no feature gate, unlike the type-level module above it:
607/// the text is there in every feature configuration, so nothing here may be
608/// contingent on one.
609#[cfg(test)]
610mod module_doc {
611 #![allow(clippy::unwrap_used, reason = "test code, per the house style")]
612
613 use alloc::string::String;
614 use alloc::vec::Vec;
615
616 /// This file's own source. The module doc is the deliverable, so it is
617 /// asserted rather than trusted.
618 const SOURCE: &str = include_str!("store.rs");
619
620 /// The third of the four heading entries — the one every change lands inside.
621 const SECTION: &str = "## Import one flavour, not both";
622
623 /// The transcript, pinned character for character.
624 ///
625 /// **The one place in this workspace where pinning a paragraph is right.**
626 /// Elsewhere a paragraph pin turns ordinary rewording into a build failure;
627 /// here rewording *is* the defect, because the block's whole job is to be the
628 /// string a stuck reader searches for and pastes into a diff against their own
629 /// terminal. Reproduced at the pinned toolchain — `rustc 1.97.1 (8bab26f4f
630 /// 2026-07-14)` — by compiling a deliberate double-import; the run's full
631 /// stderr, the command and the `rustc --version` are recorded in this story's
632 /// folder under `.bklg/docs-that-teach/reach-and-adapter-path/`.
633 ///
634 /// Candidate #1's `help:` hunk is the one thing dropped, which is the
635 /// signed-off design's yield rule (3), exercised at design time. Nothing
636 /// further may be cut, and the two `= note:` lines and the internal type name
637 /// never yield at all.
638 const TRANSCRIPT: &str = "\
639error[E0034]: multiple applicable items in scope
640 --> src/lib.rs:6:19
641 |
6426 | let _ = store.read(&query, options);
643 | ^^^^ multiple `read` found
644 |
645 = note: candidate #1 is defined in an impl of the trait `SendEventStore` for the type `MemoryEventStore`
646 = note: candidate #2 is defined in an impl of the trait `EventStore` for the type `TraitVariantBlanketType`
647help: disambiguate the method for candidate #2
648 |
6496 - let _ = store.read(&query, options);
6506 + let _ = EventStore::read(&store, &query, options);
651 |";
652
653 /// The section's source-line cap, raised from 30 to 36 at sign-off when copy
654 /// fidelity was chosen over the density budget (finding F3). The measured
655 /// projection was ~34.
656 const SECTION_LINE_CAP: usize = 36;
657
658 /// The source above this file's first test module.
659 ///
660 /// Without it every assertion about the production text would be satisfiable
661 /// by the tests' own pinned strings, since [`SOURCE`] includes this module too.
662 fn production_source() -> &'static str {
663 SOURCE.split("#[cfg(all(test").next().unwrap()
664 }
665
666 /// The `//!` comment at the top of the file, one entry per line, with the
667 /// comment marker and its single following space removed.
668 ///
669 /// A bare `//!` becomes an empty line, which is what makes the paragraph
670 /// splitting below work. `str::lines` drops a trailing carriage return, so this
671 /// is correct whichever line ending the working tree happens to carry.
672 fn doc_lines() -> Vec<&'static str> {
673 SOURCE
674 .lines()
675 .take_while(|line| line.starts_with("//!"))
676 .map(|line| {
677 if line.trim_end() == "//!" {
678 ""
679 } else {
680 line.strip_prefix("//! ")
681 .expect("every doc line is `//!` or `//! ` and content")
682 }
683 })
684 .collect()
685 }
686
687 /// [`doc_lines`] with every fenced block removed, so a heading count or a
688 /// markup check cannot be fooled by a line inside a transcript.
689 fn doc_lines_outside_fences() -> Vec<&'static str> {
690 let mut inside = false;
691 let mut kept = Vec::new();
692 for line in doc_lines() {
693 if line.starts_with("```") {
694 inside = !inside;
695 continue;
696 }
697 if !inside {
698 kept.push(line);
699 }
700 }
701 kept
702 }
703
704 /// The body of `## Import one flavour, not both` — every line after its heading
705 /// and up to the next `##`, with the blank lines that bracket it trimmed.
706 ///
707 /// This is the unit the density budget is denominated in, and it is the same
708 /// count the design measured: 13 source lines before this story, ~34 after it.
709 fn section_body() -> Vec<&'static str> {
710 let lines = doc_lines();
711 let start = lines
712 .iter()
713 .position(|line| *line == SECTION)
714 .expect("the heading ladder still carries `## Import one flavour, not both`");
715 let rest = &lines[start + 1..];
716 let end = rest
717 .iter()
718 .position(|line| line.starts_with("## "))
719 .unwrap_or(rest.len());
720 let mut body = &rest[..end];
721 while body.first() == Some(&"") {
722 body = &body[1..];
723 }
724 while body.last() == Some(&"") {
725 body = &body[..body.len() - 1];
726 }
727 body.to_vec()
728 }
729
730 /// The lines inside the section's `text` fence, fence markers excluded.
731 fn fence() -> Vec<&'static str> {
732 let body = section_body();
733 let open = body
734 .iter()
735 .position(|line| line.starts_with("```"))
736 .expect("the section carries the diagnostic in a fence");
737 let rest = &body[open + 1..];
738 let close = rest
739 .iter()
740 .position(|line| line.starts_with("```"))
741 .expect("the fence is closed");
742 rest[..close].to_vec()
743 }
744
745 /// The blank-line-separated paragraphs after the fence closes — elements (c),
746 /// (d), (e) and (f) of the signed-off composition, in source order.
747 fn paragraphs_after_fence() -> Vec<Vec<&'static str>> {
748 let body = section_body();
749 let close = body
750 .iter()
751 .rposition(|line| line.starts_with("```"))
752 .expect("the fence is closed");
753 let mut paragraphs = Vec::new();
754 let mut current: Vec<&'static str> = Vec::new();
755 for line in &body[close + 1..] {
756 if line.is_empty() {
757 if !current.is_empty() {
758 paragraphs.push(core::mem::take(&mut current));
759 }
760 } else {
761 current.push(line);
762 }
763 }
764 if !current.is_empty() {
765 paragraphs.push(current);
766 }
767 paragraphs
768 }
769
770 /// Soft-wrapped lines rejoined with single spaces, so a pinned subject string
771 /// is not broken by where a line happens to wrap.
772 fn joined(lines: &[&str]) -> String {
773 let mut out = String::new();
774 for (index, line) in lines.iter().enumerate() {
775 if index > 0 {
776 out.push(' ');
777 }
778 out.push_str(line);
779 }
780 out
781 }
782
783 /// Whether `prose` names the weaker flavour in its own right rather than only
784 /// as the tail of the stronger one — `SendEventStore` contains `EventStore`, so
785 /// a naive `contains` cannot tell "both traits are named" from "one is".
786 fn names_both_flavours(prose: &str) -> bool {
787 prose.contains("SendEventStore")
788 && prose.replace("SendEventStore", "").contains("EventStore")
789 }
790
791 // ---- AC-001: rustc's own transcript, searchable and verbatim -------------
792
793 /// The block is rustc's output, not a transcription of one.
794 ///
795 /// Equality rather than a handful of `contains` assertions, because every
796 /// weaker form passes on a block somebody has tidied. The reader's move is to
797 /// paste their own terminal beside this one and look for a difference, and any
798 /// edit at all turns that into a false positive.
799 #[test]
800 fn the_fence_is_rustcs_own_e0034_output() {
801 let expected: Vec<&str> = TRANSCRIPT.lines().collect();
802 assert_eq!(
803 fence(),
804 expected,
805 "the `text` fence is no longer the stderr of the recorded reproduction \
806 run. It is not prose and it is not edited to fit: reproduce it again at \
807 the pinned toolchain and paste what that run emitted"
808 );
809 }
810
811 /// The two strings the density budget's yield order says never yield.
812 ///
813 /// Separate from the equality above on purpose. If a later change re-pins the
814 /// transcript for a new toolchain, that test moves with it and this one does
815 /// not: the `= note:` candidate lines and the internal type name are what a
816 /// stuck reader actually searches for, and they survive every re-pin.
817 #[test]
818 fn the_two_note_lines_and_the_internal_type_name_never_yield() {
819 let fence = fence();
820 let notes = fence
821 .iter()
822 .filter(|line| line.trim_start().starts_with("= note:"))
823 .count();
824 assert_eq!(
825 notes, 2,
826 "both `= note:` candidate lines are required content: they name the two \
827 traits and the type each `read` was found on, and they are the lines a \
828 reader pastes into a search box"
829 );
830 assert!(
831 fence
832 .iter()
833 .any(|line| line.contains("TraitVariantBlanketType")),
834 "the internal type name rustc prints in candidate #2 is the string this \
835 workspace explains nowhere else; dropping it puts the reader's search \
836 back where it started"
837 );
838 }
839
840 /// Nothing inside the fence but compiler characters.
841 ///
842 /// A `rust` fence around a diagnostic would buy a green tick that means
843 /// nothing — the `ignore`-fence anti-pattern wearing a compiler — and rendered
844 /// markup inside the block would survive selection and break the reader's diff.
845 #[test]
846 fn the_fence_is_uncompiled_plain_text_a_reader_can_paste() {
847 let body = section_body();
848 assert!(
849 body.contains(&"```text"),
850 "the diagnostic sits in a `text` fence: nothing compiles a compiler \
851 transcript, and a `rust` fence would claim otherwise"
852 );
853 assert!(
854 !body
855 .iter()
856 .any(|line| line.starts_with("```rust") || line.starts_with("```ignore")),
857 "a `rust` or `ignore` fence around the diagnostic is the one tier this \
858 story's specification names so that nobody adds it"
859 );
860 for line in fence() {
861 assert!(
862 !line.contains("](") && !line.contains('<') && !line.contains("**"),
863 "rendered-only markup inside the fence: {line:?}. The block has to \
864 diff clean against a terminal, so it may carry only what rustc \
865 printed"
866 );
867 }
868 }
869
870 // ---- AC-002: the ambiguity named in words, never spatially alone ---------
871
872 /// `^^^^ multiple` is spatial. A screen reader linearises it into nothing and
873 /// so does a plain-text search hit, so the diagnosis is restated in words
874 /// immediately after the block.
875 #[test]
876 fn the_ambiguity_is_named_in_words_and_not_only_by_the_caret() {
877 let named = joined(¶graphs_after_fence()[0]);
878 assert!(
879 named.contains("store.read("),
880 "element (c) must name the method whose call is ambiguous: {named}"
881 );
882 assert!(
883 names_both_flavours(&named),
884 "element (c) must name both flavours, because the caret line names \
885 neither: {named}"
886 );
887 assert!(
888 named.contains("in scope"),
889 "element (c) must state the cause — both being in scope — and not merely \
890 that something is ambiguous: {named}"
891 );
892 }
893
894 /// Both trait names appear in the section's prose, not only inside the fence.
895 ///
896 /// The falsification of the design's anti-pattern 15, executed: delete the
897 /// transcript and the diagnosis has to survive.
898 #[test]
899 fn the_diagnosis_survives_the_fence_being_deleted() {
900 let fence = fence();
901 let outside: Vec<&str> = section_body()
902 .into_iter()
903 .filter(|line| !fence.contains(line))
904 .collect();
905 assert!(
906 names_both_flavours(&joined(&outside)),
907 "with the transcript removed the remaining prose names one flavour or \
908 neither, so colour, highlighting and spatial position are carrying the \
909 diagnosis alone"
910 );
911 }
912
913 // ---- AC-003: unstuck without a hop, the fix ahead of the pointer ---------
914
915 /// The signed-off composition, in source order, with nothing between (c) and (d).
916 ///
917 /// Four paragraphs and exactly four: separating the diagnosis from its fix is
918 /// what turns a self-sufficient page into one that requires a hop, and an
919 /// inserted paragraph is how that happens by accident.
920 #[test]
921 fn the_section_composes_in_the_designs_binding_order() {
922 let paragraphs = paragraphs_after_fence();
923 assert_eq!(
924 paragraphs.len(),
925 4,
926 "the fence is followed by exactly elements (c) the plain-words \
927 diagnosis, (d) the in-place fix, (e) the narrow limit and (f) the \
928 pointer. Nothing may be inserted between (c) and (d)"
929 );
930 assert!(
931 joined(¶graphs[1]).contains("SendEventStore::read(&store, &query, options)"),
932 "element (d), the fully-qualified escape hatch, must be the paragraph \
933 immediately after the plain-words diagnosis"
934 );
935 assert!(
936 joined(¶graphs[2]).contains("compile_fail,E0034"),
937 "element (e), the narrow limit, follows the fix"
938 );
939 assert!(
940 joined(¶graphs[3]).contains("docs/adapter-reading-order.md"),
941 "element (f), the pointer, is last"
942 );
943 }
944
945 /// A reader who never follows the pointer is still correctly unstuck.
946 ///
947 /// Executed rather than asserted: element (f) is deleted here and the rest of
948 /// the section still has to resolve the error on its own.
949 #[test]
950 fn deleting_the_pointer_leaves_the_reader_unstuck() {
951 let paragraphs = paragraphs_after_fence();
952 let kept: Vec<&str> = paragraphs[..paragraphs.len() - 1]
953 .iter()
954 .flatten()
955 .copied()
956 .collect();
957 let remaining = joined(&kept);
958 assert!(
959 !remaining.contains("docs/adapter-reading-order.md"),
960 "the pointer is the last paragraph and nothing else"
961 );
962 assert!(
963 remaining.contains("Import only the one"),
964 "with the reasoning account gone the import rule must still be here"
965 );
966 assert!(
967 remaining.contains("SendEventStore::read(&store, &query, options)"),
968 "with the reasoning account gone the escape hatch must still be here: \
969 deleting the destination may not leave a reader stuck on this page"
970 );
971 }
972
973 // ---- AC-004: the narrow limit, not the broad one -------------------------
974
975 /// The page states what is checked and what is not, and the true half is the
976 /// one that is easy to lose.
977 #[test]
978 fn the_limit_stated_is_the_narrow_one() {
979 let limit = joined(¶graphs_after_fence()[2]);
980 assert!(
981 limit.contains("`text` fence") && limit.contains("nothing compiles it"),
982 "element (e) must say the fence is uncompiled: {limit}"
983 );
984 assert!(
985 limit.contains("compile_fail,E0034")
986 && limit.contains("standards/rust/20-two-flavour-ports.md")
987 && limit.contains("standards/rust/00-prime-directives.md"),
988 "element (e) must name the compiled negatives that really do assert the \
989 error code, or it discards a guard that exists: {limit}"
990 );
991 assert!(
992 limit.contains("asserted by nothing"),
993 "element (e) must say which half is unasserted — the notes' wording and \
994 the internal type name: {limit}"
995 );
996 }
997
998 /// The broad falsehood, named so it cannot creep back as a simplification.
999 #[test]
1000 fn the_page_never_claims_that_nothing_checks_this() {
1001 assert!(
1002 !joined(&doc_lines()).contains("nothing checks this"),
1003 "\"nothing checks this\" is wrong in the direction that discards a real \
1004 guard: the error code is asserted by two compiled negatives in the \
1005 constitution"
1006 );
1007 }
1008
1009 // ---- AC-005: one recessive, correctly-formed pointer ---------------------
1010
1011 /// Exactly one hop, last, with no heading of its own.
1012 #[test]
1013 fn one_recessive_pointer_closes_the_section() {
1014 let mentions = section_body()
1015 .iter()
1016 .filter(|line| line.contains("docs/adapter-reading-order.md"))
1017 .count();
1018 assert_eq!(
1019 mentions, 1,
1020 "exactly one hop leaves the section. A second pointer is the moment the \
1021 page starts requiring a reader to leave it"
1022 );
1023 let paragraphs = paragraphs_after_fence();
1024 let pointer = joined(paragraphs.last().unwrap());
1025 assert!(
1026 pointer.contains("the adapter reading order"),
1027 "the link text is a self-describing noun phrase naming the destination, \
1028 because it is all a screen reader or an extracted link list gives the \
1029 reader: {pointer}"
1030 );
1031 assert!(
1032 !pointer.contains("http://") && !pointer.contains("https://"),
1033 "a bare URL is guarded by nothing and is forbidden to this project \
1034 outright: {pointer}"
1035 );
1036 assert!(
1037 !pointer.contains('['),
1038 "never an intra-doc link: the destination is a narrative page, not an \
1039 item, and no link form resolves in all three of the gate's rustdoc \
1040 builds. The named-but-unlinked cross-reference is the rung this pointer \
1041 took: {pointer}"
1042 );
1043 }
1044
1045 /// The pointer is carried by order and by having no heading, and by nothing else.
1046 #[test]
1047 fn the_pointer_is_recessive_and_the_section_grows_no_appendix() {
1048 assert!(
1049 !section_body().iter().any(|line| line.starts_with('#')),
1050 "the pointer takes no heading of its own; the moment it stops being \
1051 recessive, a reader starts treating the hop as required"
1052 );
1053 let doc = joined(&doc_lines());
1054 for block in ["See also", "Next steps", "Further reading"] {
1055 assert!(
1056 !doc.contains(block),
1057 "a {block:?} block is a second navigation surface bolted onto a page \
1058 that already reads in order"
1059 );
1060 }
1061 }
1062
1063 // ---- AC-008: the surface obeys the signed-off design ---------------------
1064
1065 /// Four heading entries, no fifth, no level skipped to reach one.
1066 #[test]
1067 fn the_heading_ladder_stays_at_four_entries() {
1068 let outside = doc_lines_outside_fences();
1069 let top = outside.iter().filter(|line| line.starts_with("# ")).count();
1070 let second = outside
1071 .iter()
1072 .filter(|line| line.starts_with("## "))
1073 .count();
1074 let deeper = outside
1075 .iter()
1076 .filter(|line| line.starts_with("### "))
1077 .count();
1078 assert_eq!(
1079 (top, second, deeper),
1080 (1, 3, 0),
1081 "the ladder is `# Why there are two traits` and three `##` entries. A \
1082 fifth entry, or a level skipped to reach one, is a page reorganising \
1083 itself around a single insertion"
1084 );
1085 }
1086
1087 /// No `##` whose entire body is one sentence — a heading that earns its place
1088 /// has something under it.
1089 #[test]
1090 fn no_heading_carries_a_single_sentence_body() {
1091 let outside = doc_lines_outside_fences();
1092 let heads: Vec<usize> = outside
1093 .iter()
1094 .enumerate()
1095 .filter(|(_, line)| line.starts_with("## "))
1096 .map(|(index, _)| index)
1097 .collect();
1098 for (position, start) in heads.iter().enumerate() {
1099 let end = heads.get(position + 1).copied().unwrap_or(outside.len());
1100 let filled = outside[start + 1..end]
1101 .iter()
1102 .filter(|line| !line.is_empty())
1103 .count();
1104 assert!(
1105 filled >= 3,
1106 "`{}` carries {filled} lines of body. A `##` whose whole body is one \
1107 sentence is a heading doing the work of a sentence",
1108 outside[*start]
1109 );
1110 }
1111 }
1112
1113 /// The density budget, with the real number the design measured.
1114 #[test]
1115 fn the_section_stays_inside_its_density_budget() {
1116 let measured = section_body().len();
1117 assert!(
1118 measured <= SECTION_LINE_CAP,
1119 "the section measures {measured} source lines against a cap of \
1120 {SECTION_LINE_CAP}. The yield order is (1) the limit sentence \
1121 compresses to one clause, (2) the connective prose around the pointer, \
1122 (3) the fence's non-`= note:` context lines — and the two `= note:` \
1123 lines and the internal type name never yield"
1124 );
1125 }
1126
1127 /// Everything added is persistent chrome: nothing folds, tabs or hides.
1128 #[test]
1129 fn every_element_is_persistent_chrome() {
1130 let doc = joined(&doc_lines());
1131 for widget in ["<details", "<summary", "<div", "<table", "<span", "style="] {
1132 assert!(
1133 !doc.contains(widget),
1134 "{widget:?} in the module doc. This project installs no revealed and \
1135 no opened-on-demand affordance of its own, and raw HTML also \
1136 defeats rustdoc's own theme contrast"
1137 );
1138 }
1139 }
1140
1141 // ---- AC-009: the search keys, by a stated rule ---------------------------
1142
1143 /// The keys are exactly the two strings rustc printed, and each one is still
1144 /// visible in the transcript on this page.
1145 ///
1146 /// The second half is the cheap check the design recorded as *not existing*: an
1147 /// alias whose string no longer appears in the block it was taken from has gone
1148 /// stale, and nothing else in the workspace would notice.
1149 #[test]
1150 fn every_search_key_is_a_string_rustc_printed_on_this_page() {
1151 let attributes: Vec<&str> = production_source()
1152 .lines()
1153 .filter(|line| line.starts_with("#[doc(alias"))
1154 .collect();
1155 assert_eq!(
1156 attributes,
1157 [
1158 "#[doc(alias = \"E0034\")]",
1159 "#[doc(alias = \"TraitVariantBlanketType\")]"
1160 ],
1161 "the rule admits only strings rustc, the specification or a recorded \
1162 reader question actually emits — not synonyms, and not the item's own \
1163 name"
1164 );
1165 let fence = joined(&fence());
1166 for key in ["E0034", "TraitVariantBlanketType"] {
1167 assert!(
1168 fence.contains(key),
1169 "the search key {key:?} no longer appears in the transcript it was \
1170 taken from, so the key and the page have drifted apart"
1171 );
1172 assert!(
1173 !"SendEventStore".contains(key),
1174 "a key may not be the item's own name or a substring of it: {key}"
1175 );
1176 }
1177 }
1178
1179 /// The attributes sit where `trait_variant` copies them onto the derived flavour.
1180 ///
1181 /// Two attributes, not the three the design projected, and the reason is
1182 /// mechanical rather than editorial: `SendEventStore` is *derived*, and the
1183 /// expansion rebuilds it with `..tr.clone()`, which copies the trait's
1184 /// attributes verbatim. There is no second item to write an attribute on, and
1185 /// two written here are four entries in the search index — a superset of the
1186 /// three the design asked for. Position is the whole mechanism, so position is
1187 /// what is asserted.
1188 ///
1189 /// **Position is a proxy, and the second assertion is what stops it being a
1190 /// silent one.** That the attributes sit above the derivation is necessary and
1191 /// not sufficient: the copying itself is upstream behaviour, and a
1192 /// `trait-variant` release that stopped doing it would leave this test green
1193 /// and `SendEventStore` carrying no search key at all. Nothing in this
1194 /// repository can observe the expansion, so the version is asserted instead.
1195 /// That holds for this workspace's own builds only. Its gate builds `--locked`,
1196 /// so the resolved version cannot move without someone changing it deliberately,
1197 /// and changing it is the moment to re-read `variant.rs`. A consumer's resolve
1198 /// is not locked and can float past it (ADR-0092). There the derivation's
1199 /// *types* are held by `derivation.rs`, compiled into every build of this
1200 /// crate, and the copying is held only by the guard in the parenthesis below,
1201 /// which a consumer's build does not run. The weekly `floating-deps` CI job
1202 /// runs `tests/trait_variant_pin.rs` against an unlocked resolve, so a new
1203 /// release turns that test red there first. (The other half has a guard:
1204 /// `SendEventStore` has no doc comment of its own, so if attributes stopped
1205 /// being copied, `missing_docs`, `warn` in the workspace lints and `-D
1206 /// warnings` in the gate, would fail the build.)
1207 #[test]
1208 fn the_search_keys_sit_where_trait_variant_copies_them_to_both_flavours() {
1209 let lines: Vec<&str> = production_source().lines().collect();
1210 let make = lines
1211 .iter()
1212 .position(|line| line.trim_end() == "#[trait_variant::make(SendEventStore: Send)]")
1213 .expect("the derivation that causes the collision this page documents");
1214 assert_eq!(lines[make - 2].trim_end(), "#[doc(alias = \"E0034\")]");
1215 assert_eq!(
1216 lines[make - 1].trim_end(),
1217 "#[doc(alias = \"TraitVariantBlanketType\")]"
1218 );
1219 assert_eq!(
1220 lines[make + 1].trim_end(),
1221 "pub trait EventStore {",
1222 "the attributes must sit on the trait the derivation copies from, or the \
1223 `Send` flavour carries no search key at all"
1224 );
1225 // The other half of this proof — that `trait-variant` is still the
1226 // version whose `variant.rs` was actually read, without which the
1227 // position asserted above is a silent proxy — lives in
1228 // `tests/trait_variant_pin.rs`. It has to: it reads the workspace
1229 // `Cargo.lock`, and an `include_str!` from a file under `src/` reaches
1230 // outside this package, which ships. Both still run in the workspace.
1231 }
1232}
1233
1234/// The trait-level doc block, read as text because it is published on **two**
1235/// pages.
1236///
1237/// `#[trait_variant::make(SendEventStore: Send)]` rebuilds the derived trait with
1238/// `..tr.clone()`, so every `///` line above the derivation is rendered verbatim
1239/// on `SendEventStore`'s page as well as on [`EventStore`]'s. That copying is not
1240/// an accident to be worked around — the module above *depends* on it, because
1241/// `SendEventStore` has no doc comment of its own and `missing_docs` would fail
1242/// the build the moment it stopped. One attribute set therefore serves two items,
1243/// and the obligation that follows is the one no compiler can state: **a sentence
1244/// in this block has to be true on both pages.**
1245///
1246/// The wrong implementation this rejects is the one that shipped through
1247/// `0.2.0-alpha.1` — "This is the `!Send` flavour … implement `SendEventStore`
1248/// instead" — rendered unchanged on `SendEventStore`, where the first clause is
1249/// false and the second is circular. Deixis is what breaks — "this trait", "the
1250/// one to use", "instead" all resolve against *the page*, and the page is not
1251/// fixed. Naming a flavour does not break, which is why the second test demands
1252/// it rather than merely permitting it.
1253///
1254/// The alternative that lost: write the flavour-specific sentences on the derived
1255/// trait instead. There is no derived trait to write them on — it exists only in
1256/// the expansion — and suppressing the copy to hand-write two doc blocks would
1257/// abandon `missing_docs` as the standing guard the module above relies on.
1258///
1259/// The extractor below is duplicated in `projection.rs`, which carries the same
1260/// defect behind the same derivation. Sharing it would mean a test-only module in
1261/// the crate root, and the crate root is the file `happenstance`'s
1262/// `contract_surface.rs` derives every gate from; twenty lines of test helper are
1263/// the cheaper of the two.
1264#[cfg(test)]
1265mod derived_flavour_doc {
1266 #![allow(clippy::unwrap_used, reason = "test code, per the house style")]
1267
1268 use alloc::string::String;
1269 use alloc::vec::Vec;
1270
1271 /// This file's own source. The doc block is the deliverable, so it is read
1272 /// rather than trusted.
1273 const SOURCE: &str = include_str!("store.rs");
1274
1275 /// The derivation whose expansion copies the block above it onto a second page.
1276 const DERIVATION: &str = "#[trait_variant::make(SendEventStore: Send)]";
1277
1278 /// The two flavours, in the link form a reader can click from either page.
1279 const FLAVOURS: [&str; 2] = ["[`EventStore`]", "[`SendEventStore`]"];
1280
1281 /// The `///` lines the derivation copies, marker removed and fences dropped.
1282 ///
1283 /// Fences are dropped because a doctest is code: `S: EventStore` in an example
1284 /// is a bound, not a sentence, and holding it to a prose rule would forbid the
1285 /// one thing the example exists to show.
1286 fn copied_prose() -> Vec<&'static str> {
1287 let lines: Vec<&str> = SOURCE.lines().collect();
1288 let make = lines
1289 .iter()
1290 .position(|line| line.trim_end() == DERIVATION)
1291 .expect("the derivation that copies this block onto the second page");
1292 let start = lines[..make]
1293 .iter()
1294 .rposition(|line| {
1295 !(line.starts_with("///") || line.starts_with("//") || line.starts_with("#["))
1296 })
1297 .map_or(0, |index| index + 1);
1298 let mut fenced = false;
1299 lines[start..make]
1300 .iter()
1301 .filter_map(|line| {
1302 let text = line.strip_prefix("///")?;
1303 let text = text.strip_prefix(' ').unwrap_or(text);
1304 if text.trim_start().starts_with("```") {
1305 fenced = !fenced;
1306 return None;
1307 }
1308 if fenced { None } else { Some(text) }
1309 })
1310 .collect()
1311 }
1312
1313 /// The copied prose in blank-line-separated paragraphs.
1314 ///
1315 /// The paragraph is the unit, not the sentence, because a sentence split on
1316 /// `.` fragments `https://docs.rs/…` and every fragment then satisfies the
1317 /// rule below vacuously.
1318 fn paragraphs() -> Vec<String> {
1319 copied_prose()
1320 .split(|line| line.is_empty())
1321 .filter(|block| !block.is_empty())
1322 .map(|block| block.join(" "))
1323 .collect()
1324 }
1325
1326 /// A paragraph that distinguishes the flavours names them; it does not point.
1327 ///
1328 /// Rejects the shipped text three times over, and rejects any future sentence
1329 /// that says "this" where the reader may be standing on either page.
1330 #[test]
1331 fn no_paragraph_tells_the_flavours_apart_by_deixis() {
1332 /// Pointers that resolve against the page rather than against a name.
1333 const DEIXIS: [&str; 6] = [
1334 "this trait",
1335 "this is",
1336 "this flavour",
1337 "this one",
1338 "the one to use",
1339 "instead",
1340 ];
1341 for paragraph in paragraphs() {
1342 let lower = paragraph.to_lowercase();
1343 // Only paragraphs that draw the distinction are held to the rule:
1344 // `# Implementing this trait` is true on both pages and stays.
1345 if !lower.contains("send") {
1346 continue;
1347 }
1348 for pointer in DEIXIS {
1349 assert!(
1350 !lower.contains(pointer),
1351 "{DERIVATION} copies this paragraph verbatim onto \
1352 `SendEventStore`, where {pointer:?} points at the wrong trait. \
1353 Name the flavour: {paragraph}"
1354 );
1355 }
1356 }
1357 }
1358
1359 /// Both flavours are named, in link form, in the prose a reader lands on.
1360 ///
1361 /// The negative test above is satisfiable by saying nothing at all, and
1362 /// `missing_docs` is satisfied by one line. This is what stops the fix from
1363 /// being deletion: whichever page a reader opens, the other flavour is a click
1364 /// away and the two are told apart by name.
1365 #[test]
1366 fn the_block_names_both_flavours_in_link_form() {
1367 let prose = copied_prose().join("\n");
1368 for flavour in FLAVOURS {
1369 assert!(
1370 prose.contains(flavour),
1371 "the block is rendered on both pages, so it must name {flavour} \
1372 rather than leave a reader to infer which trait they are on. \
1373 Prose as read:\n{prose}"
1374 );
1375 }
1376 }
1377}