binlog-inspect

binlog-inspect Design

Scope and Architecture

An offline MySQL binlog CLI + library in Rust 2024. It reads local files or standard input (-), or — with the remote feature enabled — first streams an HTTP(S) resource to a temporary file; HTTP is not the MySQL replication protocol. Parsing, filtering, and formatting are layered; networking and clap live only in the CLI layer, which is the default-on cli feature (R37): library consumers can build with default-features = false to drop clap, completions, datetime parsing and anyhow, and the binary declares required-features = ["cli"]. mysql_common’s EventStreamReader manages the Format Description and Table Maps; Cargo.lock records the actual dependencies, the MSRV is 1.88 (rust-version, verified and enforced in CI).

Event types have the library-level EventType enum as their single source of truth: it derives ValueEnum, so --events validation happens at argument-parse time (unknown values exit with code 2); the snake_case values of as_str are byte-for-byte identical to the historical JSON event_type strings, and from_raw handles the raw-code mapping (code 41 is folded into heartbeat; the V1 row events 23–25 map onto write/update/delete rows like their V2 counterparts; the pre-GA row events 20–22 and MariaDB 160+ map to unknown).

Post-parse filters layer on top of the type/table filters and also cannot affect parser state: byte-offset windows (--start-position inclusive, --stop-position exclusive), timestamp windows (--start-datetime/--stop-datetime, both inclusive, parsed at argument time via jiff), and an exact-match GTID allowlist (--include-gtid; UUIDs lowercased, tags validated per MySQL tag rules, GNOs ≥ 1). --stats replaces event output with one JSON summary over the kept events; --completions prints shell completions and exits before any input is opened.

Outer events are framed one at a time, with a 64 MiB raw-event cap (MAX_EVENT_SIZE; library callers can raise it via with_max_event_size). The event buffer is reused across events, the BufReader capacity is 1 MiB, hex encoding is table-driven, and input files are consumed incrementally. Decoded row images, accumulated table maps, and the collecting iterator’s transaction children use additional memory. from_reader holds an arbitrary stream after validating only the 4-byte magic, so the input need not be seekable. The file header accepts only the plaintext FE 62 69 6E; the encrypted FD 62 69 6E magic returns an explicit error. CRC32 checksums are verified by the parser; unknown algorithms, truncation, corruption, and unhandleable events stop that file and make the process exit non-zero — the next event boundary must never be guessed.

Hostile-Input Pre-Validation

The underlying crate’s previous-GTIDs decoding (code 35’s n_sids) and table-map optional metadata TLV decoding (ENUM/SET’s num_variants) perform unbounded Vec::with_capacity calls on untrusted declared counts, so hostile input can abort the process and violate the fail-closed contract. Therefore, hand pre-validation runs before the crate decodes: for code 35, the header n_sids, the tag paths, and the interval count of every SID must match the remaining bytes, and each interval must satisfy start ≥ 1, end > start (GNOs start at 1; degenerate intervals would overflow the arithmetic of set-string rendering); for table-map metadata TLVs, each item’s declared length, known type code, and every column’s ENUM/SET variant count are validated against the remaining bytes. Lenenc decoding is distinguished by read path: TLV length prefixes use the crate’s strict reader (0xfb/0xff are errors), while table-map header counts and variant counts use ParseBuf semantics (0xfb/0xff decode as 0), so encodings the crate accepts are never falsely rejected. Structural shortfalls (which the crate rejects deterministically) are not pre-checked, avoiding false rejection of legitimate files; exceeding any bound returns an InvalidData error carrying the file offset.

Events and Row Values

The event model is decoupled from the underlying crate, and every type derives Serialize + Deserialize (CellValue::Bytes is a lowercase hex string; deserialization expects the same form, enabling JSONL round-trips). GTIDs are emitted in canonical full form: untagged is uuid:gno, tagged (code 42, MySQL 8.4+) is uuid:tag:gno with an additional structured tag field (null when absent); for anonymous GTIDs (code 34) event_type is anonymous_gtid and gtid is ANONYMOUS, matching mysqlbinlog. previous_gtids (code 35) decodes into a mysqlbinlog-style set string; standard MySQL 5.7+/8.0 binlogs always contain this event, which no longer shows up as unknown. format_description.server_version is truncated at the first NUL. stop, rows_query, incident, and intvar are decoded into typed payloads; rand, user_var, begin_load_query, execute_load_query, heartbeat (including 41), ignorable, transaction_context, view_change, and xa_prepare keep their named types but carry an unknown{raw_len} payload.

FDE, Table Map, Query, XID, GTID, Rotate, and V1/V2 write/update/delete row events are converted into the stable model. If a row image’s present-bitmap bit count disagrees with the column count, an error is returned instead of silently truncating. Mirror the MySQL applier on column counts (R36): a row event may declare fewer columns than its table map records (the table grew after the event was written) — missing tail columns render as explicit absent entries — while a row event declaring more columns than the table map remains an error. Row events without a table map are marked unresolved, never guess a table name, and never match table filters. Table filtering matches against a set of (String, String) tuples with no per-event allocation; table and type filters run after parsing completes so that parser state stays correct.

