Skip to main content

moqtap_proxy/
framer.rs

1//! Byte-exact object framing for MoQT data streams.
2//!
3//! [`ObjectFramer`] turns the raw bytes of one unidirectional data stream
4//! into individually addressable objects without altering them: every item
5//! it yields is a slice of the bytes that were fed in, and concatenating
6//! those items reproduces the stream exactly.
7//!
8//! Framing is opt-in because it costs latency and memory — an object is
9//! only emitted once it is buffered whole. The proxy pays that cost only
10//! when something is observing; see `session::pipe_data`.
11
12use std::collections::HashMap;
13use std::sync::{Arc, Mutex};
14
15use bytes::{Buf, Bytes, BytesMut};
16
17use moqtap_codec::dispatch::{
18    reemit_subgroup_object, AnyFetchFrame, AnyFetchGroupOrder, AnyFetchHeader, AnyFetchObjectMeta,
19    AnyFetchObjectReader, AnyFetchObjectWriter, AnySubgroupHeader, AnySubgroupObjectMeta,
20    AnySubgroupObjectReader, FetchReemit,
21};
22use moqtap_codec::version::DraftVersion;
23
24use crate::capability::fetch_group_order_is_needed;
25use crate::event::DataStreamHeaderKind;
26use crate::instrument::Recorder;
27use crate::parser::data::is_incomplete_error;
28use crate::types::DataStreamType;
29
30pub use crate::types::{BypassReason, ObjectMeta};
31
32/// Every fetch this session has learned a Group Order for, keyed by the
33/// Request ID that names it on both the control plane and the data stream.
34///
35/// # Why a fetch stream needs something from outside itself
36///
37/// Drafts 18-23 write a fetch Object's Group ID as a difference from the
38/// Object before it, and the fetch's Group Order decides whether the
39/// difference counts up or down — draft-19 Section 11.4.4.1. Nothing on the
40/// data stream states the order, so a framer handed only the stream cannot
41/// reach an absolute Group ID, and the wrong choice decodes every Object
42/// without an error under Group IDs walking the wrong way.
43///
44/// The order is on the FETCH. Draft-19 Section 10.12.3: "The publisher
45/// responding to a FETCH is responsible for delivering all available Objects
46/// in the requested range in the requested order (see Section 10.2.8)." The
47/// session's control pipes read it off each FETCH they carry and file it
48/// here; [`ObjectFramer`] takes it out again when the response stream opens.
49///
50/// # Why an entry is taken rather than read
51///
52/// One FETCH opens one response stream, so an entry has exactly one reader
53/// and is spent by it. Taking bounds the table to the fetches that have been
54/// asked for and not yet answered, on a session that may run for hours, and
55/// it needs no rule about when to forget: the reader is the rule.
56///
57/// What that leaves is a fetch the publisher answered with an error rather
58/// than a stream, whose entry no reader ever comes for. A cap is the
59/// bound on those, and it fails closed — past it nothing is recorded, so the
60/// affected streams are bypassed and say so rather than being read against
61/// somebody else's order.
62#[derive(Debug, Default)]
63pub struct FetchGroupOrders {
64    known: Mutex<HashMap<u64, AnyFetchGroupOrder>>,
65}
66
67impl FetchGroupOrders {
68    /// How many asked-for-but-unanswered fetches one session may hold.
69    ///
70    /// Reached only by a peer that sends FETCHes whose responses never open a
71    /// stream, since every answered one takes its own entry away again.
72    const CAP: usize = 1024;
73
74    /// File the order a FETCH asked for, under the Request ID it asked under.
75    ///
76    /// Call with the order the *peer will act on*, which on a session whose
77    /// control frames a hook may rewrite is the one leaving the proxy rather
78    /// than the one that arrived.
79    pub fn record(&self, request_id: u64, order: AnyFetchGroupOrder) {
80        let mut known = self.known.lock().expect("no task holds the fetch orders across a panic");
81        if known.len() >= Self::CAP && !known.contains_key(&request_id) {
82            return;
83        }
84        known.insert(request_id, order);
85    }
86
87    /// Take the order filed for `request_id`, if one was.
88    #[must_use]
89    pub fn take(&self, request_id: u64) -> Option<AnyFetchGroupOrder> {
90        self.known
91            .lock()
92            .expect("no task holds the fetch orders across a panic")
93            .remove(&request_id)
94    }
95}
96
97/// Padding width that puts every wire length a varint can express within
98/// measuring reach.
99///
100/// Half of `usize::MAX`, so adding the buffered bytes cannot overflow
101/// [`PaddedBuf::remaining`]; a varint tops out at `2^62 - 1`, well inside
102/// it on a 64-bit target.
103const UNBOUNDED_MEASURING_PAD: usize = usize::MAX / 2;
104
105/// Configuration for [`ObjectFramer`].
106///
107/// Construct with [`FramerConfig::default`] and adjust fields, or with
108/// [`FramerConfig::new`] and the builder setters. The struct is
109/// `#[non_exhaustive]` so later releases can add knobs without a break;
110/// that also means a struct literal does not compile from outside this
111/// crate.
112#[derive(Debug, Clone)]
113#[non_exhaustive]
114pub struct FramerConfig {
115    /// Largest object the framer will buffer whole, in bytes. Objects
116    /// larger than this are streamed through as
117    /// [`FramerOut::Passthrough`] and are not individually addressable.
118    /// Default 4 MiB.
119    pub max_buffered_object_bytes: usize,
120}
121
122impl Default for FramerConfig {
123    fn default() -> Self {
124        Self { max_buffered_object_bytes: 4 * 1024 * 1024 }
125    }
126}
127
128impl FramerConfig {
129    /// A config with default values.
130    #[must_use]
131    pub fn new() -> Self {
132        Self::default()
133    }
134
135    /// Set the largest object the framer will buffer whole.
136    #[must_use]
137    pub fn with_max_buffered_object_bytes(mut self, bytes: usize) -> Self {
138        self.max_buffered_object_bytes = bytes;
139        self
140    }
141}
142
143/// One item produced by [`ObjectFramer::poll`].
144#[derive(Debug)]
145#[non_exhaustive]
146pub enum FramerOut {
147    /// The stream's header, with its exact wire bytes (stream-type field
148    /// included).
149    Header {
150        /// The decoded header.
151        header: DataStreamHeaderKind,
152        /// The header's wire bytes, including the stream-type field.
153        raw: Bytes,
154    },
155    /// A complete object, with its exact wire bytes.
156    Object {
157        /// The object's framing, without its payload.
158        meta: ObjectMeta,
159        /// The object's complete wire bytes, framing and payload.
160        raw: Bytes,
161    },
162    /// Bytes the framer is forwarding without interpreting them: an object
163    /// larger than the buffer cap, a fetch stream on a draft whose fetch
164    /// objects are not addressed, or any stream the framer has stopped
165    /// parsing. These bytes are not individually addressable.
166    Passthrough(Bytes),
167    /// The framer has stopped parsing this stream.
168    ///
169    /// Carries **no bytes**, so [`ObjectFramer::poll`]'s concatenation
170    /// invariant is untouched: this item contributes nothing to the
171    /// reconstruction. Emitted exactly once per stream.
172    ///
173    /// **Ordering: immediately after the item the bypass was decided
174    /// during, not in place of it.** Every one of `latch_bypass`'s call
175    /// sites returns a *different* `FramerOut` from the same `poll()` —
176    /// the two header sites fall through to [`Self::Header`], the
177    /// measuring-reach sites return [`Self::Passthrough`], the decode and
178    /// fix-up sites return [`Self::Error`] — and `poll()` returns one
179    /// item. The variant is therefore **deferred**: `latch_bypass` stores
180    /// a `pending_bypass: Option<BypassReason>`, and `poll()` drains it at
181    /// the top of its next call, before anything else.
182    Bypassed {
183        /// Why parsing stopped.
184        reason: BypassReason,
185        /// Whether an elide fix-up was still owed when parsing stopped.
186        ///
187        /// `true` means the remainder of this stream cannot be renumbered
188        /// and the destination must be reset rather than forwarded — the
189        /// bytes still in flight decode to Object IDs one ahead of what
190        /// was actually delivered.
191        fixup_owed: bool,
192    },
193    /// Not enough buffered bytes to produce another item.
194    NeedMore,
195    /// The stream could not be parsed. The framer switches to
196    /// [`Passthrough`](Self::Passthrough) for the remainder of the stream
197    /// and never reports a second error.
198    Error(String),
199}
200
201/// The state an elide leaves behind on a subgroup stream.
202///
203/// Read it with [`ObjectFramer::elide_cursor`]. The framer owns this state
204/// rather than the caller because it forwards objects the caller never
205/// sees an [`ObjectMeta`] for — an object one byte over
206/// [`FramerConfig::max_buffered_object_bytes`] leaves as
207/// [`FramerOut::Passthrough`], and a cursor kept outside the framer would
208/// let its stale delta go out on the wire.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub struct ElideCursor {
211    /// Absolute Object ID of the last object actually forwarded, or `None`
212    /// when none has been.
213    pub last_forwarded_id: Option<u64>,
214    /// Whether the next object the framer emits will have its leading ID
215    /// field rewritten. Always `false` on drafts 07-13, where IDs are
216    /// absolute, and on fetch streams.
217    pub fixup_pending: bool,
218}
219
220/// The object the framer emitted most recently, whose forward-or-elide
221/// disposition has not been committed to the cursor yet.
222#[derive(Debug, Clone, Copy)]
223struct PendingObject {
224    object_id: u64,
225    index_in_stream: u64,
226}
227
228/// Identity fields the stream header contributes to every object on a
229/// subgroup stream.
230#[derive(Debug, Clone, Copy, Default)]
231struct SubgroupContext {
232    track_alias: u64,
233    group_id: u64,
234    subgroup_id: Option<u64>,
235    publisher_priority: Option<u8>,
236}
237
238/// What the framer is currently decoding.
239#[derive(Debug)]
240enum Stage {
241    /// Nothing decoded yet; the next bytes are the stream header.
242    AwaitingHeader,
243    /// Subgroup objects, with the per-stream delta state.
244    Subgroup(AnySubgroupObjectReader),
245    /// Fetch objects, with the state on both sides of the framer: what the
246    /// stream said, and what has actually been forwarded from it.
247    ///
248    /// The two are the same value until something is elided, and every frame
249    /// goes through the writer regardless. A frame it never saw would leave
250    /// it a frame behind, and a survivor re-encoded against a stale
251    /// predecessor is a renumbered stream rather than a decode error.
252    Fetch { reader: AnyFetchObjectReader, writer: AnyFetchObjectWriter },
253}
254
255/// Frames a unidirectional MoQT data stream into individually addressable
256/// objects while preserving the exact wire bytes.
257///
258/// Feed it the raw bytes of one stream, in order, from the stream's first
259/// byte. Drain [`poll`](Self::poll) after each [`feed`](Self::feed) until
260/// it returns [`FramerOut::NeedMore`]. The concatenation of every `raw`
261/// and `Passthrough` payload it yields equals the concatenation of every
262/// chunk fed to it, unless [`note_elided`](Self::note_elided) has been
263/// called — see [`Self::poll`].
264#[derive(Debug)]
265pub struct ObjectFramer {
266    stream_type: DataStreamType,
267    draft: DraftVersion,
268    config: FramerConfig,
269    buf: BytesMut,
270    stage: Stage,
271    context: SubgroupContext,
272    /// Bytes still owed to an oversized object that is being streamed
273    /// through uninterpreted. Denominated in **source** bytes — see
274    /// [`Self::poll_oversized`].
275    passthrough_remaining: u64,
276    /// Set once parsing has been abandoned for the rest of the stream.
277    bypassed: bool,
278    /// Why parsing was abandoned, waiting for [`Self::poll`] to drain it
279    /// as a [`FramerOut::Bypassed`].
280    ///
281    /// `fixup_owed` is read off [`Self::fixup_pending`] at drain time
282    /// rather than being captured here, and the two are the same value:
283    /// once `bypassed` is set, `poll` never re-enters `poll_object`, which
284    /// is the only thing that clears the flag, and no `Object` item can be
285    /// emitted between the latch and the drain for `note_elided` to set it.
286    pending_bypass: Option<BypassReason>,
287    index_in_stream: u64,
288    /// Absolute Object ID of the last object actually forwarded.
289    last_forwarded_id: Option<u64>,
290    /// Whether the next object emitted still owes a fix-up: on a subgroup
291    /// stream the leading Object ID varint rewritten against
292    /// [`Self::last_forwarded_id`], on a fetch stream a survivor re-encoded
293    /// against the frame that is now in front of it.
294    ///
295    /// Both are settled by emitting one object, after which the writing
296    /// cursor is level with the reading one again.
297    fixup_pending: bool,
298    /// The fetch writer as it stood before the object emitted most recently
299    /// was re-emitted through it.
300    ///
301    /// Re-emitting advances the writer, and the caller's verdict on that
302    /// object does not land until the next poll, so an elide has to put the
303    /// writer back where it was — otherwise the survivor after it is encoded
304    /// against an object nobody received.
305    fetch_rollback: Option<AnyFetchObjectWriter>,
306    /// The object emitted most recently, awaiting the caller's verdict.
307    /// Committed lazily at the top of [`Self::poll_object`].
308    pending_disposition: Option<PendingObject>,
309    /// Slow-path counters for the session this framer belongs to.
310    counters: Arc<Recorder>,
311    /// The session's answered fetches, on the drafts where a fetch stream
312    /// cannot be read without one. `None` for a framer built outside a
313    /// session, and on every draft that needs no order.
314    fetch_orders: Option<Arc<FetchGroupOrders>>,
315}
316
317impl ObjectFramer {
318    /// A framer whose slow-path counters go to `counters`.
319    ///
320    /// **The only constructor `session.rs` may use.** The counters are
321    /// session-scoped, and a framer that cannot reach its session's
322    /// [`Recorder`] would leave `framers_created`, `framer_header_polls`,
323    /// `framer_object_polls`, `objects_not_addressable` and
324    /// `object_ids_rewritten` at zero for every real session — which is a
325    /// *passing* `Interest::NONE` proof obtained by measuring nothing.
326    ///
327    /// [`Self::new`] is kept, unchanged, for tests and downstream callers
328    /// that construct a framer to parse bytes rather than to forward them;
329    /// it is equivalent to passing a fresh `Recorder` whose counts nobody
330    /// reads. That is why this is an **addition** and not a signature
331    /// change.
332    pub fn with_recorder(
333        stream_type: DataStreamType,
334        draft: DraftVersion,
335        config: FramerConfig,
336        counters: Arc<Recorder>,
337    ) -> Self {
338        counters.note_framer_created();
339        Self {
340            stream_type,
341            draft,
342            config,
343            buf: BytesMut::with_capacity(4096),
344            stage: Stage::AwaitingHeader,
345            context: SubgroupContext::default(),
346            passthrough_remaining: 0,
347            bypassed: false,
348            pending_bypass: None,
349            index_in_stream: 0,
350            last_forwarded_id: None,
351            fixup_pending: false,
352            fetch_rollback: None,
353            pending_disposition: None,
354            counters,
355            fetch_orders: None,
356        }
357    }
358
359    /// Read this stream's fetch Objects against the order its FETCH asked for.
360    ///
361    /// Only drafts 18-23 need it — see [`FetchGroupOrders`] — and only a
362    /// fetch stream consults it; a subgroup framer given one ignores it. A
363    /// framer built without it on a draft that needs one reports
364    /// [`BypassReason::FetchGroupOrderUnknown`] and forwards the stream
365    /// uninterpreted, which is what every caller outside a session gets and
366    /// what the session itself gets for a stream naming a request it never
367    /// saw asked for.
368    #[must_use]
369    pub fn with_fetch_group_orders(mut self, orders: Arc<FetchGroupOrders>) -> Self {
370        self.fetch_orders = Some(orders);
371        self
372    }
373
374    /// Create a framer for a stream of the given kind on the given draft,
375    /// discarding its counters.
376    ///
377    /// Increments go to a private [`Recorder`] nothing can read, so a
378    /// caller that wants a session's counters to move must use
379    /// [`Self::with_recorder`]. Retained for callers that parse bytes
380    /// rather than forward them, where the counts are not the point.
381    pub fn new(stream_type: DataStreamType, draft: DraftVersion, config: FramerConfig) -> Self {
382        Self::with_recorder(stream_type, draft, config, Arc::new(Recorder::new()))
383    }
384
385    /// The state an elide has left behind on this stream.
386    ///
387    /// Read-only, and read-anytime: the framer applies the fix-up itself,
388    /// so nothing outside has to act on this.
389    #[must_use]
390    pub fn elide_cursor(&self) -> ElideCursor {
391        ElideCursor { last_forwarded_id: self.last_forwarded_id, fixup_pending: self.fixup_pending }
392    }
393
394    /// Record that the object the framer emitted **most recently** was not
395    /// forwarded.
396    ///
397    /// Call exactly once, immediately after deciding to drop an object,
398    /// and before the next [`Self::poll`]. `meta` must be the meta the
399    /// framer handed out for that object; it is `debug_assert`ed against
400    /// the framer's own record, because calling this out of order is the
401    /// one way to corrupt a stream silently.
402    ///
403    /// On drafts 07-13 subgroup streams and on drafts 07-14 fetch streams
404    /// this only suppresses the cursor advance — those Object IDs are
405    /// absolute, so the bytes of every later object already say the truth.
406    /// Elsewhere it also arms a fix-up: the leading Object ID varint on a
407    /// drafts 14-23 subgroup stream, and the whole framing of the next frame
408    /// on a drafts 15-23 fetch stream, where it additionally puts the fetch
409    /// writer back to where the last forwarded frame left it.
410    pub fn note_elided(&mut self, meta: &ObjectMeta) {
411        let pending = self.pending_disposition.take();
412        debug_assert!(
413            matches!(
414                pending,
415                Some(p) if p.object_id == meta.object_id
416                    && p.index_in_stream == meta.index_in_stream
417            ),
418            "note_elided must name the object the framer emitted most recently; \
419             got object {} at index {}, framer holds {:?}",
420            meta.object_id,
421            meta.index_in_stream,
422            pending.map(|p| (p.object_id, p.index_in_stream)),
423        );
424        // Taking `pending` is the elide: the cursor simply does not
425        // advance to it. Arming the fix-up on a `None` would renumber an
426        // object whose predecessor was already committed as forwarded.
427        if pending.is_none() {
428            return;
429        }
430        if self.elide_owes_a_fixup() {
431            self.fixup_pending = true;
432        }
433        // The frame was re-emitted through the writer before the caller saw
434        // it, so the writer is one frame ahead of what the destination
435        // received. Nothing else can restore it: the per-draft state is what
436        // the *forwarded* frames left behind, and this frame was not one.
437        if let Some(rollback) = self.fetch_rollback.take() {
438            if let Stage::Fetch { writer, .. } = &mut self.stage {
439                *writer = rollback;
440            }
441        }
442    }
443
444    /// Buffer a chunk of stream bytes.
445    pub fn feed(&mut self, chunk: &[u8]) {
446        self.buf.extend_from_slice(chunk);
447    }
448
449    /// Bytes buffered but not yet emitted. Non-zero only mid-object.
450    pub fn buffered(&self) -> usize {
451        self.buf.len()
452    }
453
454    /// `true` once the framer has stopped parsing this stream and is
455    /// forwarding bytes uninterpreted.
456    pub fn is_bypassed(&self) -> bool {
457        self.bypassed
458    }
459
460    /// Flush any buffered bytes at end of stream.
461    ///
462    /// Called when the source signals FIN. Returns whatever the framer
463    /// still holds — a truncated final object, or bytes buffered behind an
464    /// incomplete framing — so the caller can forward them before
465    /// finishing the destination stream. Forgetting this call turns a
466    /// clean FIN into silent truncation.
467    pub fn finish(&mut self) -> Option<Bytes> {
468        self.passthrough_remaining = 0;
469        if self.buf.is_empty() {
470            None
471        } else {
472            Some(self.buf.split().freeze())
473        }
474    }
475
476    /// Produce the next item, or [`FramerOut::NeedMore`].
477    ///
478    /// # Invariant
479    ///
480    /// Concatenating the `raw` field of every [`Header`](FramerOut::Header)
481    /// and [`Object`](FramerOut::Object) and the payload of every
482    /// [`Passthrough`](FramerOut::Passthrough), in the order produced,
483    /// reproduces the fed bytes exactly — on every draft, including
484    /// streams that fall back to bypass — **unless**
485    /// [`Self::note_elided`] has been called, which deliberately removes
486    /// an object's bytes and may rewrite one leading varint.
487    ///
488    /// That exception is the *only* one, and it is opt-in per stream: a
489    /// framer used as a pure observer never calls `note_elided`, so its
490    /// output stays byte-identical to its input. When `note_elided` has
491    /// been called on a drafts 14-23 subgroup stream, the next object the
492    /// framer emits has its leading Object ID varint re-encoded against
493    /// the last object actually forwarded — one field, in one object, and
494    /// every byte after it copied verbatim. Everything else, on every
495    /// other stream, still concatenates back to the source exactly.
496    ///
497    /// [`FramerOut::Bypassed`] and [`FramerOut::NeedMore`] carry no bytes
498    /// and so contribute nothing to the reconstruction either way.
499    pub fn poll(&mut self) -> FramerOut {
500        // Drained before anything else. `latch_bypass` cannot return this
501        // item itself — each of its call sites returns a different
502        // `FramerOut` from the same `poll()` — so the bypass is reported
503        // on the next call, immediately after the item it was decided
504        // during. Zero bytes, so the invariant above is untouched.
505        if let Some(reason) = self.pending_bypass.take() {
506            return FramerOut::Bypassed { reason, fixup_owed: self.fixup_pending };
507        }
508        if self.passthrough_remaining > 0 {
509            let owed = self.passthrough_remaining;
510            return self.emit_passthrough(owed);
511        }
512        if self.bypassed {
513            return self.emit_passthrough(u64::MAX);
514        }
515        match self.stage {
516            Stage::AwaitingHeader => self.poll_header(),
517            Stage::Subgroup(_) | Stage::Fetch { .. } => self.poll_object(),
518        }
519    }
520
521    /// Hand out up to `limit` buffered bytes without interpreting them.
522    fn emit_passthrough(&mut self, limit: u64) -> FramerOut {
523        if self.buf.is_empty() {
524            return FramerOut::NeedMore;
525        }
526        let take = usize::try_from(limit).unwrap_or(usize::MAX).min(self.buf.len());
527        self.passthrough_remaining = self.passthrough_remaining.saturating_sub(take as u64);
528        FramerOut::Passthrough(self.buf.split_to(take).freeze())
529    }
530
531    /// Stop parsing this stream for good, record why, and release
532    /// everything buffered.
533    ///
534    /// Draining here is what keeps memory bounded: without it a stream the
535    /// framer cannot parse grows the buffer for as long as the peer keeps
536    /// writing.
537    ///
538    /// `reason` is stored rather than returned, because every call site
539    /// returns a different [`FramerOut`] from the same
540    /// [`poll`](Self::poll); the next `poll` drains it. Guarded on
541    /// `bypassed` so a second latch — which today cannot happen, since
542    /// `poll` short-circuits once the flag is set — could never overwrite
543    /// the first reason or double-count
544    /// `Counters::streams_not_shapeable`, whose whole job is to be one per
545    /// stream.
546    fn latch_bypass(&mut self, reason: BypassReason) {
547        if !self.bypassed {
548            self.bypassed = true;
549            self.pending_bypass = Some(reason);
550            self.counters.note_stream_not_shapeable();
551        }
552        self.passthrough_remaining = 0;
553    }
554
555    fn poll_header(&mut self) -> FramerOut {
556        self.counters.note_framer_header_poll();
557        if self.buf.is_empty() {
558            return FramerOut::NeedMore;
559        }
560
561        let snapshot: &[u8] = &self.buf[..];
562        let mut cursor: &[u8] = snapshot;
563        let decoded = match self.stream_type {
564            DataStreamType::Subgroup => AnySubgroupHeader::decode_stream(self.draft, &mut cursor)
565                .map(DataStreamHeaderKind::Subgroup),
566            DataStreamType::Fetch => AnyFetchHeader::decode_stream(self.draft, &mut cursor)
567                .map(DataStreamHeaderKind::Fetch),
568        };
569
570        match decoded {
571            Ok(header) => {
572                let consumed = snapshot.len() - cursor.remaining();
573                match &header {
574                    DataStreamHeaderKind::Subgroup(h) => match AnySubgroupObjectReader::new(h) {
575                        Ok(reader) => {
576                            self.context = subgroup_context(h);
577                            self.stage = Stage::Subgroup(reader);
578                        }
579                        // A subgroup stream type the object reader
580                        // rejects. The header still decoded, so report it,
581                        // then forward the rest uninterpreted.
582                        Err(_) => self.latch_bypass(BypassReason::UnsupportedSubgroupStreamType),
583                    },
584                    // Whether this stream's Objects can be addressed is
585                    // asked of `fetch_group_order_is_needed` and of the
586                    // session's own record of what each FETCH asked for,
587                    // rather than inferred from the reader refusing. A codec
588                    // able to decode a layout is not on its own enough: on
589                    // drafts 18-23 it decodes under a Group Order nothing
590                    // on this stream states, and the wrong one decodes as
591                    // willingly as the right one.
592                    DataStreamHeaderKind::Fetch(h) => match self.fetch_stage(h) {
593                        Ok(stage) => self.stage = stage,
594                        Err(reason) => self.latch_bypass(reason),
595                    },
596                }
597                let raw = self.buf.split_to(consumed).freeze();
598                FramerOut::Header { header, raw }
599            }
600            Err(e) if is_incomplete_error(&e) => {
601                if self.buf.len() >= self.config.max_buffered_object_bytes {
602                    self.latch_bypass(BypassReason::ObjectBeyondMeasuringReach);
603                    self.emit_passthrough(u64::MAX)
604                } else {
605                    FramerOut::NeedMore
606                }
607            }
608            Err(e) => {
609                self.latch_bypass(BypassReason::DecodeError);
610                FramerOut::Error(format!("data stream header decode: {e}"))
611            }
612        }
613    }
614
615    /// The reader and writer a fetch stream is parsed with, or why it is not.
616    ///
617    /// Three drafts need an answer from off the stream and the other eleven
618    /// do not, which is [`fetch_group_order_is_needed`]. Where one is needed
619    /// it comes from the FETCH the session carried, filed under the Request ID
620    /// this header names; a stream naming a request that was never asked for
621    /// is bypassed rather than guessed at, because the guess would decode.
622    ///
623    /// The reader and writer are built with the same order. They are the two
624    /// halves of one stream — the writer re-encodes a survivor after an elide
625    /// against the frames now in front of it — so a pair built against
626    /// different orders would renumber the stream it was meant to preserve.
627    fn fetch_stage(&mut self, h: &AnyFetchHeader) -> Result<Stage, BypassReason> {
628        let order = if fetch_group_order_is_needed(self.draft) {
629            let orders = self.fetch_orders.as_ref().ok_or(BypassReason::FetchGroupOrderUnknown)?;
630            Some(orders.take(h.request_id()).ok_or(BypassReason::FetchGroupOrderUnknown)?)
631        } else {
632            None
633        };
634        // Ascending where the draft needs no answer: the branch above supplies
635        // one for every draft that does, so the fallback is only ever reached
636        // where nothing on the stream is signed and the value cannot be wrong.
637        let order = order.unwrap_or(AnyFetchGroupOrder::Ascending);
638        let built = (AnyFetchObjectReader::new(h, order), AnyFetchObjectWriter::new(h, order));
639        match built {
640            (Ok(reader), Ok(writer)) => Ok(Stage::Fetch { reader, writer }),
641            // A draft this build did not compile. Not an error — the stream
642            // is simply not addressable. The header decode above would
643            // already have failed on such a draft, so this is a second line
644            // rather than the first.
645            _ => Err(BypassReason::NoFetchObjectCodec),
646        }
647    }
648
649    fn poll_object(&mut self) -> FramerOut {
650        self.counters.note_framer_object_poll();
651
652        // Lazy commit, once, here. The pipe loop is sequential — the
653        // caller's verdict on object *N* always lands before `poll`
654        // produces object *N+1* — so an object still pending at the top of
655        // this call was forwarded. `poll_oversized` deliberately does
656        // **not** repeat this: it is only ever reached from inside this
657        // function, and a second commit would consume a disposition this
658        // one already took. If it ever gains an entry path of its own,
659        // make the commit idempotent rather than adding a second site.
660        self.commit_disposition();
661
662        if self.buf.is_empty() {
663            return FramerOut::NeedMore;
664        }
665
666        let snapshot: &[u8] = &self.buf[..];
667        let mut cursor: &[u8] = snapshot;
668
669        // Probe against a clone: a reader mutated before the object is
670        // known to be complete carries a corrupt delta state into every
671        // later object on the stream.
672        let probed = match &self.stage {
673            Stage::Subgroup(reader) => {
674                let mut probe = reader.clone();
675                probe
676                    .read_object_meta(&mut cursor)
677                    .map(|m| (Probe::Subgroup(probe), Meta::Sub(m), None))
678            }
679            // `read_object_frame` rather than `read_object_meta`: it reports
680            // the same framing and additionally keeps the shape the frame
681            // arrived in, which is what re-encoding it against a different
682            // predecessor takes.
683            Stage::Fetch { reader, .. } => {
684                let mut probe = reader.clone();
685                probe
686                    .read_object_frame(&mut cursor)
687                    .map(|frame| (Probe::Fetch(probe), Meta::Fetch(frame.meta), Some(frame)))
688            }
689            Stage::AwaitingHeader => return FramerOut::NeedMore,
690        };
691
692        match probed {
693            Ok((probe, meta, frame)) => {
694                let consumed = snapshot.len() - cursor.remaining();
695                let object_id = meta.object_id();
696                // Before the source bytes are split off, so a failure
697                // leaves them in the buffer for the bypassed poll that
698                // follows to forward verbatim rather than dropping them.
699                let rewritten = match self.apply_elide_fixup(consumed, object_id, frame.as_ref()) {
700                    Ok(rewritten) => rewritten,
701                    Err(e) => {
702                        self.latch_bypass(BypassReason::DecodeError);
703                        return FramerOut::Error(e);
704                    }
705                };
706                let source = self.buf.split_to(consumed).freeze();
707                let raw = rewritten.unwrap_or(source);
708                self.commit(probe);
709                // An object that arrives in one read completes before
710                // buffering ever reaches the cap, so the incomplete-decode
711                // path below never sees it. Judging it by its own wire
712                // length too is what makes the cap a property of the object
713                // rather than of the caller's read size. Judged on the
714                // *source* length, so an elide fix-up that widens the ID
715                // varint cannot move an object across the boundary.
716                let out = if consumed > self.config.max_buffered_object_bytes {
717                    // A `Passthrough` that is a whole object: the meta was
718                    // decoded and is about to be discarded, so nothing
719                    // outside the framer can address it.
720                    self.counters.note_object_not_addressable();
721                    FramerOut::Passthrough(raw)
722                } else {
723                    FramerOut::Object { meta: self.object_meta(meta), raw }
724                };
725                // Both branches emitted an object, so both arm the cursor:
726                // the oversized one has no `ObjectMeta` for the caller to
727                // name, which is exactly why the framer keeps the record.
728                self.pending_disposition =
729                    Some(PendingObject { object_id, index_in_stream: self.index_in_stream });
730                self.index_in_stream += 1;
731                out
732            }
733            Err(e) if is_incomplete_error(&e) => {
734                if self.buf.len() < self.config.max_buffered_object_bytes {
735                    FramerOut::NeedMore
736                } else {
737                    self.poll_oversized()
738                }
739            }
740            Err(e) => {
741                self.latch_bypass(BypassReason::DecodeError);
742                FramerOut::Error(format!("object decode: {e}"))
743            }
744        }
745    }
746
747    /// The buffer hit its cap without completing an object. Decide whether
748    /// the object's *framing* is understood — in which case its bytes can
749    /// be streamed through and framing resumes afterwards — or whether the
750    /// stream has to be abandoned.
751    ///
752    /// The framing is read against the buffered bytes followed by padding,
753    /// so the decoder can advance past a payload that has not arrived. How
754    /// wide that padding may be is [`Self::measuring_pad`]'s call.
755    fn poll_oversized(&mut self) -> FramerOut {
756        let pad = self.measuring_pad();
757        let mut padded = PaddedBuf::new(&self.buf[..], pad);
758        let probed = match &self.stage {
759            Stage::Subgroup(reader) => {
760                let mut probe = reader.clone();
761                probe.read_object_meta(&mut padded).map(|m| {
762                    (Probe::Subgroup(probe), m.object_id, m.wire_len, m.payload_length, None)
763                })
764            }
765            Stage::Fetch { reader, .. } => {
766                let mut probe = reader.clone();
767                probe.read_object_frame(&mut padded).map(|frame| {
768                    let meta = frame.meta;
769                    (
770                        Probe::Fetch(probe),
771                        meta.object_id,
772                        meta.wire_len,
773                        meta.payload_length,
774                        Some(frame),
775                    )
776                })
777            }
778            Stage::AwaitingHeader => return FramerOut::NeedMore,
779        };
780
781        let Ok((probe, object_id, wire_len, payload_length, frame)) = probed else {
782            self.latch_bypass(BypassReason::ObjectBeyondMeasuringReach);
783            return self.emit_passthrough(u64::MAX);
784        };
785
786        // Only trust the framing when every field ahead of the payload
787        // came from real bytes rather than padding.
788        let framing_len = wire_len - payload_length;
789        let buffered = self.buf.len() as u64;
790        if framing_len > buffered || wire_len <= buffered {
791            self.latch_bypass(BypassReason::ObjectBeyondMeasuringReach);
792            return self.emit_passthrough(u64::MAX);
793        }
794
795        // `framing_len <= buffered` is what makes the fix-up reachable
796        // here: the whole framing, leading Object ID varint included, is
797        // in the chunk about to be emitted. The chunk is a *prefix* of the
798        // object, which `reemit_subgroup_object` accepts — it decodes the
799        // ID field and copies the rest verbatim without validating any
800        // length.
801        let chunk = self.buf.len();
802        let rewritten = match self.apply_elide_fixup(chunk, object_id, frame.as_ref()) {
803            Ok(rewritten) => rewritten,
804            Err(e) => {
805                self.latch_bypass(BypassReason::DecodeError);
806                return FramerOut::Error(e);
807            }
808        };
809
810        self.commit(probe);
811        // The second `Passthrough`-as-an-object path. Counted once here,
812        // not once per emitted chunk: this function is entered once per
813        // oversized object, and the chunks that follow come from `poll`'s
814        // `passthrough_remaining` branch.
815        self.counters.note_object_not_addressable();
816        // Denominated in **source** bytes, and deliberately not adjusted
817        // by the fix-up's `id_bytes_after - id_bytes_before`. Its job is
818        // to say how many more bytes of the *incoming* stream belong to
819        // this object; the emitted stream is a byte or two shorter or
820        // longer for exactly one object, which is what an elide fix-up is.
821        // Correcting it here would make the framer stop consuming this
822        // object early or late and resynchronise mid-way through the next
823        // one — a silent corruption that only fires when the new delta
824        // needs a wider varint.
825        self.passthrough_remaining = wire_len - buffered;
826        self.pending_disposition =
827            Some(PendingObject { object_id, index_in_stream: self.index_in_stream });
828        self.index_in_stream += 1;
829        let source = self.buf.split().freeze();
830        FramerOut::Passthrough(rewritten.unwrap_or(source))
831    }
832
833    /// Commit the disposition of the object emitted most recently.
834    ///
835    /// An object still pending was forwarded; one the caller elided was
836    /// taken out of `pending_disposition` by [`Self::note_elided`], so the
837    /// cursor never advances to it.
838    fn commit_disposition(&mut self) {
839        if let Some(pending) = self.pending_disposition.take() {
840            self.last_forwarded_id = Some(pending.object_id);
841            // Forwarded, so the writer's advance stands and there is nothing
842            // to put back. Cleared rather than left for the next re-emit to
843            // overwrite, so that a rollback can only ever undo the frame it
844            // was taken for.
845            self.fetch_rollback = None;
846        }
847    }
848
849    /// `true` when this stream's Object IDs are written as `id - prev - 1`
850    /// rather than absolutely, so eliding one renumbers every later object.
851    ///
852    /// Subgroup streams on drafts 14-23, and no fetch stream on any draft:
853    /// this is the predicate for the *varint rewrite*, and a fetch frame is
854    /// paid for by [`Self::reemit_fetch_frame`] instead. Drafts 07-13 write
855    /// subgroup Object IDs absolutely and need neither.
856    ///
857    /// The draft half is an exhaustive match rather than a `matches!`: a draft
858    /// left off the list answers "written absolutely", the framer then forwards
859    /// the object after an elide without rewriting its leading varint, and
860    /// every later Object ID on the stream is off by one with nothing to say
861    /// so. The stream-kind half stays a `matches!` — `DataStreamType` is not a
862    /// draft list and its two variants are both named here.
863    fn delta_encodes_object_ids(&self) -> bool {
864        matches!(self.stream_type, DataStreamType::Subgroup)
865            && match self.draft {
866                DraftVersion::Draft07
867                | DraftVersion::Draft08
868                | DraftVersion::Draft09
869                | DraftVersion::Draft10
870                | DraftVersion::Draft11
871                | DraftVersion::Draft12
872                | DraftVersion::Draft13 => false,
873                DraftVersion::Draft14
874                | DraftVersion::Draft15
875                | DraftVersion::Draft16
876                | DraftVersion::Draft17
877                | DraftVersion::Draft18
878                | DraftVersion::Draft19
879                | DraftVersion::Draft20
880                | DraftVersion::Draft21
881                | DraftVersion::Draft22
882                | DraftVersion::Draft23 => true,
883            }
884    }
885
886    /// `true` when eliding an object from this stream leaves the next one
887    /// encoded against something that is no longer on the wire, so a fix-up
888    /// is owed before another object may be forwarded.
889    ///
890    /// The two stream kinds owe it for different reasons and pay it in
891    /// different ways, and the debt itself is the same: until one more object
892    /// has been emitted, the bytes the destination would receive decode to
893    /// Locations nobody sent. `fixup_owed` on a `Bypassed` is what a session
894    /// resets its destination over, and it reads this.
895    ///
896    /// Fetch streams on drafts 15-23, where a Serialization Flags field lets
897    /// a frame take any of its Group ID, Subgroup ID, Object ID and Priority
898    /// from the frame before it — draft-17 Section 10.4.4.1, Table 7: "Object
899    /// ID is the prior Object's ID plus one". Not drafts 07-14, whose fetch
900    /// objects state all four outright.
901    ///
902    /// Exhaustive rather than a `matches!` for the same reason as
903    /// [`Self::delta_encodes_object_ids`], and the consequence is larger here:
904    /// `false` means no fix-up is owed, so the session never resets the
905    /// destination and the receiver keeps a stream whose frames decode to
906    /// Locations nobody sent.
907    fn elide_owes_a_fixup(&self) -> bool {
908        match self.stream_type {
909            DataStreamType::Subgroup => self.delta_encodes_object_ids(),
910            DataStreamType::Fetch => match self.draft {
911                DraftVersion::Draft07
912                | DraftVersion::Draft08
913                | DraftVersion::Draft09
914                | DraftVersion::Draft10
915                | DraftVersion::Draft11
916                | DraftVersion::Draft12
917                | DraftVersion::Draft13
918                | DraftVersion::Draft14 => false,
919                DraftVersion::Draft15
920                | DraftVersion::Draft16
921                | DraftVersion::Draft17
922                | DraftVersion::Draft18
923                | DraftVersion::Draft19
924                | DraftVersion::Draft20
925                | DraftVersion::Draft21
926                | DraftVersion::Draft22
927                | DraftVersion::Draft23 => true,
928            },
929        }
930    }
931
932    /// Rewrite the leading Object ID varint of `self.buf[..len]` when an
933    /// elide has left the wire's delta chain one object ahead of what was
934    /// actually forwarded.
935    ///
936    /// `len` may be a prefix of the object rather than the whole of it —
937    /// the oversized path calls this with the first chunk. Returns
938    /// `Ok(None)` when no fix-up was owed, in which case the caller emits
939    /// the source bytes untouched; the borrow of `self.buf` ends before
940    /// this returns, so the caller is free to split it afterwards.
941    ///
942    /// The error is unreachable in practice — Object IDs are strictly
943    /// increasing within a stream and the caller has already established
944    /// that the ID field is whole in the buffer — but it is reported
945    /// rather than swallowed, because the alternative is emitting bytes
946    /// known to decode to the wrong ID.
947    fn apply_elide_fixup(
948        &mut self,
949        len: usize,
950        object_id: u64,
951        frame: Option<&AnyFetchFrame>,
952    ) -> Result<Option<Bytes>, String> {
953        // `frame` is `Some` exactly on a fetch stream, where the payment is a
954        // re-encode of the whole framing rather than a rewrite of one varint,
955        // and where it is the writer rather than a flag that decides whether
956        // anything is owed.
957        if let Some(frame) = frame {
958            return self.reemit_fetch_frame(len, frame);
959        }
960        if !self.fixup_pending || !self.delta_encodes_object_ids() {
961            return Ok(None);
962        }
963        let mut out = BytesMut::with_capacity(len + 8);
964        let outcome = reemit_subgroup_object(
965            self.draft,
966            self.last_forwarded_id,
967            object_id,
968            &self.buf[..len],
969            &mut out,
970        );
971        if let Err(e) = outcome {
972            // Leaves `fixup_pending` set, so the cursor keeps reporting
973            // that this stream still owes a fix-up.
974            return Err(format!("elide fix-up: {e}"));
975        }
976        self.fixup_pending = false;
977        self.counters.note_object_id_rewritten();
978        Ok(Some(out.freeze()))
979    }
980
981    /// Re-emit one fetch frame through this stream's writer.
982    ///
983    /// Called for **every** fetch frame the framer emits, not only after an
984    /// elide. The writer is what a survivor is re-encoded against, and it
985    /// only moves when it is shown a frame, so skipping the frames nothing
986    /// was owed for would leave it as many frames behind as were skipped.
987    ///
988    /// Answers `Ok(None)` when the frame's own bytes still say what the frame
989    /// says, which is every frame on a stream nothing has been removed from.
990    /// The writer is cloned first so that [`Self::note_elided`] can put it
991    /// back: this runs before the caller's verdict on the frame, and a frame
992    /// the caller drops must leave no trace on the writing side.
993    ///
994    /// `len` may be a prefix of the frame — the oversized path calls this
995    /// with the first chunk — and the codec asks only that the whole framing
996    /// be inside it, which is what the caller has already established.
997    fn reemit_fetch_frame(
998        &mut self,
999        len: usize,
1000        frame: &AnyFetchFrame,
1001    ) -> Result<Option<Bytes>, String> {
1002        let mut out = BytesMut::with_capacity(len + 16);
1003        let (outcome, rollback) = {
1004            let Stage::Fetch { writer, .. } = &mut self.stage else {
1005                return Ok(None);
1006            };
1007            let rollback = writer.clone();
1008            (writer.reemit_object(frame, &self.buf[..len], &mut out), rollback)
1009        };
1010        self.fetch_rollback = Some(rollback);
1011
1012        match outcome {
1013            Ok(FetchReemit::Unchanged) => {
1014                // The debt such as it was is settled either way. A removal
1015                // whose survivor happened to state every field it needed
1016                // costs nothing, and leaving the flag set would have the
1017                // stream report an unpaid fix-up at every later bypass.
1018                self.fixup_pending = false;
1019                Ok(None)
1020            }
1021            Ok(FetchReemit::Reframed { .. }) => {
1022                self.fixup_pending = false;
1023                self.counters.note_object_id_rewritten();
1024                Ok(Some(out.freeze()))
1025            }
1026            // Leaves `fixup_pending` set, as the subgroup path does, so the
1027            // stream keeps reporting that it still owes one.
1028            Err(e) => Err(format!("elide fix-up: {e}")),
1029        }
1030    }
1031
1032    /// How much padding [`Self::poll_oversized`] may put behind the
1033    /// buffered bytes when measuring an object that has not arrived whole.
1034    ///
1035    /// The pad costs no memory by itself — it is never materialised — but
1036    /// every copying read in the codec checks `Buf::remaining()` before it
1037    /// allocates, so the pad is exactly the bound on the allocation a
1038    /// hostile length field can provoke. That makes the choice per layout
1039    /// rather than global:
1040    ///
1041    /// * Subgroup objects on drafts 14-23, and fetch objects on draft-14,
1042    ///   are measured without a single copy — their `read_object_meta`
1043    ///   advances past the extension block and the payload rather than
1044    ///   reading them. Nothing can be talked into allocating, so the pad is
1045    ///   effectively unbounded and an object of *any* declared size stays
1046    ///   measurable: it streams through and framing resumes after it.
1047    /// * Every other object layout decodes its extension block by copying
1048    ///   it out of the buffer. Those keep a pad of one cap, which bounds
1049    ///   the copy at the price of reach: an object whose wire length
1050    ///   exceeds `buffered + cap` cannot be measured and the stream falls
1051    ///   back to passthrough for its remainder.
1052    ///
1053    /// Widening the second case needs the codec to reject an extension
1054    /// length larger than the bytes actually present, which is not this
1055    /// crate's to change.
1056    ///
1057    /// **"Every other" includes the newest fetch layouts, and that is not an
1058    /// omission.** Drafts 15 through 23 all read a fetch frame through
1059    /// `FetchObjectReader::read_object_header`, which materialises the frame's
1060    /// properties — `data_dispatch.rs` `fo15`..`fo23` each carry the block out
1061    /// of the buffer before `read_object_frame` skips the payload — so a
1062    /// declared extension length is still an allocation those drafts can be
1063    /// talked into. Only draft-14's `FetchObject::decode_meta` advances past
1064    /// the block instead. Both arms are exhaustive matches rather than
1065    /// `matches!` so that this stays a decision: a new draft answering `false`
1066    /// by omission would be *safe* here, which is precisely why nothing would
1067    /// ever notice that no one had looked at its fetch layout.
1068    fn measuring_pad(&self) -> usize {
1069        let copy_free = match self.stage {
1070            Stage::Subgroup(_) => match self.draft {
1071                DraftVersion::Draft07
1072                | DraftVersion::Draft08
1073                | DraftVersion::Draft09
1074                | DraftVersion::Draft10
1075                | DraftVersion::Draft11
1076                | DraftVersion::Draft12
1077                | DraftVersion::Draft13 => false,
1078                DraftVersion::Draft14
1079                | DraftVersion::Draft15
1080                | DraftVersion::Draft16
1081                | DraftVersion::Draft17
1082                | DraftVersion::Draft18
1083                | DraftVersion::Draft19
1084                | DraftVersion::Draft20
1085                | DraftVersion::Draft21
1086                | DraftVersion::Draft22
1087                | DraftVersion::Draft23 => true,
1088            },
1089            Stage::Fetch { .. } => match self.draft {
1090                DraftVersion::Draft14 => true,
1091                DraftVersion::Draft07
1092                | DraftVersion::Draft08
1093                | DraftVersion::Draft09
1094                | DraftVersion::Draft10
1095                | DraftVersion::Draft11
1096                | DraftVersion::Draft12
1097                | DraftVersion::Draft13
1098                | DraftVersion::Draft15
1099                | DraftVersion::Draft16
1100                | DraftVersion::Draft17
1101                | DraftVersion::Draft18
1102                | DraftVersion::Draft19
1103                | DraftVersion::Draft20
1104                | DraftVersion::Draft21
1105                | DraftVersion::Draft22
1106                | DraftVersion::Draft23 => false,
1107            },
1108            Stage::AwaitingHeader => false,
1109        };
1110        if copy_free {
1111            UNBOUNDED_MEASURING_PAD
1112        } else {
1113            self.config.max_buffered_object_bytes
1114        }
1115    }
1116
1117    /// Adopt a probe reader whose decode succeeded.
1118    fn commit(&mut self, probe: Probe) {
1119        match (&mut self.stage, probe) {
1120            (Stage::Subgroup(reader), Probe::Subgroup(probe)) => *reader = probe,
1121            (Stage::Fetch { reader, .. }, Probe::Fetch(probe)) => *reader = probe,
1122            // `probe` was cloned from `stage` a few lines earlier, so the
1123            // pairing always matches.
1124            _ => {}
1125        }
1126    }
1127
1128    fn object_meta(&self, meta: Meta) -> ObjectMeta {
1129        match meta {
1130            Meta::Sub(m) => ObjectMeta {
1131                draft: self.draft,
1132                stream_kind: DataStreamType::Subgroup,
1133                track_alias: Some(self.context.track_alias),
1134                group_id: self.context.group_id,
1135                subgroup_id: self.context.subgroup_id,
1136                object_id: m.object_id,
1137                publisher_priority: self.context.publisher_priority,
1138                index_in_stream: self.index_in_stream,
1139                payload_len: m.payload_length,
1140                status: m.status,
1141                end_of_range: None,
1142            },
1143            Meta::Fetch(m) => ObjectMeta {
1144                draft: self.draft,
1145                stream_kind: DataStreamType::Fetch,
1146                track_alias: None,
1147                group_id: m.group_id,
1148                // Not `Some(m.subgroup_id)`: from draft-15 a fetch frame
1149                // may carry no Subgroup ID at all — an object forwarded
1150                // over a datagram has no subgroup, and an End of Range
1151                // indicator names a Location rather than an object — and
1152                // the codec leaves a placeholder in the field when it says
1153                // so. Forwarding that placeholder would key a matcher on a
1154                // subgroup the publisher never named.
1155                subgroup_id: m.has_subgroup_id.then_some(m.subgroup_id),
1156                object_id: m.object_id,
1157                publisher_priority: Some(m.publisher_priority),
1158                index_in_stream: self.index_in_stream,
1159                payload_len: m.payload_length,
1160                status: m.status,
1161                end_of_range: m.end_of_range,
1162            },
1163        }
1164    }
1165}
1166
1167/// A reader clone whose decode succeeded and is ready to be adopted.
1168enum Probe {
1169    Subgroup(AnySubgroupObjectReader),
1170    Fetch(AnyFetchObjectReader),
1171}
1172
1173/// The codec-level framing of one object, either stream kind.
1174#[derive(Clone, Copy)]
1175enum Meta {
1176    Sub(AnySubgroupObjectMeta),
1177    Fetch(AnyFetchObjectMeta),
1178}
1179
1180impl Meta {
1181    /// The object's absolute Object ID, delta encoding already resolved.
1182    fn object_id(self) -> u64 {
1183        match self {
1184            Meta::Sub(m) => m.object_id,
1185            Meta::Fetch(m) => m.object_id,
1186        }
1187    }
1188}
1189
1190/// The identity fields a subgroup header contributes to its objects.
1191///
1192/// Every field comes from an [`AnySubgroupHeader`] accessor, so the
1193/// per-draft knowledge behind them — which stream types leave the subgroup
1194/// ID to the first object, which drafts fold a mode field into the
1195/// header-type octet, which drafts may omit the publisher priority — stays
1196/// in the codec beside the decoders that define it. This crate keeps no
1197/// copy of it, which is the point: a local copy (a mask constant and a
1198/// per-draft match) drifts from the decoders it copies.
1199///
1200/// Where a draft encodes the subgroup ID implicitly as the first object's
1201/// ID, the codec stores zero and [`AnySubgroupHeader::subgroup_id`]
1202/// reports `None` rather than that zero.
1203fn subgroup_context(header: &AnySubgroupHeader) -> SubgroupContext {
1204    SubgroupContext {
1205        track_alias: header.track_alias(),
1206        group_id: header.group_id(),
1207        subgroup_id: header.subgroup_id(),
1208        publisher_priority: header.publisher_priority(),
1209    }
1210}
1211
1212/// A slice followed by a run of zero bytes.
1213///
1214/// Lets a decoder walk an object's framing and advance past a payload that
1215/// has not arrived yet, so the framer can learn an object's total wire
1216/// length without buffering it. Only fields decoded from the real prefix
1217/// are trustworthy; the caller checks that before using the result, and
1218/// picks the pad width from what the decode path may copy — see
1219/// `ObjectFramer::measuring_pad`.
1220struct PaddedBuf<'a> {
1221    real: &'a [u8],
1222    pad: usize,
1223}
1224
1225/// Backing bytes for [`PaddedBuf`]'s padded region.
1226const ZEROS: [u8; 1024] = [0u8; 1024];
1227
1228impl<'a> PaddedBuf<'a> {
1229    fn new(real: &'a [u8], pad: usize) -> Self {
1230        Self { real, pad }
1231    }
1232}
1233
1234impl Buf for PaddedBuf<'_> {
1235    fn remaining(&self) -> usize {
1236        self.real.len() + self.pad
1237    }
1238
1239    fn chunk(&self) -> &[u8] {
1240        if self.real.is_empty() {
1241            &ZEROS[..self.pad.min(ZEROS.len())]
1242        } else {
1243            self.real
1244        }
1245    }
1246
1247    fn advance(&mut self, cnt: usize) {
1248        let from_real = cnt.min(self.real.len());
1249        self.real = &self.real[from_real..];
1250        self.pad = self.pad.saturating_sub(cnt - from_real);
1251    }
1252}
1253
1254// Every test below builds its input with a codec writer and reads it back
1255// with a codec reader, so every one of them needs at least one draft
1256// compiled in. With none, `AnySubgroupHeader` and friends are uninhabited
1257// enums and the helpers stop type-checking — `-D warnings` reports the
1258// `decode_stream` call as an unreachable definition. Gating the module is
1259// the honest shape: with no draft there is no framing to test, so the
1260// module vanishes rather than being kept alive by `#[allow]`.
1261#[cfg(test)]
1262#[cfg(any(
1263    feature = "draft07",
1264    feature = "draft08",
1265    feature = "draft09",
1266    feature = "draft10",
1267    feature = "draft11",
1268    feature = "draft12",
1269    feature = "draft13",
1270    feature = "draft14",
1271    feature = "draft15",
1272    feature = "draft16",
1273    feature = "draft17",
1274    feature = "draft18",
1275    feature = "draft19",
1276    feature = "draft20",
1277    feature = "draft21",
1278    feature = "draft22",
1279    feature = "draft23"
1280))]
1281mod tests {
1282    //! The elide cursor, on the wire.
1283    //! Everything here builds its input with the codec's *writer* and checks
1284    //! the framer's output by *decoding* it again — so the claim under test
1285    //! (*after eliding object N the stream still decodes to the IDs that
1286    //! survived*) is settled by the codec's readers rather than by the rewrite
1287    //! logic being tested. Byte identity in the absence of an elide stays the
1288    //! property `tests/framer_tests.rs` and
1289    //! `tests/object_framing_acceptance.rs` own; the fence here only pins that
1290    //! the new code does not fire when nothing asked it to.
1291
1292    use super::*;
1293
1294    use moqtap_codec::dispatch::{AnySubgroupObject, AnySubgroupObjectWriter};
1295
1296    /// The drafts this build actually compiled.
1297    ///
1298    /// Each element carries its own `#[cfg]`, so the sweep is the enabled
1299    /// set rather than a hardcoded list: a `--features draft14` build
1300    /// sweeps one draft and does not try to decode the headers whose
1301    /// decoders were not compiled.
1302    const DRAFTS: &[DraftVersion] = &[
1303        #[cfg(feature = "draft07")]
1304        DraftVersion::Draft07,
1305        #[cfg(feature = "draft08")]
1306        DraftVersion::Draft08,
1307        #[cfg(feature = "draft09")]
1308        DraftVersion::Draft09,
1309        #[cfg(feature = "draft10")]
1310        DraftVersion::Draft10,
1311        #[cfg(feature = "draft11")]
1312        DraftVersion::Draft11,
1313        #[cfg(feature = "draft12")]
1314        DraftVersion::Draft12,
1315        #[cfg(feature = "draft13")]
1316        DraftVersion::Draft13,
1317        #[cfg(feature = "draft14")]
1318        DraftVersion::Draft14,
1319        #[cfg(feature = "draft15")]
1320        DraftVersion::Draft15,
1321        #[cfg(feature = "draft16")]
1322        DraftVersion::Draft16,
1323        #[cfg(feature = "draft17")]
1324        DraftVersion::Draft17,
1325        #[cfg(feature = "draft18")]
1326        DraftVersion::Draft18,
1327        #[cfg(feature = "draft19")]
1328        DraftVersion::Draft19,
1329        #[cfg(feature = "draft20")]
1330        DraftVersion::Draft20,
1331        #[cfg(feature = "draft21")]
1332        DraftVersion::Draft21,
1333        #[cfg(feature = "draft22")]
1334        DraftVersion::Draft22,
1335        #[cfg(feature = "draft23")]
1336        DraftVersion::Draft23,
1337    ];
1338
1339    /// The drafts that write an Object ID as `id - prev - 1`, and so are
1340    /// the only ones where eliding an object corrupts its successors —
1341    /// intersected with the ones this build compiled.
1342    const DELTA_DRAFTS: &[DraftVersion] = &[
1343        #[cfg(feature = "draft14")]
1344        DraftVersion::Draft14,
1345        #[cfg(feature = "draft15")]
1346        DraftVersion::Draft15,
1347        #[cfg(feature = "draft16")]
1348        DraftVersion::Draft16,
1349        #[cfg(feature = "draft17")]
1350        DraftVersion::Draft17,
1351        #[cfg(feature = "draft18")]
1352        DraftVersion::Draft18,
1353        #[cfg(feature = "draft19")]
1354        DraftVersion::Draft19,
1355        #[cfg(feature = "draft20")]
1356        DraftVersion::Draft20,
1357        #[cfg(feature = "draft21")]
1358        DraftVersion::Draft21,
1359        #[cfg(feature = "draft22")]
1360        DraftVersion::Draft22,
1361        #[cfg(feature = "draft23")]
1362        DraftVersion::Draft23,
1363    ];
1364
1365    /// The stream-type field opening a subgroup stream that carries an
1366    /// explicit subgroup ID and no extensions, per draft.
1367    fn subgroup_stream_type(draft: DraftVersion) -> u8 {
1368        match draft {
1369            DraftVersion::Draft07
1370            | DraftVersion::Draft08
1371            | DraftVersion::Draft09
1372            | DraftVersion::Draft10 => 0x04,
1373            DraftVersion::Draft11 => 0x0C,
1374            _ => 0x14,
1375        }
1376    }
1377
1378    /// Wire bytes of a subgroup header: track alias 1, group 0, subgroup 0,
1379    /// publisher priority 128, no extensions.
1380    fn header_bytes(draft: DraftVersion) -> Vec<u8> {
1381        vec![subgroup_stream_type(draft), 0x01, 0x00, 0x00, 0x80]
1382    }
1383
1384    fn object(object_id: u64, payload_len: usize) -> AnySubgroupObject {
1385        AnySubgroupObject {
1386            object_id,
1387            extension_headers: Vec::new(),
1388            extension_count: None,
1389            status: None,
1390            payload: vec![0xAB; payload_len],
1391        }
1392    }
1393
1394    /// Encode a whole subgroup stream: header plus `objects`, on `draft`.
1395    fn build_stream(draft: DraftVersion, objects: &[AnySubgroupObject]) -> Vec<u8> {
1396        let head = header_bytes(draft);
1397        let mut cursor: &[u8] = &head;
1398        let header = AnySubgroupHeader::decode_stream(draft, &mut cursor)
1399            .unwrap_or_else(|e| panic!("[{draft}] header decode: {e}"));
1400        let mut writer = AnySubgroupObjectWriter::new(&header)
1401            .unwrap_or_else(|e| panic!("[{draft}] writer: {e}"));
1402
1403        let mut out = head;
1404        for obj in objects {
1405            writer
1406                .write_object(obj, &mut out)
1407                .unwrap_or_else(|e| panic!("[{draft}] write object {}: {e}", obj.object_id));
1408        }
1409        out
1410    }
1411
1412    /// A subgroup framer on `draft`, reporting into `counters`.
1413    ///
1414    /// Every framer in this module goes through
1415    /// [`ObjectFramer::with_recorder`] rather than [`ObjectFramer::new`]:
1416    /// it keeps `src/` free of the string standing gate 7 greps for
1417    /// without the gate having to filter comments, and it gives the
1418    /// counter assertions below something to read.
1419    fn framer_for(
1420        draft: DraftVersion,
1421        config: FramerConfig,
1422        counters: &Arc<Recorder>,
1423    ) -> ObjectFramer {
1424        ObjectFramer::with_recorder(DataStreamType::Subgroup, draft, config, Arc::clone(counters))
1425    }
1426
1427    /// What one run of the framer produced.
1428    struct Run {
1429        /// Every byte the framer emitted, in order.
1430        bytes: Vec<u8>,
1431        /// The Object IDs the framer itself resolved while producing them.
1432        ///
1433        /// Objects that left as `Passthrough` are absent — they were never
1434        /// addressable — so this is also the record of *where framing
1435        /// resumed* after one of them.
1436        framed_ids: Vec<u64>,
1437        /// The run's own counters.
1438        counters: Arc<Recorder>,
1439    }
1440
1441    /// Feed `stream` to a framer in `chunk`-sized pieces, dropping every
1442    /// object whose ID is in `elide`, and return what the framer produced.
1443    ///
1444    /// A bypass is a panic rather than a recorded outcome: every test that
1445    /// uses this helper is about an elide surviving, and a stream that
1446    /// quietly stopped being parsed would satisfy the byte assertions
1447    /// while proving nothing.
1448    fn run_eliding(
1449        draft: DraftVersion,
1450        stream: &[u8],
1451        chunk: usize,
1452        config: FramerConfig,
1453        elide: &[u64],
1454    ) -> Run {
1455        let counters = Arc::new(Recorder::new());
1456        let mut framer = framer_for(draft, config, &counters);
1457        let mut run = Run { bytes: Vec::new(), framed_ids: Vec::new(), counters };
1458        for piece in stream.chunks(chunk.max(1)) {
1459            framer.feed(piece);
1460            loop {
1461                match framer.poll() {
1462                    FramerOut::NeedMore => break,
1463                    FramerOut::Header { raw, .. } => run.bytes.extend_from_slice(&raw),
1464                    FramerOut::Object { meta, raw } => {
1465                        run.framed_ids.push(meta.object_id);
1466                        if elide.contains(&meta.object_id) {
1467                            framer.note_elided(&meta);
1468                        } else {
1469                            run.bytes.extend_from_slice(&raw);
1470                        }
1471                    }
1472                    FramerOut::Passthrough(raw) => run.bytes.extend_from_slice(&raw),
1473                    FramerOut::Bypassed { reason, fixup_owed } => {
1474                        panic!("[{draft}] unexpected bypass: {reason:?}, fixup_owed {fixup_owed}")
1475                    }
1476                    FramerOut::Error(e) => panic!("[{draft}] framer error: {e}"),
1477                }
1478            }
1479        }
1480        if let Some(tail) = framer.finish() {
1481            run.bytes.extend_from_slice(&tail);
1482        }
1483        run
1484    }
1485
1486    /// Decode `bytes` as a subgroup stream and report the Object IDs the
1487    /// codec's readers resolve from it.
1488    ///
1489    /// The framer used here has the default cap, so every object is framed
1490    /// individually no matter how the producing run chose to emit it.
1491    fn framed_object_ids(draft: DraftVersion, bytes: &[u8]) -> Vec<u64> {
1492        let counters = Arc::new(Recorder::new());
1493        let mut framer = framer_for(draft, FramerConfig::default(), &counters);
1494        framer.feed(bytes);
1495        let mut ids = Vec::new();
1496        loop {
1497            match framer.poll() {
1498                FramerOut::NeedMore => break,
1499                FramerOut::Header { .. } => {}
1500                FramerOut::Object { meta, .. } => ids.push(meta.object_id),
1501                FramerOut::Passthrough(raw) => {
1502                    panic!("[{draft}] re-decode fell back to passthrough after {} bytes", raw.len())
1503                }
1504                FramerOut::Bypassed { reason, .. } => {
1505                    panic!("[{draft}] re-decode bypassed: {reason:?}")
1506                }
1507                FramerOut::Error(e) => panic!("[{draft}] re-decode: {e}"),
1508            }
1509        }
1510        assert_eq!(framer.buffered(), 0, "[{draft}] re-decode left bytes buffered");
1511        ids
1512    }
1513
1514    /// Eliding an object leaves a stream that still decodes to exactly the
1515    /// objects that survived, on every draft.
1516    ///
1517    /// On drafts 14-23 that is only true because the framer rewrites the
1518    /// next object's leading Object ID varint; on 07-13 the IDs are
1519    /// absolute and the surviving bytes already say the truth.
1520    #[test]
1521    fn eliding_an_object_renumbers_the_rest_of_the_stream() {
1522        for &draft in DRAFTS {
1523            let objects: Vec<_> = (0..4).map(|id| object(id, 16)).collect();
1524            let stream = build_stream(draft, &objects);
1525
1526            let run = run_eliding(draft, &stream, stream.len(), FramerConfig::default(), &[1]);
1527
1528            assert_eq!(
1529                framed_object_ids(draft, &run.bytes),
1530                vec![0, 2, 3],
1531                "[{draft}] elided stream must decode to the surviving IDs"
1532            );
1533        }
1534    }
1535
1536    /// The elide survives an object the framer cannot address
1537    /// individually.
1538    ///
1539    /// Object 65 is over the buffer cap, so it leaves as `Passthrough` with
1540    /// no `ObjectMeta` for anyone outside the framer to name. A cursor
1541    /// owned by the caller could not renumber it, and its stale delta would
1542    /// shift every later object for the rest of the stream. The IDs are
1543    /// chosen so the correction changes the varint's *width*:
1544    /// `65 - 1 - 1 = 63` is one byte, `65 - 0 - 1 = 64` is two.
1545    #[test]
1546    fn an_oversized_object_after_an_elide_is_still_renumbered() {
1547        for &draft in DRAFTS {
1548            let objects = vec![object(0, 8), object(1, 8), object(65, 4096), object(66, 8)];
1549            let stream = build_stream(draft, &objects);
1550            let config = FramerConfig::new().with_max_buffered_object_bytes(64);
1551
1552            // Whole stream in one feed: the oversized object decodes
1553            // completely and `poll_object` routes it by its own wire length.
1554            let run = run_eliding(draft, &stream, stream.len(), config, &[1]);
1555            assert_eq!(
1556                run.framed_ids,
1557                vec![0, 1, 66],
1558                "[{draft}] object 65 left as passthrough and framing resumed on 66"
1559            );
1560            assert_eq!(
1561                framed_object_ids(draft, &run.bytes),
1562                vec![0, 65, 66],
1563                "[{draft}] oversized successor of an elide, decoded whole"
1564            );
1565        }
1566    }
1567
1568    /// The same, through `poll_oversized`: the object never arrives whole,
1569    /// so it is measured against padding and streamed out in chunks.
1570    ///
1571    /// This is the path where `passthrough_remaining` matters. It is
1572    /// computed from the *source* wire length while the emitted chunk is a
1573    /// byte longer, and the objects are picked so that gap is real.
1574    ///
1575    /// Restricted to the six delta drafts because they are the only ones
1576    /// whose object layout the codec can measure past an unarrived payload;
1577    /// on 07-13 a 4 KiB object with a 64-byte cap is out of measuring reach
1578    /// and the stream bypasses instead, which is a different property.
1579    #[test]
1580    fn an_elide_survives_an_object_streamed_through_in_chunks() {
1581        for &draft in DELTA_DRAFTS {
1582            let objects = vec![object(0, 8), object(1, 8), object(65, 4096), object(66, 8)];
1583            let stream = build_stream(draft, &objects);
1584            let config = FramerConfig::new().with_max_buffered_object_bytes(64);
1585
1586            let run = run_eliding(draft, &stream, 32, config, &[1]);
1587            // The accounting claim: `passthrough_remaining` is denominated
1588            // in source bytes, so the framer consumes object 65 exactly and
1589            // resynchronises on object 66's first byte — even though what
1590            // it emitted for object 65 is a byte longer than what it read.
1591            assert_eq!(
1592                run.framed_ids,
1593                vec![0, 1, 66],
1594                "[{draft}] framing must resume exactly on object 66"
1595            );
1596            assert_eq!(
1597                framed_object_ids(draft, &run.bytes),
1598                vec![0, 65, 66],
1599                "[{draft}] oversized successor of an elide, streamed through"
1600            );
1601        }
1602    }
1603
1604    /// A framer nobody elides on emits its input back, byte for byte.
1605    ///
1606    /// The regression fence for the fix-up code: it must be inert until
1607    /// [`ObjectFramer::note_elided`] is called. This is the property the
1608    /// acceptance suite rests on, restated where the code that could break
1609    /// it lives.
1610    #[test]
1611    fn a_stream_with_no_elide_is_emitted_byte_for_byte() {
1612        for &draft in DRAFTS {
1613            let objects: Vec<_> = (0..4).map(|id| object(id, 16)).collect();
1614            let stream = build_stream(draft, &objects);
1615
1616            for chunk in [1usize, 7, stream.len()] {
1617                let run = run_eliding(draft, &stream, chunk, FramerConfig::default(), &[]);
1618                assert_eq!(run.bytes, stream, "[{draft}] chunk {chunk}: byte identity");
1619            }
1620        }
1621    }
1622
1623    /// A non-minimally encoded Object ID field survives untouched when
1624    /// nothing was elided.
1625    ///
1626    /// QUIC varints may be written wider than they need to be, and a
1627    /// producer that does so is still emitting a legal stream. Re-encoding
1628    /// such a field would change bytes the proxy was asked to forward
1629    /// unchanged — so the fix-up must be reached only when an elide
1630    /// actually armed it, not merely when the draft delta-encodes.
1631    #[test]
1632    fn a_widened_object_id_field_is_not_re_encoded() {
1633        for &draft in DELTA_DRAFTS {
1634            let stream = build_stream(draft, &[object(0, 8), object(1, 8)]);
1635
1636            // Object 0 starts right after the five header bytes, and its
1637            // leading field is the one-byte varint 0. The two-byte form of the
1638            // same value differs by draft: `0x40 0x00` under RFC 9000, and
1639            // `0x80 0x00` from draft-17, where `0x40` is the one-byte 64.
1640            let head = header_bytes(draft).len();
1641            assert_eq!(stream[head], 0x00, "[{draft}] object 0's ID field is not where expected");
1642            let two_byte_zero: [u8; 2] =
1643                if draft.uses_moqt_varint() { [0x80, 0x00] } else { [0x40, 0x00] };
1644            let mut widened = stream[..head].to_vec();
1645            widened.extend_from_slice(&two_byte_zero);
1646            widened.extend_from_slice(&stream[head + 1..]);
1647
1648            let run = run_eliding(draft, &widened, widened.len(), FramerConfig::default(), &[]);
1649            assert_eq!(run.framed_ids, vec![0, 1], "[{draft}] widened field must still decode");
1650            assert_eq!(run.bytes, widened, "[{draft}] widened field must be forwarded verbatim");
1651        }
1652    }
1653
1654    /// No draft-16 subgroup header the decoder accepts sets both the
1655    /// explicit-subgroup-ID bit and the first-object bit, so the proxy
1656    /// never has to choose between them.
1657    ///
1658    /// Setting `0x04` (explicit subgroup ID) and `0x02` (subgroup ID is the
1659    /// first object's) together puts bits one and two at `0b11`, and
1660    /// draft-16 Section 10.4.2 reserves that Subgroup ID mode. The decoder
1661    /// refuses all eight bytes that spell it, so no such header decodes,
1662    /// and the sweep below covers the whole reserved mode rather than one
1663    /// byte of it.
1664    ///
1665    /// Why the proxy reads the field through the uniform accessor rather
1666    /// than off the header's bits: those two bits are one two-bit field,
1667    /// and a predicate reading `0x02` alone answers `true` for the reserved
1668    /// mode as well — at the same time as one reading `0x04` alone, for a
1669    /// state one two-bit field cannot be in.
1670    /// [`AnySubgroupHeader::subgroup_id`] reads the mode as a field
1671    /// instead: it answers `None` for the reserved mode — the header
1672    /// determines no Subgroup ID — and reads the explicit field only for
1673    /// mode 2, which is the only mode the decoder reads one for.
1674    #[test]
1675    #[cfg(feature = "draft16")]
1676    fn draft16_refuses_the_reserved_subgroup_id_mode() {
1677        let draft = DraftVersion::Draft16;
1678        // Bits one and two are the Subgroup ID mode; 0b11 is reserved.
1679        // These are the eight subgroup types that set it, with and without
1680        // the extensions and priority bits.
1681        for ty in [0x16u8, 0x17, 0x1E, 0x1F, 0x36, 0x37, 0x3E, 0x3F] {
1682            // Track alias 1, group 0, subgroup 42, publisher priority 128 —
1683            // a complete body, so a refusal is of the type and never of a
1684            // short buffer.
1685            let head = vec![ty, 0x01, 0x00, 0x2A, 0x80];
1686            let mut cursor: &[u8] = &head;
1687            assert!(
1688                AnySubgroupHeader::decode_stream(draft, &mut cursor).is_err(),
1689                "type {ty:#04x} sets the reserved Subgroup ID mode and must be refused",
1690            );
1691        }
1692    }
1693
1694    /// The cursor advances lazily, one object behind the framer.
1695    ///
1696    /// An object's disposition is not known when it is emitted — the caller
1697    /// decides afterwards — so `last_forwarded_id` moves at the top of the
1698    /// *next* `poll_object`. The fix-up flag is the part that must be
1699    /// visible immediately, because it is what a bypass has to report as
1700    /// still owed.
1701    #[test]
1702    fn the_elide_cursor_tracks_the_last_object_actually_forwarded() {
1703        for &draft in DRAFTS {
1704            let delta = DELTA_DRAFTS.contains(&draft);
1705            let objects: Vec<_> = (0..3).map(|id| object(id, 8)).collect();
1706            let stream = build_stream(draft, &objects);
1707
1708            let counters = Arc::new(Recorder::new());
1709            let mut framer = framer_for(draft, FramerConfig::default(), &counters);
1710            framer.feed(&stream);
1711
1712            assert_eq!(
1713                framer.elide_cursor(),
1714                ElideCursor { last_forwarded_id: None, fixup_pending: false },
1715                "[{draft}] fresh framer"
1716            );
1717
1718            assert!(matches!(framer.poll(), FramerOut::Header { .. }));
1719
1720            // Object 0, forwarded.
1721            let FramerOut::Object { meta, .. } = framer.poll() else {
1722                panic!("[{draft}] expected object 0");
1723            };
1724            assert_eq!(meta.object_id, 0);
1725            assert_eq!(
1726                framer.elide_cursor().last_forwarded_id,
1727                None,
1728                "[{draft}] object 0's disposition is not known yet"
1729            );
1730
1731            // Object 1, elided. Polling for it commits object 0 first.
1732            let FramerOut::Object { meta, .. } = framer.poll() else {
1733                panic!("[{draft}] expected object 1");
1734            };
1735            assert_eq!(meta.object_id, 1);
1736            assert_eq!(
1737                framer.elide_cursor().last_forwarded_id,
1738                Some(0),
1739                "[{draft}] object 0 committed as forwarded"
1740            );
1741            framer.note_elided(&meta);
1742            assert_eq!(
1743                framer.elide_cursor(),
1744                ElideCursor { last_forwarded_id: Some(0), fixup_pending: delta },
1745                "[{draft}] the elide is visible at once, and only delta drafts owe a fix-up"
1746            );
1747
1748            // Object 2 clears the fix-up as it is emitted, and the cursor
1749            // still names object 0 until the object after it is asked for.
1750            let FramerOut::Object { meta, .. } = framer.poll() else {
1751                panic!("[{draft}] expected object 2");
1752            };
1753            assert_eq!(meta.object_id, 2);
1754            assert_eq!(
1755                framer.elide_cursor(),
1756                ElideCursor { last_forwarded_id: Some(0), fixup_pending: false },
1757                "[{draft}] the fix-up is spent on the object that carried it"
1758            );
1759
1760            assert!(matches!(framer.poll(), FramerOut::NeedMore));
1761            assert_eq!(
1762                framer.elide_cursor().last_forwarded_id,
1763                Some(2),
1764                "[{draft}] object 2 committed as forwarded"
1765            );
1766        }
1767    }
1768
1769    /// A bypass is reported once, as a zero-byte item, on the poll *after*
1770    /// the one that decided it.
1771    ///
1772    /// A draft-19 fetch stream is the cleanest case: the header decodes,
1773    /// so it is emitted, and only then is the stream found to be one whose
1774    /// objects are not addressed. `latch_bypass` cannot return the
1775    /// `Bypassed` item from that poll — the poll already owes a `Header` —
1776    /// so it is deferred.
1777    #[test]
1778    #[cfg(feature = "draft19")]
1779    fn a_bypass_is_reported_once_on_the_poll_after_the_item_that_decided_it() {
1780        let draft = DraftVersion::Draft19;
1781        // Fetch stream type 0x05, request ID 42, then four bytes of
1782        // whatever the publisher was sending.
1783        let stream = vec![0x05u8, 0x2A, 0xDE, 0xAD, 0xBE, 0xEF];
1784
1785        let counters = Arc::new(Recorder::new());
1786        let mut framer = ObjectFramer::with_recorder(
1787            DataStreamType::Fetch,
1788            draft,
1789            FramerConfig::default(),
1790            Arc::clone(&counters),
1791        );
1792        framer.feed(&stream);
1793
1794        let FramerOut::Header { raw, .. } = framer.poll() else {
1795            panic!("expected the fetch header");
1796        };
1797        assert_eq!(&raw[..], &stream[..2], "the header is still emitted in full");
1798        assert!(framer.is_bypassed(), "the bypass was decided before the header was handed out");
1799
1800        assert!(
1801            matches!(
1802                framer.poll(),
1803                FramerOut::Bypassed {
1804                    reason: BypassReason::FetchGroupOrderUnknown,
1805                    fixup_owed: false
1806                }
1807            ),
1808            "the bypass follows the header rather than replacing it"
1809        );
1810
1811        let FramerOut::Passthrough(rest) = framer.poll() else {
1812            panic!("expected the remainder to be forwarded uninterpreted");
1813        };
1814        assert_eq!(&rest[..], &stream[2..], "no byte is lost to the bypass");
1815
1816        assert!(matches!(framer.poll(), FramerOut::NeedMore));
1817        assert!(matches!(framer.poll(), FramerOut::NeedMore), "reported exactly once");
1818
1819        let c = counters.snapshot();
1820        assert_eq!(c.framers_created, 1);
1821        assert_eq!(c.framer_header_polls, 1);
1822        assert_eq!(c.framer_object_polls, 0, "a bypassed stream never enters the object path");
1823        assert_eq!(c.streams_not_shapeable, 1);
1824        assert_eq!(c.objects_not_addressable, 0, "no object was ever decoded");
1825    }
1826
1827    /// A bypass while a fix-up is owed says so, because the bytes still in
1828    /// flight decode to Object IDs one ahead of what was delivered.
1829    ///
1830    /// Objects 0 and 1 are written normally and object 1 is elided, which
1831    /// arms the fix-up. The third object is a hand-written all-ones varint —
1832    /// `2^62 - 1` in eight bytes under RFC 9000, `2^64 - 1` in nine from
1833    /// draft-17. Either is legal and its delta resolves to an Object ID above
1834    /// the ceiling, so `read_object_meta` returns `InvalidField` rather than
1835    /// an incomplete-input error and the framer abandons the stream with the
1836    /// fix-up unspent.
1837    #[test]
1838    fn a_bypass_that_strands_a_fix_up_reports_it_as_owed() {
1839        for &draft in DELTA_DRAFTS {
1840            let mut stream = build_stream(draft, &[object(0, 8), object(1, 8)]);
1841            // All-ones is the largest varint the draft's encoding can express:
1842            // eight bytes under RFC 9000, nine from draft-17.
1843            if draft.uses_moqt_varint() {
1844                stream.extend_from_slice(&[0xFFu8; 9]);
1845            } else {
1846                stream.extend_from_slice(&[0xFFu8; 8]);
1847            }
1848
1849            let counters = Arc::new(Recorder::new());
1850            let mut framer = framer_for(draft, FramerConfig::default(), &counters);
1851            framer.feed(&stream);
1852
1853            assert!(matches!(framer.poll(), FramerOut::Header { .. }));
1854            assert!(matches!(framer.poll(), FramerOut::Object { .. }), "[{draft}] object 0");
1855            let FramerOut::Object { meta, .. } = framer.poll() else {
1856                panic!("[{draft}] expected object 1");
1857            };
1858            framer.note_elided(&meta);
1859            assert!(framer.elide_cursor().fixup_pending, "[{draft}] the fix-up is armed");
1860
1861            assert!(
1862                matches!(framer.poll(), FramerOut::Error(_)),
1863                "[{draft}] the third object must fail to decode outright"
1864            );
1865            assert!(
1866                matches!(
1867                    framer.poll(),
1868                    FramerOut::Bypassed { reason: BypassReason::DecodeError, fixup_owed: true }
1869                ),
1870                "[{draft}] the stranded fix-up must be reported"
1871            );
1872
1873            assert_eq!(counters.snapshot().streams_not_shapeable, 1, "[{draft}] one latch");
1874            assert_eq!(
1875                counters.snapshot().object_ids_rewritten,
1876                0,
1877                "[{draft}] the fix-up never got the chance to be written"
1878            );
1879        }
1880    }
1881
1882    /// The counters move where — and only where — the slow path ran.
1883    ///
1884    /// This is the falsifiable half of the `Interest::NONE` claim: the
1885    /// framer is the slow path, so a framer that counts nothing makes the
1886    /// proof pass by measuring nothing.
1887    #[test]
1888    fn the_framer_counts_the_slow_path_work_it_did() {
1889        for &draft in DRAFTS {
1890            let delta = DELTA_DRAFTS.contains(&draft);
1891            let objects: Vec<_> = (0..4).map(|id| object(id, 16)).collect();
1892            let stream = build_stream(draft, &objects);
1893
1894            let run = run_eliding(draft, &stream, stream.len(), FramerConfig::default(), &[1]);
1895            let c = run.counters.snapshot();
1896
1897            assert_eq!(c.framers_created, 1, "[{draft}]");
1898            assert_eq!(c.framer_header_polls, 1, "[{draft}] one poll decoded the header");
1899            // Four objects plus the poll that returned `NeedMore`.
1900            assert_eq!(c.framer_object_polls, 5, "[{draft}]");
1901            assert_eq!(
1902                c.object_ids_rewritten,
1903                u64::from(delta),
1904                "[{draft}] one rewrite, and only where IDs are deltas"
1905            );
1906            assert_eq!(c.objects_not_addressable, 0, "[{draft}] every object was framed");
1907            assert_eq!(c.streams_not_shapeable, 0, "[{draft}] nothing was bypassed");
1908        }
1909    }
1910
1911    /// An object too big to buffer is counted as unaddressable exactly
1912    /// once, on both of the paths that produce one.
1913    ///
1914    /// The whole-stream feed routes object 65 through `poll_object`'s
1915    /// oversized branch; the 32-byte feed routes it through
1916    /// `poll_oversized`, which emits it as several `Passthrough` chunks
1917    /// and must still count *one* object.
1918    #[test]
1919    fn an_unaddressable_object_is_counted_once_per_object_not_per_chunk() {
1920        for &draft in DELTA_DRAFTS {
1921            let objects = vec![object(0, 8), object(1, 8), object(65, 4096), object(66, 8)];
1922            let stream = build_stream(draft, &objects);
1923            let config = FramerConfig::new().with_max_buffered_object_bytes(64);
1924
1925            for chunk in [stream.len(), 32] {
1926                let run = run_eliding(draft, &stream, chunk, config.clone(), &[1]);
1927                let c = run.counters.snapshot();
1928                assert_eq!(
1929                    c.objects_not_addressable, 1,
1930                    "[{draft}] chunk {chunk}: one object, however many chunks it left in"
1931                );
1932                assert_eq!(c.object_ids_rewritten, 1, "[{draft}] chunk {chunk}");
1933                assert_eq!(c.streams_not_shapeable, 0, "[{draft}] chunk {chunk}: no bypass");
1934            }
1935        }
1936    }
1937}