Skip to content

resolvers: expand magic32 metaformat subformat metadata and fixtures - #1628

Merged
reyammer merged 4 commits into
google:mainfrom
corkamig:resolvers-magic32-subformats
Nov 18, 2026
Merged

reyammer merged 4 commits into
google:mainfrom
corkamig:resolvers-magic32-subformats

Conversation

@corkamig

@corkamig corkamig commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Follow-up to #1624 (#1618): expand RegularFileType::metadata (subformat, plus more specific pronom_puid / loc_fdd overrides where standardized) across major magic32-dispatched metaformats, with minimal test fixtures under tests_data/resolvers/fixtures/ and zero changes to ContentType decisions, VETOS, or generated KB artifacts.

Commit 1: Zero-new-parsing subformats (fields already parsed & validated)

  • ISOBMFF (isobmff.rs): name all 35 MP4, 8 HEIF, and 25 3GPP major brands via direct match (replacing linear .contains() scans), preserving brand allowlists.
  • SQLite 3 (sqlite.rs): distinguish MBTiles MPBX header vs schema matches and map 22 well-known registered application_id values (@68) on Label::Sqlite.
  • ELF (elf.rs): combine already-validated class, endianness, and e_type (@16) via a static lookup table, preserving fmt/688..fmt/691.
  • Mach-O (executable.rs): combine already-validated width, endianness, and filetype (@12) via a static lookup table, preserving fmt/692 and fmt/693.
  • Windows PE (executable.rs): combine PE32/PE32+, DLL flag, and subsystem (@68) in a single header pass, preserving fmt/899 and fmt/900.
  • Java .class (overlap.rs): map already-validated major versions 45..=71 (@6) to Java 1.0/1.1..Java 27 class files while leaving 72..=80 bare.