Partial JSON diff events (code 39 partial_update_rows, WL#2955) are decoded independently, no longer mislabeled as update_rows. The before image is a full row image; the after image carries a sequence of JSON diffs per JSON column, which the decoder applies against the before image’s JSON value: an applied column renders as a full JSON document ("type": "json"), and a diff that cannot be applied (no before value, missing path, invalid operation) renders as the loss-marking "type": "partial_json" value with the preserved diffs and the reason — never a silent guess and never a hard failure of the event. Table maps of such files carry optional metadata types 14/15 that the underlying library rejects; they are accepted by the pre-validation walk and stripped from the bytes handed to the library (checksum first verified on the original bytes), with signedness extracted by the tool’s own SIGNEDNESS TLV walk instead of the library’s extractor. Numeric values carry the canonical constant name of the MySQL column type (not the crate’s Debug formatting) plus signedness metadata, marked unknown when missing: the underlying crate defaults to a signed interpretation, which alone cannot determine the original SQL type.

A header log_pos that does not land right after its event (offset + size) indicates tampering or a spliced file; it is reported as a non-fatal advisory warning on stderr (R35) — parsing continues, the exit status is unaffected, zero log_pos (artificial events) is ignored, and the warning buffer is capped so a corrupt file cannot grow it without limit. BinlogParser::take_warnings exposes the same warnings to library callers.

Row images are presented in table column order, with missing columns and SQL NULL explicitly marked; binary and character content is rendered as hex bytes without guessing a character set. Without complete column-name metadata, names may be generated ones (such as @0) and must not be treated as the actual table schema.

Output, Exit Codes, and Atomic Writes

JSON Lines emits one record per event; text is {ts} {event_type} server={id} pos={log_pos} {payload_json}; CSV emits one row per row change (kind=rows) and per partial-update row pair (kind=partial_update_rows), with before/after image fields as CSV-escaped JSON strings. Timestamps are Unix seconds. The Formatter trait writes directly to &mut dyn Write (serde_json::to_writer writes straight through, with no per-event intermediate String) and returns whether the event produced output. Output can contain raw business data; handle it in a trusted destination.

Exit codes are layered: 0 success; 1 hard error (input cannot be opened, invalid header, output target already exists, first parse error under --strict); 2 clap usage error; 3 partial parse failure (default mode: an error stops the current file, remaining files are still processed, and stderr lists paths and offsets per file; in that case --output contains the successfully parsed prefix, which is intentional). A closed stdout (for example when piped into head) is treated as a normal end and exits 0.

--output writes atomically: on unix it first creates a hidden temporary file in the target directory (mode 0600) and, after full success, publishes it via hard_link + remove_file rather than rename: link fails unconditionally when the target already exists (AlreadyExists), whereas rename would silently replace an existing file — including a hard link or symlink pointing at the input file; on other platforms the target itself is created with create_new, whose overwrite guarantee makes publishing a no-op. Both platforms perform an existence check first to produce a fast, friendly error. Any hard error (including a failed publish) deletes the written file, leaving nothing behind.

Functional Boundaries

Verification Strategy

Synthetic tests cover the file header, event boundaries, CRC, parse failures, filtering, formats, stdin, atomic output, layered exit codes, remote downloads, and encrypted-file rejection. User-provided real samples are validated locally only and never enter the repository, test fixtures, or public logs. Event counts and types are compared against an independent event-header traversal, and mysqlbinlog --verify-binlog-checksum verifies checksums; the scope of value comparisons against reference tools must be reported separately, and agreement in counts must not be taken as proof that all values are correct. CI runs format checks, Clippy (default, all-features and no-default-features), the test matrix across the feature combinations (including --no-default-features --features remote), an MSRV job on 1.88, and both feature builds on stable.

Incremental Transaction Visitors

BinlogParser::visit_events emits ordinary events and a start/inner-event/end sequence for each compressed transaction. It shares the framing, checksum verification, payload validation and table-map state with the collecting iterator. Inner event offsets are relative to the decompressed stream and parent_offset identifies the enclosing file offset. The start notification follows outer-event validation and decompressor creation. The end notification confirms complete payload decoding.

Callbacks receive borrowed events and return io::Result<ControlFlow<()>>. An error or Break ends the stream. A callback panic also leaves the parser terminated when caught by the caller. Earlier callbacks remain observable if a later inner event fails, so consumers that require transaction-wide atomicity must stage their effects until the matching end notification.

The visitor holds the outer compressed event, the current inner event and shared table maps. Individual decoded row images can exceed their wire size. The events() iterator collects the children of a payload to preserve the complete nested-event output contract; the CLI’s --stream-payload-events flag drives this visitor instead, streaming each child as its own JSONL line under the partial-output contract documented in Functional Boundaries.