Skip to main content

moqtap_proxy/
capability.rs

1//! What is representable, per draft, per site, per stream — and why not.
2//!
3//! One function answers that question — [`classify`] — and it has exactly
4//! two callers: [`Capabilities::supports`] / [`Capabilities::supports_on`],
5//! which publish the table a scenario author reads before a run, and the
6//! engine's executor, which decides what actually happens during one. That
7//! is the whole of the design: the table and the engine are the same code,
8//! so the table cannot become a documented lie about the engine.
9//! `tests/action_matrix.rs` asserts it against observed behaviour on all
10//! thirteen drafts.
11//!
12//! # Where each [`Refusal`] comes from
13//!
14//! Not every refusal is a `(site, kind)` fact, so not every refusal is
15//! [`classify`]'s to produce:
16//!
17//! * **Classified here**, from `(site, kind)` plus [`CapCtx`]:
18//!   [`Refusal::WrongSite`], [`Refusal::ControlStreamResetIllegal`],
19//!   [`Refusal::LengthChanged`], [`Refusal::WouldRedefineSubgroupId`],
20//!   [`Refusal::WouldDestroyStatusObject`], [`Refusal::ReservedHeaderMode`] and
21//!   [`Refusal::PayloadNotDelimited`].
22//! * **Produced by the executor**, because they depend on the action's payload
23//!   or on session state rather than on the pair: [`Refusal::WrongComposition`]
24//!   (what a `Delay` / `Hold` wrapped), [`Refusal::ErrorCodeOutOfRange`] (the
25//!   numeric code) and [`Refusal::SessionAlreadyClosing`] (a close already in
26//!   flight). They are reachable, and the sweep observes them; they are simply
27//!   not decidable from a kind.
28//! * **Table-only**: [`Refusal::StreamNotFramed`] and
29//!   [`Refusal::ControlFrameNotDecodable`]. Both appear only inside
30//!   [`Support::NotAttemptable`] and [`Support::Unreachable`], where nothing is
31//!   ever attempted, so neither is ever emitted as a
32//!   `ProxyEvent::ActionRefused`.
33//!
34//! `tests/action_matrix.rs::every_declared_refusal_is_reachable_or_declared_table_only`
35//! asserts that split per *variant*, in both directions.
36//!
37//! # The table answers for a **build**, not only for a draft
38//!
39//! [`DraftVersion`] carries all thirteen variants under every feature set,
40//! so [`Capabilities::for_draft`] answers for drafts this binary cannot
41//! speak. A reduced-draft build — `--no-default-features --features
42//! draft07`, a shipped configuration and one of CI's fourteen rows — cannot
43//! frame a byte of the twelve drafts it left out, and
44//! `ProxySessionConfig::default().draft` is `Draft14` with nothing
45//! validating it against the compiled set. [`draft_is_compiled`] is
46//! therefore a fact [`classify`] reads, exactly like the draft number, and
47//! the object **and control** sites on an uncompiled draft are
48//! [`Support::Unreachable`] rather than [`Support::Yes`]. The two fail in
49//! different decoders and report different events, so they are two reads
50//! of the same fact rather than one; see [`Instead`], which is where each
51//! names what a run emits in its place. In the default all-drafts build
52//! every row of the table is unchanged.
53
54use moqtap_codec::version::DraftVersion;
55
56use crate::shape::{ClassRule, MatchKind, Matcher, ShapeProfile};
57use crate::types::BypassReason;
58use crate::types::DataStreamType;
59
60/// The fourth value of the two-bit subgroup-ID mode, which no draft assigns.
61///
62/// Drafts 16 through 19 reserve it by name and list the type bytes that carry
63/// it; draft-15 arrives at the same eight bytes by leaving them out of its
64/// table. Either way no header the decoder returns holds this value.
65///
66/// The codec stores a placeholder zero for **both** mode 1 (*subgroup ID is the
67/// first object's ID*) and this one, which is why [`CapCtx::subgroup_id_mode`]
68/// exists at all: without it a reserved-mode header is indistinguishable from a
69/// first-object-mode header and the elide guard reports
70/// [`Refusal::WouldRedefineSubgroupId`] for something that is not a subgroup ID
71/// question.
72const RESERVED_SUBGROUP_ID_MODE: u8 = 3;
73
74/// Where a decision was taken.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum Site {
78    /// [`ProxyHook::on_control_message`](crate::hook::ProxyHook::on_control_message).
79    Control,
80    /// [`ProxyHook::on_object`](crate::hook::ProxyHook::on_object).
81    Object,
82    /// [`ProxyHook::on_datagram`](crate::hook::ProxyHook::on_datagram).
83    Datagram,
84    /// [`ProxyHook::on_stream_open`](crate::hook::ProxyHook::on_stream_open).
85    StreamOpen,
86    /// [`ProxyHook::on_stream_header`](crate::hook::ProxyHook::on_stream_header).
87    StreamHeader,
88    /// [`ProxyHook::on_stream_end`](crate::hook::ProxyHook::on_stream_end).
89    ///
90    /// Honours [`Action::Pass`](crate::action::Action::Pass),
91    /// [`Action::ResetStream`](crate::action::Action::ResetStream) on a
92    /// **data** stream, and
93    /// [`Action::CloseSession`](crate::action::Action::CloseSession) on
94    /// either kind of stream — a session close is session-scoped, so no
95    /// site can be the wrong one for it. Everything else is refused;
96    /// delaying a stream's end is expressed by delaying its last object.
97    /// [`CapCtx::is_control_stream`] is what splits the two published
98    /// columns.
99    StreamEnd,
100}
101
102/// A capability, named independently of whether
103/// [`Action`](crate::action::Action) can express it.
104///
105/// Every kind here names a capability some value can express. A kind that
106/// nothing could construct used to be published too, so the table could
107/// document the gap — but a variant that no value can carry is a unit that
108/// compiles and never runs, and a table row saying so is a row about this
109/// crate's plans rather than about what it does. Two such kinds were
110/// removed; the capabilities they named are simply absent, and absence is
111/// what the table now says by not listing them.
112///
113/// [`Self::OpenAfter`] and [`Self::SerializeAfter`] were in that family
114/// until 0.4.0, when that release shipped
115/// [`StreamAction::OpenAfter`](crate::action::StreamAction::OpenAfter) and
116/// [`StreamAction::SerializeAfter`](crate::action::StreamAction::SerializeAfter);
117/// their rustdoc now carries ordinary doc-tests that *construct* them,
118/// where it used to carry `compile_fail` blocks that could not.
119///
120/// [`Self::ReplaceObject`] is deliberately **not** in that family, and the
121/// distinction is what keeps the table honest: a value that carries it to
122/// [`Site::Object`] exists (`Action::Replace(b)`), so the engine really is
123/// asked and really does refuse, with [`Refusal::WrongSite`]. The
124/// deferred-capability id printed on the *variant* names the gap; it is
125/// not the refusal a run emits. See the variant's own rustdoc.
126///
127/// **Attempt mapping** — how `tests/action_matrix.rs` turns a `(site,
128/// kind)` pair into something to run. Every kind maps to exactly one
129/// expression, and a kind whose mapping does not typecheck at a site is
130/// precisely a `NotAttemptable` cell:
131///
132/// | Kind | The attempt |
133/// |---|---|
134/// | `Pass` | `Action::Pass` |
135/// | `Replace` | `Action::Replace(b)` |
136/// | `ReplacePayload` | `Action::ReplacePayload(b)`, `b.len() == payload_len` |
137/// | `ReplaceObject` | `Action::Replace(b)` **at `Site::Object` only** — the same expression as `Replace`, so those two cells must agree, and `action_matrix.rs` asserts that they do. At every other site there is no attempt: the same expression there is `Replace`'s attempt, and this kind names a unit those sites do not carry (`NotAttemptable::KindNotDefinedAtThisSite`) |
138/// | `Delay` | `Action::Pass.delayed(d)` |
139/// | `Hold` | `Action::Pass.held(gate)` |
140/// | `DropElide` | `Action::Drop(DropMode::Elide)` |
141/// | `Truncate` | `Action::Truncate { bytes, code }` |
142/// | `ResetStream` | `Action::ResetStream { code }` |
143/// | `CloseSession` | `Action::CloseSession { code, reason }` |
144/// | `Open` | `StreamAction::Open` |
145/// | `Reject` | `StreamAction::Reject { code }` |
146/// | `OpenAfter` | `StreamAction::OpenAfter(d)` |
147/// | `SerializeAfter` | `StreamAction::SerializeAfter(key)` |
148///
149/// `Action::ReplacePayload` with a mismatched length **is** constructible,
150/// and it is refused with [`Refusal::LengthChanged`] — the `ReplacePayload`
151/// cell's `Conditional` failing. Re-framing an object around a new length
152/// is a different capability, and it has no row here because it has no
153/// value: there is nothing to attempt and therefore nothing to refuse.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155#[non_exhaustive]
156pub enum ActionKind {
157    /// [`Action::Pass`](crate::action::Action::Pass).
158    Pass,
159    /// [`Action::Replace`](crate::action::Action::Replace).
160    Replace,
161    /// [`Action::ReplacePayload`](crate::action::Action::ReplacePayload) at
162    /// the original length.
163    ReplacePayload,
164    /// [`Action::Delay`](crate::action::Action::Delay).
165    Delay,
166    /// [`Action::Hold`](crate::action::Action::Hold).
167    Hold,
168    /// [`Action::Drop`](crate::action::Action::Drop) with
169    /// [`DropMode::Elide`](crate::action::DropMode::Elide).
170    DropElide,
171    /// [`Action::Truncate`](crate::action::Action::Truncate).
172    Truncate,
173    /// [`Action::ResetStream`](crate::action::Action::ResetStream).
174    ResetStream,
175    /// [`Action::CloseSession`](crate::action::Action::CloseSession).
176    CloseSession,
177    /// [`StreamAction::Open`](crate::action::StreamAction::Open).
178    Open,
179    /// [`StreamAction::Reject`](crate::action::StreamAction::Reject).
180    Reject,
181    /// Replacing a whole wire object. **Attemptable and refused, not
182    /// unconstructible** — `Action::Replace(b)` at [`Site::Object`] is
183    /// exactly this attempt, so the engine is really asked and answers
184    /// with [`Refusal::WrongSite`]. Whole-object replacement at the object
185    /// site is a real attempt that really is refused, which is why this
186    /// kind is published and why its refusal is one a run emits.
187    ///
188    /// At every non-object site it is
189    /// `NotAttemptable { why: KindNotDefinedAtThisSite, refusal:
190    /// WrongSite { site, action: ReplaceObject } }`: a control frame, a
191    /// datagram and a stream are not objects, so no value carries this
192    /// kind there and nothing is ever attempted.
193    ReplaceObject,
194    /// Opening the peer stream after a delay.
195    /// [`StreamAction::OpenAfter`](crate::action::StreamAction::OpenAfter),
196    /// shipped in 0.4.0; this kind is no longer in the constructor-less
197    /// family.
198    ///
199    /// `open_after_and_serialize_after_are_constructible` — the pair of
200    /// doc-tests that used to prove this capability's *absence* now proves
201    /// its presence, and they remain the crate's only compile-time proof
202    /// that the two variants exist with the shape they do. They are ordinary
203    /// doc-tests rather than inverted `compile_fail` blocks on purpose: a
204    /// `compile_fail` block that fails for the *wrong* reason reports `ok`
205    /// exactly as loudly as one that fails for the right one, which is how
206    /// the two blocks this replaces went on passing while asserting a
207    /// **struct**-variant syntax (`OpenAfter { after: … }`) that never
208    /// matched the tuple variants that actually exist. An ordinary
209    /// doc-test can only pass by compiling *and* running.
210    ///
211    /// ```
212    /// // open_after_and_serialize_after_are_constructible (1 of 2)
213    /// use std::time::Duration;
214    /// use moqtap_proxy::action::StreamAction;
215    ///
216    /// let a = StreamAction::OpenAfter(Duration::from_millis(1));
217    /// assert!(matches!(a, StreamAction::OpenAfter(d) if d == Duration::from_millis(1)));
218    /// ```
219    ///
220    /// ```
221    /// // open_after_and_serialize_after_are_constructible (2 of 2)
222    /// use moqtap_proxy::action::StreamAction;
223    /// use moqtap_proxy::event::ProxySide;
224    /// use moqtap_proxy::shape::StreamKey;
225    ///
226    /// // A session-local id plus the side it arrived on — never a
227    /// // transport stream id, which is the constant 0 on WebTransport.
228    /// let key = StreamKey { side: ProxySide::ClientToProxy, id: 7 };
229    /// let b = StreamAction::SerializeAfter(key);
230    /// assert!(matches!(b, StreamAction::SerializeAfter(k) if k == key));
231    /// ```
232    ///
233    /// And the verdicts, which is the one place the two kinds disagree:
234    /// `SerializeAfter` takes exactly the verdict
235    /// [`Self::Open`] takes at every site, and `OpenAfter` takes the same
236    /// except at [`Site::StreamHeader`], where the peer stream already
237    /// exists and there is nothing left to defer.
238    ///
239    /// ```
240    /// use moqtap_proxy::capability::{classify, ActionKind, CapCtx, Refusal, Site, Support};
241    /// for site in [Site::StreamOpen, Site::StreamHeader] {
242    ///     assert_eq!(
243    ///         classify(site, ActionKind::SerializeAfter, &CapCtx::default()),
244    ///         classify(site, ActionKind::Open, &CapCtx::default()),
245    ///         "SerializeAfter tracks Open at every site",
246    ///     );
247    /// }
248    /// assert_eq!(
249    ///     classify(Site::StreamOpen, ActionKind::OpenAfter, &CapCtx::default()),
250    ///     Support::Yes,
251    /// );
252    /// assert_eq!(
253    ///     classify(Site::StreamHeader, ActionKind::OpenAfter, &CapCtx::default()),
254    ///     Support::No(Refusal::WrongSite {
255    ///         site: Site::StreamHeader,
256    ///         action: ActionKind::OpenAfter,
257    ///     }),
258    /// );
259    /// ```
260    OpenAfter,
261    /// Head-of-line simulation.
262    /// [`StreamAction::SerializeAfter`](crate::action::StreamAction::SerializeAfter),
263    /// shipped in 0.4.0; this kind is no longer in the constructor-less
264    /// family either.
265    ///
266    /// Its constructor proof hangs on [`Self::OpenAfter`], with its pair,
267    /// as its `compile_fail` block used to.
268    SerializeAfter,
269}
270
271/// Whether a capability is available.
272///
273/// Five verdicts, not three. The earlier design had `Yes` / `No` /
274/// `Conditional` only, and a large part of the published matrix fits none
275/// of them: 30 site×kind pairs are ruled out by the *return type* (a site
276/// that returns [`StreamAction`](crate::action::StreamAction) cannot be
277/// handed an [`Action`](crate::action::Action), and four [`ActionKind`]s
278/// have no constructor at all), and every cell on a draft this build did not
279/// compile names a refusal the engine can never emit because the hook is
280/// never invoked there. Both classes used to be written `—` or "unreachable" in prose,
281/// which `tests/action_matrix.rs` cannot assert. They are now verdicts.
282#[derive(Debug, Clone, PartialEq, Eq)]
283#[non_exhaustive]
284pub enum Support {
285    /// The engine executes it and the wire changes.
286    Yes,
287    /// Attemptable, and the engine refuses it with this reason. Exactly
288    /// one `ProxyEvent::ActionRefused` per attempt.
289    No(Refusal),
290    /// Executable, gated on a per-unit fact the table caller did not
291    /// supply. The precondition is named so a scenario can test for it.
292    Conditional(Precondition),
293    /// **No value of [`Action`](crate::action::Action) or
294    /// [`StreamAction`](crate::action::StreamAction) can carry this kind to
295    /// this site**, so the engine can never be asked and no
296    /// `ActionRefused` can ever be emitted.
297    ///
298    /// Three families, and [`NotAttemptable`] names which:
299    ///
300    /// 1. a site whose return type is the other enum (`Pass` at
301    ///    `StreamOpen`, `Reject` at `Object`, …) — two variants,
302    ///    [`NotAttemptable::SiteReturnsAction`] and
303    ///    [`NotAttemptable::SiteReturnsStreamAction`], so that the table
304    ///    says which direction the mismatch runs in;
305    /// 2. a kind whose unit does not exist at this site —
306    ///    [`ActionKind::ReplaceObject`] anywhere but [`Site::Object`].
307    ///
308    /// `refusal` is what the published table reports and is never emitted
309    /// as an event. For both families it is a variant that *is* reachable
310    /// elsewhere in the matrix ([`Refusal::WrongSite`]). The split is per
311    /// *variant*, not per cell: a variant is table-only when no cell
312    /// anywhere emits it as a real `ActionRefused`.
313    /// What the sweep observes is **zero action events** — no `ActionApplied`,
314    /// no `ActionRefused`, no `ActionFailed` — and `actions_refused` unchanged.
315    /// It is not *zero events of any kind*: per-stream impairments are a
316    /// property of the stream, not of the kind swept, so a stream the framer
317    /// gave up on still reports its one `Impairment { FramerBypass { .. } }`
318    /// while every `NotAttemptable` cell on it stays silent.
319    NotAttemptable {
320        /// Which family, so a reader is not left to infer it.
321        why: NotAttemptable,
322        /// What the table reports. Never emitted as an event.
323        refusal: Refusal,
324    },
325    /// Constructible and well-formed, but the hook is **never invoked**
326    /// for this cell, so nothing is ever attempted and no `ActionRefused`
327    /// is ever emitted.
328    ///
329    /// Two occupants, each reporting what the run does emit rather than
330    /// the refusal it cannot. Both are a draft this build did not compile,
331    /// one decoder apart — see `object_framing_bypass`:
332    ///
333    /// 1. **any** stream on such a draft, where the stream *header* decode
334    ///    returns `UnsupportedDraft` first — see [`draft_is_compiled`], which
335    ///    is why this verdict is a build fact and not only a draft fact.
336    /// 2. the **control** site on such a draft, where
337    ///    `AnyControlMessage::decode` has no arm and
338    ///    `ControlStreamParser::feed` steps over every frame before the
339    ///    hook is offered one. Same fact as case 1, a different decoder,
340    ///    and a different report — which is what [`Instead`] is for.
341    ///
342    /// There was a third, and its going is worth a sentence because it is
343    /// the shape of thing this enum is easiest to be wrong about. A fetch
344    /// stream on drafts 18 and 19 used to occupy this verdict, on the
345    /// grounds that nothing on such a stream settles the Group Order its
346    /// Group IDs are differences against. Nothing on the *stream* still
347    /// does; the FETCH that opened it always did, and the session reads it
348    /// now — see `fetch_group_order_is_needed`. The cell was answering a
349    /// question about a draft with a fact about one component.
350    ///
351    /// A caller that reads the table by draft number alone will not see
352    /// case 1 coming, which is why the table answers by build rather than by
353    /// number. It is not a state a *session* can now reach —
354    /// [`ProxySession::run`](crate::session::ProxySession::run) refuses an
355    /// uncompiled draft with
356    /// [`ProxyError::DraftNotCompiled`](crate::error::ProxyError::DraftNotCompiled)
357    /// before it dials — but the table is answerable without a session, and a
358    /// caller asking it about a draft this build does not carry has to be
359    /// told the truth about that draft rather than about draft numbers in
360    /// general.
361    Unreachable {
362        /// What the table reports. Never emitted as an event.
363        refusal: Refusal,
364        /// What the run emits instead, and how often.
365        instead: Instead,
366    },
367}
368
369/// What a run reports in place of the action event a
370/// [`Support::Unreachable`] cell can never produce.
371///
372/// Every `Unreachable` cell owes one, and giving the field a type of its own is
373/// what collects the debt: a cell whose only honest answer would be *nothing at
374/// all is emitted* finds no variant here to reach for, so it cannot be
375/// published until the report it needs exists. The control site on an
376/// uncompiled draft sat outside this enum for exactly that reason, answering
377/// [`Support::Yes`] for a cell no hook is ever offered, until
378/// [`ImpairmentKind::ControlFrameNotDecodable`](crate::event::ImpairmentKind::ControlFrameNotDecodable)
379/// gave it something true to point at.
380///
381/// The field is not a second copy of `refusal`. A refusal names what the
382/// *table* would say; this names what an observer will actually see on the
383/// wire-facing side, which is the only thing a run can be checked against.
384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385#[non_exhaustive]
386pub enum Instead {
387    /// [`ProxyEvent::Impairment`](crate::event::ProxyEvent::Impairment)
388    /// carrying
389    /// [`ImpairmentKind::FramerBypass`](crate::event::ImpairmentKind::FramerBypass)
390    /// with this reason, **once per such stream**.
391    FramerBypass(BypassReason),
392    /// [`ProxyEvent::Impairment`](crate::event::ProxyEvent::Impairment)
393    /// carrying
394    /// [`ImpairmentKind::ControlFrameNotDecodable`](crate::event::ImpairmentKind::ControlFrameNotDecodable),
395    /// **once per control stream direction**, however many frames were
396    /// refused; the running figure is
397    /// [`Counters::control_frames_not_decodable`](crate::instrument::Counters::control_frames_not_decodable).
398    ///
399    /// Carries no reason, because on this cell there is only one: the
400    /// build. A frame refused on a draft that *was* compiled produces the
401    /// same event and no table cell, since it is a fact about one frame.
402    ControlFrameNotDecodable,
403}
404
405/// Why a [`Support::NotAttemptable`] cell cannot be reached.
406#[derive(Debug, Clone, Copy, PartialEq, Eq)]
407#[non_exhaustive]
408pub enum NotAttemptable {
409    /// This site's hook method returns
410    /// [`StreamAction`](crate::action::StreamAction), and `kind` names a
411    /// content action.
412    SiteReturnsStreamAction,
413    /// This site's hook method returns [`Action`](crate::action::Action),
414    /// and `kind` names a stream action.
415    SiteReturnsAction,
416    /// No value of [`Action`](crate::action::Action) or
417    /// [`StreamAction`](crate::action::StreamAction) carries this kind to
418    /// this site, so nothing here can be attempted.
419    NoConstructor,
420    /// The kind names a unit this site does not carry, so no value can
421    /// bring it here even though the *expression* that would carry it is
422    /// well-typed at this site under a different kind.
423    ///
424    /// The only occupant is [`ActionKind::ReplaceObject`] at any
425    /// site but [`Site::Object`]: `Action::Replace(b)` typechecks at
426    /// `Site::Control` and `Site::Datagram`, but there it *is* the
427    /// [`ActionKind::Replace`] attempt — a control frame is not an
428    /// object. The accompanying refusal is
429    /// [`Refusal::WrongSite`], the same refusal the attemptable
430    /// `ReplaceObject × Object` cell really emits, so a reader comparing
431    /// the table against a run sees one consistent answer.
432    KindNotDefinedAtThisSite,
433}
434
435// ── Table-only refusals ────────────────────────────────────────────────
436//
437// `Support::NotAttemptable` and `Support::Unreachable` both carry a
438// `Refusal` the engine never emits, because in both cases nothing is ever
439// attempted. Exactly one `Refusal` variant is table-only —
440// `Refusal::StreamNotFramed` — and
441// `tests/action_matrix.rs::every_declared_refusal_is_reachable_or_declared_table_only`
442// asserts that split in both directions: every other variant must be
443// observed as a real `ActionRefused` somewhere in the sweep, and this one
444// must never be.
445
446/// A runtime fact a [`Support::Conditional`] verdict depends on.
447#[derive(Debug, Clone, Copy, PartialEq, Eq)]
448#[non_exhaustive]
449pub enum Precondition {
450    /// The replacement must be exactly `ObjectMeta::payload_len` bytes and
451    /// the object must not carry a status.
452    ReplacementLengthEqualsPayload,
453    /// The object must not be index 0 of a stream whose subgroup ID is
454    /// defined as the first object's ID.
455    NotFirstObjectOfImplicitSubgroup,
456    /// The object must not carry an Object Status.
457    NotAStatusObject,
458    /// The unit's payload must start at a known offset.
459    ///
460    /// True at the object site on every draft (`wire_len -
461    /// payload_length`). At the **datagram** site it is true on
462    /// twelve drafts and false on three counts:
463    ///
464    /// * **draft-14**, where `AnyDatagramHeader` is a `DatagramObject`
465    ///   whose `decode` consumes the payload, so the only derivable
466    ///   offset is the whole datagram;
467    /// * a **status datagram**, which has no payload slot;
468    /// * a datagram whose header **did not decode**, where the hook still
469    ///   fires but no offset exists.
470    ///
471    /// Failing it is [`Refusal::PayloadNotDelimited`].
472    DatagramPayloadDelimited,
473    /// The replacement must fit the connection's maximum datagram size.
474    ///
475    /// **[`classify`] cannot evaluate this one.** Nothing in
476    /// `moqtap-client`'s transport exposes a maximum datagram size, so
477    /// [`CapCtx`] has no field for it and this verdict is always
478    /// `Conditional`: the actual answer comes from `send_datagram`
479    /// failing. That makes it the one precondition whose failure is a
480    /// `ProxyEvent::ActionFailed` rather than an `ActionRefused` — the
481    /// action was admitted and the transport rejected it. Stated here
482    /// rather than left to be inferred.
483    WithinMaxDatagramSize,
484}
485
486/// Why an action could not be executed.
487///
488/// Reported per attempt, never once per stream. A rule that would have
489/// fired forty times and was refused forty times reports forty.
490#[derive(Debug, Clone, PartialEq, Eq)]
491#[non_exhaustive]
492pub enum Refusal {
493    /// The action has no meaning at this site.
494    WrongSite {
495        /// Where it was attempted.
496        site: Site,
497        /// What was attempted.
498        action: ActionKind,
499    },
500    /// A `Delay` or `Hold` wrapped an action the engine cannot schedule.
501    WrongComposition {
502        /// What the modifier wrapped.
503        detail: &'static str,
504    },
505    /// Performing it would be a session-level protocol violation — a reset
506    /// or truncation of a control stream, on any draft 07-19.
507    ControlStreamResetIllegal,
508    /// `ReplacePayload` whose length differs from the original.
509    LengthChanged {
510        /// The original payload length.
511        from: u64,
512        /// The replacement's length.
513        to: u64,
514    },
515    /// Eliding index 0 of a stream whose subgroup ID is the first object's
516    /// ID would silently redefine the subgroup ID downstream.
517    WouldRedefineSubgroupId,
518    /// Eliding an object that carries an Object Status would destroy what
519    /// may be a boundary marker.
520    WouldDestroyStatusObject,
521    /// The stream header's subgroup-ID mode field holds a value this
522    /// draft reserves, so the header is not interpretable and no object
523    /// on the stream can be safely renumbered.
524    /// Distinct from [`Self::WouldRedefineSubgroupId`] on purpose. On drafts
525    /// 15 through 19 the codec stores a placeholder zero for **both** mode 1
526    /// (*subgroup ID is the first object's ID*) and mode 3 (reserved), so an
527    /// accessor returning `Option<u64>` cannot tell them apart and the earlier
528    /// guard would have reported `WouldRedefineSubgroupId` for a reserved-mode
529    /// header, where that reason is simply untrue.
530    /// `AnySubgroupHeader::subgroup_id_mode()` is what makes the distinction
531    /// available.
532    ReservedHeaderMode {
533        /// The mode value read from the header-type octet.
534        mode: u8,
535    },
536    /// The unit's payload boundary is not derivable, so a
537    /// payload-preserving splice cannot be located.
538    ///
539    /// Datagrams only. See [`Precondition::DatagramPayloadDelimited`] for
540    /// the three cases.
541    PayloadNotDelimited {
542        /// Which case: `*draft-14 header decode consumes the payload*`,
543        /// `*status datagram has no payload*`, or `*datagram header did not
544        /// decode*`.
545        detail: &'static str,
546    },
547    /// The framer stopped parsing this stream, so there is nothing
548    /// addressable to act on.
549    ///
550    /// **Table-only** — see the module's note above [`Precondition`]. The
551    /// engine never emits it, because when it is true the hook is never
552    /// called.
553    StreamNotFramed {
554        /// Why the framer gave up.
555        reason: BypassReason,
556    },
557    /// The decoder refused this control frame, so there is nothing decoded
558    /// to act on.
559    ///
560    /// **Table-only** — see the module's note above [`Precondition`]. The
561    /// engine never emits it, because when it is true
562    /// [`ProxyHook::on_control_message`](crate::hook::ProxyHook::on_control_message)
563    /// is never called: the message it would be handed is the thing that
564    /// did not decode.
565    ///
566    /// Published for a draft this build did not compile, where
567    /// `AnyControlMessage::decode` has no arm and refuses every frame the
568    /// stream carries. One malformed frame on a draft that *is* compiled
569    /// is refused for the same reason, but that is a fact about one frame
570    /// rather than about the pair the table answers for, so no cell
571    /// publishes it and the run reports it as
572    /// [`ImpairmentKind::ControlFrameNotDecodable`](crate::event::ImpairmentKind::ControlFrameNotDecodable)
573    /// instead.
574    ControlFrameNotDecodable,
575    /// The application error code exceeds the QUIC varint range
576    /// (2^62 - 1). Nothing was sent and the stream stays usable.
577    ErrorCodeOutOfRange {
578        /// The code that was requested.
579        code: u64,
580    },
581    /// A session close is already in flight.
582    SessionAlreadyClosing,
583}
584
585/// The facts [`classify`] needs.
586///
587/// A caller building the published table leaves the per-unit fields `None`
588/// and gets [`Support::Conditional`] where the answer depends on them; the
589/// engine fills them in and gets [`Support::Yes`] or [`Support::No`].
590///
591/// The struct is `#[non_exhaustive]`, so build one with
592/// [`CapCtx::default`] and assign the fields that are known.
593#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
594#[non_exhaustive]
595pub struct CapCtx {
596    /// The draft the session is running as.
597    pub draft: Option<DraftVersion>,
598    /// Which stream kind, at the object site.
599    pub stream_kind: Option<DataStreamType>,
600    /// Whether the stream is a control stream.
601    ///
602    /// Read at [`Site::StreamEnd`], which publishes two columns: `Some(true)`
603    /// selects the control column, and `Some(false)` or `None` the data one.
604    pub is_control_stream: Option<bool>,
605    /// Zero-based index of the object within its stream.
606    pub index_in_stream: Option<u64>,
607    /// Whether the stream header determines the subgroup ID.
608    pub subgroup_id_resolved: Option<bool>,
609    /// Whether the object carries an Object Status.
610    pub is_status_object: Option<bool>,
611    /// Declared payload length.
612    pub payload_len: Option<u64>,
613    /// Length of a proposed replacement payload.
614    pub replacement_len: Option<u64>,
615    /// Whether this unit's payload starts at a known offset.
616    ///
617    /// Always `Some(true)` at the object site. At the datagram site the
618    /// engine sets it from `data.len() - cursor.len()` being a real
619    /// boundary — false on draft-14, on a status datagram, and when the
620    /// header did not decode. Drives
621    /// [`Precondition::DatagramPayloadDelimited`].
622    pub payload_delimited: Option<bool>,
623    /// The two-bit subgroup-ID mode, on the drafts 15-19 whose header type
624    /// carries one. `None` on drafts 07-14, which have no such pair of bits,
625    /// and when the caller did not supply it. Mode 1 is *subgroup ID is the
626    /// first object's ID*; mode 3 is the value no draft assigns. Drives the
627    /// split between [`Refusal::WouldRedefineSubgroupId`] and
628    /// [`Refusal::ReservedHeaderMode`].
629    pub subgroup_id_mode: Option<u8>,
630}
631
632/// The single source of truth for what is executable.
633///
634/// [`Capabilities::supports`] and the engine's executor are its only two
635/// callers, which is what keeps the published table and the engine from
636/// disagreeing. `tests/action_matrix.rs` asserts the table against observed
637/// behaviour on all thirteen drafts.
638///
639/// # How the verdict is reached
640///
641/// In order, because the order is what makes [`ActionKind::ReplaceObject`]
642/// have exactly one reading:
643///
644/// 1. `ReplaceObject` off [`Site::Object`] is `NotAttemptable
645///    { KindNotDefinedAtThisSite, WrongSite { .. } }`, and at `Site::Object`
646///    it is the same `No(WrongSite { .. })` as `Replace` — one value for
647///    both rows, since one expression carries both.
648/// 3. A return-type mismatch is `NotAttemptable { SiteReturns.., WrongSite
649///    { .. } }`.
650/// 4. The object site behind a stream the framer cannot address is
651///    [`Support::Unreachable`]: the hook is never invoked there, so no
652///    refusal can be emitted and the run's reportable fact is the bypass.
653///    One fact reaches this step: a draft this build did not compile
654///    ([`draft_is_compiled`]). A fetch stream used to bring a second, and no
655///    longer does — see `fetch_group_order_is_needed` for where that went.
656/// 5. The control site on a draft this build did not compile is
657///    [`Support::Unreachable`] too, for the same reason one decoder later:
658///    every frame is stepped over before the hook is offered one.
659/// 6. Otherwise the per-site rules apply.
660///
661/// # What an unsupplied fact means
662///
663/// A `None` field is *the caller did not say*, which yields
664/// [`Support::Conditional`] naming the fact — never a guess. Two `None`s are
665/// read structurally rather than conditionally, because a table caller supplies
666/// neither and the published cell must still be the right one:
667///
668/// * `draft: None` reads as *no draft-specific restriction applies*, so the
669///   elide guard is evaluated as though the draft had a first-object subgroup
670///   mode — the conservative side, since it yields `Conditional` rather than
671///   `Yes`.
672/// * `stream_kind: None` reads as a **subgroup** stream, which is what
673///   [`Capabilities::supports`] publishes; [`Capabilities::supports_on`] is how
674///   a caller asks about fetch.
675pub fn classify(site: Site, kind: ActionKind, cx: &CapCtx) -> Support {
676    if let Some(answer) = not_attemptable(site, kind) {
677        return answer;
678    }
679
680    // A stream the framer cannot address never reaches the object site, so
681    // nothing can be attempted and nothing can be refused. One fact lands
682    // here: *any* stream on a draft this build did not compile. A fetch
683    // stream on drafts 18 and 19 used to land here too, and does not now —
684    // see `fetch_group_order_is_needed`.
685    let framing_bypass = match (site, cx.draft) {
686        (Site::Object, Some(draft)) => object_framing_bypass(draft, cx.stream_kind),
687        _ => None,
688    };
689    if let Some(reason) = framing_bypass {
690        return Support::Unreachable {
691            refusal: Refusal::StreamNotFramed { reason },
692            instead: Instead::FramerBypass(reason),
693        };
694    }
695
696    // The same build fact one decoder later. On a draft this build did not
697    // compile, `AnyControlMessage::decode` has no arm, so
698    // `ControlStreamParser::feed` steps over every frame and the hook is
699    // never offered one — nothing is attempted here and nothing can be
700    // refused. It is a separate check rather than a wider `framing_bypass`
701    // because the two report different events, and a cell that pointed at
702    // the wrong one would send a reader looking for a `FramerBypass` that
703    // no control stream emits.
704    //
705    // `draft: None` falls through to the per-site rules, as everywhere
706    // else in this function: it means the caller did not say, and a build
707    // fact cannot be read off a draft nobody named.
708    if site == Site::Control && cx.draft.is_some_and(|draft| !draft_is_compiled(draft)) {
709        return Support::Unreachable {
710            refusal: Refusal::ControlFrameNotDecodable,
711            instead: Instead::ControlFrameNotDecodable,
712        };
713    }
714
715    match site {
716        Site::Control => classify_control(kind),
717        Site::Object => classify_object(kind, cx),
718        Site::Datagram => classify_datagram(kind, cx),
719        Site::StreamOpen | Site::StreamHeader => classify_stream_decision(site, kind),
720        Site::StreamEnd => classify_stream_end(kind, cx),
721    }
722}
723
724/// What a draft can express, queryable before a run.
725#[derive(Debug, Clone, Copy)]
726pub struct Capabilities {
727    draft: DraftVersion,
728}
729
730impl Capabilities {
731    /// The capability table for a draft.
732    #[must_use]
733    pub fn for_draft(draft: DraftVersion) -> Self {
734        Self { draft }
735    }
736
737    /// Whether `kind` is available at `site`, with no per-unit facts.
738    ///
739    /// At [`Site::Object`] this is the **subgroup**-stream column;
740    /// [`Self::supports_on`] answers for a named stream kind.
741    #[must_use]
742    pub fn supports(&self, site: Site, kind: ActionKind) -> Support {
743        classify(site, kind, &CapCtx { draft: Some(self.draft), ..CapCtx::default() })
744    }
745
746    /// Whether `kind` is available at `site` for a given stream kind.
747    #[must_use]
748    pub fn supports_on(
749        &self,
750        site: Site,
751        kind: ActionKind,
752        stream_kind: DataStreamType,
753    ) -> Support {
754        classify(
755            site,
756            kind,
757            &CapCtx {
758                draft: Some(self.draft),
759                stream_kind: Some(stream_kind),
760                ..CapCtx::default()
761            },
762        )
763    }
764
765    /// Whether a shaping rule keyed on `field` can ever claim a unit
766    /// arriving as `kind`. [`supports_matcher`], bound to this draft.
767    #[must_use]
768    pub fn supports_matcher(&self, kind: MatchKind, field: MatcherKey) -> bool {
769        supports_matcher(self.draft, kind, field)
770    }
771
772    /// Admit one class rule, or refuse it naming the draft and the key.
773    ///
774    /// The first key the rule names that [`supports_matcher`] answers
775    /// `false` for is the refusal, in the order the keys are declared on
776    /// [`Matcher`] — the same first-match convention
777    /// [`ShapeProfile::try_new`] uses for
778    /// [`ShapeError::InertMatcher`](crate::shape::ShapeError::InertMatcher),
779    /// so a rule with two dead keys reports the one an author reading their
780    /// own configuration top to bottom reaches first.
781    ///
782    /// # A rule that names no stream kind is judged against both
783    ///
784    /// [`Matcher::stream_kind`] is optional, and a rule that omits it claims
785    /// units of **any** kind. Such a rule is refused only when its key is
786    /// carried by none of them, because refusing it for being dead on fetch
787    /// alone would reject a rule that shapes subgroup traffic perfectly well
788    /// — and a false rejection here is worse than the silence this exists to
789    /// end, since it rejects a configuration that works.
790    pub fn admit_class(&self, class: &ClassRule) -> Result<(), UnsupportedMatcherKey> {
791        let aimed = class.matcher.stream_kind;
792        for key in keys_named(&class.matcher).into_iter().flatten() {
793            let carried = match aimed {
794                Some(kind) => supports_matcher(self.draft, kind, key),
795                None => ANY_KIND.iter().any(|&kind| supports_matcher(self.draft, kind, key)),
796            };
797            if !carried {
798                return Err(UnsupportedMatcherKey {
799                    class: class.name.clone(),
800                    draft: self.draft,
801                    kind: aimed,
802                    key,
803                });
804            }
805        }
806        Ok(())
807    }
808
809    /// Admit every class in a profile, or refuse at the first dead key.
810    ///
811    /// The pre-run check [`ShapeProfile::try_new`] cannot make: that
812    /// constructor validates the configuration alone and has no draft, so a
813    /// rule keyed on something the negotiated draft does not carry is valid
814    /// to it. This is the same question asked once a draft is known.
815    ///
816    /// # A session asks it twice, and the second time is not redundant
817    ///
818    /// Once before it dials, against the draft it is about to frame with,
819    /// which is the only moment a profile can be refused with nothing yet
820    /// forwarded. And once more when the peers name a draft, which drafts 07
821    /// to 14 do in their SETUP rather than in the ALPN they share — so for
822    /// that cohort the first answer was given about a configured guess and
823    /// the second is given about the session actually running. The two
824    /// differ only where a draft this build did not compile is involved, and
825    /// that is exactly the case where every rule in the profile is dead.
826    pub fn admit_profile(&self, profile: &ShapeProfile) -> Result<(), UnsupportedMatcherKey> {
827        profile.classes().iter().try_for_each(|class| self.admit_class(class))
828    }
829}
830
831// ── What a shaping rule may key on ─────────────────────────────────────
832
833/// Every kind a rule that names none of them may claim.
834///
835/// All three, and the list is read only for a matcher whose
836/// [`Matcher::stream_kind`] is `None`: such a rule is refused for a key only
837/// when **no** kind carries it. Leaving [`MatchKind::Datagram`] out of the list
838/// would refuse a rule keyed on something only a datagram carries, and
839/// including a kind that carried nothing would admit a rule that claims nothing
840/// — which is why the list is the answer to *what could this rule claim* rather
841/// than a restatement of the enum.
842const ANY_KIND: [MatchKind; 3] = [MatchKind::Subgroup, MatchKind::Fetch, MatchKind::Datagram];
843
844/// One value key a [`Matcher`] can be built on.
845///
846/// Six variants, spelled as the [`Matcher`] fields are, so a refusal names
847/// something an author can search their own configuration for — the same
848/// contract
849/// [`ShapeError::InertMatcher`](crate::shape::ShapeError::InertMatcher)'s
850/// `key` field carries, and deliberately the same spelling, so the two
851/// rejections read alike.
852///
853/// Two [`Matcher`] fields are **not** here, and their absence is a decision
854/// rather than an omission:
855///
856/// * [`Matcher::side`] is the forwarding task's own direction label, not a
857///   field any unit carries, so no draft can fail to carry it. The one side
858///   value that names nothing a hook site sees is already rejected by
859///   [`ShapeProfile::try_new`].
860/// * [`Matcher::stream_kind`] names *which* units a rule claims rather than a
861///   field those units carry. It is [`supports_matcher`]'s second argument, not
862///   one of its answers.
863///
864/// Distinct from
865/// [`MatcherField`](crate::shape::MatcherField), which is the *run's*
866/// vocabulary and covers a different set: that enum names the four keys a
867/// live session can report absent on a unit it actually saw, this one names
868/// the six keys a configuration can be built on before any session exists.
869/// They overlap on three names and neither is a superset of the other.
870#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
871#[non_exhaustive]
872pub enum MatcherKey {
873    /// [`Matcher::track_alias`].
874    TrackAlias,
875    /// [`Matcher::group_id`].
876    GroupId,
877    /// [`Matcher::subgroup_id`].
878    SubgroupId,
879    /// [`Matcher::object_id`].
880    ObjectId,
881    /// [`Matcher::priority`], MoQT's `publisher_priority`.
882    Priority,
883    /// [`Matcher::every_nth`].
884    EveryNth,
885}
886
887impl MatcherKey {
888    /// Every key, in the order the fields are declared on [`Matcher`].
889    ///
890    /// Published so a caller can sweep the whole axis without transcribing
891    /// it; [`Capabilities::admit_class`] reports in this order too.
892    pub const ALL: [MatcherKey; 6] = [
893        MatcherKey::TrackAlias,
894        MatcherKey::GroupId,
895        MatcherKey::SubgroupId,
896        MatcherKey::ObjectId,
897        MatcherKey::Priority,
898        MatcherKey::EveryNth,
899    ];
900
901    /// The key's name as the [`Matcher`] field is spelled.
902    #[must_use]
903    pub const fn field_name(self) -> &'static str {
904        match self {
905            MatcherKey::TrackAlias => "track_alias",
906            MatcherKey::GroupId => "group_id",
907            MatcherKey::SubgroupId => "subgroup_id",
908            MatcherKey::ObjectId => "object_id",
909            MatcherKey::Priority => "priority",
910            MatcherKey::EveryNth => "every_nth",
911        }
912    }
913}
914
915/// Whether a rule keyed on `field` can **ever** claim a unit arriving as
916/// `kind`, on `draft`, in this build.
917///
918/// A shaping rule keyed on something the negotiated draft does not carry
919/// arms, matches nothing, and reports success — the silent no-op this crate
920/// exists to make loud. Before this predicate the only way to learn it was
921/// to run the session and read `Impairment{ShapeRuleUnmatchable}` out of the
922/// report, which requires a run, traffic of the right shape, and a reader.
923/// The answer needs nothing but the draft and the compiled feature set, so
924/// it is answerable before the run, and [`Capabilities::admit_profile`] turns
925/// it into a refusal.
926///
927/// # Why the second argument is a [`MatchKind`] and not a [`Site`]
928///
929/// Shaping only ever sees framed objects. [`Site`] spans the control frame,
930/// the two stream decisions and the stream end, none of which a [`Matcher`]
931/// can be aimed at, and it does *not* distinguish the two things that decide
932/// this question — a subgroup stream from a fetch one. [`MatchKind`] is the
933/// axis the answer actually varies on, and it is the axis a rule is written
934/// against.
935///
936/// # The three facts, in the order they are read
937///
938/// 1. **A draft this build did not compile frames nothing at all.** The
939///    stream header decode returns `UnsupportedDraft`, the framer latches
940///    [`BypassReason::DecodeError`] and forwards the stream uninterpreted,
941///    so no [`ObjectMeta`](crate::framer::ObjectMeta) is ever built and *no*
942///    key can match — see [`draft_is_compiled`], which is reachable by
943///    default rather than only under exotic flags. This is why the predicate
944///    answers for a build and not only for a draft, exactly as
945///    [`classify`] does.
946/// 2. **A fetch stream carries no track alias, and a datagram carries no
947///    subgroup ID, on any draft.** A fetch header carries a request ID
948///    where a subgroup header carries an alias, and no datagram of any
949///    draft belongs to a subgroup. These are the two answers that vary by
950///    *kind* rather than by draft, and they are why the predicate takes
951///    the kind at all.
952///
953/// # What it deliberately does not refuse, and why
954///
955/// [`Matcher::subgroup_id`] and [`Matcher::priority`] are the two keys whose
956/// absence can be a property of one **header** rather than of the draft — a
957/// header in *subgroup ID is the first object's ID* mode (eight drafts) or
958/// drafts 17-19's reserved mode 3 carries no subgroup ID, and drafts 15-19 omit
959/// the publisher priority whenever the header sets the default-priority bit, on
960/// a subgroup header and on a datagram alike. Neither is a *draft* fact. Every
961/// one of the thirteen drafts also has header shapes that carry both — modes 0
962/// and 2 on 17-19, an explicit subgroup ID field elsewhere, and a clear
963/// default-priority bit — and every fetch object on the drafts that frame one
964/// carries both unconditionally. So a rule keyed on either can match on every
965/// draft, and this predicate answers `true`.
966///
967/// There is deliberately no fact about a stream *kind* that yields no unit
968/// at all. There used to be one — a [`MatchKind::Fetch`] class on drafts 18
969/// and 19, refused before the run because no fetch stream there could be
970/// framed — and it went when those streams became readable; see
971/// `fetch_group_order_is_needed`. A fetch stream the session cannot resolve
972/// is now one stream rather than a draft, and it reports itself as
973/// `Impairment { FramerBypass { FetchGroupOrderUnknown } }` while it happens.
974///
975/// The one place `subgroup_id` crosses the line is a rule aimed at
976/// [`MatchKind::Datagram`], which fact 2 above refuses: there the absence is
977/// not a header's but the carrier's, and no draft has a datagram shape that
978/// carries one. A rule that names **no** kind and keys on `subgroup_id` is
979/// still admitted, because it is a working subgroup rule that datagram
980/// traffic simply walks past.
981///
982/// Refusing them would reject rules that work, which is a worse failure than
983/// the one being fixed: a run that shapes nothing can at least be observed,
984/// while a configuration rejected at startup cannot run at all. A key the
985/// wire withheld from **one unit** stays what it already was —
986/// `Impairment{ShapeRuleUnmatchable}`, reported per class per field, once
987/// per session — because that answer depends on the traffic and nothing
988/// before the run can know it.
989#[must_use]
990pub fn supports_matcher(draft: DraftVersion, kind: MatchKind, field: MatcherKey) -> bool {
991    // Read in the same wire order `object_framing_bypass` reads them: the
992    // stream header decodes first, so an uncompiled draft fails before the
993    // fetch-object question is ever reached.
994    if !draft_is_compiled(draft) {
995        return false;
996    }
997    // A fetch header carries a request ID where a subgroup header carries a
998    // track alias, so `ObjectFramer` builds every fetch object with
999    // `track_alias: None` and an absent key never matches.
1000    if kind == MatchKind::Fetch && field == MatcherKey::TrackAlias {
1001        return false;
1002    }
1003    // A datagram carries one Object and belongs to no subgroup, on every one
1004    // of the thirteen drafts. There is no header shape anywhere in the family
1005    // that puts a Subgroup ID on one, which is what makes this a refusal here
1006    // rather than a `MatcherField::SubgroupId` report from a run: the answer
1007    // does not depend on a header the session has not seen yet.
1008    !(kind == MatchKind::Datagram && field == MatcherKey::SubgroupId)
1009}
1010
1011/// The keys a matcher names, in [`Matcher`] field order.
1012///
1013/// A fixed-size array of `Option` rather than a `Vec`, matching
1014/// `Matcher::unmatchable_fields`: the shape reads as the struct does, so a
1015/// key added to [`Matcher`] and forgotten here is visible as a missing row
1016/// rather than as a shorter list.
1017fn keys_named(matcher: &Matcher) -> [Option<MatcherKey>; 6] {
1018    [
1019        matcher.track_alias.as_ref().map(|_| MatcherKey::TrackAlias),
1020        matcher.group_id.as_ref().map(|_| MatcherKey::GroupId),
1021        matcher.subgroup_id.as_ref().map(|_| MatcherKey::SubgroupId),
1022        matcher.object_id.as_ref().map(|_| MatcherKey::ObjectId),
1023        matcher.priority.as_ref().map(|_| MatcherKey::Priority),
1024        matcher.every_nth.map(|_| MatcherKey::EveryNth),
1025    ]
1026}
1027
1028/// A class rule keyed on something no unit it could claim ever carries.
1029///
1030/// Returned by [`Capabilities::admit_class`] and
1031/// [`Capabilities::admit_profile`] **before** a session forwards anything,
1032/// so the rule never arms. The message names the draft and the key, because
1033/// either alone is unactionable: "keys on `track_alias`" does not say which
1034/// session it is dead in, and "draft-19" does not say what to change.
1035///
1036/// `#[non_exhaustive]` with public fields: nobody constructs an error, and a
1037/// later release naming a seventh key must not be a breaking change.
1038/// Reading the fields from outside the crate stays legal, which is what lets
1039/// a caller branch on the key rather than parse the message.
1040///
1041/// [`Display`](std::fmt::Display) is hand-written rather than a `thiserror`
1042/// attribute, unlike
1043/// [`ShapeError`](crate::shape::ShapeError): the message has two shapes,
1044/// because a rule that named no [`MatchKind`] was judged against both framed
1045/// kinds and naming one of them in the refusal would misreport what the rule
1046/// asked for.
1047#[derive(Debug, Clone, PartialEq, Eq)]
1048#[non_exhaustive]
1049pub struct UnsupportedMatcherKey {
1050    /// The [`ClassRule::name`] holding the dead key.
1051    pub class: String,
1052    /// The draft the session would run as.
1053    pub draft: DraftVersion,
1054    /// The stream kind the rule was aimed at, or `None` when it named none
1055    /// and the key is carried by neither framed kind on this draft.
1056    pub kind: Option<MatchKind>,
1057    /// The key that can never match.
1058    pub key: MatcherKey,
1059}
1060
1061impl std::fmt::Display for UnsupportedMatcherKey {
1062    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1063        let (class, key, draft) = (&self.class, self.key.field_name(), self.draft);
1064        match self.kind {
1065            Some(kind) => {
1066                write!(f, "class {class} keys on {key}, which no {kind:?} unit carries on {draft}")
1067            }
1068            None => {
1069                write!(f, "class {class} keys on {key}, which no framed unit carries on {draft}")
1070            }
1071        }
1072    }
1073}
1074
1075impl std::error::Error for UnsupportedMatcherKey {}
1076
1077// ── The three site-independent `NotAttemptable` families ───────────────
1078
1079/// Whether this site's hook method returns
1080/// [`StreamAction`](crate::action::StreamAction) rather than
1081/// [`Action`](crate::action::Action).
1082const fn site_returns_stream_action(site: Site) -> bool {
1083    matches!(site, Site::StreamOpen | Site::StreamHeader)
1084}
1085
1086/// Whether this kind is one of the four
1087/// [`StreamAction`](crate::action::StreamAction) decisions.
1088///
1089/// **The compiler does not check this list.** It is a `matches!`, not an
1090/// exhaustive `match`, so a `StreamAction` variant left out of it silently
1091/// becomes `NotAttemptable { SiteReturnsStreamAction }` at
1092/// [`Site::StreamOpen`] and [`Site::StreamHeader`] — the published table
1093/// then says a site's return type rules out a variant of that very return
1094/// type. `tests/action_matrix.rs::the_published_table_and_classify_agree`
1095/// is the gate that catches it, because its hand-transcribed twin of this
1096/// list is written independently.
1097const fn is_stream_decision(kind: ActionKind) -> bool {
1098    matches!(
1099        kind,
1100        ActionKind::Open | ActionKind::Reject | ActionKind::OpenAfter | ActionKind::SerializeAfter
1101    )
1102}
1103
1104/// Families 1-3 of [`Support::NotAttemptable`], in the order [`classify`]
1105/// documents: no constructor, then `ReplaceObject`'s single reading, then
1106/// the return-type mismatch.
1107fn not_attemptable(site: Site, kind: ActionKind) -> Option<Support> {
1108    if kind == ActionKind::ReplaceObject && site != Site::Object {
1109        return Some(Support::NotAttemptable {
1110            why: NotAttemptable::KindNotDefinedAtThisSite,
1111            refusal: Refusal::WrongSite { site, action: kind },
1112        });
1113    }
1114
1115    let why = match (site_returns_stream_action(site), is_stream_decision(kind)) {
1116        (true, false) => NotAttemptable::SiteReturnsStreamAction,
1117        (false, true) => NotAttemptable::SiteReturnsAction,
1118        _ => return None,
1119    };
1120    Some(Support::NotAttemptable { why, refusal: Refusal::WrongSite { site, action: kind } })
1121}
1122
1123/// The answer [`not_attemptable`] already gave, restated.
1124///
1125/// Every kind that reaches a site helper's "filtered earlier" arm was
1126/// answered before dispatch. Recomputing it keeps each helper a total
1127/// function instead of a panicking one — a capability table that can panic
1128/// is worse than one that repeats itself.
1129fn filtered_earlier(site: Site, kind: ActionKind) -> Support {
1130    not_attemptable(site, kind).unwrap_or(Support::NotAttemptable {
1131        why: NotAttemptable::KindNotDefinedAtThisSite,
1132        refusal: Refusal::WrongSite { site, action: kind },
1133    })
1134}
1135
1136// ── Per-draft facts ────────────────────────────────────────────────────
1137
1138/// Why [`ObjectFramer`](crate::framer::ObjectFramer) cannot address objects
1139/// on a stream of this shape, if it cannot.
1140///
1141/// One reason survives here, and it is the one the **wire** reaches first: a
1142/// draft this build did not compile fails at the stream header and reports
1143/// [`BypassReason::DecodeError`], so nothing after it is ever asked.
1144///
1145/// A fetch stream on drafts 18 and 19 used to answer a second reason. It no
1146/// longer does, because whether such a stream can be addressed is no longer a
1147/// property of the draft: the session reads the Group Order off the FETCH and
1148/// the framer takes it from there — see [`fetch_group_order_is_needed`]. What
1149/// is left of that case belongs to one stream rather than to the table, and
1150/// is reported per stream as before.
1151///
1152/// `stream_kind: None` reads as a subgroup stream, matching
1153/// [`Capabilities::supports`]'s published column.
1154const fn object_framing_bypass(
1155    draft: DraftVersion,
1156    stream_kind: Option<DataStreamType>,
1157) -> Option<BypassReason> {
1158    let _ = stream_kind;
1159    if !draft_is_compiled(draft) {
1160        return Some(BypassReason::DecodeError);
1161    }
1162    None
1163}
1164
1165/// Whether **this build** compiled a codec for `draft`.
1166///
1167/// [`DraftVersion`] carries all thirteen variants under every feature set,
1168/// so the table is *answerable* for a draft this binary cannot speak — and
1169/// that is exactly the case worth getting right. A build that did not
1170/// compile a draft cannot frame one byte of it, so a table that answers by
1171/// draft **number** alone publishes [`Support::Yes`] for work the binary
1172/// cannot do: the documented lie this module exists to prevent.
1173///
1174/// It is reachable **by default**, not only under exotic flags:
1175/// `ProxySessionConfig::default().draft` is [`DraftVersion::Draft14`], so a
1176/// `--no-default-features --features draft07` binary — a shipped
1177/// configuration and one of CI's fourteen rows — is configured for draft 14
1178/// unless its caller says otherwise.
1179///
1180/// # This is also the predicate a session is admitted on
1181///
1182/// [`ProxySession::run`](crate::session::ProxySession::run) asks this before
1183/// it dials and refuses with
1184/// [`ProxyError::DraftNotCompiled`](crate::error::ProxyError::DraftNotCompiled)
1185/// when the answer is `false`, so the run that the paragraph below describes
1186/// no longer happens to anybody. One predicate serves both, which is what
1187/// keeps the table's verdict and the session's admission from becoming two
1188/// lists that disagree — and the paragraph below stays because it is still
1189/// the reason the verdict is [`Support::Unreachable`] rather than
1190/// [`Support::Yes`].
1191///
1192/// # The mechanism, so the verdict is not taken on trust
1193///
1194/// `moqtap-proxy`'s `draftNN` features forward to **both** `moqtap-codec` and
1195/// `moqtap-client`, so a draft that is off here is off in the codec.
1196/// `AnySubgroupHeader::decode_stream` and `AnyFetchHeader::decode_stream` then
1197/// fall through to their catch-all arm and return
1198/// `CodecError::UnsupportedDraft(*draft DraftNN not enabled via feature
1199/// flag*)`. That is not an incomplete-input error
1200/// (`parser::data::is_incomplete_error` admits only `UnexpectedEnd`), so
1201/// [`ObjectFramer`](crate::framer::ObjectFramer)'s header poll takes its
1202/// terminal `Err` arm, latches [`BypassReason::DecodeError`] and forwards the
1203/// stream uninterpreted. No object on it ever reaches
1204/// [`ProxyHook::on_object`](crate::hook::ProxyHook::on_object), which is
1205/// precisely [`Support::Unreachable`].
1206///
1207/// # Why `cfg!` and not `#[cfg]`
1208///
1209/// A `cfg!` per arm keeps the function **total**. A `#[cfg]` per arm would
1210/// make the match non-exhaustive and force a catch-all, and the table would
1211/// stop being able to answer for the very drafts this exists to answer for.
1212///
1213/// # The control site reads it too, one decoder later
1214///
1215/// [`Site::Control`] on an uncompiled draft is never invoked either:
1216/// `ControlStreamParser::feed` steps over a frame whose
1217/// `AnyControlMessage::decode` fails, so the hook is offered nothing. That
1218/// cell published [`Support::Yes`] for a while, because the honest verdict
1219/// needs `instead` to name a report and this path emitted none. It emits
1220/// [`ImpairmentKind::ControlFrameNotDecodable`](crate::event::ImpairmentKind::ControlFrameNotDecodable)
1221/// now, so the cell is [`Support::Unreachable`] with
1222/// [`Instead::ControlFrameNotDecodable`] — see [`classify`], step 5.
1223///
1224/// # What it does *not* cover
1225///
1226/// [`Site::StreamOpen`], [`Site::StreamEnd`] and [`Site::Datagram`] need no
1227/// codec to fire and are unaffected; [`Site::StreamHeader`] fires only
1228/// behind a decoded header and shares the object site's fate.
1229#[must_use]
1230pub const fn draft_is_compiled(draft: DraftVersion) -> bool {
1231    match draft {
1232        DraftVersion::Draft07 => cfg!(feature = "draft07"),
1233        DraftVersion::Draft08 => cfg!(feature = "draft08"),
1234        DraftVersion::Draft09 => cfg!(feature = "draft09"),
1235        DraftVersion::Draft10 => cfg!(feature = "draft10"),
1236        DraftVersion::Draft11 => cfg!(feature = "draft11"),
1237        DraftVersion::Draft12 => cfg!(feature = "draft12"),
1238        DraftVersion::Draft13 => cfg!(feature = "draft13"),
1239        DraftVersion::Draft14 => cfg!(feature = "draft14"),
1240        DraftVersion::Draft15 => cfg!(feature = "draft15"),
1241        DraftVersion::Draft16 => cfg!(feature = "draft16"),
1242        DraftVersion::Draft17 => cfg!(feature = "draft17"),
1243        DraftVersion::Draft18 => cfg!(feature = "draft18"),
1244        DraftVersion::Draft19 => cfg!(feature = "draft19"),
1245    }
1246}
1247
1248/// Every draft this build could take as a default, in the order it would take
1249/// them.
1250///
1251/// Draft-14 first, because that is the value this had before the build's own
1252/// draft list was consulted and a full build should not change; then the newest
1253/// draft downwards, because a build that trimmed its drafts kept the ones it
1254/// means to speak and the newest of those is the likeliest thing meant by
1255/// naming none.
1256const DEFAULT_DRAFT_ORDER: [DraftVersion; 13] = [
1257    DraftVersion::Draft14,
1258    DraftVersion::Draft19,
1259    DraftVersion::Draft18,
1260    DraftVersion::Draft17,
1261    DraftVersion::Draft16,
1262    DraftVersion::Draft15,
1263    DraftVersion::Draft13,
1264    DraftVersion::Draft12,
1265    DraftVersion::Draft11,
1266    DraftVersion::Draft10,
1267    DraftVersion::Draft09,
1268    DraftVersion::Draft08,
1269    DraftVersion::Draft07,
1270];
1271
1272/// The draft a session configuration takes when the caller names none.
1273///
1274/// Draft-14 wherever the build has it, which is every build that did not trim
1275/// its drafts, and the newest draft the build does have otherwise. The value is
1276/// what it always was on a full build; what changes is that a reduced-draft
1277/// build no longer starts out naming a draft it cannot speak.
1278///
1279/// # Why a default cannot simply refuse
1280///
1281/// [`Default`] returns a value, so it has no way to tell a caller that the
1282/// build left out the draft it would have chosen. Keeping draft-14 regardless
1283/// does not avoid the problem, it moves it: on a build without draft-14
1284/// [`draft_is_compiled`] answers `false`, [`supports_matcher`] refuses every
1285/// key on every stream kind, and a class rule that is perfectly well formed is
1286/// reported as naming a key the draft does not carry. That is a configuration
1287/// error raised against the author of a configuration that has nothing wrong
1288/// with it.
1289///
1290/// # The check below is a compile-time one, and it has to be
1291///
1292/// A test asserting the same thing would never run. The per-draft rows build
1293/// this crate thirteen times under `--no-default-features --features draftNN`
1294/// and stop at `clippy --all-targets`, so a reduced-draft build is *compiled*
1295/// thirteen times a round and its tests are run none — and a reduced-draft
1296/// build is the only kind that can have this defect. A const assertion fails
1297/// the compile, which is the one thing those rows do look at.
1298///
1299/// # Ablated, and the numbers are the account of why this survived
1300///
1301/// Putting the old value back — draft-14 chosen without consulting the build:
1302///
1303/// ```text
1304/// error[E0080]: evaluation panicked: the default draft is one this build did not compile
1305/// error: could not compile `moqtap-proxy` (lib) due to 1 previous error
1306/// ```
1307///
1308/// **Exit 101 under `--no-default-features --features draft07`, exit 101 under
1309/// the same with draft19, and exit 0 under `--all-features`.** The build every
1310/// round runs first cannot see this defect at all, and the thirteen that can
1311/// are compiled and never run.
1312pub const DEFAULT_DRAFT: DraftVersion = default_draft();
1313
1314const fn default_draft() -> DraftVersion {
1315    let mut i = 0;
1316    while i < DEFAULT_DRAFT_ORDER.len() {
1317        if draft_is_compiled(DEFAULT_DRAFT_ORDER[i]) {
1318            return DEFAULT_DRAFT_ORDER[i];
1319        }
1320        i += 1;
1321    }
1322    panic!("this build compiled no draft at all, so there is no default to take")
1323}
1324
1325const _: () = assert!(
1326    draft_is_compiled(DEFAULT_DRAFT),
1327    "the default draft is one this build did not compile"
1328);
1329
1330/// Whether a fetch stream on this draft can be read only by an endpoint that
1331/// knows the Group Order the fetch was asked for.
1332///
1333/// A statement about the draft, not about the build and not about any one
1334/// session; whether the draft was compiled at all is [`draft_is_compiled`],
1335/// asked first by [`object_framing_bypass`] because the header decode happens
1336/// first.
1337///
1338/// **False on drafts 07-17.** Drafts 07-14 write each object's identity
1339/// outright, and drafts 15, 16 and 17 let an object leave a field off and
1340/// take the object before it — draft-16 Section 10.4.4.1: "Group ID is the
1341/// prior Object's Group ID" — which the reader carries the running state
1342/// for. Either way an absolute Location comes out of the stream and nothing
1343/// else, which is all addressing an object needs.
1344///
1345/// **True on drafts 18 and 19**, where the Group ID is a difference and the
1346/// fetch's Group Order decides its sign. Nothing on the data stream states
1347/// the order, and the wrong choice decodes as willingly as the right one, so
1348/// a reader has to be told — see [`BypassReason::FetchGroupOrderUnknown`],
1349/// where the consequence of the wrong answer is written out.
1350///
1351/// # Where the answer comes from
1352///
1353/// One control message settles it. Draft-19 Section 10.12.3: "The publisher
1354/// responding to a FETCH is responsible for delivering all available Objects
1355/// in the requested range in the requested order (see Section 10.2.8)", and
1356/// draft-19 Section 10.2.8 states what a FETCH that carries no GROUP_ORDER
1357/// parameter has asked for: "If omitted from FETCH, the receiver uses
1358/// Ascending (0x1)." So a session that reads the FETCH knows the order for
1359/// that Request ID,
1360/// carrying it in a
1361/// [`FetchGroupOrders`](crate::framer::FetchGroupOrders) table the framer
1362/// takes it out of when the response stream opens.
1363///
1364/// That is why this is a draft fact and the bypass is not. The bypass now
1365/// belongs to one stream: a fetch stream naming a request this session never
1366/// saw asked for, which is a publisher answering something nobody requested.
1367pub(crate) const fn fetch_group_order_is_needed(draft: DraftVersion) -> bool {
1368    matches!(draft, DraftVersion::Draft18 | DraftVersion::Draft19)
1369}
1370
1371/// Whether this draft defines a *subgroup ID is the first object's ID* stream
1372/// type.
1373///
1374/// Nine drafts do: every one from 11 on. Drafts 07-10 always carry the
1375/// subgroup ID explicitly, so eliding index 0 there redefines nothing.
1376///
1377/// The two wordings are worth telling apart, because reading only the later
1378/// one makes the earlier drafts look as though they lack the mode. Drafts 11
1379/// through 15 state it as a property of the type value — draft-15 Section
1380/// 10.4.2: "the Subgroup ID is either 0 (for Types 0x10-11 and 0x18-19) or the
1381/// Object ID of the first object transmitted in this subgroup (for Types
1382/// 0x12-13 and 0x1A-1B)" — while drafts 16 through 19 name a SUBGROUP_ID_MODE
1383/// field and give mode 1 the sentence "The Subgroup ID field is absent and the
1384/// Subgroup ID is the Object ID of the first Object transmitted in this
1385/// Subgroup". Different prose, one stream: `0x12` on both sides of the change.
1386///
1387/// Draft-15's absence here was not a narrower guard but a silent one. Skipping
1388/// the block admitted the elide instead of refusing it, so a hook removing
1389/// index 0 of a draft-15 first-object stream handed the receiver a stream
1390/// whose subgroup ID had become the second object's. The draft list the tests
1391/// sweep carried the same omission, so no run ever asked.
1392///
1393/// **Nothing that checks this list may read it.** Two places state the same
1394/// partition independently and are what a narrowing here contradicts: the
1395/// `a_first_object_carrier_exists` in this module's tests, which names every
1396/// draft in an exhaustive match, and the copy in `tests/action_matrix.rs`,
1397/// transcribed from the drafts and driving end-to-end probes. Both cuts have
1398/// been run — dropping draft-15, and narrowing to 17-19 — and each is caught
1399/// by both. A test that took the fact from *here* instead passed under both.
1400const fn has_implicit_subgroup_id_mode(draft: DraftVersion) -> bool {
1401    matches!(
1402        draft,
1403        DraftVersion::Draft11
1404            | DraftVersion::Draft12
1405            | DraftVersion::Draft13
1406            | DraftVersion::Draft14
1407            | DraftVersion::Draft15
1408            | DraftVersion::Draft16
1409            | DraftVersion::Draft17
1410            | DraftVersion::Draft18
1411            | DraftVersion::Draft19
1412    )
1413}
1414
1415/// Whether a header's reserved subgroup-ID mode has to be told apart from
1416/// mode 1 before an object behind it can be judged. Drafts 15-19.
1417///
1418/// **Not the drafts that name a SUBGROUP_ID_MODE field**, which is neither a
1419/// superset nor a subset of this. Drafts 16 through 19 name one — draft-16:
1420/// "Type values with SUBGROUP_ID_MODE set to 0b11: 0x16, 0x17, 0x1E, 0x1F,
1421/// 0x36, 0x37, 0x3E, 0x3F. This mode is reserved for future use." Draft-15
1422/// names nothing and states the same three carriers as table columns, then
1423/// leaves the fourth combination out of the table. The wording is what
1424/// differs; the two bits and their four values are not.
1425///
1426/// What decides it is where `AnySubgroupHeader::subgroup_id` answers `None`
1427/// for more than one reason. On these five it answers `None` for both mode 1
1428/// and the fourth combination, so `None` alone cannot say whether the first
1429/// object defines the subgroup or the header is one no receiver should read,
1430/// and the mode has to be consulted. Drafts 11 through 14 give each carrier a
1431/// stream type of its own and assign every type they define, so their `None`
1432/// means the first object and nothing else; drafts 07-10 always put the ID on
1433/// the wire and never answer `None` at all.
1434///
1435/// Both were outside this set while the codec still resolved their fourth
1436/// combination to a subgroup ID — draft-15 to zero by falling through, draft-16
1437/// to whatever varint it went on to read — and being outside it was right then,
1438/// because a `None` from those two really did mean mode 1 and nothing else. The
1439/// codec now answers `None` for both readings, as it always did on 17-19, so
1440/// the sentence above is what picks the drafts rather than a list of the ones
1441/// that name a field.
1442const fn subgroup_id_mode_must_be_consulted(draft: DraftVersion) -> bool {
1443    matches!(
1444        draft,
1445        DraftVersion::Draft15
1446            | DraftVersion::Draft16
1447            | DraftVersion::Draft17
1448            | DraftVersion::Draft18
1449            | DraftVersion::Draft19
1450    )
1451}
1452
1453// ── Per-site rules ─────────────────────────────────────────────────────
1454
1455/// The control site, which is honoured on every draft.
1456///
1457/// The site is shown every message the session's control plane carries,
1458/// whichever shape that plane has. On drafts 07-16 the plane is the one
1459/// client-initiated bidirectional stream. On 17-19 it is a pair of
1460/// unidirectional streams — each peer opens one and begins it with SETUP —
1461/// and bidirectional streams carry requests; `session.rs` identifies the
1462/// pair by its stream type and pipes both it and the request streams through
1463/// the control path, so SETUP reaches the hook there too.
1464///
1465/// Draft-16 is both at once and is the only draft that is: a bidirectional
1466/// control stream, and SUBSCRIBE_NAMESPACE on a bidirectional stream of its
1467/// own beside it. Its request streams take the same control path, so this
1468/// column reads the same for it as for every other draft.
1469///
1470/// This column carried a `Conditional` for 17-19 while the engine believed
1471/// the control plane was the first bidirectional stream on every draft.
1472/// `tests/control_plane_uni.rs` is the end-to-end reading that replaced it,
1473/// and `tests/draft16_request_streams.rs` is the one for the draft that
1474/// needs both answers.
1475fn classify_control(kind: ActionKind) -> Support {
1476    let honoured = Support::Yes;
1477
1478    match kind {
1479        ActionKind::Pass
1480        | ActionKind::Replace
1481        | ActionKind::Delay
1482        | ActionKind::Hold
1483        | ActionKind::DropElide
1484        | ActionKind::CloseSession => honoured,
1485        // A control frame has no payload slot the proxy can locate.
1486        ActionKind::ReplacePayload => {
1487            Support::No(Refusal::WrongSite { site: Site::Control, action: kind })
1488        }
1489        // On every draft: a request stream is still a control-plane
1490        // stream, so 17-19 are refused for the same reason as 07-16.
1491        ActionKind::Truncate | ActionKind::ResetStream => {
1492            Support::No(Refusal::ControlStreamResetIllegal)
1493        }
1494        ActionKind::Open
1495        | ActionKind::Reject
1496        | ActionKind::ReplaceObject
1497        | ActionKind::OpenAfter
1498        | ActionKind::SerializeAfter => filtered_earlier(Site::Control, kind),
1499    }
1500}
1501
1502/// The object site, on a stream the framer can address: subgroup streams
1503/// on every compiled draft, and fetch streams on the drafts whose objects
1504/// this codec can read.
1505fn classify_object(kind: ActionKind, cx: &CapCtx) -> Support {
1506    match kind {
1507        ActionKind::Pass
1508        | ActionKind::Delay
1509        | ActionKind::Hold
1510        | ActionKind::Truncate
1511        | ActionKind::ResetStream
1512        | ActionKind::CloseSession => Support::Yes,
1513        // One classification for both rows: `Action::Replace(b)` is the
1514        // attempt for each, so the cells are the same value, and the
1515        // refusal names the capability being refused.
1516        ActionKind::Replace | ActionKind::ReplaceObject => Support::No(Refusal::WrongSite {
1517            site: Site::Object,
1518            action: ActionKind::ReplaceObject,
1519        }),
1520        ActionKind::ReplacePayload => object_replace_payload(cx),
1521        ActionKind::DropElide => object_drop_elide(cx),
1522        ActionKind::Open
1523        | ActionKind::Reject
1524        | ActionKind::OpenAfter
1525        | ActionKind::SerializeAfter => filtered_earlier(Site::Object, kind),
1526    }
1527}
1528
1529/// The object site's `ReplacePayload` rule: the replacement must be the
1530/// declared payload length, and the object must not carry a status.
1531///
1532/// The status guard is evaluated first: an object with a status has no
1533/// payload slot to splice into, so its length is not the interesting fact.
1534fn object_replace_payload(cx: &CapCtx) -> Support {
1535    if cx.is_status_object == Some(true) {
1536        return Support::No(Refusal::WouldDestroyStatusObject);
1537    }
1538    match (cx.payload_len, cx.replacement_len) {
1539        (Some(from), Some(to)) if from != to => Support::No(Refusal::LengthChanged { from, to }),
1540        (Some(_), Some(_)) if cx.is_status_object == Some(false) => Support::Yes,
1541        (Some(_), Some(_)) => Support::Conditional(Precondition::NotAStatusObject),
1542        _ => Support::Conditional(Precondition::ReplacementLengthEqualsPayload),
1543    }
1544}
1545
1546/// The object site's `DropElide` rule, in guard order: facts about the
1547/// stream before facts about the object.
1548///
1549/// On a subgroup stream, the header's subgroup-ID mode first (a reserved
1550/// mode says something different about the wire than a first-object mode
1551/// does), then whether eliding this object would redefine the subgroup ID.
1552/// The status guard is last and applies on every draft and every stream
1553/// kind.
1554///
1555/// **A fetch stream reaches only the status guard**, on every draft. Nothing
1556/// about a fetch object's own bytes can stop a removal: the framer pays for one
1557/// by re-encoding the survivor's framing against the frame that is now in front
1558/// of it. The subgroup guards below are skipped rather than answered, because a
1559/// fetch object states its own Subgroup ID or states that it has none, so
1560/// *eliding this would redefine the subgroup ID* is not a sentence about it.
1561fn object_drop_elide(cx: &CapCtx) -> Support {
1562    let subgroup_stream = cx.stream_kind != Some(DataStreamType::Fetch);
1563
1564    let implicit_mode = cx.draft.is_none_or(has_implicit_subgroup_id_mode);
1565
1566    if subgroup_stream && implicit_mode {
1567        match cx.index_in_stream {
1568            // Not the first object: the subgroup ID is already pinned by
1569            // an object that is still on the wire, so eliding this one
1570            // redefines nothing.
1571            Some(index) if index != 0 => {}
1572            Some(_) => {
1573                if cx.draft.is_none_or(subgroup_id_mode_must_be_consulted)
1574                    && cx.subgroup_id_mode == Some(RESERVED_SUBGROUP_ID_MODE)
1575                {
1576                    return Support::No(Refusal::ReservedHeaderMode {
1577                        mode: RESERVED_SUBGROUP_ID_MODE,
1578                    });
1579                }
1580                match cx.subgroup_id_resolved {
1581                    Some(false) => return Support::No(Refusal::WouldRedefineSubgroupId),
1582                    None => {
1583                        return Support::Conditional(Precondition::NotFirstObjectOfImplicitSubgroup)
1584                    }
1585                    Some(true) => {}
1586                }
1587            }
1588            None => {
1589                return Support::Conditional(Precondition::NotFirstObjectOfImplicitSubgroup);
1590            }
1591        }
1592    }
1593
1594    match cx.is_status_object {
1595        Some(true) => Support::No(Refusal::WouldDestroyStatusObject),
1596        Some(false) => Support::Yes,
1597        None => Support::Conditional(Precondition::NotAStatusObject),
1598    }
1599}
1600
1601/// The datagram site.
1602///
1603/// # A datagram is policed and never paced, and that is a decision
1604///
1605/// `Truncate` and `ResetStream` name a stream and a datagram has none, so
1606/// those two are a type error wearing a refusal. `Delay` and `Hold` are
1607/// refused for a different reason, and an author who reaches that refusal is
1608/// owed the reason rather than the mechanism.
1609///
1610/// **A rate aimed at datagrams drops what it cannot cover, at the instant the
1611/// datagram arrived.** `forward_datagrams` asks the class's bucket and
1612/// discards every answer but *now* — including `Later`, where an instant does
1613/// exist and the datagram could have been held until it. So a datagram-mode
1614/// track can be held to a rate; what it cannot be is smoothed.
1615///
1616/// Smoothing would need a per-connection queue, and the argument against one
1617/// is not that it is hard:
1618///
1619/// - **It would model nothing.** A bottleneck queues by link, not by track: a
1620///   router does not know which track a datagram belongs to. Class-aware
1621///   *policing* is a real box — an operator rate-limiter drops over rate —
1622///   and class-aware *smoothing* is a scheduler inside a router, which is not
1623///   a condition a player is ever placed in.
1624/// - **It would impose an order the protocol does not have.** A datagram
1625///   belongs to no stream and has no successor to renumber. A FIFO would make
1626///   this proxy the one hop on the path that never reorders, which is a less
1627///   faithful network, not a more controlled one.
1628/// - **The capability already exists one layer down.** `quinn-netem` delays,
1629///   jitters and reorders at the socket, under the whole connection — which
1630///   is exactly the scope a link-level queue has. It is not class-aware, and
1631///   that is the correct scope for it rather than a gap in it.
1632///
1633/// So the answer for *smooth this traffic* is `quinn-netem`, and the answer
1634/// for *hold this track to a rate* is a class over a bucket, which is here.
1635/// The framed sites keep `Delay` and `Hold` because a stream **has** a
1636/// delivery order: holding object N and then N+1 preserves a guarantee the
1637/// protocol makes, where holding two datagrams would manufacture one.
1638///
1639/// `tests/actions_shaping.rs` pins both halves — that a dry bucket discards,
1640/// and that a *live* rate discards too rather than deferring to the instant
1641/// it names, which is the assertion a queue would break.
1642fn classify_datagram(kind: ActionKind, cx: &CapCtx) -> Support {
1643    match kind {
1644        ActionKind::Pass | ActionKind::DropElide | ActionKind::CloseSession => Support::Yes,
1645        // Always conditional: no transport in the workspace exposes a
1646        // maximum datagram size, so the verdict comes from
1647        // `send_datagram` failing, as `ActionFailed`.
1648        ActionKind::Replace => Support::Conditional(Precondition::WithinMaxDatagramSize),
1649        ActionKind::ReplacePayload => datagram_replace_payload(cx),
1650        // Two refusals with two reasons, both above: a stream action naming a
1651        // carrier that has no stream, and a deliberate absence of pacing.
1652        ActionKind::Delay | ActionKind::Hold | ActionKind::Truncate | ActionKind::ResetStream => {
1653            Support::No(Refusal::WrongSite { site: Site::Datagram, action: kind })
1654        }
1655        ActionKind::Open
1656        | ActionKind::Reject
1657        | ActionKind::ReplaceObject
1658        | ActionKind::OpenAfter
1659        | ActionKind::SerializeAfter => filtered_earlier(Site::Datagram, kind),
1660    }
1661}
1662
1663/// The datagram site's `ReplacePayload` rule: the payload's start offset
1664/// must be derivable, or there is nowhere to splice the replacement in.
1665fn datagram_replace_payload(cx: &CapCtx) -> Support {
1666    match cx.payload_delimited {
1667        Some(true) => Support::Yes,
1668        Some(false) => {
1669            Support::No(Refusal::PayloadNotDelimited { detail: payload_not_delimited_detail(cx) })
1670        }
1671        None => Support::Conditional(Precondition::DatagramPayloadDelimited),
1672    }
1673}
1674
1675/// Which of [`Precondition::DatagramPayloadDelimited`]'s three cases failed.
1676fn payload_not_delimited_detail(cx: &CapCtx) -> &'static str {
1677    if cx.draft == Some(DraftVersion::Draft14) {
1678        "draft-14 header decode consumes the payload"
1679    } else if cx.is_status_object == Some(true) {
1680        "status datagram has no payload"
1681    } else {
1682        "datagram header did not decode"
1683    }
1684}
1685
1686/// The two stream-decision sites.
1687///
1688/// [`ActionKind::SerializeAfter`] takes exactly the verdict
1689/// [`ActionKind::Open`] takes at both sites: it defers the first *write*,
1690/// which either site can still decide. [`ActionKind::OpenAfter`] takes the
1691/// same at [`Site::StreamOpen`] and is refused at [`Site::StreamHeader`],
1692/// because the peer stream is opened before a byte of the source is read —
1693/// by the header site there is nothing left to defer, and moving `open_uni`
1694/// behind the header decision would erase the published difference between
1695/// the two reject sites.
1696///
1697/// The refusal is what keeps the header cell honest, and it is observable:
1698/// the engine reports `ProxyEvent::ActionRefused` naming
1699/// [`Refusal::WrongSite`], and the stream is forwarded unchanged. Admitting
1700/// it there instead would publish a delay nothing performs —
1701/// `tests/open_after_ordering.rs` runs exactly that mutation and records
1702/// what a caller would get.
1703fn classify_stream_decision(site: Site, kind: ActionKind) -> Support {
1704    match kind {
1705        ActionKind::Open | ActionKind::Reject | ActionKind::SerializeAfter => Support::Yes,
1706        ActionKind::OpenAfter => match site {
1707            Site::StreamOpen => Support::Yes,
1708            _ => Support::No(Refusal::WrongSite { site, action: kind }),
1709        },
1710        ActionKind::Pass
1711        | ActionKind::Replace
1712        | ActionKind::ReplacePayload
1713        | ActionKind::Delay
1714        | ActionKind::Hold
1715        | ActionKind::DropElide
1716        | ActionKind::Truncate
1717        | ActionKind::ResetStream
1718        | ActionKind::CloseSession
1719        | ActionKind::ReplaceObject => filtered_earlier(site, kind),
1720    }
1721}
1722
1723/// The stream-end site's two columns: data streams and control streams.
1724///
1725/// `CloseSession` is honoured on both: a session close is session-scoped,
1726/// so no site can be the wrong one for it. `ResetStream` turns a clean FIN
1727/// into a reset on a **data** stream and is refused on a control stream,
1728/// where it would be a session-level protocol violation — as is
1729/// `Truncate`, which is the same violation with a prefix attached.
1730fn classify_stream_end(kind: ActionKind, cx: &CapCtx) -> Support {
1731    let control = cx.is_control_stream == Some(true);
1732    match kind {
1733        ActionKind::Pass | ActionKind::CloseSession => Support::Yes,
1734        ActionKind::ResetStream => {
1735            if control {
1736                Support::No(Refusal::ControlStreamResetIllegal)
1737            } else {
1738                Support::Yes
1739            }
1740        }
1741        ActionKind::Truncate => {
1742            if control {
1743                Support::No(Refusal::ControlStreamResetIllegal)
1744            } else {
1745                Support::No(Refusal::WrongSite { site: Site::StreamEnd, action: kind })
1746            }
1747        }
1748        // Delaying a stream's end is expressed by delaying its last object;
1749        // there is no unit here to replace or drop.
1750        ActionKind::Replace
1751        | ActionKind::ReplacePayload
1752        | ActionKind::Delay
1753        | ActionKind::Hold
1754        | ActionKind::DropElide => {
1755            Support::No(Refusal::WrongSite { site: Site::StreamEnd, action: kind })
1756        }
1757        ActionKind::Open
1758        | ActionKind::Reject
1759        | ActionKind::ReplaceObject
1760        | ActionKind::OpenAfter
1761        | ActionKind::SerializeAfter => filtered_earlier(Site::StreamEnd, kind),
1762    }
1763}
1764
1765#[cfg(test)]
1766mod tests {
1767    use super::*;
1768
1769    /// Every draft, in publication order. Not feature-gated:
1770    /// [`DraftVersion`] carries all thirteen variants under every draft
1771    /// feature set, so the table is answerable for a draft this build
1772    /// cannot speak.
1773    const DRAFTS: [DraftVersion; 13] = [
1774        DraftVersion::Draft07,
1775        DraftVersion::Draft08,
1776        DraftVersion::Draft09,
1777        DraftVersion::Draft10,
1778        DraftVersion::Draft11,
1779        DraftVersion::Draft12,
1780        DraftVersion::Draft13,
1781        DraftVersion::Draft14,
1782        DraftVersion::Draft15,
1783        DraftVersion::Draft16,
1784        DraftVersion::Draft17,
1785        DraftVersion::Draft18,
1786        DraftVersion::Draft19,
1787    ];
1788
1789    /// All sixteen kinds — the axis every table test below sweeps.
1790    const KINDS: [ActionKind; 14] = [
1791        ActionKind::Pass,
1792        ActionKind::Replace,
1793        ActionKind::ReplacePayload,
1794        ActionKind::Delay,
1795        ActionKind::Hold,
1796        ActionKind::DropElide,
1797        ActionKind::Truncate,
1798        ActionKind::ResetStream,
1799        ActionKind::CloseSession,
1800        ActionKind::Open,
1801        ActionKind::Reject,
1802        ActionKind::ReplaceObject,
1803        ActionKind::OpenAfter,
1804        ActionKind::SerializeAfter,
1805    ];
1806
1807    const SITES: [Site; 6] = [
1808        Site::Control,
1809        Site::Object,
1810        Site::Datagram,
1811        Site::StreamOpen,
1812        Site::StreamHeader,
1813        Site::StreamEnd,
1814    ];
1815
1816    fn wrong_site(site: Site, action: ActionKind) -> Support {
1817        Support::No(Refusal::WrongSite { site, action })
1818    }
1819
1820    fn returns_action(site: Site, action: ActionKind) -> Support {
1821        Support::NotAttemptable {
1822            why: NotAttemptable::SiteReturnsAction,
1823            refusal: Refusal::WrongSite { site, action },
1824        }
1825    }
1826
1827    fn returns_stream_action(site: Site, action: ActionKind) -> Support {
1828        Support::NotAttemptable {
1829            why: NotAttemptable::SiteReturnsStreamAction,
1830            refusal: Refusal::WrongSite { site, action },
1831        }
1832    }
1833
1834    fn kind_not_here(site: Site, action: ActionKind) -> Support {
1835        Support::NotAttemptable {
1836            why: NotAttemptable::KindNotDefinedAtThisSite,
1837            refusal: Refusal::WrongSite { site, action },
1838        }
1839    }
1840
1841    fn unreachable_with(reason: BypassReason) -> Support {
1842        Support::Unreachable {
1843            refusal: Refusal::StreamNotFramed { reason },
1844            instead: Instead::FramerBypass(reason),
1845        }
1846    }
1847
1848    /// The control site's verdict on a draft this build did not compile.
1849    fn unreachable_control() -> Support {
1850        Support::Unreachable {
1851            refusal: Refusal::ControlFrameNotDecodable,
1852            instead: Instead::ControlFrameNotDecodable,
1853        }
1854    }
1855
1856    /// The object-site verdict the framing facts alone dictate, or `None`
1857    /// when the framer can address the stream and the per-kind rules decide.
1858    ///
1859    /// Built from [`object_framing_bypass`], which is the function under
1860    /// test — so it is used only to *select* which expectation applies, never
1861    /// as the expectation itself. The compiled-set rows are asserted against
1862    /// the feature flags directly in
1863    /// [`the_object_site_is_unreachable_on_a_draft_this_build_did_not_compile`].
1864    fn framing_verdict(draft: DraftVersion, stream_kind: DataStreamType) -> Option<Support> {
1865        object_framing_bypass(draft, Some(stream_kind)).map(unreachable_with)
1866    }
1867
1868    /// A draft this build compiled, for the per-unit tests whose subject is
1869    /// a guard that does not depend on the draft.
1870    ///
1871    /// The `expect` is unreachable, not a skip: this helper and its two
1872    /// callers are compiled exactly when at least one draft feature is on,
1873    /// so `find` always succeeds. A `--no-default-features` build has no
1874    /// object site at all — it is not that those two facts go untested
1875    /// there, it is that there is no object site for them to be facts
1876    /// about, the same reason `exec.rs` compiles its object-site units only
1877    /// where their draft was compiled. What is *not* acceptable is the
1878    /// shape this replaced: a build that compiles clean under
1879    /// `-D warnings` and then panics at run time.
1880    #[cfg(any(
1881        feature = "draft07",
1882        feature = "draft08",
1883        feature = "draft09",
1884        feature = "draft10",
1885        feature = "draft11",
1886        feature = "draft12",
1887        feature = "draft13",
1888        feature = "draft14",
1889        feature = "draft15",
1890        feature = "draft16",
1891        feature = "draft17",
1892        feature = "draft18",
1893        feature = "draft19"
1894    ))]
1895    fn some_compiled_draft() -> DraftVersion {
1896        DRAFTS
1897            .into_iter()
1898            .find(|d| draft_is_compiled(*d))
1899            .expect("gated on `any(draft07..draft19)`, so the compiled set is non-empty")
1900    }
1901
1902    /// A configuration nobody edited can shape the traffic it will see.
1903    ///
1904    /// The consequence rather than the value. A class rule naming an ordinary
1905    /// key is put to the capability table at the draft a default configuration
1906    /// takes, and it is carried. Where the default names a draft the build did
1907    /// not compile, [`supports_matcher`] answers `false` for every key on every
1908    /// stream kind, and a rule with nothing wrong with it is refused as naming
1909    /// one the draft does not carry.
1910    ///
1911    /// **This cannot fail on a full build**, which is why the const assertion
1912    /// beside [`DEFAULT_DRAFT`] is what holds the invariant and this is the
1913    /// statement of what the invariant is for. A reduced-draft build is the
1914    /// only kind that can have the defect, and those are compiled rather than
1915    /// run.
1916    #[test]
1917    fn a_default_configuration_can_shape_the_draft_it_names() {
1918        let draft = crate::session::ProxySessionConfig::default().draft;
1919        assert!(
1920            supports_matcher(draft, MatchKind::Subgroup, MatcherKey::GroupId),
1921            "a default configuration names {draft:?}, which this build did not compile, so \
1922             every matcher key is refused on it"
1923        );
1924    }
1925
1926    /// The compiled drafts for which `pred` holds, so a sweep that needs a
1927    /// draft-shape property still runs in a reduced-draft build and is
1928    /// simply empty where no such draft was compiled.
1929    ///
1930    /// **Do not pass a predicate the sweep is checking.** Narrowing such a
1931    /// predicate narrows this loop rather than failing a row in it: the drafts
1932    /// that drop out stop being asked, every draft left passes, and the sweep
1933    /// reports green over a smaller set than it covered before. Pass
1934    /// `|_| true` and let the body name each draft's answer, or pass a fact
1935    /// the code under test does not read.
1936    fn compiled_drafts_where(pred: fn(DraftVersion) -> bool) -> Vec<DraftVersion> {
1937        DRAFTS.into_iter().filter(|d| draft_is_compiled(*d) && pred(*d)).collect()
1938    }
1939
1940    /// Whether a subgroup stream on this draft can take its Subgroup ID from
1941    /// the first object on it — stated here, per draft, and deliberately not
1942    /// read from [`has_implicit_subgroup_id_mode`].
1943    ///
1944    /// Two tests below turn on this fact and both used to take it from that
1945    /// predicate, which made each of them agree with whatever it said. Both
1946    /// narrowings were run. Removing draft-15 — the exact omission that once
1947    /// let the engine forward a stream whose Subgroup ID had silently become
1948    /// the second object's — left both passing, as did narrowing the predicate
1949    /// all the way to drafts 17-19.
1950    ///
1951    /// Eight other tests caught that second cut, so the fence was real; it was
1952    /// simply not here. `tests/action_matrix.rs` keeps its own copy of this
1953    /// fact, transcribed from the drafts rather than read off the engine, and
1954    /// the end-to-end probes it guards are what failed. This is the in-crate
1955    /// statement of the same fact, and the two are checked against each other
1956    /// by every verdict they both predict.
1957    ///
1958    /// The match is exhaustive on purpose: a fourteenth draft cannot join
1959    /// either side of the partition without an answer being written here.
1960    fn a_first_object_carrier_exists(draft: DraftVersion) -> bool {
1961        match draft {
1962            // Drafts 07-10 always put an explicit Subgroup ID in the header,
1963            // so index 0 defines nothing that outlives it.
1964            DraftVersion::Draft07
1965            | DraftVersion::Draft08
1966            | DraftVersion::Draft09
1967            | DraftVersion::Draft10 => false,
1968            DraftVersion::Draft11
1969            | DraftVersion::Draft12
1970            | DraftVersion::Draft13
1971            | DraftVersion::Draft14
1972            | DraftVersion::Draft15
1973            | DraftVersion::Draft16
1974            | DraftVersion::Draft17
1975            | DraftVersion::Draft18
1976            | DraftVersion::Draft19 => true,
1977        }
1978    }
1979
1980    /// The object site on a subgroup stream: every cell, on every draft.
1981    #[test]
1982    fn object_site_on_subgroup_streams_matches_the_published_table() {
1983        for draft in DRAFTS {
1984            let caps = Capabilities::for_draft(draft);
1985            let cell = |kind| caps.supports_on(Site::Object, kind, DataStreamType::Subgroup);
1986            // A subgroup stream is addressable on every draft this build
1987            // compiled, and on none it did not — see `draft_is_compiled`.
1988            let bypassed = framing_verdict(draft, DataStreamType::Subgroup);
1989
1990            for kind in [
1991                ActionKind::Pass,
1992                ActionKind::Delay,
1993                ActionKind::Hold,
1994                ActionKind::Truncate,
1995                ActionKind::ResetStream,
1996                ActionKind::CloseSession,
1997            ] {
1998                let want = bypassed.clone().unwrap_or(Support::Yes);
1999                assert_eq!(cell(kind), want, "{draft:?} {kind:?}");
2000            }
2001
2002            let want = bypassed
2003                .clone()
2004                .unwrap_or(Support::Conditional(Precondition::ReplacementLengthEqualsPayload));
2005            assert_eq!(cell(ActionKind::ReplacePayload), want, "{draft:?}: ReplacePayload support");
2006
2007            // Only the status guard on 07-10, the four drafts that always put
2008            // the subgroup ID on the wire and so have no first-object
2009            // carrier; the subgroup-ID guard leads on every other draft. The
2010            // fact comes from this module's tests rather than from the
2011            // predicate the table consults, so that narrowing that predicate
2012            // contradicts this row instead of moving it.
2013            let elide_headline = if a_first_object_carrier_exists(draft) {
2014                Precondition::NotFirstObjectOfImplicitSubgroup
2015            } else {
2016                Precondition::NotAStatusObject
2017            };
2018            let want = bypassed.clone().unwrap_or(Support::Conditional(elide_headline));
2019            assert_eq!(cell(ActionKind::DropElide), want, "{draft:?} elide");
2020
2021            let whole_object =
2022                bypassed.clone().unwrap_or(wrong_site(Site::Object, ActionKind::ReplaceObject));
2023            assert_eq!(cell(ActionKind::Replace), whole_object, "{draft:?}");
2024            assert_eq!(cell(ActionKind::ReplaceObject), whole_object, "{draft:?}");
2025
2026            for kind in [
2027                ActionKind::Open,
2028                ActionKind::Reject,
2029                ActionKind::OpenAfter,
2030                ActionKind::SerializeAfter,
2031            ] {
2032                assert_eq!(cell(kind), returns_action(Site::Object, kind), "{draft:?}");
2033            }
2034        }
2035    }
2036
2037    /// The object site on a fetch stream: every cell, on every draft.
2038    ///
2039    /// One column now, where there were two. A fetch stream is addressable on
2040    /// every draft this build compiled, and the drafts that need the fetch's
2041    /// Group Order to read one get it from the session rather than from the
2042    /// table — see [`fetch_group_order_is_needed`].
2043    #[test]
2044    fn object_site_on_fetch_streams_matches_the_published_table() {
2045        for draft in DRAFTS {
2046            let caps = Capabilities::for_draft(draft);
2047            let cell = |kind| caps.supports_on(Site::Object, kind, DataStreamType::Fetch);
2048            // `DecodeError` on any draft this build left out, and nothing
2049            // on any it compiled: the header decode fails first there, so a
2050            // fetch stream's own reasons are never reached.
2051            let bypassed = framing_verdict(draft, DataStreamType::Fetch);
2052            if !draft_is_compiled(draft) {
2053                assert_eq!(
2054                    bypassed.clone(),
2055                    Some(unreachable_with(BypassReason::DecodeError)),
2056                    "{draft:?} is not compiled: the header decode is what fails"
2057                );
2058            } else {
2059                assert_eq!(
2060                    bypassed.clone(),
2061                    None,
2062                    "{draft:?} is compiled, so its fetch objects are the per-kind rules' to                      decide"
2063                );
2064            }
2065
2066            for kind in [
2067                ActionKind::Pass,
2068                ActionKind::Delay,
2069                ActionKind::Hold,
2070                ActionKind::Truncate,
2071                ActionKind::ResetStream,
2072                ActionKind::CloseSession,
2073            ] {
2074                let want = bypassed.clone().unwrap_or(Support::Yes);
2075                assert_eq!(cell(kind), want, "{draft:?} {kind:?}");
2076            }
2077
2078            let want = bypassed
2079                .clone()
2080                .unwrap_or(Support::Conditional(Precondition::ReplacementLengthEqualsPayload));
2081            assert_eq!(cell(ActionKind::ReplacePayload), want, "{draft:?}");
2082
2083            // The status guard is the only one a fetch stream reaches, on
2084            // every draft: no subgroup-ID guard applies to an object that
2085            // states its own subgroup, and a removal that moves the survivors
2086            // is paid for by the framer rather than refused.
2087            let want =
2088                bypassed.clone().unwrap_or(Support::Conditional(Precondition::NotAStatusObject));
2089            assert_eq!(cell(ActionKind::DropElide), want, "{draft:?}");
2090
2091            for kind in [ActionKind::Replace, ActionKind::ReplaceObject] {
2092                let want =
2093                    bypassed.clone().unwrap_or(wrong_site(Site::Object, ActionKind::ReplaceObject));
2094                assert_eq!(cell(kind), want, "{draft:?} {kind:?}");
2095            }
2096
2097            // The unconstructible two and the four stream decisions stay
2098            // `NotAttemptable` even where the hook is never invoked — the
2099            // return-type family is decided before the framing bypass, so
2100            // a fetch cell on 18-19 is `NotAttemptable`, not `Unreachable`.
2101            for kind in [
2102                ActionKind::Open,
2103                ActionKind::Reject,
2104                ActionKind::OpenAfter,
2105                ActionKind::SerializeAfter,
2106            ] {
2107                assert_eq!(cell(kind), returns_action(Site::Object, kind), "{draft:?}");
2108            }
2109        }
2110    }
2111
2112    /// The control site on every draft, which is one column and not two:
2113    /// the six honoured kinds are `Yes` on all thirteen this build carries.
2114    ///
2115    /// A draft it does not carry moves the **whole** classified column to
2116    /// [`Support::Unreachable`] together, refusals included. That is the
2117    /// object site's rule one decoder later and for the same reason: the
2118    /// hook is never offered a frame, so `ControlStreamResetIllegal` is a
2119    /// refusal nothing would ever be there to receive. Publishing it beside
2120    /// an unreachable `Pass` would say a reset was considered and declined
2121    /// where in fact nothing was considered at all.
2122    #[test]
2123    fn control_site_matches_the_published_table() {
2124        for draft in DRAFTS {
2125            let caps = Capabilities::for_draft(draft);
2126            let cell = |kind| caps.supports(Site::Control, kind);
2127
2128            // The two `NotAttemptable` families below are decided ahead of
2129            // reachability — `classify` step 1 — so they keep their own
2130            // answers on every build, and this wrapper is deliberately not
2131            // applied to them.
2132            let unreachable = !draft_is_compiled(draft);
2133            let or_unreachable =
2134                |want: Support| if unreachable { unreachable_control() } else { want };
2135
2136            for kind in [
2137                ActionKind::Pass,
2138                ActionKind::Replace,
2139                ActionKind::Delay,
2140                ActionKind::Hold,
2141                ActionKind::DropElide,
2142                ActionKind::CloseSession,
2143            ] {
2144                assert_eq!(cell(kind), or_unreachable(Support::Yes), "{draft:?} {kind:?}");
2145            }
2146
2147            assert_eq!(
2148                cell(ActionKind::ReplacePayload),
2149                or_unreachable(wrong_site(Site::Control, ActionKind::ReplacePayload)),
2150                "{draft:?}"
2151            );
2152            for kind in [ActionKind::Truncate, ActionKind::ResetStream] {
2153                assert_eq!(
2154                    cell(kind),
2155                    or_unreachable(Support::No(Refusal::ControlStreamResetIllegal)),
2156                    "{draft:?} {kind:?}"
2157                );
2158            }
2159            for kind in [ActionKind::Open, ActionKind::Reject] {
2160                assert_eq!(cell(kind), returns_action(Site::Control, kind), "{draft:?}");
2161            }
2162            assert_eq!(
2163                cell(ActionKind::ReplaceObject),
2164                kind_not_here(Site::Control, ActionKind::ReplaceObject),
2165                "{draft:?}"
2166            );
2167        }
2168    }
2169
2170    /// The datagram site on every draft.
2171    #[test]
2172    fn datagram_site_matches_the_published_table() {
2173        for draft in DRAFTS {
2174            let caps = Capabilities::for_draft(draft);
2175            let cell = |kind| caps.supports(Site::Datagram, kind);
2176
2177            for kind in [ActionKind::Pass, ActionKind::DropElide, ActionKind::CloseSession] {
2178                assert_eq!(cell(kind), Support::Yes, "{draft:?} {kind:?}");
2179            }
2180            assert_eq!(
2181                cell(ActionKind::Replace),
2182                Support::Conditional(Precondition::WithinMaxDatagramSize),
2183                "{draft:?}"
2184            );
2185            assert_eq!(
2186                cell(ActionKind::ReplacePayload),
2187                Support::Conditional(Precondition::DatagramPayloadDelimited),
2188                "{draft:?}"
2189            );
2190            for kind in
2191                [ActionKind::Delay, ActionKind::Hold, ActionKind::Truncate, ActionKind::ResetStream]
2192            {
2193                assert_eq!(cell(kind), wrong_site(Site::Datagram, kind), "{draft:?} {kind:?}");
2194            }
2195        }
2196    }
2197
2198    /// The two stream-decision sites on every draft.
2199    #[test]
2200    fn stream_decision_sites_match_the_published_table() {
2201        for draft in DRAFTS {
2202            let caps = Capabilities::for_draft(draft);
2203            for site in [Site::StreamOpen, Site::StreamHeader] {
2204                assert_eq!(caps.supports(site, ActionKind::Open), Support::Yes);
2205                assert_eq!(caps.supports(site, ActionKind::Reject), Support::Yes);
2206                // `SerializeAfter` tracks `Open` at both sites;
2207                // `OpenAfter` is refused at the header site, where the peer
2208                // stream already exists.
2209                assert_eq!(
2210                    caps.supports(site, ActionKind::SerializeAfter),
2211                    Support::Yes,
2212                    "{draft:?} {site:?}"
2213                );
2214                let open_after = if site == Site::StreamOpen {
2215                    Support::Yes
2216                } else {
2217                    wrong_site(site, ActionKind::OpenAfter)
2218                };
2219                assert_eq!(
2220                    caps.supports(site, ActionKind::OpenAfter),
2221                    open_after,
2222                    "{draft:?} {site:?}"
2223                );
2224
2225                for kind in [
2226                    ActionKind::Pass,
2227                    ActionKind::Replace,
2228                    ActionKind::ReplacePayload,
2229                    ActionKind::Delay,
2230                    ActionKind::Hold,
2231                    ActionKind::DropElide,
2232                    ActionKind::Truncate,
2233                    ActionKind::ResetStream,
2234                    ActionKind::CloseSession,
2235                ] {
2236                    assert_eq!(
2237                        caps.supports(site, kind),
2238                        returns_stream_action(site, kind),
2239                        "{draft:?} {site:?} {kind:?}"
2240                    );
2241                }
2242                assert_eq!(
2243                    caps.supports(site, ActionKind::ReplaceObject),
2244                    kind_not_here(site, ActionKind::ReplaceObject)
2245                );
2246            }
2247        }
2248    }
2249
2250    /// The stream-end site's two columns — the split
2251    /// `CapCtx::is_control_stream` exists to express, swept both ways.
2252    #[test]
2253    fn stream_end_is_answered_for_both_data_and_control_streams() {
2254        for draft in DRAFTS {
2255            for is_control in [false, true] {
2256                let cx = CapCtx {
2257                    draft: Some(draft),
2258                    is_control_stream: Some(is_control),
2259                    ..CapCtx::default()
2260                };
2261                let cell = |kind| classify(Site::StreamEnd, kind, &cx);
2262
2263                // Honoured on both columns.
2264                assert_eq!(cell(ActionKind::Pass), Support::Yes, "{draft:?}");
2265                assert_eq!(cell(ActionKind::CloseSession), Support::Yes, "{draft:?}");
2266
2267                let reset = cell(ActionKind::ResetStream);
2268                if is_control {
2269                    assert_eq!(reset, Support::No(Refusal::ControlStreamResetIllegal));
2270                } else {
2271                    assert_eq!(reset, Support::Yes);
2272                }
2273
2274                let truncate = cell(ActionKind::Truncate);
2275                if is_control {
2276                    assert_eq!(truncate, Support::No(Refusal::ControlStreamResetIllegal));
2277                } else {
2278                    assert_eq!(truncate, wrong_site(Site::StreamEnd, ActionKind::Truncate));
2279                }
2280
2281                for kind in [
2282                    ActionKind::Replace,
2283                    ActionKind::ReplacePayload,
2284                    ActionKind::Delay,
2285                    ActionKind::Hold,
2286                    ActionKind::DropElide,
2287                ] {
2288                    assert_eq!(
2289                        cell(kind),
2290                        wrong_site(Site::StreamEnd, kind),
2291                        "{draft:?} control={is_control} {kind:?}"
2292                    );
2293                }
2294            }
2295        }
2296    }
2297
2298    /// The whole point of the module: one reading, not three.
2299    #[test]
2300    fn replace_object_has_exactly_one_reading() {
2301        for site in SITES {
2302            let verdict = classify(site, ActionKind::ReplaceObject, &CapCtx::default());
2303            if site == Site::Object {
2304                assert_eq!(
2305                    verdict,
2306                    wrong_site(Site::Object, ActionKind::ReplaceObject),
2307                    "the object site really is asked, and really refuses"
2308                );
2309            } else {
2310                assert_eq!(verdict, kind_not_here(site, ActionKind::ReplaceObject), "{site:?}");
2311            }
2312        }
2313    }
2314
2315    /// At the object site the two rows are one expression, so they are one
2316    /// value.
2317    #[test]
2318    fn replace_and_replace_object_agree_at_the_object_site() {
2319        for draft in DRAFTS {
2320            for stream_kind in [DataStreamType::Subgroup, DataStreamType::Fetch] {
2321                let caps = Capabilities::for_draft(draft);
2322                assert_eq!(
2323                    caps.supports_on(Site::Object, ActionKind::Replace, stream_kind),
2324                    caps.supports_on(Site::Object, ActionKind::ReplaceObject, stream_kind),
2325                    "{draft:?} {stream_kind:?}"
2326                );
2327            }
2328        }
2329    }
2330    /// The table half of
2331    /// `every_declared_refusal_is_reachable_or_declared_table_only`: the
2332    /// table-only variant appears **only** inside `NotAttemptable` /
2333    /// `Unreachable`, never as a `No(..)` the engine would have to emit.
2334    #[test]
2335    fn table_only_refusals_never_appear_as_no() {
2336        for draft in DRAFTS {
2337            let caps = Capabilities::for_draft(draft);
2338            for site in SITES {
2339                for kind in KINDS {
2340                    for verdict in [
2341                        caps.supports(site, kind),
2342                        caps.supports_on(site, kind, DataStreamType::Subgroup),
2343                        caps.supports_on(site, kind, DataStreamType::Fetch),
2344                    ] {
2345                        let Support::No(refusal) = verdict else {
2346                            continue;
2347                        };
2348                        assert!(
2349                            !matches!(
2350                                refusal,
2351                                Refusal::StreamNotFramed { .. }
2352                            ),
2353                            "{draft:?} {site:?} {kind:?} declares a table-only refusal as No({refusal:?})"
2354                        );
2355                    }
2356                }
2357            }
2358        }
2359    }
2360
2361    /// Every cell of the sweep axis has a verdict — no `(site, kind)` pair
2362    /// falls through a helper's filtered arm into a wrong answer.
2363    #[test]
2364    fn every_site_kind_pair_is_answered() {
2365        for draft in DRAFTS {
2366            let caps = Capabilities::for_draft(draft);
2367            for site in SITES {
2368                for kind in KINDS {
2369                    let verdict = caps.supports(site, kind);
2370                    // A filtered-arm leak would surface as a
2371                    // `KindNotDefinedAtThisSite` on a kind that is not
2372                    // `ReplaceObject`.
2373                    if let Support::NotAttemptable {
2374                        why: NotAttemptable::KindNotDefinedAtThisSite,
2375                        ..
2376                    } = verdict
2377                    {
2378                        assert_eq!(
2379                            kind,
2380                            ActionKind::ReplaceObject,
2381                            "{site:?} {kind:?} fell through to the filtered arm"
2382                        );
2383                    }
2384                }
2385            }
2386        }
2387    }
2388
2389    // ── The per-unit facts: `Conditional` resolving both ways ───────────
2390
2391    /// The length guard reads no draft field, so it is asserted on whatever
2392    /// draft this build compiled rather than on a hard-coded one — which is
2393    /// what keeps it running in a reduced-draft build, where a hard-coded
2394    /// draft-11 would be [`Support::Unreachable`] and measure nothing.
2395    ///
2396    /// Compiled where any draft was, because [`some_compiled_draft`] has an
2397    /// answer exactly there; a zero-draft build reaches no object site.
2398    #[cfg(any(
2399        feature = "draft07",
2400        feature = "draft08",
2401        feature = "draft09",
2402        feature = "draft10",
2403        feature = "draft11",
2404        feature = "draft12",
2405        feature = "draft13",
2406        feature = "draft14",
2407        feature = "draft15",
2408        feature = "draft16",
2409        feature = "draft17",
2410        feature = "draft18",
2411        feature = "draft19"
2412    ))]
2413    #[test]
2414    fn replace_payload_length_mismatch_is_length_changed() {
2415        let cx = CapCtx {
2416            draft: Some(some_compiled_draft()),
2417            payload_len: Some(1200),
2418            replacement_len: Some(800),
2419            is_status_object: Some(false),
2420            ..CapCtx::default()
2421        };
2422        assert_eq!(
2423            classify(Site::Object, ActionKind::ReplacePayload, &cx),
2424            Support::No(Refusal::LengthChanged { from: 1200, to: 800 })
2425        );
2426
2427        let ok = CapCtx { replacement_len: Some(1200), ..cx };
2428        assert_eq!(classify(Site::Object, ActionKind::ReplacePayload, &ok), Support::Yes);
2429    }
2430
2431    /// Gated with its neighbour, and for the same reason.
2432    #[cfg(any(
2433        feature = "draft07",
2434        feature = "draft08",
2435        feature = "draft09",
2436        feature = "draft10",
2437        feature = "draft11",
2438        feature = "draft12",
2439        feature = "draft13",
2440        feature = "draft14",
2441        feature = "draft15",
2442        feature = "draft16",
2443        feature = "draft17",
2444        feature = "draft18",
2445        feature = "draft19"
2446    ))]
2447    #[test]
2448    fn replace_payload_on_a_status_object_is_refused() {
2449        let cx = CapCtx {
2450            draft: Some(some_compiled_draft()),
2451            payload_len: Some(0),
2452            replacement_len: Some(0),
2453            is_status_object: Some(true),
2454            ..CapCtx::default()
2455        };
2456        assert_eq!(
2457            classify(Site::Object, ActionKind::ReplacePayload, &cx),
2458            Support::No(Refusal::WouldDestroyStatusObject)
2459        );
2460    }
2461
2462    /// The reserved-mode split, on every draft whose two mode bits have to be
2463    /// consulted **and** was compiled. Empty in a build that left all five
2464    /// out, which is the honest answer there: those cells are `Unreachable`.
2465    #[test]
2466    fn elide_guards_follow_the_execution_order() {
2467        for draft in compiled_drafts_where(subgroup_id_mode_must_be_consulted) {
2468            let base = CapCtx {
2469                draft: Some(draft),
2470                stream_kind: Some(DataStreamType::Subgroup),
2471                index_in_stream: Some(0),
2472                subgroup_id_resolved: Some(false),
2473                is_status_object: Some(false),
2474                ..CapCtx::default()
2475            };
2476
2477            // Mode 1: the first object defines the subgroup ID.
2478            assert_eq!(
2479                classify(Site::Object, ActionKind::DropElide, &base),
2480                Support::No(Refusal::WouldRedefineSubgroupId),
2481                "{draft:?}"
2482            );
2483
2484            // Mode 3 is reserved, and says something different about the wire.
2485            let reserved = CapCtx { subgroup_id_mode: Some(3), ..base };
2486            assert_eq!(
2487                classify(Site::Object, ActionKind::DropElide, &reserved),
2488                Support::No(Refusal::ReservedHeaderMode { mode: 3 }),
2489                "{draft:?}"
2490            );
2491
2492            // Later objects on the same stream redefine nothing.
2493            let later = CapCtx { index_in_stream: Some(1), ..base };
2494            assert_eq!(
2495                classify(Site::Object, ActionKind::DropElide, &later),
2496                Support::Yes,
2497                "{draft:?}"
2498            );
2499
2500            // A status object is a boundary marker on every draft.
2501            let status = CapCtx { is_status_object: Some(true), ..later };
2502            assert_eq!(
2503                classify(Site::Object, ActionKind::DropElide, &status),
2504                Support::No(Refusal::WouldDestroyStatusObject),
2505                "{draft:?}"
2506            );
2507        }
2508    }
2509
2510    /// What a reserved mode is answered with, on every compiled draft, from a
2511    /// list written out here rather than taken from
2512    /// [`subgroup_id_mode_must_be_consulted`].
2513    ///
2514    /// The test above sweeps that predicate, which makes it blind in one
2515    /// direction: narrowing the predicate narrows its loop, so coverage
2516    /// disappears without a failure and the drafts that dropped out are simply
2517    /// no longer asked. This match is exhaustive over [`DraftVersion`] and
2518    /// names every draft's answer, so narrowing the predicate contradicts a
2519    /// line here instead, and a fourteenth draft cannot be added without one.
2520    ///
2521    /// Three answers, and each is a different sentence about the wire:
2522    ///
2523    /// - Drafts 07-10 always put the Subgroup ID on the wire, so index 0 is
2524    ///   not special and there is nothing to refuse.
2525    /// - Drafts 11-14 name each carrier with a stream type of its own and
2526    ///   assign every type they define, so a header that determines no
2527    ///   Subgroup ID is a first-object header and nothing else — the mode
2528    ///   field is not theirs to read, and `WouldRedefineSubgroupId` is exactly
2529    ///   what is true of one.
2530    /// - Drafts 15-19 encode the carrier in two bits with a fourth
2531    ///   combination none of them assigns, so a header can determine no
2532    ///   Subgroup ID for either reason and the mode is what separates them.
2533    ///
2534    /// *Ablation (measured):* return to naming only drafts 17, 18 and 19 in
2535    /// `subgroup_id_mode_must_be_consulted`, which is the set it held while the
2536    /// codec still resolved the fourth combination on 15 and 16:
2537    ///
2538    /// ```text
2539    /// assertion `left == right` failed: Draft15
2540    ///   left: No(WouldRedefineSubgroupId)
2541    ///  right: No(ReservedHeaderMode { mode: 3 })
2542    /// ```
2543    ///
2544    /// The test above passes under that same ablation, which is why this one
2545    /// is here.
2546    #[test]
2547    fn a_reserved_mode_is_answered_as_itself_wherever_a_header_can_carry_one() {
2548        for draft in compiled_drafts_where(|_| true) {
2549            let cx = CapCtx {
2550                draft: Some(draft),
2551                stream_kind: Some(DataStreamType::Subgroup),
2552                index_in_stream: Some(0),
2553                subgroup_id_resolved: Some(false),
2554                is_status_object: Some(false),
2555                subgroup_id_mode: Some(RESERVED_SUBGROUP_ID_MODE),
2556                ..CapCtx::default()
2557            };
2558            let want = match draft {
2559                DraftVersion::Draft07
2560                | DraftVersion::Draft08
2561                | DraftVersion::Draft09
2562                | DraftVersion::Draft10 => Support::Yes,
2563                DraftVersion::Draft11
2564                | DraftVersion::Draft12
2565                | DraftVersion::Draft13
2566                | DraftVersion::Draft14 => Support::No(Refusal::WouldRedefineSubgroupId),
2567                DraftVersion::Draft15
2568                | DraftVersion::Draft16
2569                | DraftVersion::Draft17
2570                | DraftVersion::Draft18
2571                | DraftVersion::Draft19 => {
2572                    Support::No(Refusal::ReservedHeaderMode { mode: RESERVED_SUBGROUP_ID_MODE })
2573                }
2574            };
2575            assert_eq!(classify(Site::Object, ActionKind::DropElide, &cx), want, "{draft:?}");
2576        }
2577    }
2578
2579    /// A header that determines its own Subgroup ID frees index 0 on **every**
2580    /// draft, first-object carrier or not.
2581    ///
2582    /// This swept only the drafts with no such carrier, taken from the
2583    /// predicate under test, and asserted the one thing that is true of them —
2584    /// which made it two tests' worth of blind spot for one test's worth of
2585    /// claim. Narrowing the predicate narrowed the loop rather than failing a
2586    /// row, and the drafts it added to the loop answered `Yes` anyway, because
2587    /// a resolved Subgroup ID satisfies the guard on every draft that has one.
2588    ///
2589    /// That last sentence is the claim worth making, so the sweep is now all
2590    /// thirteen and the expected answer is one value. The contrast it used to
2591    /// gesture at — refused where the carrier exists, allowed where it does
2592    /// not — is
2593    /// [`the_first_object_subgroup_guard_turns_on_the_stream_kind`], which
2594    /// states it per draft.
2595    #[test]
2596    fn a_resolved_subgroup_id_frees_the_first_object_on_every_draft() {
2597        for draft in compiled_drafts_where(|_| true) {
2598            let cx = CapCtx {
2599                draft: Some(draft),
2600                stream_kind: Some(DataStreamType::Subgroup),
2601                index_in_stream: Some(0),
2602                subgroup_id_resolved: Some(true),
2603                is_status_object: Some(false),
2604                ..CapCtx::default()
2605            };
2606            assert_eq!(
2607                classify(Site::Object, ActionKind::DropElide, &cx),
2608                Support::Yes,
2609                "{draft:?}"
2610            );
2611        }
2612    }
2613
2614    /// Index 0 with an unresolved subgroup ID — the exact shape the subgroup
2615    /// guard refuses — is refused on a subgroup stream and allowed on a fetch
2616    /// one, on every draft that addresses both.
2617    ///
2618    /// Both halves in one test because the claim is a contrast rather than
2619    /// two facts: the guard turns on the stream kind, and a fetch cell that
2620    /// happened to answer `Yes` for some other reason would be
2621    /// indistinguishable from one the guard never reached. A fetch object
2622    /// states its own Subgroup ID or states that it has none, so
2623    /// `WouldRedefineSubgroupId` is a sentence that is not true about it.
2624    ///
2625    /// The subgroup half takes which drafts have a first-object carrier from
2626    /// [`a_first_object_carrier_exists`] rather than from the predicate
2627    /// `classify` consults. Reading it from that predicate made this test
2628    /// agree with it whatever it said.
2629    ///
2630    /// *Ablation (measured):* narrow `has_implicit_subgroup_id_mode` to drafts
2631    /// 17, 18 and 19. With the fact taken independently, this now fails on the
2632    /// first draft that lost the guard:
2633    ///
2634    /// ```text
2635    /// assertion `left == right` failed: Draft11 subgroup
2636    ///   left: Yes
2637    ///  right: No(WouldRedefineSubgroupId)
2638    /// ```
2639    #[test]
2640    fn the_first_object_subgroup_guard_turns_on_the_stream_kind() {
2641        for draft in compiled_drafts_where(|_| true) {
2642            let cx = |stream_kind| CapCtx {
2643                draft: Some(draft),
2644                stream_kind: Some(stream_kind),
2645                index_in_stream: Some(0),
2646                subgroup_id_resolved: Some(false),
2647                is_status_object: Some(false),
2648                ..CapCtx::default()
2649            };
2650            assert_eq!(
2651                classify(Site::Object, ActionKind::DropElide, &cx(DataStreamType::Fetch)),
2652                Support::Yes,
2653                "{draft:?} fetch"
2654            );
2655            let subgroup =
2656                classify(Site::Object, ActionKind::DropElide, &cx(DataStreamType::Subgroup));
2657            if a_first_object_carrier_exists(draft) {
2658                assert_eq!(
2659                    subgroup,
2660                    Support::No(Refusal::WouldRedefineSubgroupId),
2661                    "{draft:?} subgroup"
2662                );
2663            } else {
2664                assert_eq!(subgroup, Support::Yes, "{draft:?} subgroup");
2665            }
2666        }
2667    }
2668
2669    /// Eliding a fetch object turns on the object's status and on nothing
2670    /// else — not on its index, and not on the draft.
2671    /// The index half is the one worth stating: a fetch stream is the case
2672    /// where *the first object of the stream* carries no special meaning,
2673    /// because a fetch object's Subgroup ID is its own rather than the
2674    /// header's.
2675    ///
2676    /// Draft-15 is the only draft where the status half can be shown at all
2677    /// — 16 through 19 removed the Object Status field from fetch objects,
2678    /// so nothing there is ever `is_status_object: Some(true)` off the wire.
2679    /// It is swept on every addressable draft anyway, because the guard is
2680    /// draft-neutral and a context this crate cannot produce is still a
2681    /// context the published table answers.
2682    #[test]
2683    fn eliding_a_fetch_object_turns_only_on_its_status() {
2684        for draft in compiled_drafts_where(|_| true) {
2685            for index in [0u64, 1, 7] {
2686                for status in [Some(false), Some(true), None] {
2687                    let cx = CapCtx {
2688                        draft: Some(draft),
2689                        stream_kind: Some(DataStreamType::Fetch),
2690                        index_in_stream: Some(index),
2691                        is_status_object: status,
2692                        ..CapCtx::default()
2693                    };
2694                    let want = match status {
2695                        Some(true) => Support::No(Refusal::WouldDestroyStatusObject),
2696                        Some(false) => Support::Yes,
2697                        None => Support::Conditional(Precondition::NotAStatusObject),
2698                    };
2699                    assert_eq!(
2700                        classify(Site::Object, ActionKind::DropElide, &cx),
2701                        want,
2702                        "{draft:?} index {index} status {status:?}"
2703                    );
2704                }
2705            }
2706        }
2707    }
2708
2709    #[test]
2710    fn datagram_payload_not_delimited_names_its_case() {
2711        let undelimited = |draft, status| CapCtx {
2712            draft: Some(draft),
2713            payload_delimited: Some(false),
2714            is_status_object: status,
2715            ..CapCtx::default()
2716        };
2717        let detail = |cx: CapCtx| match classify(Site::Datagram, ActionKind::ReplacePayload, &cx) {
2718            Support::No(Refusal::PayloadNotDelimited { detail }) => detail,
2719            other => panic!("expected PayloadNotDelimited, got {other:?}"),
2720        };
2721
2722        assert_eq!(
2723            detail(undelimited(DraftVersion::Draft14, Some(false))),
2724            "draft-14 header decode consumes the payload"
2725        );
2726        assert_eq!(
2727            detail(undelimited(DraftVersion::Draft19, Some(true))),
2728            "status datagram has no payload"
2729        );
2730        assert_eq!(
2731            detail(undelimited(DraftVersion::Draft19, None)),
2732            "datagram header did not decode"
2733        );
2734
2735        let delimited = CapCtx {
2736            draft: Some(DraftVersion::Draft19),
2737            payload_delimited: Some(true),
2738            ..CapCtx::default()
2739        };
2740        assert_eq!(classify(Site::Datagram, ActionKind::ReplacePayload, &delimited), Support::Yes);
2741    }
2742
2743    // ── The control column does not split on the draft ──────────────────
2744
2745    /// The control site is honoured on all thirteen drafts, 17-19 included.
2746    ///
2747    /// Those three moved the control plane onto a pair of unidirectional
2748    /// streams, and while the engine still took the first bidirectional
2749    /// stream to be the control stream this column published
2750    /// `Conditional(SiteSeesTheControlStream)` there — the site was shown a
2751    /// request stream and SETUP never reached the hook. `session.rs` now
2752    /// identifies the pair by its stream type, so the whole control plane
2753    /// reaches the site and the split is gone.
2754    ///
2755    /// The draft rows are written out rather than derived, so the claim is
2756    /// made against the draft numbers and not against the function under
2757    /// test. *Ablation:* return anything but `Support::Yes` from
2758    /// `classify_control` for the three drafts named below and every one of
2759    /// their rows goes red.
2760    #[test]
2761    fn the_control_site_is_honoured_on_every_draft() {
2762        const UNI_CONTROL_PLANE: [DraftVersion; 3] =
2763            [DraftVersion::Draft17, DraftVersion::Draft18, DraftVersion::Draft19];
2764
2765        // The kinds the control site honours — including the two whose
2766        // misreading is expensive.
2767        const HONOURED: [ActionKind; 6] = [
2768            ActionKind::Pass,
2769            ActionKind::Replace,
2770            ActionKind::Delay,
2771            ActionKind::Hold,
2772            ActionKind::DropElide,
2773            ActionKind::CloseSession,
2774        ];
2775
2776        for draft in DRAFTS {
2777            let caps = Capabilities::for_draft(draft);
2778            let uni_control_plane = UNI_CONTROL_PLANE.contains(&draft);
2779
2780            // The one split this column does take is not a draft split at
2781            // all, and it is asserted next door rather than here: see
2782            // [`the_control_site_is_unreachable_on_a_draft_this_build_did_not_compile`].
2783            // Skipped rather than folded in, so this test stays a claim
2784            // about draft numbers and that one stays a claim about the
2785            // build.
2786            if !draft_is_compiled(draft) {
2787                continue;
2788            }
2789
2790            for kind in HONOURED {
2791                let verdict = caps.supports(Site::Control, kind);
2792                assert_eq!(
2793                    verdict,
2794                    Support::Yes,
2795                    "{draft:?} {kind:?} (pair-of-unidirectional control plane: \
2796                     {uni_control_plane})"
2797                );
2798
2799                // Restated structurally: `Unreachable` and `NotAttemptable` are
2800                // the module's two verdicts for *nothing is ever attempted
2801                // here*, and neither is what this site publishes.
2802                assert!(
2803                    !matches!(
2804                        verdict,
2805                        Support::Unreachable { .. } | Support::NotAttemptable { .. }
2806                    ),
2807                    "{draft:?} {kind:?}: the control site is attemptable on every draft"
2808                );
2809            }
2810
2811            // The contrast, on the same draft, so "attemptable" is measured
2812            // against a cell that really is inert rather than asserted in
2813            // isolation: the object site is `Unreachable` on any draft this
2814            // build did not compile.
2815            if !draft_is_compiled(draft) {
2816                assert!(
2817                    matches!(
2818                        caps.supports_on(Site::Object, ActionKind::Pass, DataStreamType::Fetch),
2819                        Support::Unreachable { .. }
2820                    ),
2821                    "{draft:?}: the module does have a verdict for 'never invoked'"
2822                );
2823            }
2824
2825            // The reset-and-truncate refusal is untouched by any of the
2826            // above, on every draft: a request stream is a control-plane
2827            // stream too, so resetting one is still refused.
2828            for kind in [ActionKind::Truncate, ActionKind::ResetStream] {
2829                assert_eq!(
2830                    caps.supports(Site::Control, kind),
2831                    Support::No(Refusal::ControlStreamResetIllegal),
2832                    "{draft:?} {kind:?}"
2833                );
2834            }
2835        }
2836    }
2837
2838    // ── The compiled draft set is a fact the table reads ────────────────
2839
2840    /// The **control** site is unreachable there too, one decoder later.
2841    ///
2842    /// Sibling of
2843    /// [`the_object_site_is_unreachable_on_a_draft_this_build_did_not_compile`]
2844    /// and separate from it on purpose: the two fail in different decoders
2845    /// and a run reports them with different events, so a single verdict
2846    /// covering both would send a reader looking for a `FramerBypass` that
2847    /// no control stream emits. `AnyControlMessage::decode` has no arm for
2848    /// an uncompiled draft, so `ControlStreamParser::feed` refuses every
2849    /// frame on the stream and `ProxyHook::on_control_message` is never
2850    /// offered one.
2851    ///
2852    /// This cell published [`Support::Yes`] until the run had something
2853    /// truthful to point at. It is the shape of documented lie this module
2854    /// exists to prevent, and the reason it survived is worth keeping: the
2855    /// honest verdict needs [`Support::Unreachable`]'s `instead`, and until
2856    /// [`ImpairmentKind::ControlFrameNotDecodable`](crate::event::ImpairmentKind::ControlFrameNotDecodable)
2857    /// existed there was nothing to put there.
2858    ///
2859    /// Vacuous under `--all-features` and load-bearing under a reduced
2860    /// build, exactly like its sibling: `cargo test -p moqtap-proxy
2861    /// --no-default-features --features draft07 --lib capability::` is
2862    /// where twelve of the thirteen rows take the assertion.
2863    ///
2864    /// *Ablation (measured):* delete the `Site::Control` guard from
2865    /// [`classify`]. Green under `--all-features`, and under
2866    /// `--features draft07`:
2867    ///
2868    /// ```text
2869    /// ---- capability::tests::the_control_site_is_unreachable_on_a_draft_this_build_did_not_compile stdout ----
2870    /// assertion `left == right` failed: Draft08
2871    ///   left: Yes
2872    ///  right: Unreachable { refusal: ControlFrameNotDecodable, instead: ControlFrameNotDecodable }
2873    /// ```
2874    ///
2875    /// `Yes` for a site this build cannot reach, on the first of the twelve
2876    /// drafts it left out.
2877    #[test]
2878    fn the_control_site_is_unreachable_on_a_draft_this_build_did_not_compile() {
2879        for draft in DRAFTS {
2880            let caps = Capabilities::for_draft(draft);
2881            let want = if draft_is_compiled(draft) { Support::Yes } else { unreachable_control() };
2882            assert_eq!(caps.supports(Site::Control, ActionKind::Pass), want, "{draft:?}");
2883
2884            // The reset kinds move with the column rather than keeping
2885            // their refusal. A refusal is what the engine would hand a
2886            // hook, and on this draft no hook is ever reached, so
2887            // publishing `ControlStreamResetIllegal` here would describe a
2888            // decision nothing takes. The object site answers the same way
2889            // for the same reason.
2890            assert_eq!(
2891                caps.supports(Site::Control, ActionKind::ResetStream),
2892                if draft_is_compiled(draft) {
2893                    Support::No(Refusal::ControlStreamResetIllegal)
2894                } else {
2895                    unreachable_control()
2896                },
2897                "{draft:?}: the reset refusal is published only where a hook could receive it"
2898            );
2899
2900            // What does *not* move: the kinds no value can carry to this
2901            // site. They are decided before reachability is consulted, so
2902            // a reduced build must not turn them into `Unreachable` as
2903            // collateral.
2904            assert_eq!(
2905                caps.supports(Site::Control, ActionKind::ReplaceObject),
2906                kind_not_here(Site::Control, ActionKind::ReplaceObject),
2907                "{draft:?}: a control frame is not an object on any build"
2908            );
2909        }
2910    }
2911
2912    /// The table must not publish [`Support::Yes`] for a draft this binary
2913    /// cannot frame.
2914    ///
2915    /// Runs in every feature configuration and has teeth in the reduced
2916    /// ones — `cargo test -p moqtap-proxy --no-default-features --features
2917    /// draft07 --lib capability::` is where twelve of the thirteen rows take
2918    /// the `else` branch. It is deliberately not vacuous in the all-drafts
2919    /// build either: there it asserts that every row stayed `Yes`, which is
2920    /// the claim that this fix changed nothing in the shipped default.
2921    ///
2922    /// *Ablation:* drop the `draft_is_compiled` guard from
2923    /// [`object_framing_bypass`]. Green under `--all-features`, red under
2924    /// `--features draft07` on all twelve uncompiled drafts.
2925    ///
2926    /// `ProxySessionConfig::default().draft` is `Draft14` and nothing
2927    /// validates it against the compiled set, so the draft-14 row is the
2928    /// default configuration of a draft07-only binary, not a corner case.
2929    #[test]
2930    fn the_object_site_is_unreachable_on_a_draft_this_build_did_not_compile() {
2931        for draft in DRAFTS {
2932            let caps = Capabilities::for_draft(draft);
2933            for stream_kind in [DataStreamType::Subgroup, DataStreamType::Fetch] {
2934                let verdict = caps.supports_on(Site::Object, ActionKind::Pass, stream_kind);
2935
2936                if draft_is_compiled(draft) {
2937                    assert_eq!(verdict, Support::Yes, "{draft:?} {stream_kind:?}");
2938                } else {
2939                    assert_eq!(
2940                        verdict,
2941                        unreachable_with(BypassReason::DecodeError),
2942                        "{draft:?} {stream_kind:?} is not compiled: the stream header decode \
2943                         returns UnsupportedDraft, the framer latches DecodeError, and no object \
2944                         reaches the hook"
2945                    );
2946                }
2947            }
2948        }
2949    }
2950
2951    /// The sweep above chooses its own expectation with `draft_is_compiled`,
2952    /// so it is only meaningful if that function reports the build rather
2953    /// than a constant: answering `false` everywhere would make the whole
2954    /// object column `Unreachable` and pass, and answering `true` everywhere
2955    /// would make it all `Yes` and pass just as quietly.
2956    ///
2957    /// The invariant is therefore *agreement with the build*, not a
2958    /// non-empty set. "Non-empty" is simply false under
2959    /// `--no-default-features`, which is a supported configuration — the
2960    /// codec compiles with no draft, CI has a row for it, and a consumer
2961    /// vendoring one draft depends on that machinery — so a test asserting
2962    /// it was asserting a defect into a row that has none. Stated as
2963    /// agreement it runs, and bites, in all sixteen rows.
2964    ///
2965    /// *Ablation:* replace `draft_is_compiled`'s body with `false` — red in
2966    /// the fifteen rows that compile a draft. With `true` — red in the
2967    /// zero-draft row, which the previous wording could not reach at all.
2968    #[test]
2969    fn the_compiled_draft_set_agrees_with_the_enabled_features() {
2970        let compiled: Vec<DraftVersion> =
2971            DRAFTS.into_iter().filter(|d| draft_is_compiled(*d)).collect();
2972        let build_has_a_draft = cfg!(any(
2973            feature = "draft07",
2974            feature = "draft08",
2975            feature = "draft09",
2976            feature = "draft10",
2977            feature = "draft11",
2978            feature = "draft12",
2979            feature = "draft13",
2980            feature = "draft14",
2981            feature = "draft15",
2982            feature = "draft16",
2983            feature = "draft17",
2984            feature = "draft18",
2985            feature = "draft19"
2986        ));
2987        assert_eq!(
2988            !compiled.is_empty(),
2989            build_has_a_draft,
2990            "`draft_is_compiled` reports {compiled:?}, but this build has {} draft feature \
2991             enabled",
2992            if build_has_a_draft { "at least one" } else { "no" }
2993        );
2994    }
2995
2996    /// And the shipped default really is all thirteen, so the fix above is
2997    /// inert in the configuration the acceptance suite runs under.
2998    #[cfg(feature = "all-drafts")]
2999    #[test]
3000    fn the_default_build_compiles_every_draft() {
3001        for draft in DRAFTS {
3002            assert!(draft_is_compiled(draft), "{draft:?} is missing from `all-drafts`");
3003        }
3004    }
3005
3006    /// A default [`CapCtx`] answers the whole table without panicking, and
3007    /// without ever claiming `Yes` on a fact it was not given.
3008    #[test]
3009    fn a_default_context_is_answerable_at_every_cell() {
3010        for site in SITES {
3011            for kind in KINDS {
3012                let _ = classify(site, kind, &CapCtx::default());
3013            }
3014        }
3015    }
3016}