Commit 2: O(1) fixed-offset header subformats (zero scanning)

  • Ogg (audio.rs): inspect the BOS identification packet header at @(27 + page_segments) via a 1-byte switch (Vorbis fmt/203/fdd000117, Opus fmt/946, Theora fmt/945, FLAC fmt/947/fdd000227, Speex fmt/948/fdd000260, Skeleton, Kate, CELT, Dirac, Daala, MIDI, PCM), with a single O(1) Page 1 peek when Page 0 is Ogg Skeleton (fishead\0).
  • Unix ar (ar.rs): classify the first member header name at @8..24 on Label::Ar (GNU/SVR4 symbol table, 64-bit symbol table, long filename table, BSD/macOS inline & #1/<len> symbol tables, BSD extended filename).
  • RIFF / RIFX WAVE (riff.rs): inspect only the initial chunk at @12 ("fmt " + wFormatTag at @20 for PCM fmt/141/fdd000002, Extensible fmt/143/fdd000001, MS ADPCM, IEEE float, A-Law, mu-Law, IMA ADPCM, MP3; "bext" + EBU Tech 3285 Version at @366 for Broadcast WAVE v0 fmt/1, v1 fmt/2/fdd000356, v2 fmt/527/fdd000357, and generic BWF; plus big-endian RIFX WAVE format tags) without walking chunks.
  • TIFF (image.rs): identify Canon RAW 2 ("CR\x02\x00" at @8..12 with IFD0 offset >= 16) on little-endian TIFF (fmt/592/fdd000241).
  • ZIP (zip.rs): reuse the already-extracted stored "mimetype" first-entry payload on Label::Zip fallback paths for OpenDocument subtypes/templates (odg, odf, odb, odc, odi, ott, ots, otp, otg, odm with fdd000247), Krita (fmt/999), OpenRaster (fmt/998), and Adobe InDesign IDML (fmt/1184), plus Empty ZIP archive on empty EOCD archives (with or without an archive comment).

Commit 3: Reflet SQLite application_id ("RFLT")

  • SQLite 3 (sqlite.rs): map application_id "RFLT" (@68) to "Reflet database (.reflet)" on Label::Sqlite (23 SQLite application_id subformats total).

Commit 4: Review fixes & fixture layout consolidation

  • Address review findings across ar.rs (#1/<len> + __.SYMDEF), audio.rs (Ogg Skeleton Page 1 codec peek), zip.rs (empty ZIP comment vs trailing bytes), and overlap.rs (Java 1.0/1.1 class file).
  • Move all 93 subformat fixtures out of tests_data/resolvers/subformats/ directly into tests_data/resolvers/fixtures/ (_ar, _elf, _isobmff, _macho, _ogg, _pe, _riff, _sqlite, _tiff, _zip, bytecode), restore full ftyp box lengths (20/24 B) on the 11 _isobmff/ fixtures, and document resolvers/fixtures/ and the "!" synthesis convention in tests_data/README.md.

Testing & Performance

  • rustup run nightly cargo fmt -- --check across all rust/ crates (verified against rust/rustfmt.toml)
  • rustup run stable & rustup run nightly ./test.sh in rust/lib (unit tests + doctest, clippy --all-targets --features=pipeline,serde -- --deny=warnings, RUSTDOCFLAGS=--deny=warnings cargo doc --features=_doc)
  • rust/cli, rust/pyo3, rust/ffi test suites
  • uv run scripts/sync_kb.py --self-test & --check, check_copyright.py, check_documentation.py
  • Differential & mutation/truncation testing: 5M+ mutated/truncated/boundary evaluations + 400k multi-threaded concurrent evaluations — 0 ContentType drift, 0 panics, 0 metadata leakage.

@reyammer reyammer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: This is a review from yanickf@'s bot.

Review Verdict: CONCERNS

Summary & Risk Assessment

This is a clean, well-scoped follow-up to #1624 (#1618). Expanding Subformat from naming existing branches to also reading O(1) fixed-offset header fields inside already-validated containers (without loops, scanning, extra allocations, or changes to ContentType / VETOS) fits naturally on top of the thread-local SUBFORMAT mechanism, and several Commit 1 changes (isobmff.rs direct match tables replacing .contains() scans, executable.rs folding windows_pe_subformat into a single pass) simplify the existing code. None of the newly surfaced subformats collide with standalone labels in assets/content_types.yaml, and all PRONOM PUID, LoC FDD, and SQLite application_id constants match upstream specs/registries.

Runtime/regression risk is low (ContentType decisions are unchanged and all slice reads are bounds-checked), with three [medium] items below — two real-world container layout details in ar.rs and audio.rs (both still fixable in O(1) fixed-offset arithmetic), plus a question/cleanup around the 93 committed binary stubs in tests_data/resolvers/subformats/.


Findings

  1. [medium] rust/lib/src/resolvers/magic/verifiers/meta/ar.rs:76-83 — Modern BSD / macOS static libraries (#1/<len> + __.SYMDEF) are classified as "Unix ar (BSD extended filename)" instead of "Unix ar (BSD/macOS symbol table)"

    • Why: In 4.4BSD and Darwin/macOS (ar, ranlib, libtool, llvm-ar --format=bsd, llvm-ar --format=darwin), archive symbol table members (__.SYMDEF, __.SYMDEF SORTED, __.SYMDEF_64, __.SYMDEF_64 SORTED) use the BSD #1/<len> extended filename header (e.g. !<arch>\n#1/12 ...\n__.SYMDEF\0\0\0 or #1/20 + __.SYMDEF SORTED\0\0\0\0), placing the actual member name at fixed offset @68 right after `\n (@66..68). Matching only name_hdr at @8..24 means AR_BSD_SYMDEF only triggers on legacy pre-4.4BSD inline headers (like !ar_bsd_symdef.a), whereas real-world BSD and macOS .a static libraries hit #1/ and report "Unix ar (BSD extended filename)".
    • Suggested fix: Check @68 in O(1) when #1/<len> declares at least 9 name bytes (n is already validated ASCII 0x20..=0x7E of length 16):
      n if n.starts_with(b"__.SYMDEF") => with_subformat(Label::Ar, &AR_BSD_SYMDEF),
      n if n.starts_with(b"#1/") => {
          let is_symdef =
              (n[3] == b'9' || n[4].is_ascii_digit()) && eq_at(prefix, 68, b"__.SYMDEF");
          with_subformat(Label::Ar, if is_symdef { &AR_BSD_SYMDEF } else { &AR_BSD_EXT })
      }
      plus a unit test in resolvers_populate_o1_header_subformats for a #1/12 or #1/20 __.SYMDEF archive.
  2. [medium] rust/lib/src/resolvers/magic/verifiers/category/audio.rs:135-165 — Multiplexed Ogg files with an Ogg Skeleton (fishead\0) track report "Ogg Skeleton" (fmt/944) instead of their media codec (fmt/945 Ogg Theora, fmt/203 Ogg Vorbis, etc.)

    • Why: Per the Xiph Ogg Skeleton 3.0/4.0 specification (and PRONOM fmt/945's variant signature), fishead\0 is a track-index metadata stream whose BOS page must appear as Page 0 (@0) of the physical Ogg bitstream, immediately ahead of the primary media track's BOS page (\x80theora, \x01vorbis, OpusHead, BBCD, etc.) at Page 1. Returning &OGG_SKELETON on Page 0 causes Skeleton-indexed .ogv/.oga files (such as ffmpeg2theora / Wikimedia Theora videos) to lose both their codec subformat ("Ogg Theora" / "Ogg Vorbis") and their specific PRONOM PUID (fmt/945 / fmt/203), falling back to generic fmt/944 / fdd000026.
    • Suggested fix: Because a fishead\0 BOS packet always fits in a single lacing segment (page_segments == 1: 64 bytes in Skeleton 3.0, 80 bytes in Skeleton 4.0, < 255), peeking at Page 1 requires no loop or scan — just one O(1) offset jump next = payload_off + usize::from(prefix[HEADER_FIXED_LEN]):
      if let Some(mut sub) = prefix.get(payload_off..).and_then(bos_subformat) {
          if core::ptr::eq(sub, &OGG_SKELETON)
              && page_segments == 1
              && let Some(seg_len) = u8_at(prefix, HEADER_FIXED_LEN)
          {
              let next = payload_off + usize::from(seg_len);
              if eq_at(prefix, next, MAGIC)
                  && matches!(u8_at(prefix, next + HEADER_TYPE), Some(0x02 | 0x06))
                  && le32(prefix, next + PAGE_SEQ_NO) == Some(0)
                  && let Some(next_segs @ 1..) = u8_at(prefix, next + PAGE_SEGMENTS)
                  && let Some(media_sub) = prefix
                      .get(next + HEADER_FIXED_LEN + usize::from(next_segs)..)
                      .and_then(bos_subformat)
                  && !core::ptr::eq(media_sub, &OGG_SKELETON)
              {
                  sub = media_sub;
              }
          }
          return with_subformat(Label::Ogg, sub);
      }
      Skeleton-only stubs (!ogg_skeleton.ogx) continue to return "Ogg Skeleton", while Skeleton+Theora / Skeleton+Vorbis files resolve to their media codec and PUID/FDD.
  3. [medium] tests_data/resolvers/subformats/* & rust/lib/src/resolvers.rs:612-1243 — 93 committed synthetic binary stubs (including 11 truncated ISOBMFF boxes and an undocumented ! filename prefix) vs. in-memory test builders

    • Why:
      • #1624 tested 437 subformats across 129 content types with zero committed binary files, using readable in-memory slice builders in resolvers.rs (matching AGENTS.md and website-ng/src/content/docs/contributing/developer-guide.md:95), and this PR already tests the same verifiers in memory in resolvers_populate_magic32_subformats and resolvers_populate_o1_header_subformats (resolvers.rs:1246-1463). All 93 files in tests_data/resolvers/subformats/ are synthetic zero-filled stubs (4–27 nonzero bytes, or output of the archive(&[stored(b"mimetype", ...)], b"") helper at resolvers.rs:1469), which are opaque in git diff and add ~590 lines of table boilerplate in resolvers.rs:612-1200.
      • Inside the committed fixtures:
        1. All 11 tests_data/resolvers/subformats/isobmff/* files are 16 bytes on disk (0x10) yet declare box_len = 20 (0x14) or 24 (0x18) at @0..4, leaving every ISOBMFF fixture truncated mid-ftyp box (box_len > file_size).
        2. 59 of the 93 filenames start with !, but unlike resolvers_identify_fixtures (resolvers.rs:298), resolvers_identify_subformat_fixtures never strips or checks !, tests_data/README.md still only lists basic/ and mitra/, and ! is applied inconsistently across equally synthetic/truncated stubs (e.g. isobmff/3gp_r4.3gp, heif_heic.heic, elf/elf64_le_dyn.elf, and sqlite/*.sqlite have no !, whereas !3gp_r6.3gp and !elf64_le_exec.elf do).
    • Options:
      • Option A (Preferred unless external tools consume this directory): Drop tests_data/resolvers/subformats/ and fold any cases not already covered by resolvers_populate_magic32_subformats / resolvers_populate_o1_header_subformats into in-memory builders in rust/lib/src/resolvers.rs (matching #1624).
      • Option B (If an on-disk subformat micro-corpus is intentionally wanted alongside tests_data/resolvers/fixtures for multi-tool comparison): Fix the 11 isobmff/* fixtures so box_len matches the file length (0x10 or pad to 20/24 bytes), and document resolvers/{fixtures,subformats} and the ! filename prefix convention in tests_data/README.md (and/or a comment on resolvers_identify_subformat_fixtures).
  4. [nit] rust/lib/src/resolvers/magic/verifiers/meta/zip.rs:863-865 — ZIP_EMPTY_ARCHIVE on size > 22 vs. commented empty ZIPs

    • if size >= 22 && prefix.len() >= 22 && starts(prefix, ZIP_EMPTY_ARCHIVE) labels inputs with size > 22 and !valid (22 empty-EOCD bytes followed by trailing bytes) as "Empty ZIP archive", whereas a valid empty ZIP with an archive comment (valid with PK\x05\x06 + 16 zero bytes at @0..20 and comment_len > 0 at @20..22) falls through to if valid and gets bare Label::Zip. Gating &ZIP_EMPTY on (valid && starts(prefix, bytes!(ZIP_EOCD_SIGNATURE, &[0u8; 16]))) || (size == 22 && starts(prefix, ZIP_EMPTY_ARCHIVE)) (while still returning bare Some(Label::Zip) for size > 22 && starts(prefix, ZIP_EMPTY_ARCHIVE) so ContentType stays identical) handles both cleanly.
  5. [nit] rust/lib/src/resolvers/magic/verifiers/overlap.rs:58 — JVM .class major version 45

    • Major version 45 covers both JDK 1.0.2 (45.0..=45.3) and JDK 1.1 (45.3..=45.65535); "Java 1.0/1.1 class file" (or checking minor at @4) is slightly more exact, though "Java 1.1 class file" matches common file(1) convention.

Questions / Notes

  • Intent of tests_data/resolvers/subformats/: Is this directory intended for external multi-tool benchmarking (like Mitra / tests_data/resolvers/fixtures), or purely for rust/lib unit tests?
  • SQLite "Sqlr" (APP_SQLAR): Note that SQLite's built-in sqlite3 -Ac SQLAR archiver (shell.c.in) leaves application_id == 0 rather than "Sqlr"; keeping APP_SQLAR is harmless (zero false-positive risk, and files with application_id == 0 stay bare Label::Sqlite), just worth noting that sqlite3 -Ac archives won't hit this branch.

@corkamig
corkamig force-pushed the resolvers-magic32-subformats branch from 7b65fd6 to 70fd4f0 Compare November 18, 2026 05:07
@corkamig

corkamig commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review! Rebased onto main and addressed all items in 70fd4f0:

  1. ar.rs (#1/<len> + __.SYMDEF): Fixed in O(1) — parses the decimal extended-name byte count in #1/<len> (ext_len >= 9, avoiding short zero-padded headers like #1/05 where payload bytes bleed into @68..77) and checks @68 for b"__.SYMDEF", with unit tests covering #1/9, #1/12, #1/16 (__.SYMDEF_64), #1/20 (__.SYMDEF SORTED), #1/05, truncated 68-byte headers, and malformed #1/ headers.
  2. audio.rs (Ogg Skeleton fishead\0 Page 0): Fixed in O(1) without a loop — when Page 0 is OGG_SKELETON with page_segments == 1, peeks once at Page 1 (next = payload_off + usize::from(seg_len)) and promotes to the primary media BOS subformat + PUID/FDD (Ogg Theora fmt/945, Ogg Vorbis fmt/203/fdd000117, Ogg Opus fmt/946, etc.), while keeping "Ogg Skeleton" (fmt/944) for Skeleton-only, non-BOS (fisbone\0), seq_no != 0, or truncated inputs.
  3. tests_data/ fixtures, _isobmff/ box lengths & "!" prefix:
    • Keeping fixtures & removing subformats/: Unprefixed fixtures are hollowed, truncated minimal headers from real samples — they preserve real-world header geometry while staying shareable and PII-free (including for multi-tool comparison alongside mitra/). Agreed they did not belong in a separate subformats/ tree: moved all 93 files directly into tests_data/resolvers/fixtures/ under the existing <category>/ and _<metaformat>/ layout (_ar/, _elf/, _isobmff/, _macho/, _ogg/, _pe/, _riff/, _sqlite/, _tiff/, _zip/, bytecode/) and unified resolvers_identify_fixtures() (310 primary + 93 subformat fixtures, including path vs. pathless parity).
    • 11 _isobmff/ fixtures: Grew all 11 files back from 16 B to their declared ftyp box_len (24 B for 3gp_r4.3gp, 20 B for the other 10) so file_size == box_len with realistic ftyp box sizes.
    • "!" filename convention: Kept "!" (matching the 8 existing "!" fixtures from rust/lib:rewrite standard resolvers #1606) and documented both resolvers/fixtures/ and "!" in tests_data/README.md: "!" marks fixtures synthesized from format specifications — either when no redistributable wild sample is available yet, or forcibly synthesized whenever wild samples carry PII or security risk.
  4. zip.rs (empty ZIP gating): Commented empty ZIPs (valid with PK\x05\x06 + 16 zero bytes) now report "Empty ZIP archive", while size > 22 && !valid trailing-byte inputs return bare Label::Zip (preserving ContentType).
  5. overlap.rs (JVM .class major 45): Updated to "Java 1.0/1.1 class file".
  6. SQLAR ("Sqlr") note: Indeed, there are at least 3 SQLAR implementations/DDL variants in the wild, and sqlite3 -Ac leaves application_id == 0. Keeping APP_SQLAR here covers the "Sqlr" (0x53716C72) header application_id in O(1), while resolvers: add SQLite subformats identification via schema parsing (header, hashes, tables, anchors) #1631 covers application_id == 0 SQLAR archives via normalized schema matching (sqlar(name, mode, mtime, sz, data)).

(Note on CI: all 23 Rust/Python/JS/KB/CodeQL checks are green; the Go - build and run tests failure is an unrelated upstream outage — github.com/microsoft/onnxruntime is currently returning HTTP 404, so go/docker/Dockerfile fails downloading onnxruntime-linux-x64-1.19.2.tgz.)

Record subformat names (and more specific PRONOM PUID / LoC FDD overrides
where applicable) from header fields already parsed and validated by the
ISOBMFF, SQLite 3, ELF, Mach-O, Windows PE, and Java .class verifiers:

- ISOBMFF: name all MP4, HEIF, and 3GPP major brands without altering
  the brand allowlists, replacing linear slice scans with direct matches.
- SQLite 3: distinguish MBTiles header vs schema matches and map
  well-known registered application_id values at @68 on Label::Sqlite.
- ELF: combine already-validated class, endianness, and e_type (@16) via
  a static lookup table while preserving fmt/688..fmt/691.
- Mach-O: combine already-validated width, endianness, and filetype (@12)
  via a static lookup table while preserving fmt/692 and fmt/693.
- Windows PE: combine PE32/PE32+, DLL flag, and subsystem (@68) in a
  single header pass, removing the redundant e_lfanew re-read.
- Java .class: map already-validated major versions 45..=71 (@6) to
  Java 1.1..Java 27 class files while keeping 72..=80 as bare javabytecode.

No ContentType decisions, VETOS, or KB outputs are changed. Adds minimal
subformat fixtures under tests_data/resolvers/subformats/ and unit tests.
… and ZIP

Populate finer-grained `subformat` metadata (and more specific PRONOM PUID /
LoC FDD identifiers where standardized) for five magic32-dispatched
metaformats using only O(1) fixed-offset header checks within already-matched
containers, with zero scanning and zero changes to `ContentType` decisions,
`VETOS`, or generated KB artifacts:

- Ogg (`audio.rs`): inspect the BOS identification packet header at
  `@(27 + page_segments)` via a single-byte switch (Vorbis `fmt/203`/
  `fdd000117`, Opus `fmt/946`, Theora `fmt/945`, FLAC `fmt/947`/`fdd000227`,
  Speex `fmt/948`/`fdd000260`, Skeleton, Kate, CELT, Dirac, Daala, MIDI, PCM).
- Unix ar (`ar.rs`): classify the first member header name at `@8..24` on
  `Label::Ar` (GNU/SVR4 symbol table, 64-bit symbol table, long filename
  table, BSD/macOS symbol table, BSD extended filename).
- RIFF/RIFX WAVE (`riff.rs`): inspect only the initial chunk at `@12`
  (`"fmt "` + `wFormatTag` at `@20` for PCM `fmt/141`/`fdd000002`, Extensible
  `fmt/143`/`fdd000001`, MS ADPCM, IEEE float, A-Law, mu-Law, IMA ADPCM, MP3;
  `"bext"` + EBU Tech 3285 `Version` at `@366` for Broadcast WAVE v0 `fmt/1`,
  v1 `fmt/2`/`fdd000356`, v2 `fmt/527`/`fdd000357`, and generic BWF; plus
  big-endian `RIFX WAVE` format tags) without walking chunks.
- TIFF (`image.rs`): recognize Canon RAW 2 (`"CR\x02\x00"` at `@8..12` with
  IFD0 offset >= 16) on little-endian TIFF (`fmt/592`/`fdd000241`).
- ZIP (`zip.rs`): reuse the already-extracted stored `"mimetype"` first-entry
  payload on `Label::Zip` fallback paths for OpenDocument subtypes/templates
  (`odg`, `odf`, `odb`, `odc`, `odi`, `ott`, `ots`, `otp`, `otg`, `odm` with
  `fdd000247`), Krita (`fmt/999`), OpenRaster (`fmt/998`), and Adobe InDesign
  IDML (`fmt/1184`), plus `Empty ZIP archive` on 22-byte EOCD archives.

Adds 40 minimal subformat test fixtures under
`tests_data/resolvers/subformats/{ar,ogg,tiff,wav,zip}/` and unit tests
covering both fixtures and boundary/edge cases.
Map the SQLite 3 application_id "RFLT" (@68) to "Reflet database (.reflet)"
on Label::Sqlite and add a minimal 132-byte header fixture under
tests_data/resolvers/subformats/sqlite/reflet.reflet with test coverage.
@reyammer
reyammer force-pushed the resolvers-magic32-subformats branch from 70fd4f0 to e34140a Compare November 18, 2026 15:39
@reyammer
reyammer enabled auto-merge November 18, 2026 15:39
@reyammer

Copy link
Copy Markdown
Collaborator

Thank you! Merging.

@reyammer
reyammer merged commit c63f4aa into google:main Nov 18, 2026
31 of 32 checks passed
mvanhorn added a commit to mvanhorn/magika that referenced this pull request Nov 18, 2026
Resolve the conflict with google#1628 by taking main's ftyp verifier; the
mif1 handling is reworked in the next commit.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants