Skip to main content

binlog_inspect/
parser.rs

1// Copyright (c) 2026 houseme
2// SPDX-License-Identifier: Apache-2.0
3
4//! Stateful, streaming MySQL binlog reader.
5use crate::event::{EventPayload, EventType, ParsedEvent, RowChange};
6use mysql_common::binlog::{
7    EventStreamReader,
8    consts::{
9        BinlogChecksumAlg, BinlogVersion, IncidentType, IntvarEventType,
10        TransactionPayloadCompressionType,
11    },
12    events::{Event, EventData, PreviousGtidsEvent, RowsEventData, TransactionPayloadReader},
13};
14use std::{
15    collections::HashMap,
16    convert::Infallible,
17    fs::File,
18    io::{self, BufRead, BufReader, Cursor, Read},
19    ops::ControlFlow,
20    path::Path,
21};
22
23/// Upper bound on the accepted size of a single event, including its header.
24pub const MAX_EVENT_SIZE: u32 = 64 * 1024 * 1024;
25
26/// Upper bound on the inner events the collecting [`BinlogParser::events`]
27/// iterator buffers per transaction payload (R46b).
28///
29/// The bound targets the pathological tiny-event case: a payload of 250,000
30/// minimal events decodes to roughly 250 MB of retained event values, which
31/// is the heaviest shape one payload can produce, while sitting about two
32/// orders of magnitude above real transactions so legitimate payloads never
33/// reach it. Breaching the bound returns [`ParserError::TooManyInnerEvents`]
34/// instead of growing memory without limit. The bound can be raised through
35/// [`BinlogParser::with_inner_event_limit`], and
36/// [`BinlogParser::visit_events`] is not affected: its callback consumes
37/// each inner event immediately, so the user applies backpressure.
38pub const DEFAULT_INNER_EVENT_LIMIT: usize = 250_000;
39
40/// Capacity of the buffered reader wrapping the input.
41const READ_BUFFER_CAPACITY: usize = 1 << 20;
42
43/// Upper bound on the uncompressed size a transaction payload may declare.
44///
45/// The declared value is metadata from the event header and is checked before
46/// any decompression starts; exceeding it is corruption or an attack.
47const MAX_UNCOMPRESSED_PAYLOAD_SIZE: u64 = 1 << 30;
48
49/// Tolerance applied to the declared uncompressed size while counting the
50/// decompressed bytes of a transaction payload.
51const PAYLOAD_SIZE_SLACK: u64 = 1 << 20;
52
53/// Failure opening or reading a binlog.
54///
55/// This enum is `#[non_exhaustive]` (R45): downstream matches require a
56/// wildcard arm, so structured variants can be added without a semver-major
57/// release. [`ParserError::Io`] stays the documented catch-all for failures
58/// without a dedicated variant.
59#[derive(Debug, thiserror::Error)]
60#[non_exhaustive]
61pub enum ParserError {
62    /// Encrypted MySQL binlogs must be read through the server.
63    #[error(
64        "encrypted binlog detected; use mysqlbinlog --read-from-remote-server against the MySQL server"
65    )]
66    EncryptedBinlog,
67    /// The input does not have the plaintext MySQL binlog magic.
68    #[error("invalid or truncated binlog file header")]
69    InvalidHeader,
70    /// Any other input or event decoding failure.
71    #[error("binlog error at offset {offset}: {source}")]
72    Io {
73        /// File offset at which the failure was detected.
74        offset: u64,
75        /// The underlying failure.
76        #[source]
77        source: io::Error,
78    },
79    /// The event's CRC32 checksum does not match its bytes.
80    ///
81    /// The Display string is identical to the message this path emitted
82    /// before the variant existed (R45); the offset is structured so callers
83    /// can locate the corruption programmatically.
84    #[error("binlog error at offset {offset}: event checksum mismatch")]
85    Checksum {
86        /// File offset at which the failed event begins.
87        offset: u64,
88    },
89    /// The event body ended before its declared size was read.
90    ///
91    /// The Display string is identical to the underlying `read_exact` EOF
92    /// failure the truncated/EOF path surfaced before the variant existed
93    /// (R45).
94    #[error("binlog error at offset {offset}: failed to fill whole buffer")]
95    Truncated {
96        /// File offset at which the truncated event begins.
97        offset: u64,
98    },
99    /// The declared event size is outside the valid range: below the
100    /// 19-byte event header or above the configured per-event cap.
101    ///
102    /// The Display string is identical to the message this path emitted
103    /// before the variant existed (R45); `size` and `limit` are structured
104    /// fields, not part of the message.
105    #[error("binlog error at offset {offset}: invalid or oversized event")]
106    OversizedEvent {
107        /// File offset at which the rejected event begins.
108        offset: u64,
109        /// Declared size carried in the event header.
110        size: u32,
111        /// The configured per-event size cap.
112        limit: u32,
113    },
114    /// A transaction payload carried more inner events than the configured
115    /// inner-event collection bound allows (R46b).
116    ///
117    /// The collecting [`BinlogParser::events`] iterator buffers every inner
118    /// event of a payload; this error stops the input before the buffer can
119    /// grow without limit. The message names the CLI flag and the uncapped
120    /// visiting alternative so the remedy is discoverable.
121    #[error(
122        "transaction payload at offset {offset} contains more than {limit} inner events; raise --max-inner-events or use visit_events"
123    )]
124    TooManyInnerEvents {
125        /// File offset of the enclosing transaction payload event.
126        offset: u64,
127        /// The configured inner-event collection bound.
128        limit: usize,
129    },
130}
131
132/// One notification from [`BinlogParser::visit_events`].
133///
134/// Compressed transactions produce a start notification, their inner events
135/// in stream order, and an end notification after successful decoding. An
136/// error or an early stop can leave a start without a matching end.
137#[derive(Debug)]
138#[non_exhaustive]
139pub enum VisitEvent<'a> {
140    /// A decoded ordinary event or one inner event of a compressed transaction.
141    Event {
142        /// The current event, borrowed only for this callback invocation.
143        event: &'a ParsedEvent,
144        /// File offset of the enclosing transaction payload, or `None` for
145        /// an ordinary outer event. Inner event offsets are relative to the
146        /// decompressed stream.
147        parent_offset: Option<u64>,
148    },
149    /// A validated transaction payload about to be decoded.
150    TransactionPayloadStart {
151        /// Byte offset of the outer event in the binlog file.
152        offset: u64,
153        /// Outer timestamp, inherited by every inner event.
154        timestamp: u32,
155        /// Outer server identifier, inherited by every inner event.
156        server_id: u32,
157        /// Original outer event size, including its header and checksum.
158        event_size: u32,
159        /// Position recorded in the outer event header.
160        log_pos: u32,
161        /// Canonical compression name, `"NONE"` or `"ZSTD"`.
162        compression: &'a str,
163        /// Uncompressed size declared by the payload header.
164        uncompressed_size: u64,
165    },
166    /// All inner events and the end of the decompression stream were read
167    /// successfully.
168    TransactionPayloadEnd {
169        /// File offset of the corresponding outer transaction payload.
170        offset: u64,
171    },
172}
173
174/// A checked outer event together with its original on-disk coordinates.
175struct FramedEvent {
176    event: Event,
177    offset: u64,
178    size: u32,
179}
180
181impl FramedEvent {
182    fn into_parsed(self, payload: EventPayload) -> ParsedEvent {
183        let header = self.event.header();
184        ParsedEvent {
185            offset: self.offset,
186            timestamp: header.timestamp(),
187            event_type: EventType::from_raw(header.event_type_raw()),
188            event_type_code: header.event_type_raw(),
189            server_id: header.server_id(),
190            event_size: self.size,
191            log_pos: header.log_pos(),
192            payload,
193        }
194    }
195}
196
197#[derive(Clone, Copy)]
198struct PayloadInfo {
199    compression: &'static str,
200    uncompressed_size: u64,
201}
202
203enum PayloadItem {
204    Start(PayloadInfo),
205    Event(ParsedEvent),
206}
207
208/// Framing-layer failure raised by [`BinlogParser::read_framed_event`].
209///
210/// The helper runs where the failed event's file offset is known to its
211/// callers but not to itself, so it reports the framing problem without one;
212/// the callers map it onto the public [`ParserError`] structured variants
213/// with the starting offset (R45).
214#[derive(Debug, thiserror::Error)]
215enum FrameError {
216    /// The event's CRC32 checksum does not match its bytes.
217    #[error("event checksum mismatch")]
218    Checksum,
219    /// The event body ended before its declared size was read.
220    #[error("failed to fill whole buffer")]
221    Truncated,
222    /// The declared event size is outside the valid range.
223    #[error("invalid or oversized event")]
224    OversizedEvent {
225        /// Declared size carried in the event header.
226        size: u32,
227        /// The configured per-event size cap.
228        limit: u32,
229    },
230    /// Any other I/O failure while framing the event.
231    #[error(transparent)]
232    Io(#[from] io::Error),
233}
234
235impl FrameError {
236    /// Attaches the file offset where the failed event begins, keeping every
237    /// public Display string identical to the one the path emitted before
238    /// the structured variants existed (R45).
239    fn into_parser_error(self, offset: u64) -> ParserError {
240        match self {
241            Self::Checksum => ParserError::Checksum { offset },
242            Self::Truncated => ParserError::Truncated { offset },
243            Self::OversizedEvent { size, limit } => ParserError::OversizedEvent {
244                offset,
245                size,
246                limit,
247            },
248            Self::Io(source) => ParserError::Io { offset, source },
249        }
250    }
251}
252
253/// Classifies an I/O failure while filling the raw event buffer: a short
254/// read is the truncated/EOF path (R45), everything else stays a plain I/O
255/// error with its original source.
256fn truncated_or_io(error: io::Error) -> FrameError {
257    if error.kind() == io::ErrorKind::UnexpectedEof {
258        FrameError::Truncated
259    } else {
260        FrameError::Io(error)
261    }
262}
263
264#[derive(Debug, thiserror::Error)]
265#[error("transaction payload at inner offset {offset}: {source}")]
266struct InnerEventError {
267    offset: u64,
268    #[source]
269    source: io::Error,
270}
271
272/// Maintains the format description and table maps while reading one event at a time.
273///
274/// The reader works on any [`Read`] input (a file, standard input, or an
275/// in-memory buffer). Raw event sizes are capped at [`MAX_EVENT_SIZE`] by
276/// default, configurable through [`BinlogParser::with_max_event_size`], and
277/// the inner-event collection of the collecting [`BinlogParser::events`]
278/// iterator is bounded by [`DEFAULT_INNER_EVENT_LIMIT`], configurable
279/// through [`BinlogParser::with_inner_event_limit`] (R46b). Decoded row
280/// images can consume more memory than their wire data.
281/// [`BinlogParser::visit_events`] delivers and releases each inner event in
282/// turn while retaining the outer raw payload and shared table-map state.
283pub struct BinlogParser<R: Read = File> {
284    reader: EventStreamReader,
285    input: BufReader<R>,
286    offset: u64,
287    stopped: bool,
288    buffer: Vec<u8>,
289    max_event_size: u32,
290    /// Inner-event collection bound of the collecting iterator (R46b).
291    inner_event_limit: usize,
292    warnings: Vec<String>,
293    /// Per-table signedness metadata (R42): `signedness()` walks the table
294    /// map's serialized body, so it is computed once per registration instead
295    /// of once per row event. Entries are replaced when a table map
296    /// re-registers the same table id.
297    signedness_cache: HashMap<u64, std::sync::Arc<Vec<Option<bool>>>>,
298}
299
300impl BinlogParser<File> {
301    /// Open a plaintext binlog. Encrypted input is explicitly rejected.
302    pub fn open(path: impl AsRef<Path>) -> Result<Self, ParserError> {
303        let file = File::open(path).map_err(|source| ParserError::Io { offset: 0, source })?;
304        Self::from_reader(file)
305    }
306}
307
308impl<R: Read> BinlogParser<R> {
309    /// Read from an arbitrary streaming source after validating the four-byte
310    /// binlog magic.
311    ///
312    /// Only the magic is consumed here; events are read lazily through
313    /// [`BinlogParser::events`], so the input does not need to be seekable.
314    pub fn from_reader(reader: R) -> Result<Self, ParserError> {
315        let mut input = BufReader::with_capacity(READ_BUFFER_CAPACITY, reader);
316        let mut magic = [0; 4];
317        input.read_exact(&mut magic).map_err(|e| {
318            if e.kind() == io::ErrorKind::UnexpectedEof {
319                ParserError::InvalidHeader
320            } else {
321                ParserError::Io {
322                    offset: 0,
323                    source: e,
324                }
325            }
326        })?;
327        match &magic {
328            b"\xfd\x62\x69\x6e" => return Err(ParserError::EncryptedBinlog),
329            b"\xfe\x62\x69\x6e" => (),
330            _ => return Err(ParserError::InvalidHeader),
331        }
332        Ok(Self {
333            reader: EventStreamReader::new(BinlogVersion::Version4),
334            input,
335            offset: 4,
336            stopped: false,
337            buffer: Vec::new(),
338            max_event_size: MAX_EVENT_SIZE,
339            inner_event_limit: DEFAULT_INNER_EVENT_LIMIT,
340            warnings: Vec::new(),
341            signedness_cache: HashMap::new(),
342        })
343    }
344
345    /// Overrides the per-event size cap (defaulting to [`MAX_EVENT_SIZE`]).
346    pub fn with_max_event_size(mut self, cap: u32) -> Self {
347        self.max_event_size = cap;
348        self
349    }
350
351    /// Overrides the inner-event collection bound of the collecting
352    /// [`BinlogParser::events`] iterator (defaulting to
353    /// [`DEFAULT_INNER_EVENT_LIMIT`], R46b).
354    ///
355    /// Like [`Self::with_max_event_size`], this is infallible builder-style
356    /// configuration: a limit of zero cannot be expressed because the
357    /// argument is a [`core::num::NonZeroUsize`]. Only the collecting path
358    /// is bounded; [`Self::visit_events`] stays uncapped because its
359    /// callback applies backpressure.
360    pub fn with_inner_event_limit(mut self, limit: core::num::NonZeroUsize) -> Self {
361        self.inner_event_limit = limit.get();
362        self
363    }
364
365    /// Drains the advisory warnings collected so far.
366    ///
367    /// Warnings are non-fatal observations that do not stop parsing — most
368    /// notably a header `log_pos` that does not land right after its event.
369    /// The buffer is bounded, so a corrupt file cannot grow it without limit;
370    /// call this periodically (the CLI drains after each input).
371    pub fn take_warnings(&mut self) -> Vec<String> {
372        std::mem::take(&mut self.warnings)
373    }
374
375    /// Iterate over events, retrying transient [`io::ErrorKind::Interrupted`]
376    /// reads. Other I/O errors and framing or decoding errors terminate the stream.
377    ///
378    /// This iterator collects the inner events of each transaction payload
379    /// into `EventPayload::TransactionPayload.events`, so that collection is
380    /// bounded by [`DEFAULT_INNER_EVENT_LIMIT`] (configurable through
381    /// [`Self::with_inner_event_limit`], R46b); breaching the bound stops the
382    /// stream with [`ParserError::TooManyInnerEvents`].
383    pub fn events(&mut self) -> impl Iterator<Item = Result<ParsedEvent, ParserError>> + '_ {
384        std::iter::from_fn(move || self.next_event())
385    }
386
387    /// Visit the remaining events, consuming compressed transactions one
388    /// inner event at a time.
389    ///
390    /// Unlike [`Self::events`], this method does not collect the decoded inner
391    /// events of a transaction into a vector. The parser retains the outer
392    /// compressed event, the current inner event, and its shared table maps.
393    /// A single decoded event can still contain multiple row images. The
394    /// collecting path's [`DEFAULT_INNER_EVENT_LIMIT`] does not apply here:
395    /// the callback consumes each inner event immediately, so memory stays
396    /// bounded by backpressure instead of a numeric cap (R46b).
397    ///
398    /// The callback receives [`VisitEvent::TransactionPayloadStart`] only
399    /// after outer framing, checksum, and payload-header validation and
400    /// decompressor creation succeed. [`VisitEvent::TransactionPayloadEnd`]
401    /// confirms that all inner events and the decompression stream completed.
402    /// Previously delivered callbacks cannot be rolled back on a later error.
403    ///
404    /// Return [`ControlFlow::Break`] from the callback to stop immediately.
405    /// EOF returns [`ControlFlow::Continue`]. Both outcomes leave this parser
406    /// terminated. Callback errors carry the current outer
407    /// file offset through [`ParserError::Io`]. A callback error or panic
408    /// also terminates the parser, so subsequent calls cannot resume with
409    /// partially updated table-map state.
410    ///
411    /// # Example
412    ///
413    /// ```no_run
414    /// use binlog_inspect::parser::{BinlogParser, VisitEvent};
415    /// use std::ops::ControlFlow;
416    ///
417    /// let mut parser = BinlogParser::open("mysql-bin.000001")?;
418    /// let mut inner_events = 0u64;
419    /// let outcome = parser.visit_events(|notification| {
420    ///     if let VisitEvent::Event { parent_offset: Some(_), .. } = notification {
421    ///         inner_events += 1;
422    ///     }
423    ///     Ok(ControlFlow::Continue(()))
424    /// })?;
425    /// assert_eq!(outcome, ControlFlow::Continue(()));
426    /// println!("Decoded {inner_events} inner events");
427    /// # Ok::<(), Box<dyn std::error::Error>>(())
428    /// ```
429    pub fn visit_events(
430        &mut self,
431        mut visitor: impl FnMut(VisitEvent<'_>) -> io::Result<ControlFlow<()>>,
432    ) -> Result<ControlFlow<()>, ParserError> {
433        if self.stopped {
434            return Ok(ControlFlow::Continue(()));
435        }
436        // The raw framing helper does not consult this flag. Setting it
437        // before invoking user code also makes a caught callback panic fuse
438        // the public parser without a guard or unsafe code.
439        self.stopped = true;
440        loop {
441            let offset = self.offset;
442            let Some(framed) = self
443                .read_framed_event()
444                .map_err(|error| error.into_parser_error(offset))?
445            else {
446                return Ok(ControlFlow::Continue(()));
447            };
448            let result = (|| -> io::Result<ControlFlow<()>> {
449                if framed.event.header().event_type_raw() == 40 {
450                    let header = framed.event.header();
451                    let flow =
452                        self.walk_transaction_payload(&framed.event, &mut |item| match item {
453                            PayloadItem::Start(info) => {
454                                visitor(VisitEvent::TransactionPayloadStart {
455                                    offset,
456                                    timestamp: header.timestamp(),
457                                    server_id: header.server_id(),
458                                    event_size: framed.size,
459                                    log_pos: header.log_pos(),
460                                    compression: info.compression,
461                                    uncompressed_size: info.uncompressed_size,
462                                })
463                            }
464                            PayloadItem::Event(event) => visitor(VisitEvent::Event {
465                                event: &event,
466                                parent_offset: Some(offset),
467                            }),
468                        })?;
469                    if flow.is_break() {
470                        return Ok(ControlFlow::Break(()));
471                    }
472                    visitor(VisitEvent::TransactionPayloadEnd { offset })
473                } else {
474                    let payload = self.payload_for(&framed.event)?;
475                    let event = framed.into_parsed(payload);
476                    visitor(VisitEvent::Event {
477                        event: &event,
478                        parent_offset: None,
479                    })
480                }
481            })();
482            if result
483                .map_err(|source| ParserError::Io { offset, source })?
484                .is_break()
485            {
486                return Ok(ControlFlow::Break(()));
487            }
488        }
489    }
490
491    /// Length of the trailing checksum the underlying library will strip from
492    /// an event of the given raw type, according to the active format
493    /// description.
494    fn checksum_len(&self, raw_type: u8) -> usize {
495        if raw_type != 15
496            && self
497                .reader
498                .get_fde()
499                .footer()
500                .get_checksum_alg()
501                .ok()
502                .flatten()
503                == Some(BinlogChecksumAlg::BINLOG_CHECKSUM_ALG_CRC32)
504        {
505            4
506        } else {
507            0
508        }
509    }
510
511    fn next_event(&mut self) -> Option<Result<ParsedEvent, ParserError>> {
512        if self.stopped {
513            return None;
514        }
515        let offset = self.offset;
516        let result = (|| -> Result<Option<ParsedEvent>, ParserError> {
517            let Some(framed) = self
518                .read_framed_event()
519                .map_err(|error| error.into_parser_error(offset))?
520            else {
521                return Ok(None);
522            };
523            let payload = if framed.event.header().event_type_raw() == 40 {
524                self.transaction_payload(&framed.event, offset)?
525            } else {
526                self.payload_for(&framed.event)
527                    .map_err(|source| ParserError::Io { offset, source })?
528            };
529            Ok(Some(framed.into_parsed(payload)))
530        })();
531        match result {
532            Ok(Some(e)) => Some(Ok(e)),
533            Ok(None) => {
534                self.stopped = true;
535                None
536            }
537            Err(error) => {
538                self.stopped = true;
539                Some(Err(error))
540            }
541        }
542    }
543
544    /// Read and validate one outer event, retaining its original coordinates
545    /// when table-map metadata is stripped before library decoding.
546    ///
547    /// Failures are reported as [`FrameError`] without the file offset; the
548    /// callers attach the offset where the event begins and map them onto
549    /// the public [`ParserError`] variants (R45).
550    fn read_framed_event(&mut self) -> Result<Option<FramedEvent>, FrameError> {
551        let offset = self.offset;
552        // Validate framing before allowing the library to allocate the event buffer.
553        let mut head = [0u8; 19];
554        // Retry transient interruptions without treating a reader's
555        // UnexpectedEof error as a clean event boundary.
556        let first = loop {
557            match self.input.read(&mut head[..1]) {
558                Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
559                result => break result?,
560            }
561        };
562        if first == 0 {
563            return Ok(None);
564        }
565        self.input
566            .read_exact(&mut head[1..])
567            .map_err(truncated_or_io)?;
568        let size = u32::from_le_bytes(head[9..13].try_into().unwrap());
569        if !(19..=self.max_event_size).contains(&size) {
570            return Err(FrameError::OversizedEvent {
571                size,
572                limit: self.max_event_size,
573            });
574        }
575        // mysql_common assumes the complete event body is available.
576        if head[4] == 15 && size < 19 + 57 {
577            return Err(FrameError::Io(io::Error::new(
578                io::ErrorKind::InvalidData,
579                "short format description",
580            )));
581        }
582        if head[4] != 15 && self.checksum_len(head[4]) > 0 && size < 23 {
583            return Err(FrameError::Io(io::Error::new(
584                io::ErrorKind::InvalidData,
585                "short checksummed event",
586            )));
587        }
588        // Resizing without clearing only zero-fills the newly observed
589        // tail; every byte is overwritten by the head and body anyway.
590        self.buffer.resize(size as usize, 0);
591        self.buffer[..19].copy_from_slice(&head);
592        self.input
593            .read_exact(&mut self.buffer[19..])
594            .map_err(truncated_or_io)?;
595        // Hostile-input prevalidation before the library decodes anything:
596        // its previous-GTIDs and table-map metadata parsers allocate from
597        // untrusted declared counts, and its transaction-payload header
598        // parser unwraps the compression type, so crafted input would
599        // abort the process.
600        let data_len = self.buffer.len() - 19 - self.checksum_len(head[4]);
601        let body = &self.buffer[19..19 + data_len];
602        if head[4] == 35 {
603            validate_previous_gtids(body)?;
604        }
605        if head[4] == 19 {
606            let header_len = self.reader.get_fde().get_event_type_header_length(
607                mysql_common::binlog::consts::EventType::TABLE_MAP_EVENT,
608            );
609            crate::row_decode::validate_table_map_metadata(body, header_len)?;
610        }
611        if head[4] == 40 {
612            validate_transaction_payload_header(body)?;
613        }
614        // Table maps of partial-JSON binlogs (WL#2955) carry optional
615        // metadata types the library's lazily iterated metadata rejects;
616        // those entries are stripped from the bytes the library parses,
617        // so the stored table map stays acceptable for every later row
618        // event. The strip runs after the prevalidation of the original
619        // bytes, and only for table maps.
620        let mut stripped_tlv_bytes = 0usize;
621        if head[4] == 19 {
622            let header_len = self.reader.get_fde().get_event_type_header_length(
623                mysql_common::binlog::consts::EventType::TABLE_MAP_EVENT,
624            );
625            let ranges =
626                crate::row_decode::unsupported_tlv_ranges(body, header_len)?.unwrap_or_default();
627            if !ranges.is_empty() {
628                // The checksum must be verified on the original bytes:
629                // stripping changes everything the library would hash.
630                if self.checksum_len(head[4]) > 0 {
631                    verify_event_checksum(&self.buffer)?;
632                }
633                stripped_tlv_bytes = remove_ranges(&mut self.buffer, 19, &ranges);
634                let new_size = u32::try_from(self.buffer.len()).map_err(|_| {
635                    io::Error::new(io::ErrorKind::InvalidData, "invalid event size")
636                })?;
637                self.buffer[9..13].copy_from_slice(&new_size.to_le_bytes());
638            }
639        }
640        let Some(event) = self.reader.read(&mut Cursor::new(self.buffer.as_slice()))? else {
641            return Ok(None);
642        };
643        let checksum_algorithm = event
644            .footer()
645            .get_checksum_alg()
646            .map_err(|err| io::Error::new(io::ErrorKind::Unsupported, err))?;
647        if stripped_tlv_bytes == 0
648            && let (Some(checksum), Some(alg)) = (event.checksum(), checksum_algorithm)
649            && u32::from_le_bytes(checksum) != event.calc_checksum(alg)
650        {
651            return Err(FrameError::Checksum);
652        }
653        let h = event.header();
654        // The header `event_size` reflects the stripped bytes; the
655        // original size is what positions the stream and the output.
656        self.offset += u64::from(size);
657        // Advisory only (R35): on a master-written file each header's
658        // log_pos lands right after its event. A mismatch suggests
659        // tampering or a spliced file but does not stop parsing; a zero
660        // log_pos is how artificial events mark "no position".
661        const WARNING_CAP: usize = 100;
662        let log_pos = u64::from(h.log_pos());
663        let expected = offset + u64::from(size);
664        if log_pos != 0 && log_pos != expected && self.warnings.len() < WARNING_CAP {
665            self.warnings.push(format!(
666                "log_pos {log_pos} does not match offset {offset} + event size {size}"
667            ));
668        }
669        Ok(Some(FramedEvent {
670            event,
671            offset,
672            size,
673        }))
674    }
675
676    /// Maps a decoded event onto the stable payload model.
677    ///
678    /// Shared between the outer event stream and the events decompressed out
679    /// of a transaction payload: table maps registered by inner events live in
680    /// the same reader state, so inner and later outer row events resolve
681    /// identically.
682    fn payload_for(&mut self, event: &Event) -> io::Result<EventPayload> {
683        let payload = match event.read_data()? {
684            Some(EventData::FormatDescriptionEvent(e)) => EventPayload::FormatDescription {
685                server_version: server_version(e.server_version_raw()),
686            },
687            Some(EventData::TableMapEvent(e)) => {
688                // Refresh the signedness cache on every registration: a
689                // re-registered table id carries a new schema, so the cached
690                // entry must be replaced (R42).
691                let table_id = e.table_id();
692                if let Some(map) = self.reader.get_tme(table_id) {
693                    let computed = std::sync::Arc::new(crate::row_decode::signedness(map)?);
694                    self.signedness_cache.insert(table_id, computed);
695                }
696                EventPayload::TableMap {
697                    table_id: e.table_id(),
698                    database: e.database_name().into_owned(),
699                    table: e.table_name().into_owned(),
700                    column_count: e.columns_count(),
701                }
702            }
703            Some(EventData::QueryEvent(e)) => EventPayload::Query {
704                database: e.schema().into_owned(),
705                sql: e.query().into_owned(),
706            },
707            Some(EventData::XidEvent(e)) => EventPayload::Xid { xid: e.xid },
708            Some(EventData::RotateEvent(e)) => EventPayload::Rotate {
709                next_file: e.name().into_owned(),
710                position: e.position(),
711            },
712            Some(EventData::GtidEvent(e)) => {
713                let mut gtid = format_sid(&e.sid());
714                let tag = e.tag().map(|tag| tag.as_str().to_owned());
715                if let Some(tag) = &tag {
716                    gtid.push(':');
717                    gtid.push_str(tag);
718                }
719                gtid.push(':');
720                gtid.push_str(&e.gno().to_string());
721                EventPayload::Gtid { gtid, tag }
722            }
723            // Anonymous GTID events carry no GTID; mysqlbinlog renders the
724            // placeholder "ANONYMOUS".
725            Some(EventData::AnonymousGtidEvent(_)) => EventPayload::Gtid {
726                gtid: "ANONYMOUS".to_owned(),
727                tag: None,
728            },
729            Some(EventData::PreviousGtidsEvent(e)) => EventPayload::PreviousGtids {
730                gtid_set: format_gtid_set(&e),
731            },
732            Some(EventData::StopEvent) => EventPayload::Stop,
733            Some(EventData::RowsQueryEvent(e)) => EventPayload::RowsQuery {
734                sql: e.query().into_owned(),
735            },
736            Some(EventData::IncidentEvent(e)) => EventPayload::Incident {
737                incident_type: match e.incident_type() {
738                    // The canonical name is pinned below (R51), not the
739                    // library's Debug rendering, so a library rename cannot
740                    // change the output.
741                    Ok(incident_type) => incident_type_name(incident_type).to_owned(),
742                    Err(unknown) => format!("UNKNOWN({})", u16::from(unknown)),
743                },
744                message: e.message().into_owned(),
745            },
746            Some(EventData::IntvarEvent(e)) => EventPayload::Intvar {
747                var_type: intvar_type_name(e.subtype()).to_owned(),
748                value: e.value(),
749            },
750            Some(EventData::RowsEvent(RowsEventData::PartialUpdateRowsEvent(e))) => {
751                // Partial update rows (WL#2955): the before image is a full
752                // row image, the after image carries JSON diffs per JSON
753                // column. The pair decode applies each diff sequence against
754                // the before value; unappliable diffs surface as loss-marked
755                // PartialJson cells instead of failing the event.
756                let id = e.table_id();
757                match self.reader.get_tme(id) {
758                    Some(map) => {
759                        // Mirror the MySQL applier: a row event may declare
760                        // fewer columns than the table map records (the table
761                        // grew after the event was written), but never more.
762                        if e.num_columns() > map.columns_count() {
763                            return Err(io::Error::new(
764                                io::ErrorKind::InvalidData,
765                                "row event column count exceeds the table map",
766                            ));
767                        }
768                        let n = usize::try_from(map.columns_count()).map_err(|_| {
769                            io::Error::new(io::ErrorKind::InvalidData, "column count overflow")
770                        })?;
771                        let declared = usize::try_from(e.num_columns()).map_err(|_| {
772                            io::Error::new(io::ErrorKind::InvalidData, "column count overflow")
773                        })?;
774                        let pad = |bits: Vec<bool>| {
775                            let mut bits = bits;
776                            bits.resize(n, false);
777                            bits
778                        };
779                        let before_bitmap = Some(e.columns_before_image())
780                            .map(|bits| {
781                                crate::row_decode::present_bits(bits.iter().by_vals(), declared)
782                                    .map(pad)
783                            })
784                            .transpose()?;
785                        let after_bitmap = Some(e.columns_after_image())
786                            .map(|bits| {
787                                crate::row_decode::present_bits(bits.iter().by_vals(), declared)
788                                    .map(pad)
789                            })
790                            .transpose()?;
791                        // The signedness walk re-serializes the table map, so
792                        // it is cached per table id at registration (R42);
793                        // the fallback covers ids the cache has not seen.
794                        let signedness = {
795                            if let Some(cached) = self.signedness_cache.get(&id) {
796                                std::sync::Arc::clone(cached)
797                            } else {
798                                let computed =
799                                    std::sync::Arc::new(crate::row_decode::signedness(map)?);
800                                self.signedness_cache
801                                    .insert(id, std::sync::Arc::clone(&computed));
802                                computed
803                            }
804                        };
805                        // R50: prevalidate the row layout before the library
806                        // iterates the rows — hostile packed decimals and
807                        // trailing bytes are rejected with precise messages
808                        // instead of the dependency's panics or silent
809                        // misdecoding. The after image carries the WL#2955
810                        // value-options header here.
811                        // The partial-update accessors return the bitmaps
812                        // directly (both images are always present here).
813                        let before_layout = Some(e.columns_before_image())
814                            .zip(before_bitmap.as_deref())
815                            .map(|(bits, present)| crate::row_decode::RowImageLayout {
816                                bitmap_ones: bits.count_ones(),
817                                present,
818                                partial_header: false,
819                            });
820                        let after_layout = Some(e.columns_after_image())
821                            .zip(after_bitmap.as_deref())
822                            .map(|(bits, present)| crate::row_decode::RowImageLayout {
823                                bitmap_ones: bits.count_ones(),
824                                present,
825                                partial_header: true,
826                            });
827                        crate::row_decode::prevalidate_row_layout(
828                            e.rows_data(),
829                            &[before_layout, after_layout],
830                            map.json_column_count(),
831                            map,
832                        )?;
833                        // R48-refinement: every jsonb value decoded for this
834                        // event shares one node counter bounded by the
835                        // event's wire size.
836                        let mut event_budget =
837                            crate::row_decode::EventNodeBudget::new(event.header().event_size());
838                        let mut before = Vec::new();
839                        let mut after = Vec::new();
840                        for row in e.rows(map) {
841                            let (before_row, after_row) = row?;
842                            let (before_image, after_image) = crate::row_decode::decode_rows_pair(
843                                before_row.as_ref(),
844                                after_row.as_ref(),
845                                before_bitmap.as_deref(),
846                                after_bitmap.as_deref(),
847                                &signedness,
848                                &mut event_budget,
849                            )?;
850                            before.push(before_image);
851                            after.push(after_image);
852                        }
853                        EventPayload::PartialUpdateRows {
854                            table_id: id,
855                            database: map.database_name().into_owned(),
856                            table: map.table_name().into_owned(),
857                            before,
858                            after,
859                        }
860                    }
861                    None => EventPayload::Unresolved { table_id: id },
862                }
863            }
864            Some(EventData::RowsEvent(e)) => {
865                let id = e.table_id();
866                if let Some(map) = self.reader.get_tme(id) {
867                    // With no selected columns, an ordinary row consumes
868                    // neither a NULL bitmap nor values. The dependency's
869                    // iterator would repeatedly yield an empty row while
870                    // retaining the same nonempty data buffer.
871                    if !e.rows_data().is_empty()
872                        && !e.columns_before_image().is_some_and(|bits| bits.any())
873                        && !e.columns_after_image().is_some_and(|bits| bits.any())
874                    {
875                        return Err(io::Error::new(
876                            io::ErrorKind::InvalidData,
877                            "row data with no selected columns cannot make progress",
878                        ));
879                    }
880                    // See the PartialUpdateRows arm: a row event may
881                    // declare fewer columns than the table map, never
882                    // more; missing tail columns render as absent.
883                    if e.num_columns() > map.columns_count() {
884                        return Err(io::Error::new(
885                            io::ErrorKind::InvalidData,
886                            "row event column count exceeds the table map",
887                        ));
888                    }
889                    let n = usize::try_from(map.columns_count()).map_err(|_| {
890                        io::Error::new(io::ErrorKind::InvalidData, "column count overflow")
891                    })?;
892                    let declared = usize::try_from(e.num_columns()).map_err(|_| {
893                        io::Error::new(io::ErrorKind::InvalidData, "column count overflow")
894                    })?;
895                    let pad = |bits: Vec<bool>| {
896                        let mut bits = bits;
897                        bits.resize(n, false);
898                        bits
899                    };
900                    let before_bitmap = e
901                        .columns_before_image()
902                        .map(|bits| {
903                            crate::row_decode::present_bits(bits.iter().by_vals(), declared)
904                                .map(pad)
905                        })
906                        .transpose()?;
907                    let after_bitmap = e
908                        .columns_after_image()
909                        .map(|bits| {
910                            crate::row_decode::present_bits(bits.iter().by_vals(), declared)
911                                .map(pad)
912                        })
913                        .transpose()?;
914                    // Cached per table id at registration (R42); see the
915                    // PartialUpdateRows arm for the fallback.
916                    let signedness = {
917                        if let Some(cached) = self.signedness_cache.get(&id) {
918                            std::sync::Arc::clone(cached)
919                        } else {
920                            let computed = std::sync::Arc::new(crate::row_decode::signedness(map)?);
921                            self.signedness_cache
922                                .insert(id, std::sync::Arc::clone(&computed));
923                            computed
924                        }
925                    };
926                    // R50: prevalidate the row layout before the library
927                    // iterates the rows — hostile packed decimals and
928                    // trailing bytes are rejected with precise messages
929                    // instead of the dependency's panics or silent
930                    // misdecoding.
931                    let before_layout = e.columns_before_image().zip(before_bitmap.as_deref()).map(
932                        |(bits, present)| crate::row_decode::RowImageLayout {
933                            bitmap_ones: bits.count_ones(),
934                            present,
935                            partial_header: false,
936                        },
937                    );
938                    let after_layout = e.columns_after_image().zip(after_bitmap.as_deref()).map(
939                        |(bits, present)| crate::row_decode::RowImageLayout {
940                            bitmap_ones: bits.count_ones(),
941                            present,
942                            partial_header: false,
943                        },
944                    );
945                    crate::row_decode::prevalidate_row_layout(
946                        e.rows_data(),
947                        &[before_layout, after_layout],
948                        map.json_column_count(),
949                        map,
950                    )?;
951                    // R48-refinement: every jsonb value decoded for this
952                    // event shares one node counter bounded by the event's
953                    // wire size.
954                    let mut event_budget =
955                        crate::row_decode::EventNodeBudget::new(event.header().event_size());
956                    let mut changes = Vec::new();
957                    for row in e.rows(map) {
958                        let (before_row, after_row) = row?;
959                        // The pair decode applies partial-JSON after images
960                        // (WL#2955) to their before values; images without
961                        // diffs decode exactly like single images.
962                        let (before, after) = crate::row_decode::decode_rows_pair(
963                            before_row.as_ref(),
964                            after_row.as_ref(),
965                            before_bitmap.as_deref(),
966                            after_bitmap.as_deref(),
967                            &signedness,
968                            &mut event_budget,
969                        )?;
970                        changes.push(RowChange { before, after });
971                    }
972                    EventPayload::Rows {
973                        table_id: id,
974                        database: map.database_name().into_owned(),
975                        table: map.table_name().into_owned(),
976                        changes,
977                    }
978                } else {
979                    EventPayload::Unresolved { table_id: id }
980                }
981            }
982            // Named but undecoded event types (rand, user_var, heartbeat,
983            // ignorable, ...) and event types the library cannot decode at
984            // all (e.g. code 41) keep only their raw length. Nested
985            // transaction payloads never reach here: they are rejected while
986            // streaming the inner event.
987            _ => EventPayload::Unknown {
988                raw_len: event.data().len(),
989            },
990        };
991        Ok(payload)
992    }
993
994    /// Decodes a compressed transaction payload (code 40, WL#3549).
995    ///
996    /// The framing layer has already validated the payload header (see
997    /// [`validate_transaction_payload_header`]). The declared uncompressed
998    /// size is bounded before any decompression, and the library's streaming
999    /// `decompressed()` reader is wrapped in a [`PayloadStream`] that counts
1000    /// every decompressed byte against the declaration and prevalidates each
1001    /// inner event before the library parses it. Inner events carry no
1002    /// checksums (WL#3549), and the library registers their table maps in the
1003    /// shared reader state so later outer row events resolve. `offset` is the
1004    /// outer event's file position, attached to failures (R45).
1005    fn transaction_payload(
1006        &mut self,
1007        event: &Event,
1008        offset: u64,
1009    ) -> Result<EventPayload, ParserError> {
1010        // R46b: only the collecting path buffers inner events into memory,
1011        // so only this path enforces the inner-event limit. The visiting
1012        // path hands each event to the callback, which applies backpressure.
1013        let limit = self.inner_event_limit;
1014        let mut events = Vec::new();
1015        let mut over_limit = false;
1016        let flow = self
1017            .walk_transaction_payload(event, &mut |item| {
1018                if let PayloadItem::Event(event) = item {
1019                    if events.len() >= limit {
1020                        over_limit = true;
1021                        return Err(io::Error::new(
1022                            io::ErrorKind::InvalidData,
1023                            "transaction payload inner event limit exceeded",
1024                        ));
1025                    }
1026                    events.push(event);
1027                }
1028                Ok(ControlFlow::<Infallible>::Continue(()))
1029            })
1030            .map_err(|source| {
1031                // The closure records the breach before returning: the only
1032                // error that can carry the flag out of the walk is this one,
1033                // because an emit error propagates immediately.
1034                if over_limit {
1035                    ParserError::TooManyInnerEvents { offset, limit }
1036                } else {
1037                    ParserError::Io { offset, source }
1038                }
1039            })?;
1040        let info = match flow {
1041            ControlFlow::Continue(info) => info,
1042            ControlFlow::Break(never) => match never {},
1043        };
1044        Ok(EventPayload::TransactionPayload {
1045            compression: info.compression.to_owned(),
1046            uncompressed_size: info.uncompressed_size,
1047            events,
1048        })
1049    }
1050
1051    /// Shared payload decoder. The collecting API owns each emitted event;
1052    /// the visiting API borrows it for one callback and then drops it.
1053    fn walk_transaction_payload<B>(
1054        &mut self,
1055        event: &Event,
1056        emit: &mut impl FnMut(PayloadItem) -> io::Result<ControlFlow<B>>,
1057    ) -> io::Result<ControlFlow<B, PayloadInfo>> {
1058        let Some(EventData::TransactionPayloadEvent(payload)) = event.read_data()? else {
1059            return Err(io::Error::new(
1060                io::ErrorKind::InvalidData,
1061                "malformed transaction payload",
1062            ));
1063        };
1064        let compression = match payload.algorithm() {
1065            TransactionPayloadCompressionType::NONE => "NONE",
1066            TransactionPayloadCompressionType::ZSTD => "ZSTD",
1067        };
1068        let uncompressed_size = payload.uncompressed_size();
1069        if uncompressed_size > MAX_UNCOMPRESSED_PAYLOAD_SIZE {
1070            return Err(io::Error::new(
1071                io::ErrorKind::InvalidData,
1072                "compressed payload declares excessive uncompressed size",
1073            ));
1074        }
1075        // The library only writes uncompressed_size for compressed payloads
1076        // (NONE payloads carry 0 on the wire); for NONE the decompressed
1077        // stream is the payload bytes themselves, so the exact payload size
1078        // is the honest limit — the limit below is looser than exact by the
1079        // header TLV bytes the framing already consumed, a difference the
1080        // 1 MiB slack covers intentionally. Compressed payloads get the
1081        // declared size plus a small slack so a bomb must lie by more than
1082        // the slack to pass.
1083        let limit = match payload.algorithm() {
1084            TransactionPayloadCompressionType::NONE => u64::from(event.header().event_size())
1085                .saturating_sub(19)
1086                .saturating_add(PAYLOAD_SIZE_SLACK),
1087            TransactionPayloadCompressionType::ZSTD => {
1088                uncompressed_size.saturating_add(PAYLOAD_SIZE_SLACK)
1089            }
1090        };
1091        let tme_header_len = self
1092            .reader
1093            .get_fde()
1094            .get_event_type_header_length(mysql_common::binlog::consts::EventType::TABLE_MAP_EVENT);
1095        let mut stream = PayloadStream::new(
1096            payload.decompressed()?,
1097            limit,
1098            u64::from(self.max_event_size),
1099            tme_header_len,
1100        );
1101        let info = PayloadInfo {
1102            compression,
1103            uncompressed_size,
1104        };
1105        if let ControlFlow::Break(value) = emit(PayloadItem::Start(info))? {
1106            return Ok(ControlFlow::Break(value));
1107        }
1108        let timestamp = event.header().timestamp();
1109        let server_id = event.header().server_id();
1110        loop {
1111            let offset = stream.position;
1112            let decoded = (|| -> io::Result<Option<ParsedEvent>> {
1113                let Some(inner) = self.reader.read_decompressed(&mut stream)? else {
1114                    return Ok(None);
1115                };
1116                let h = inner.header();
1117                Ok(Some(ParsedEvent {
1118                    offset: stream.last_event_offset(),
1119                    timestamp,
1120                    event_type: EventType::from_raw(h.event_type_raw()),
1121                    event_type_code: h.event_type_raw(),
1122                    server_id,
1123                    // The declared size, not the stripped one the library saw.
1124                    event_size: stream.last_event_size(),
1125                    log_pos: h.log_pos(),
1126                    payload: self.payload_for(&inner)?,
1127                }))
1128            })()
1129            .map_err(|source| io::Error::new(source.kind(), InnerEventError { offset, source }))?;
1130            let Some(decoded) = decoded else {
1131                break;
1132            };
1133            if let ControlFlow::Break(value) = emit(PayloadItem::Event(decoded))? {
1134                return Ok(ControlFlow::Break(value));
1135            }
1136        }
1137        Ok(ControlFlow::Continue(info))
1138    }
1139}
1140
1141/// Streaming adapter over the decompressed payload of a transaction payload
1142/// event.
1143///
1144/// The library reader yields raw decompressed bytes. This adapter re-frames
1145/// them into whole inner events (the inner stream carries no event checksums,
1146/// WL#3549), hands them to the library one event at a time, and enforces the
1147/// compressed-payload safety rules: every byte is counted against the declared
1148/// uncompressed size, a single inner event may not exceed the parser's event
1149/// size cap, and each inner event is prevalidated exactly like an outer one so
1150/// the library's hostile-input allocation paths are never reached.
1151struct PayloadStream<'a> {
1152    inner: TransactionPayloadReader<'a>,
1153    /// The fully buffered inner event currently being consumed.
1154    pending: Vec<u8>,
1155    /// Bytes of `pending` already handed downstream.
1156    consumed: usize,
1157    /// Total bytes handed downstream, i.e. the byte position in the
1158    /// decompressed stream.
1159    position: u64,
1160    /// Start position of the most recently buffered inner event.
1161    event_start: u64,
1162    /// Maximum total decompressed bytes: declared uncompressed size plus slack.
1163    limit: u64,
1164    /// Per-event cap mirroring the parser's own event size limit.
1165    max_event_size: u64,
1166    /// Post-header length of table map events per the active format
1167    /// description, needed to prevalidate inner table maps.
1168    tme_header_len: u8,
1169    /// Declared size of the most recently buffered inner event, before any
1170    /// partial-JSON metadata stripping changed the buffered bytes.
1171    last_event_size: u32,
1172}
1173
1174impl<'a> PayloadStream<'a> {
1175    fn new(
1176        inner: TransactionPayloadReader<'a>,
1177        limit: u64,
1178        max_event_size: u64,
1179        tme_header_len: u8,
1180    ) -> Self {
1181        Self {
1182            inner,
1183            pending: Vec::new(),
1184            consumed: 0,
1185            position: 0,
1186            event_start: 0,
1187            limit,
1188            max_event_size,
1189            tme_header_len,
1190            last_event_size: 0,
1191        }
1192    }
1193
1194    /// Byte offset within the decompressed stream of the most recently
1195    /// buffered inner event.
1196    fn last_event_offset(&self) -> u64 {
1197        self.event_start
1198    }
1199
1200    /// Declared size (header included) of the most recently buffered inner
1201    /// event, before any partial-JSON metadata stripping.
1202    fn last_event_size(&self) -> u32 {
1203        self.last_event_size
1204    }
1205
1206    /// Buffers the next inner event. Returns `false` at a clean end of the
1207    /// decompressed stream.
1208    fn load_next_event(&mut self) -> io::Result<bool> {
1209        let mut header = [0u8; 19];
1210        match fill_from(&mut self.inner, &mut header)? {
1211            0 => return Ok(false),
1212            // The stream ended between events; anything else is truncation.
1213            n if n < header.len() => {
1214                return Err(io::Error::new(
1215                    io::ErrorKind::InvalidData,
1216                    "truncated transaction payload",
1217                ));
1218            }
1219            _ => (),
1220        }
1221        let size = u32::from_le_bytes(header[9..13].try_into().unwrap());
1222        let raw = header[4];
1223        if size < 19 {
1224            return Err(io::Error::new(
1225                io::ErrorKind::InvalidData,
1226                "invalid inner event size",
1227            ));
1228        }
1229        if raw == 40 {
1230            return Err(io::Error::new(
1231                io::ErrorKind::InvalidData,
1232                "nested transaction payload",
1233            ));
1234        }
1235        // A format description or rotate inside a payload would rewrite the
1236        // shared parser state (checksum handling, table maps); legitimate
1237        // payloads only carry the transaction's data events.
1238        if raw == 15 || raw == 4 {
1239            return Err(io::Error::new(
1240                io::ErrorKind::InvalidData,
1241                "unexpected event inside transaction payload",
1242            ));
1243        }
1244        let size = usize::try_from(size)
1245            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid inner event size"))?;
1246        let max = usize::try_from(self.max_event_size)
1247            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid event size limit"))?;
1248        if size > max {
1249            return Err(io::Error::new(
1250                io::ErrorKind::InvalidData,
1251                "inner event exceeds the event size limit",
1252            ));
1253        }
1254        if self.position + u64::try_from(size).unwrap_or(u64::MAX) > self.limit {
1255            return Err(io::Error::new(
1256                io::ErrorKind::InvalidData,
1257                "decompressed payload exceeds declared size",
1258            ));
1259        }
1260        self.pending.clear();
1261        self.pending.resize(size, 0);
1262        self.pending[..header.len()].copy_from_slice(&header);
1263        if fill_from(&mut self.inner, &mut self.pending[header.len()..])? != size - header.len() {
1264            return Err(io::Error::new(
1265                io::ErrorKind::InvalidData,
1266                "truncated transaction payload",
1267            ));
1268        }
1269        // Hostile-input prevalidation, identical to the outer framing: the
1270        // library allocates from declared counts when parsing these bodies.
1271        let body = &self.pending[header.len()..];
1272        if raw == 19 {
1273            crate::row_decode::validate_table_map_metadata(body, self.tme_header_len)?;
1274        }
1275        if raw == 35 {
1276            validate_previous_gtids(body)?;
1277        }
1278        // The offsets and sizes reported for inner events always refer to the
1279        // original decompressed stream, including stripped bytes.
1280        self.event_start = self.position;
1281        self.last_event_size = u32::try_from(size)
1282            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid inner event size"))?;
1283        if raw == 19 {
1284            // Inner table maps are stripped exactly like outer ones: the
1285            // library's metadata iterator would reject the partial-JSON
1286            // entries when decoding later row events. The inner stream
1287            // carries no checksums (WL#3549), so nothing needs re-verification.
1288            let ranges = crate::row_decode::unsupported_tlv_ranges(body, self.tme_header_len)?
1289                .unwrap_or_default();
1290            if !ranges.is_empty() {
1291                let removed = remove_ranges(&mut self.pending, header.len(), &ranges);
1292                let new_size = u32::try_from(self.pending.len()).map_err(|_| {
1293                    io::Error::new(io::ErrorKind::InvalidData, "invalid inner event size")
1294                })?;
1295                self.pending[9..13].copy_from_slice(&new_size.to_le_bytes());
1296                // The stripped bytes never reach the reader, so the position
1297                // is advanced here to keep the declared-size accounting exact.
1298                self.position += u64::try_from(removed).unwrap_or(u64::MAX);
1299            }
1300        }
1301        Ok(true)
1302    }
1303}
1304
1305impl Read for PayloadStream<'_> {
1306    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1307        let available = self.fill_buf()?;
1308        if available.is_empty() {
1309            return Ok(0);
1310        }
1311        let n = available.len().min(buf.len());
1312        buf[..n].copy_from_slice(&available[..n]);
1313        self.consume(n);
1314        Ok(n)
1315    }
1316}
1317
1318impl BufRead for PayloadStream<'_> {
1319    fn fill_buf(&mut self) -> io::Result<&[u8]> {
1320        if self.consumed >= self.pending.len() {
1321            self.pending.clear();
1322            self.consumed = 0;
1323            if !self.load_next_event()? {
1324                return Ok(&[]);
1325            }
1326        }
1327        Ok(&self.pending[self.consumed..])
1328    }
1329
1330    fn consume(&mut self, amt: usize) {
1331        let amt = amt.min(self.pending.len() - self.consumed);
1332        self.consumed += amt;
1333        self.position += amt as u64;
1334    }
1335}
1336
1337/// Reads `buf.len()` bytes from `reader` unless the stream ends first and
1338/// returns the number of bytes read; the library's payload reader is a plain
1339/// `Read` whose `read` may return short reads.
1340fn fill_from(reader: &mut TransactionPayloadReader<'_>, buf: &mut [u8]) -> io::Result<usize> {
1341    let mut filled = 0;
1342    while filled < buf.len() {
1343        match reader.read(&mut buf[filled..]) {
1344            Ok(0) => break,
1345            Ok(n) => filled += n,
1346            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
1347            Err(error) => return Err(error),
1348        }
1349    }
1350    Ok(filled)
1351}
1352
1353/// Renders the server version with any NUL padding removed.
1354fn server_version(raw: &[u8]) -> String {
1355    let end = raw.iter().position(|&byte| byte == 0).unwrap_or(raw.len());
1356    String::from_utf8_lossy(&raw[..end]).into_owned()
1357}
1358
1359/// Canonical stable name for a replication incident type.
1360///
1361/// The library's `Debug` output must not leak into the output model, so
1362/// every [`IncidentType`] variant maps to its constant name; a library
1363/// rename cannot change the output (R51, mirroring the `column_type_name`
1364/// pattern).
1365fn incident_type_name(incident_type: IncidentType) -> &'static str {
1366    match incident_type {
1367        IncidentType::INCIDENT_NONE => "INCIDENT_NONE",
1368        IncidentType::INCIDENT_LOST_EVENTS => "INCIDENT_LOST_EVENTS",
1369    }
1370}
1371
1372/// Canonical stable name for an intvar event subtype.
1373///
1374/// See [`incident_type_name`] for why the names are pinned instead of taken
1375/// from the library's `Debug` rendering (R51).
1376fn intvar_type_name(subtype: IntvarEventType) -> &'static str {
1377    match subtype {
1378        IntvarEventType::INVALID_INT_EVENT => "INVALID_INT_EVENT",
1379        IntvarEventType::LAST_INSERT_ID_EVENT => "LAST_INSERT_ID_EVENT",
1380        IntvarEventType::INSERT_ID_EVENT => "INSERT_ID_EVENT",
1381    }
1382}
1383
1384/// Lowercase hex digits shared with the row decoder.
1385const HEX: [u8; 16] = *b"0123456789abcdef";
1386
1387/// Renders a 16-byte SID as the canonical hyphenated lowercase UUID.
1388fn format_sid(sid: &[u8; 16]) -> String {
1389    let mut out = String::with_capacity(36);
1390    for (index, byte) in sid.iter().enumerate() {
1391        if index == 4 || index == 6 || index == 8 || index == 10 {
1392            out.push('-');
1393        }
1394        out.push(HEX[usize::from(byte >> 4)] as char);
1395        out.push(HEX[usize::from(byte & 0x0f)] as char);
1396    }
1397    out
1398}
1399
1400/// Renders a previous-GTIDs event in the mysqlbinlog textual form:
1401/// `uuid[:tag]:gno` per interval (single GTIDs without a dash, ranges as
1402/// `start-end` inclusive), with entries separated by commas.
1403fn format_gtid_set(event: &PreviousGtidsEvent<'_>) -> String {
1404    use std::fmt::Write as _;
1405    let mut parts: Vec<String> = Vec::new();
1406    for sid in event.sids() {
1407        let mut part = format_sid(&sid.uuid());
1408        if let Some(tag) = sid.tag() {
1409            let _ = write!(part, ":{}", tag.as_str());
1410        }
1411        for interval in sid.intervals() {
1412            let (start, end) = (interval.start(), interval.end());
1413            // Validation rejects degenerate intervals; the saturating
1414            // arithmetic keeps rendering total even if the library ever
1415            // yields one.
1416            let last = end.saturating_sub(1);
1417            if last == start {
1418                let _ = write!(part, ":{start}");
1419            } else {
1420                let _ = write!(part, ":{start}-{last}");
1421            }
1422        }
1423        parts.push(part);
1424    }
1425    parts.join(",")
1426}
1427
1428/// Validates a previous-GTIDs event body before the library parses it.
1429///
1430/// The library sizes its SID and interval vectors from untrusted declared
1431/// counts, which aborts the process on crafted input. This walk mirrors the
1432/// library's wire format (8-byte header, then per SID: 16-byte UUID, optional
1433/// varlen tag, 8-byte interval count, 16 bytes per interval) and rejects any
1434/// declared count that the remaining bytes cannot satisfy, plus intervals the
1435/// renderer could not format safely.
1436fn validate_previous_gtids(body: &[u8]) -> io::Result<()> {
1437    const OVERSIZED: &str = "previous gtids payload exceeds event bounds";
1438    const INVALID_INTERVAL: &str = "invalid previous gtids interval";
1439    if body.len() < 8 {
1440        // Too short for the header; the library rejects this deterministically.
1441        return Ok(());
1442    }
1443    let header = u64::from_le_bytes(body[..8].try_into().unwrap());
1444    let tagged = (header >> 56) != 0;
1445    let n_sids = if tagged {
1446        (header >> 8) & ((1 << 48) - 1)
1447    } else {
1448        header & ((1 << 56) - 1)
1449    };
1450    // Conservative minimum per SID: 16 bytes of UUID plus 8 bytes of interval count.
1451    if u64::try_from(body.len() - 8).unwrap_or(u64::MAX) < n_sids.saturating_mul(24) {
1452        return Err(io::Error::new(io::ErrorKind::InvalidData, OVERSIZED));
1453    }
1454    let mut pos = 8usize;
1455    for _ in 0..n_sids {
1456        if body.len() - pos < 24 {
1457            return Err(io::Error::new(io::ErrorKind::InvalidData, OVERSIZED));
1458        }
1459        pos += 16; // UUID
1460        if tagged {
1461            let tag_len = read_varlen_uint(body, &mut pos)?;
1462            if u64::try_from(body.len() - pos).unwrap_or(u64::MAX) < tag_len {
1463                return Err(io::Error::new(io::ErrorKind::InvalidData, OVERSIZED));
1464            }
1465            pos += tag_len as usize;
1466            if body.len() - pos < 8 {
1467                return Err(io::Error::new(io::ErrorKind::InvalidData, OVERSIZED));
1468            }
1469        }
1470        let n_intervals = u64::from_le_bytes(body[pos..pos + 8].try_into().unwrap());
1471        pos += 8;
1472        if u64::try_from(body.len() - pos).unwrap_or(u64::MAX) < n_intervals.saturating_mul(16) {
1473            return Err(io::Error::new(io::ErrorKind::InvalidData, OVERSIZED));
1474        }
1475        for _ in 0..n_intervals {
1476            let start = u64::from_le_bytes(body[pos..pos + 8].try_into().unwrap());
1477            let end = u64::from_le_bytes(body[pos + 8..pos + 16].try_into().unwrap());
1478            // MySQL GNOs start at one and intervals are [start, end); the
1479            // renderer subtracts one from `end`, so degenerate values must
1480            // never reach it.
1481            if start == 0 || end <= start {
1482                return Err(io::Error::new(io::ErrorKind::InvalidData, INVALID_INTERVAL));
1483            }
1484            pos += 16;
1485        }
1486    }
1487    Ok(())
1488}
1489
1490/// Reads a MySQL serialization library variable-length unsigned integer,
1491/// mirroring the library's encoding.
1492fn read_varlen_uint(buf: &[u8], pos: &mut usize) -> io::Result<u64> {
1493    let Some(&first) = buf.get(*pos) else {
1494        return Err(io::Error::new(
1495            io::ErrorKind::InvalidData,
1496            "unexpected end of varlen integer",
1497        ));
1498    };
1499    let trailing_ones = first.trailing_ones() as usize;
1500    if trailing_ones == 8 {
1501        let end = pos
1502            .checked_add(9)
1503            .filter(|end| *end <= buf.len())
1504            .ok_or_else(|| {
1505                io::Error::new(
1506                    io::ErrorKind::InvalidData,
1507                    "unexpected end of varlen integer",
1508                )
1509            })?;
1510        let mut raw = [0u8; 8];
1511        raw.copy_from_slice(&buf[*pos + 1..end]);
1512        *pos = end;
1513        return Ok(u64::from_le_bytes(raw));
1514    }
1515    let num_bytes = trailing_ones + 1;
1516    let end = pos
1517        .checked_add(num_bytes)
1518        .filter(|end| *end <= buf.len())
1519        .ok_or_else(|| {
1520            io::Error::new(
1521                io::ErrorKind::InvalidData,
1522                "unexpected end of varlen integer",
1523            )
1524        })?;
1525    let mut raw = [0u8; 8];
1526    raw[..num_bytes].copy_from_slice(&buf[*pos..end]);
1527    *pos = end;
1528    Ok(u64::from_le_bytes(raw) >> num_bytes)
1529}
1530
1531/// Validates the TLV header of a transaction payload event body before the
1532/// library parses it.
1533///
1534/// The header starts right after the 19-byte event header and is a sequence of
1535/// fields, each a length-encoded type followed by field-specific content:
1536/// `0` marks the header end, `1` is the payload size, `2` the compression
1537/// algorithm, `3` the uncompressed size, anything else is skipped by declared
1538/// length. The library's parser panics on an unknown algorithm byte, on a
1539/// field type above `u8::MAX` (its error constructor cannot hold one), and on
1540/// a skip length or length prefix that runs past the buffer, so this walk
1541/// mirrors its loop and turns each of those into a clean `InvalidData` error.
1542/// Truncations on the strictly parsed fields are left to the library, which
1543/// rejects them deterministically.
1544fn validate_transaction_payload_header(body: &[u8]) -> io::Result<()> {
1545    const UNSUPPORTED: &str = "unsupported transaction payload compression algorithm";
1546    const SHORT: &str = "truncated transaction payload header";
1547    let mut pos = 0usize;
1548    while pos < body.len() {
1549        let Some(field_type) = read_strict_lenenc(body, &mut pos) else {
1550            // The library reports invalid prefixes and short fields itself.
1551            return Ok(());
1552        };
1553        if field_type > u64::from(u8::MAX) {
1554            // The library's unknown-field error cannot represent this value
1555            // and panics while constructing it.
1556            return Err(io::Error::new(
1557                io::ErrorKind::InvalidData,
1558                "unknown transaction payload header field",
1559            ));
1560        }
1561        match field_type {
1562            // End of header; the remaining payload is only consumed in place.
1563            0 => return Ok(()),
1564            1..=3 => {
1565                // The declared field length is read but ignored by the
1566                // library, which parses the value immediately after it.
1567                let (Some(_), Some(value)) = (
1568                    read_strict_lenenc(body, &mut pos),
1569                    read_strict_lenenc(body, &mut pos),
1570                ) else {
1571                    return Ok(());
1572                };
1573                if field_type == 2 && (value > u64::from(u8::MAX) || (value != 0 && value != 255)) {
1574                    // The library unwraps this conversion; only ZSTD (0) and
1575                    // NONE (255) exist.
1576                    return Err(io::Error::new(io::ErrorKind::InvalidData, UNSUPPORTED));
1577                }
1578            }
1579            _ => {
1580                // Unknown field: the library reads a length-encoded length
1581                // through its lenient in-place reader, which panics past the
1582                // end of the buffer, then skips that many bytes, which also
1583                // panics if the length exceeds the remaining bytes.
1584                let Some(&first) = body.get(pos) else {
1585                    return Err(io::Error::new(io::ErrorKind::InvalidData, SHORT));
1586                };
1587                pos += 1;
1588                let length = match first {
1589                    x @ 0..=0xfa => u64::from(x),
1590                    0xfc => {
1591                        let Some(raw) = body.get(pos..pos + 2) else {
1592                            return Err(io::Error::new(io::ErrorKind::InvalidData, SHORT));
1593                        };
1594                        pos += 2;
1595                        u64::from(u16::from_le_bytes(raw.try_into().unwrap()))
1596                    }
1597                    0xfd => {
1598                        let Some(raw) = body.get(pos..pos + 3) else {
1599                            return Err(io::Error::new(io::ErrorKind::InvalidData, SHORT));
1600                        };
1601                        pos += 3;
1602                        u64::from(u32::from_le_bytes([raw[0], raw[1], raw[2], 0]))
1603                    }
1604                    0xfe => {
1605                        let Some(raw) = body.get(pos..pos + 8) else {
1606                            return Err(io::Error::new(io::ErrorKind::InvalidData, SHORT));
1607                        };
1608                        pos += 8;
1609                        u64::from_le_bytes(raw.try_into().unwrap())
1610                    }
1611                    // The library decodes the non-canonical prefixes to zero.
1612                    _ => 0,
1613                };
1614                if length > (body.len() - pos) as u64 {
1615                    return Err(io::Error::new(io::ErrorKind::InvalidData, SHORT));
1616                }
1617                pos += length as usize;
1618            }
1619        }
1620    }
1621    Ok(())
1622}
1623
1624/// Reads a MySQL length-encoded integer the way the library's strict
1625/// `read_lenenc_int` does: the non-canonical `0xfb`/`0xff` prefixes and a
1626/// truncated field are errors, signaled here as `None` so the caller can leave
1627/// the rejection to the library, whose error is identical.
1628fn read_strict_lenenc(buf: &[u8], pos: &mut usize) -> Option<u64> {
1629    let first = *buf.get(*pos)?;
1630    *pos += 1;
1631    let extra = match first {
1632        x if x <= 0xfa => return Some(u64::from(x)),
1633        0xfc => 2,
1634        0xfd => 3,
1635        0xfe => 8,
1636        // Invalid length-encoded integer prefix.
1637        _ => return None,
1638    };
1639    let raw = buf.get(*pos..*pos + extra)?;
1640    *pos += extra;
1641    let mut bytes = [0u8; 8];
1642    bytes[..extra].copy_from_slice(raw);
1643    Some(u64::from_le_bytes(bytes))
1644}
1645
1646/// CRC-32 (IEEE 802.3, reflected) used for binlog event checksums.
1647struct Crc32 {
1648    state: u32,
1649}
1650
1651impl Crc32 {
1652    fn new() -> Self {
1653        Self { state: !0 }
1654    }
1655
1656    fn update(&mut self, data: &[u8]) {
1657        for &byte in data {
1658            let index = ((self.state ^ u32::from(byte)) & 0xff) as usize;
1659            self.state = CRC32_TABLE[index] ^ (self.state >> 8);
1660        }
1661    }
1662
1663    fn finalize(self) -> u32 {
1664        !self.state
1665    }
1666}
1667
1668/// Lookup table for [`Crc32`], built at compile time.
1669const CRC32_TABLE: [u32; 256] = {
1670    const fn build() -> [u32; 256] {
1671        let mut table = [0u32; 256];
1672        let mut i = 0;
1673        while i < 256 {
1674            let mut value = i as u32;
1675            let mut bit = 0;
1676            while bit < 8 {
1677                value = if value & 1 != 0 {
1678                    0xedb88320 ^ (value >> 1)
1679                } else {
1680                    value >> 1
1681                };
1682                bit += 1;
1683            }
1684            table[i] = value;
1685            i += 1;
1686        }
1687        table
1688    }
1689    build()
1690};
1691
1692/// Verifies the CRC32 checksum of an event directly on its raw bytes.
1693///
1694/// This mirrors the library's `Event::calc_checksum` (header with the
1695/// "binlog in use" flag cleared, then the body). It is needed when a table
1696/// map event body is modified by stripping before the library parses it: the
1697/// library's own verification would then hash the modified bytes against the
1698/// original checksum. A mismatch is framed as [`FrameError::Checksum`] so it
1699/// surfaces as the structured [`ParserError::Checksum`] variant (R45).
1700fn verify_event_checksum(buffer: &[u8]) -> Result<(), FrameError> {
1701    // `EventFlags::LOG_EVENT_BINLOG_IN_USE_F` (0x0001) is cleared before the
1702    // checksum is computed, both by the server when writing and by the
1703    // library when verifying.
1704    const BINLOG_IN_USE_FLAG: u16 = 0x0001;
1705    let Some(body_len) = buffer.len().checked_sub(4) else {
1706        return Err(FrameError::Io(io::Error::new(
1707            io::ErrorKind::InvalidData,
1708            "short checksummed event",
1709        )));
1710    };
1711    let mut header = [0u8; 19];
1712    header.copy_from_slice(&buffer[..19]);
1713    let mut flags = u16::from_le_bytes([header[17], header[18]]);
1714    if flags & BINLOG_IN_USE_FLAG != 0 {
1715        flags &= !BINLOG_IN_USE_FLAG;
1716        header[17..19].copy_from_slice(&flags.to_le_bytes());
1717    }
1718    let mut crc = Crc32::new();
1719    crc.update(&header);
1720    crc.update(&buffer[19..body_len]);
1721    let recorded = u32::from_le_bytes(buffer[body_len..].try_into().unwrap());
1722    if crc.finalize() != recorded {
1723        return Err(FrameError::Checksum);
1724    }
1725    Ok(())
1726}
1727
1728/// Removes the given byte ranges (relative to `base`) from `buffer` in place,
1729/// returning the number of bytes removed. Ranges must be ascending and
1730/// non-overlapping, which the TLV scan guarantees.
1731fn remove_ranges(buffer: &mut Vec<u8>, base: usize, ranges: &[std::ops::Range<usize>]) -> usize {
1732    let mut removed = 0;
1733    let mut read = base;
1734    let mut write = base;
1735    for range in ranges {
1736        let start = base + range.start;
1737        let end = base + range.end;
1738        buffer.copy_within(read..start, write);
1739        write += start - read;
1740        read = end;
1741        removed += end - start;
1742    }
1743    buffer.copy_within(read.., write);
1744    buffer.truncate(buffer.len() - removed);
1745    removed
1746}
1747
1748#[cfg(test)]
1749mod tests {
1750    use super::*;
1751
1752    #[test]
1753    fn structured_parser_errors_keep_their_display_strings() {
1754        // R45: the structured variants carry the offset (and size/limit) as
1755        // fields while their Display strings stay identical to the messages
1756        // the paths emitted before the variants existed.
1757        assert_eq!(
1758            ParserError::Checksum { offset: 125 }.to_string(),
1759            "binlog error at offset 125: event checksum mismatch"
1760        );
1761        assert_eq!(
1762            ParserError::Truncated { offset: 4 }.to_string(),
1763            "binlog error at offset 4: failed to fill whole buffer"
1764        );
1765        assert_eq!(
1766            ParserError::OversizedEvent {
1767                offset: 31,
1768                size: 0,
1769                limit: MAX_EVENT_SIZE
1770            }
1771            .to_string(),
1772            "binlog error at offset 31: invalid or oversized event"
1773        );
1774        assert_eq!(
1775            FrameError::Checksum.into_parser_error(125).to_string(),
1776            ParserError::Checksum { offset: 125 }.to_string()
1777        );
1778        assert_eq!(
1779            truncated_or_io(io::Error::new(io::ErrorKind::UnexpectedEof, "ignored"))
1780                .into_parser_error(4)
1781                .to_string(),
1782            ParserError::Truncated { offset: 4 }.to_string()
1783        );
1784        // A non-EOF failure while filling the buffer stays a plain I/O error.
1785        let interrupted = io::Error::new(io::ErrorKind::Interrupted, "retry");
1786        assert!(matches!(truncated_or_io(interrupted), FrameError::Io(_)));
1787    }
1788
1789    #[test]
1790    fn intvar_and_incident_type_names_are_pinned() {
1791        // R51: the intvar and incident type names are pinned constants, not
1792        // the library's Debug rendering, so a library rename cannot change
1793        // the output.
1794        assert_eq!(
1795            intvar_type_name(IntvarEventType::INVALID_INT_EVENT),
1796            "INVALID_INT_EVENT"
1797        );
1798        assert_eq!(
1799            intvar_type_name(IntvarEventType::LAST_INSERT_ID_EVENT),
1800            "LAST_INSERT_ID_EVENT"
1801        );
1802        assert_eq!(
1803            intvar_type_name(IntvarEventType::INSERT_ID_EVENT),
1804            "INSERT_ID_EVENT"
1805        );
1806        assert_eq!(
1807            incident_type_name(IncidentType::INCIDENT_NONE),
1808            "INCIDENT_NONE"
1809        );
1810        assert_eq!(
1811            incident_type_name(IncidentType::INCIDENT_LOST_EVENTS),
1812            "INCIDENT_LOST_EVENTS"
1813        );
1814    }
1815
1816    #[test]
1817    fn server_version_stops_at_first_nul() {
1818        let mut raw = vec![b'8', b'.', b'0', b'.', b'3', b'0'];
1819        raw.resize(50, 0);
1820        assert_eq!(server_version(&raw), "8.0.30");
1821        assert_eq!(server_version(&[0; 50]), "");
1822    }
1823
1824    #[test]
1825    fn sid_is_rendered_hyphenated() {
1826        let sid = [
1827            0x55, 0x77, 0x89, 0x04, 0x02, 0x99, 0x11, 0xf1, 0xb1, 0xb8, 0x4e, 0xf0, 0xc4, 0x95,
1828            0x6f, 0xeb,
1829        ];
1830        assert_eq!(format_sid(&sid), "55778904-0299-11f1-b1b8-4ef0c4956feb");
1831    }
1832
1833    #[test]
1834    fn oversized_previous_gtids_are_rejected() {
1835        // Untagged header declaring more SIDs than the body can hold.
1836        let mut body = 8u64.to_le_bytes().to_vec();
1837        body[0] = 0x01;
1838        assert!(validate_previous_gtids(&body).is_err());
1839        // Tagged header (format byte in the top bits) with the same abuse.
1840        let header = (1u64 << 56) | (1 << 8) | 1;
1841        let mut body = header.to_le_bytes().to_vec();
1842        body.extend_from_slice(&[0u8; 23]);
1843        assert!(validate_previous_gtids(&body).is_err());
1844        // A single SID with an inflated interval count is also rejected.
1845        let mut body = 1u64.to_le_bytes().to_vec();
1846        body.extend_from_slice(&[0u8; 16]); // UUID
1847        body.extend_from_slice(&1_000_000u64.to_le_bytes()); // n_intervals
1848        assert!(validate_previous_gtids(&body).is_err());
1849    }
1850
1851    #[test]
1852    fn well_formed_previous_gtids_is_accepted() {
1853        // One untagged SID with interval [1, 3).
1854        let mut body = 1u64.to_le_bytes().to_vec();
1855        body.extend_from_slice(&[0x55; 16]);
1856        body.extend_from_slice(&1u64.to_le_bytes());
1857        body.extend_from_slice(&1u64.to_le_bytes());
1858        body.extend_from_slice(&3u64.to_le_bytes());
1859        validate_previous_gtids(&body).unwrap();
1860    }
1861
1862    #[test]
1863    fn degenerate_previous_gtids_intervals_are_rejected() {
1864        let interval = |start: u64, end: u64| {
1865            let mut body = 1u64.to_le_bytes().to_vec();
1866            body.extend_from_slice(&[0x55; 16]);
1867            body.extend_from_slice(&1u64.to_le_bytes()); // n_intervals
1868            body.extend_from_slice(&start.to_le_bytes());
1869            body.extend_from_slice(&end.to_le_bytes());
1870            body
1871        };
1872        // GNOs start at one; an interval starting at zero is malformed.
1873        let err = validate_previous_gtids(&interval(0, 0)).unwrap_err();
1874        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1875        // Empty and reversed intervals would break the inclusive renderer.
1876        for (start, end) in [(5, 5), (10, 4), (u64::MAX, u64::MAX)] {
1877            let err = validate_previous_gtids(&interval(start, end)).unwrap_err();
1878            assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1879        }
1880        // The largest well-formed single-GNO interval is accepted.
1881        validate_previous_gtids(&interval(1, u64::MAX)).unwrap();
1882        validate_previous_gtids(&interval(u64::MAX - 1, u64::MAX)).unwrap();
1883    }
1884
1885    /// Writes a MySQL length-encoded integer like the library does.
1886    fn put_lenenc(out: &mut Vec<u8>, value: u64) {
1887        if value < 251 {
1888            out.push(value as u8);
1889        } else if value < 65536 {
1890            out.push(0xfc);
1891            out.extend_from_slice(&(value as u16).to_le_bytes());
1892        } else if value < 1 << 24 {
1893            out.push(0xfd);
1894            out.extend_from_slice(&(value as u32).to_le_bytes()[..3]);
1895        } else {
1896            out.push(0xfe);
1897            out.extend_from_slice(&value.to_le_bytes());
1898        }
1899    }
1900
1901    /// Appends a header field: type, declared length, value.
1902    fn tlv(field: u64, value: u64) -> Vec<u8> {
1903        let mut out = Vec::new();
1904        put_lenenc(&mut out, field);
1905        put_lenenc(&mut out, 1);
1906        put_lenenc(&mut out, value);
1907        out
1908    }
1909
1910    fn payload_header(algorithm: u64) -> Vec<u8> {
1911        let mut body = tlv(2, algorithm);
1912        body.extend(tlv(1, 0));
1913        body.push(0); // end mark
1914        body
1915    }
1916
1917    #[test]
1918    fn well_formed_payload_header_is_accepted() {
1919        for algorithm in [0u64, 255] {
1920            validate_transaction_payload_header(&payload_header(algorithm)).unwrap();
1921        }
1922    }
1923
1924    #[test]
1925    fn unknown_payload_algorithm_is_rejected() {
1926        for algorithm in [1u64, 7, 254, 256, u64::MAX] {
1927            let err = validate_transaction_payload_header(&payload_header(algorithm)).unwrap_err();
1928            assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1929            assert!(err.to_string().contains("compression algorithm"));
1930        }
1931    }
1932
1933    #[test]
1934    fn payload_field_type_above_u8_is_rejected() {
1935        // A field type encoded with the 8-byte prefix panics the library's
1936        // error construction and must be rejected here.
1937        let mut body = vec![0xfe];
1938        body.extend_from_slice(&5_000_000u64.to_le_bytes());
1939        let err = validate_transaction_payload_header(&body).unwrap_err();
1940        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1941    }
1942
1943    #[test]
1944    fn payload_unknown_field_skip_overflow_is_rejected() {
1945        // An unknown field declaring a 65535-byte skip in a tiny body would
1946        // panic the library's in-place skip.
1947        let mut body = vec![5, 0xfc];
1948        body.extend_from_slice(&65535u16.to_le_bytes());
1949        let err = validate_transaction_payload_header(&body).unwrap_err();
1950        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1951        // A skip that fits is accepted.
1952        let body = vec![5, 3, 1, 2, 3, 0];
1953        validate_transaction_payload_header(&body).unwrap();
1954    }
1955
1956    #[test]
1957    fn truncated_payload_header_walks_without_panic() {
1958        // Truncations on strictly parsed fields are left to the library,
1959        // which rejects them deterministically.
1960        for body in [
1961            vec![2],          // compression field without length and value
1962            vec![2, 1],       // length without value
1963            vec![2, 1, 0xfc], // truncated 2-byte value
1964            vec![1, 1, 0],    // payload size without end mark
1965            vec![0xfc],       // invalid prefix in the type position
1966        ] {
1967            validate_transaction_payload_header(&body).unwrap();
1968        }
1969    }
1970
1971    /// An inner XID event: 19-byte header plus the 8-byte transaction id.
1972    fn inner_xid(xid: u64) -> Vec<u8> {
1973        let mut event = Vec::new();
1974        event.extend_from_slice(&0u32.to_le_bytes()); // timestamp
1975        event.push(16); // XID_EVENT
1976        event.extend_from_slice(&7u32.to_le_bytes()); // server id
1977        event.extend_from_slice(&27u32.to_le_bytes()); // event size
1978        event.extend_from_slice(&27u32.to_le_bytes()); // log pos
1979        event.extend_from_slice(&0u16.to_le_bytes()); // flags
1980        event.extend_from_slice(&xid.to_le_bytes());
1981        event
1982    }
1983
1984    #[test]
1985    fn payload_stream_frames_inner_events_with_offsets() {
1986        use mysql_common::binlog::events::EventData;
1987        let mut bytes = inner_xid(11);
1988        bytes.extend(inner_xid(22));
1989        let reader = TransactionPayloadReader::new_uncompressed(&bytes);
1990        let mut stream = PayloadStream::new(reader, 1 << 20, u64::from(MAX_EVENT_SIZE), 0);
1991        let mut parser_events = EventStreamReader::new(BinlogVersion::Version4);
1992        let first = parser_events
1993            .read_decompressed(&mut stream)
1994            .unwrap()
1995            .unwrap();
1996        assert_eq!(stream.last_event_offset(), 0);
1997        assert_eq!(first.header().event_type_raw(), 16);
1998        assert!(matches!(
1999            first.read_data().unwrap(),
2000            Some(EventData::XidEvent(e)) if e.xid == 11
2001        ));
2002        let second = parser_events
2003            .read_decompressed(&mut stream)
2004            .unwrap()
2005            .unwrap();
2006        assert_eq!(stream.last_event_offset(), 27);
2007        assert!(matches!(
2008            second.read_data().unwrap(),
2009            Some(EventData::XidEvent(e)) if e.xid == 22
2010        ));
2011        assert!(
2012            parser_events
2013                .read_decompressed(&mut stream)
2014                .unwrap()
2015                .is_none()
2016        );
2017    }
2018
2019    #[test]
2020    fn payload_stream_enforces_declared_size() {
2021        // Two inner events total 54 bytes; a limit just below rejects the
2022        // second one before it is handed to the library.
2023        let mut bytes = inner_xid(11);
2024        bytes.extend(inner_xid(22));
2025        let reader = TransactionPayloadReader::new_uncompressed(&bytes);
2026        let mut stream = PayloadStream::new(reader, 40, u64::from(MAX_EVENT_SIZE), 0);
2027        let mut parser_events = EventStreamReader::new(BinlogVersion::Version4);
2028        assert!(
2029            parser_events
2030                .read_decompressed(&mut stream)
2031                .unwrap()
2032                .is_some()
2033        );
2034        let err = parser_events.read_decompressed(&mut stream).unwrap_err();
2035        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2036        assert!(err.to_string().contains("declared size"));
2037    }
2038
2039    #[test]
2040    fn payload_stream_rejects_truncation_and_nested_payload() {
2041        // A truncated inner event body is a clean error, not EOF.
2042        let mut bytes = inner_xid(11);
2043        bytes.truncate(bytes.len() - 2);
2044        let reader = TransactionPayloadReader::new_uncompressed(&bytes);
2045        let mut stream = PayloadStream::new(reader, 1 << 20, u64::from(MAX_EVENT_SIZE), 0);
2046        let mut parser_events = EventStreamReader::new(BinlogVersion::Version4);
2047        let err = parser_events.read_decompressed(&mut stream).unwrap_err();
2048        assert!(err.to_string().contains("truncated"), "{err}");
2049
2050        // A nested transaction payload event is rejected before the library
2051        // would see it.
2052        let mut nested = Vec::new();
2053        nested.extend_from_slice(&0u32.to_le_bytes());
2054        nested.push(40);
2055        nested.extend_from_slice(&7u32.to_le_bytes());
2056        nested.extend_from_slice(&39u32.to_le_bytes());
2057        nested.extend_from_slice(&39u32.to_le_bytes());
2058        nested.extend_from_slice(&0u16.to_le_bytes());
2059        nested.extend_from_slice(&[2, 1, 0, 0]);
2060        let mut bytes = inner_xid(11);
2061        bytes.extend(nested);
2062        let reader = TransactionPayloadReader::new_uncompressed(&bytes);
2063        let mut stream = PayloadStream::new(reader, 1 << 20, u64::from(MAX_EVENT_SIZE), 0);
2064        let mut parser_events = EventStreamReader::new(BinlogVersion::Version4);
2065        assert!(
2066            parser_events
2067                .read_decompressed(&mut stream)
2068                .unwrap()
2069                .is_some()
2070        );
2071        let err = parser_events.read_decompressed(&mut stream).unwrap_err();
2072        assert!(err.to_string().contains("nested"), "{err}");
2073    }
2074}