musicbrainz: tier-B offline pack generator and mmap reader
- Commit
6405673f0ac56ecc59150a9802c5eca199bd639d- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-20 21:02 UTC (3 months ago)
- Parents
9c6763f
Diff
scripts/musicbrainz/mb_ingest/.gitignore
diff --git a/scripts/musicbrainz/mb_ingest/.gitignore b/scripts/musicbrainz/mb_ingest/.gitignorenew file mode 100644index 0000000000..ea8c4bf7f3--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/.gitignore@@ -0,0 +1 @@+/target
scripts/musicbrainz/mb_ingest/Cargo.lock
diff --git a/scripts/musicbrainz/mb_ingest/Cargo.lock b/scripts/musicbrainz/mb_ingest/Cargo.locknew file mode 100644index 0000000000..4a863f7f3a--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/Cargo.lock@@ -0,0 +1,7 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "mb_ingest"+version = "0.1.0"
scripts/musicbrainz/mb_ingest/Cargo.toml
diff --git a/scripts/musicbrainz/mb_ingest/Cargo.toml b/scripts/musicbrainz/mb_ingest/Cargo.tomlnew file mode 100644index 0000000000..875161bab4--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/Cargo.toml@@ -0,0 +1,35 @@+# Host-side MusicBrainz ingest tool for the offline MusicBrainz pack ("MBP1").+#+# Deliberately DETACHED from the repo-root Rust workspace (the empty [workspace]+# table below), exactly as scripts/maps/gtfs_ingest is: it is a std-only host+# crate with zero external dependencies, so `cargo build` here resolves offline+# and never pulls the aarch64-android toolchain or the app crates' lints.+#+# It is a LIBRARY plus a thin CLI. The library half is consumed two ways:+# * `mb_ingest::build` turns an mbdump full export into a `.pack`;+# * `mb_ingest::reader` reads a `.pack` back, and is what the server calls+# in-process (see src/reader.rs -- it takes a &[u8], so the caller owns the+# mmap and this crate needs no memmap dependency).+[package]+name = "mb_ingest"+version = "0.1.0"+edition = "2021"+publish = false+license = "GPL-2.0-only"+description = "MusicBrainz mbdump -> compact offline pack for the musicbrainz app"++[lib]+name = "mb_ingest"+path = "src/lib.rs"++[[bin]]+name = "mb_ingest"+path = "src/main.rs"++[dependencies]++[profile.release]+opt-level = 3++# Detach from the repo-root workspace so this host tool builds standalone/offline.+[workspace]
scripts/musicbrainz/mb_ingest/README.md
diff --git a/scripts/musicbrainz/mb_ingest/README.md b/scripts/musicbrainz/mb_ingest/README.mdnew file mode 100644index 0000000000..8b4a7392c2--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/README.md@@ -0,0 +1,172 @@+# `mb_ingest` — MusicBrainz offline pack builder and reader++Turns a MusicBrainz full export into one mmap-able `.pack` file, and reads it+back. The point is to delete the `musicbrainz` app's dependence on the WS/2 API,+whose 1 req/s client-side rate limiter (`MusicBrainzApi.kt:21-40`) is what makes+the artist screen take 3-5 seconds — two serialised calls, not network latency.++Design: `c:\Users\Vayun\.llms\plans\mb_pack.plan.md` (pack-designer, task 2).+Format spec: the `//!` header of `src/pack.rs`, which is the source of truth.+Reader: `src/reader.rs`, which must stay in sync with it.++Detached from the repo-root Cargo workspace and dependency-free, the same+convention as `scripts/maps/gtfs_ingest`.++## Use++```sh+cargo build --release++# Build from the real export. Either a .tar.bz2 (streamed through `tar`, nothing+# is extracted to disk) or a directory of already-extracted tables.+./target/release/mb_ingest build mbdump.tar.bz2 musicbrainz.pack++# Prove the whole pipeline on a synthetic dump in ~a second.+./target/release/mb_ingest fixture /tmp/mb/mbdump+./target/release/mb_ingest build /tmp/mb musicbrainz.pack+./target/release/mb_ingest inspect musicbrainz.pack++cargo test # 31 tests, including a full round trip through the reader+```++Flags: `--tier-a` adds track MBIDs (+918 MB at full scale), `--official-only`+drops the 9.4% of releases that are not Official, `--no-isrcs`,+`--no-recording-search`, `--no-recording-mbids`.++## Input++Only **`mbdump.tar.bz2`** (7 GB) is needed. Verified against the live export+(`20260819-002541`), not assumed:++* core-dump members are `mbdump/<table>`, unprefixed, in ASCII order, after+ `TIMESTAMP`, `COPYING`, `README`, `REPLICATION_SEQUENCE`, `SCHEMA_SEQUENCE`.+ The non-`musicbrainz`-schema dumps use `mbdump/<schema>.<table>` instead.+* tables are PostgreSQL `COPY` TEXT: TAB-separated, `\N` for NULL, backslash+ escapes for embedded tabs and newlines. Real titles contain both, so the+ unescaping in `src/copy.rs` is load-bearing.++Tables read: `area`, `iso_3166_1`, `artist_type`,+`release_group_primary_type`, `release_group_secondary_type`, `release_status`,+`medium_format`, `artist_credit`, `artist_credit_name`, `artist`,+`release_group`, `release_group_meta`,+`release_group_secondary_type_join`, `release`, `release_country`,+`release_unknown_country`, `medium`, `recording`, `track`, `isrc`.++**`mbdump-derived.tar.bz2` is not needed** — it holds annotations, ratings, user+tags and search indexes, none of which the app requests, and depending on it+would drag in `mbdump-editor.tar.bz2` as well. `mbdump-edit.tar.bz2` (15 GB) is+irrelevant.++Column order is hard-coded from `admin/sql/CreateTables.sql` (schema sequence 31)+and every table's arity plus its distinctive columns are checked on the first row.+If MusicBrainz reorders a column the build stops with the table name rather than+producing a plausible-looking wrong pack.++### Integrity++The export directory publishes `SHA256SUMS` and `SHA256SUMS.asc`. Verify the+checksum as a baseline; verifying `SHA256SUMS.asc` against MusicBrainz's GPG key+`C777580F` (fingerprint `D5E6 3B4B DCCE 1956 4294 8684 B8FC 2375 C777 580F`) is+strictly stronger, because it authenticates the checksum list itself rather than+only detecting truncation.++## What it costs at full scale++Row counts are pack-designer's measurements from `musicbrainz.org/statistics`+(retrieved 2026-08-20, page dated 2026-08-19). `MB` means 10⁶ bytes. These are+**projections from the measured row counts, not from a completed full run** — the+7 GB dump has not been downloaded.++| section | MB |+|---|---|+| `STRINGS` (uncompressed) | 635 |+| `RECORDING_MBID` | 638 |+| `RECORDINGS` | 359 |+| `TRACKS` (varint, overrides inline) | ~235 |+| `SEARCH_POSTINGS` | ~173 |+| `REC_FIRST_RELEASE` | 160 |+| `RELEASES` + `RELEASE_MBID` | 217 |+| `RELEASE_GROUPS` + `RG_MBID` | 134 |+| `ARTISTS` + `ARTIST_MBID` | 101 |+| `ISRCS` | 69 |+| `SEARCH_TERMS` + `SEARCH_TERM_IDX` | ~88 |+| CSR indexes, `MEDIA`, `CREDITS`, buckets | ~158 |+| **total, tier B** | **~2 970** |++**~2.97 GB as built today.** The single biggest lever left is the string pool:+block-compressing it with zstd takes 635 MB to ~181 MB, i.e. **~2.51 GB**, at the+cost of this crate's zero-dependency property and of zero-copy string reads. The+header reserves a flag and a section for it (`FLAG_STRINGS_COMPRESSED`,+`STRINGS_BLKIDX`) and the reader refuses such a pack rather than misreading it, so+turning it on later is not a format break. Other levers, in order:+`REC_FIRST_RELEASE` is 160 MB for one field of one search result row;+delta-coding `ISRCS` in blocks saves ~44 MB; `SEARCH_TERM_IDX` can lose ~22 MB.++Tier A (add track MBIDs) is ~3.89 GB. Nothing else in the tier ladder is+implemented as a filter beyond `--official-only`.++## Where the memory goes++Peak RSS, not wall time, is the binding constraint. Two rules the code follows:++* **`TRACKS` is never a `Vec<TrackRec>`.** It is built as a varint byte stream as+ the tracks are visited. This is the failure recorded at+ `scripts/maps/gtfs_ingest/src/index.rs:15-27`, where a fixed-size record per+ stop per trip made a world transit pack 10-20 GB and overflowed a u32.+* **id maps are dense `Vec<u32>` keyed by the dump's integer primary key**, not+ hash maps keyed by MBID. The dumps use integer foreign keys, so the recording+ map is ~180 MB rather than the ~2 GB a `HashMap<[u8;16], u32>` would cost. The+ design doc assumed the latter.++Section offsets and lengths are u64, so the file may exceed 4 GB. The u32+ceilings that remain are checked and asserted: the string pool (635 MB raw, 6.8x+headroom — the first field that would break if scope grew), the `TRACKS` byte+length, and the 30-bit entity index inside a search posting.++Projected peak for a full run, again a projection and not a measurement:++| structure | MB |+|---|---|+| `track` sort buffer (57.4 M x 28 B) | ~1 600 |+| recording rows + gids, dense by id | ~1 100 |+| string pool + its open-addressed index | ~900 |+| search postings before grouping | ~700 |+| output section buffers | ~1 200 |+| dense id maps | ~300 |+| **peak** | **~5-6 GB** |++An external merge sort for the track pass, and spilling the output sections to+temporary files, are the two changes that would bring that down if a build has to+run somewhere smaller. Wall time is dominated by bz2 decompression: `tar` is+invoked once per table, so the archive is decompressed ~20 times. Extracting the+20 tables once and building from the directory is much faster if the disk is+available (~13 GB for the tables this crate reads, versus ~40 GB for everything).++## What tier B gives up++Track MBIDs, and therefore the `MUSICBRAINZ_RELEASETRACKID` Vorbis tag. Nothing+else. `LibrarySnapshot.hasTrack` (`data/library/LibraryIndex.kt:30-42`) is a+four-tier cascade with every parameter nullable; dropping the tag removes tier 1+only, and recording MBIDs — tier 2, also exact — are in the pack. The precision+that tag adds is already absent for most of a real library, because+`MatchKeys.trackKey` is release-agnostic by construction.++Also given up, deliberately:++* **there is no `recording_by_mbid` and no `track_by_mbid`.** Recordings are+ stored in tracklist-clustered order, which is what makes the `TRACKS` deltas+ cheap; a sorted MBID index would cost more than it saves. The WS/2 endpoint+ that would have needed it is dead code with no callers.+* **search is word-prefix, not substring and not Lucene.** "dark side" finds+ "The Dark Side of the Moon"; "loitude" does not find "Solitude". Query words are+ ANDed. Results will differ from musicbrainz.org.+* a track's own `length` is kept (inline, only when it differs from the+ recording's), but as **seconds, not milliseconds** — the UI renders m:ss, Tidal+ matching uses a ±3 s tolerance and LRCLIB takes seconds.++## Possible follow-up, not in scope here++`mbdump-cover-art-archive.tar.bz2` (158 MB) records which releases actually have+cover art. The app currently builds coverartarchive.org URLs blindly and absorbs+the 404s. A presence bitmap over the 5.7 M releases is ~0.7 MB in the pack and+would remove those wasted round trips.
scripts/musicbrainz/mb_ingest/src/build.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/build.rs b/scripts/musicbrainz/mb_ingest/src/build.rsnew file mode 100644index 0000000000..e7cc289d7e--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/src/build.rs@@ -0,0 +1,1283 @@+//! The ingest passes: mbdump tables in, one `.pack` out.+//!+//! Column orders are hard-coded from the MusicBrainz schema's+//! `admin/sql/CreateTables.sql` and every table's arity and distinctive columns+//! are checked on the first row (see `copy::Shape`), because a silently shifted+//! column would produce a plausible-looking but wrong pack.+//!+//! # Memory+//!+//! Peak RSS is the binding constraint, not wall time. Two rules:+//!+//! * per-row data is never accumulated for the output. `TRACKS` is built as a+//! varint byte stream as the tracks are visited, not as a `Vec<TrackRec>` —+//! that is the failure recorded in `scripts/maps/gtfs_ingest/src/index.rs:15-27`,+//! where a fixed-size record per stop per trip made a world pack 10-20 GB.+//! * id -> index maps are dense `Vec<u32>` keyed by the dump's integer primary+//! key, not `HashMap<[u8;16], u32>` keyed by MBID. The dumps use integer+//! foreign keys, so at full scale the recording map is ~180 MB instead of the+//! ~2 GB a gid hash map would cost.+//!+//! One buffer is genuinely large and unavoidable without an external sort: the+//! `track` rows have to be grouped by medium, and the dump is in primary-key+//! order, so 57.4 M x 24 B = ~1.4 GB is held while sorting. `BuildStats` reports+//! it. An external merge sort would remove it if a full run ever needs to fit in+//! less.++use std::collections::HashMap;+use std::io::{self, Seek, Write};++use crate::copy::{other_err, Input, Row, Shape};+use crate::pack::{+ self, build_mbid_table, pack_date, pack_isrc, parse_mbid, search_terms, EnumPool, HeaderCounts,+ Mbid, PackWriter, StringPool,+};+use crate::reader::encode_recording_credit;++/// Guard against a hostile or corrupt dump asking us to allocate a dense map for+/// an absurd primary key.+const MAX_ID: u32 = 400_000_000;++#[derive(Clone, Copy)]+pub struct BuildOptions {+ pub include_track_mbids: bool,+ pub include_recording_mbids: bool,+ pub include_isrcs: bool,+ pub include_recording_search: bool,+ pub official_only: bool,+ pub verbose: bool,+}++impl Default for BuildOptions {+ /// Tier B of the design doc's §2.4: everything except track MBIDs, which is+ /// the single 918 MB section and the only thing tier B gives up.+ fn default() -> Self {+ BuildOptions {+ include_track_mbids: false,+ include_recording_mbids: true,+ include_isrcs: true,+ include_recording_search: true,+ official_only: false,+ verbose: false,+ }+ }+}++impl BuildOptions {+ pub fn tier_a() -> Self {+ BuildOptions { include_track_mbids: true, ..Self::default() }+ }++ fn flags(&self) -> u32 {+ let mut f = 0;+ if self.include_track_mbids {+ f |= pack::FLAG_TRACK_MBIDS;+ }+ if self.include_recording_mbids {+ f |= pack::FLAG_RECORDING_MBIDS;+ }+ if self.include_isrcs {+ f |= pack::FLAG_ISRCS;+ }+ if self.include_recording_search {+ f |= pack::FLAG_RECORDING_SEARCH;+ }+ if self.official_only {+ f |= pack::FLAG_OFFICIAL_ONLY;+ }+ f+ }+}++/// The measured numbers a build prints. The four ratios were estimates in the+/// design doc (its R2, ~285 MB of budget between them); a real run closes them.+#[derive(Default)]+pub struct BuildStats {+ pub rows: Vec<(&'static str, u64)>,+ pub sections: Vec<(&'static str, u64)>,+ pub total_bytes: u64,+ pub distinct_strings: usize,+ pub string_pool_bytes: usize,+ pub recording_titles: u64,+ pub distinct_recording_titles: u64,+ pub tracks_title_same: u64,+ pub tracks_credit_same: u64,+ pub tracks_length_same: u64,+ pub standalone_recordings: u64,+ pub skipped: Vec<(&'static str, u64)>,+ pub isrc_rejects: u64,+ pub track_sort_buffer_bytes: u64,+ pub dense_map_bytes: u64,+ pub search_postings: u64,+}++impl BuildStats {+ pub fn report(&self) -> String {+ let mb = |b: u64| b as f64 / 1_000_000.0;+ let pct = |a: u64, b: u64| if b == 0 { 0.0 } else { 100.0 * a as f64 / b as f64 };+ let mut s = String::new();+ s.push_str("input rows\n");+ for (name, n) in &self.rows {+ s.push_str(&format!(" {name:<38} {n:>12}\n"));+ }+ if !self.skipped.is_empty() {+ s.push_str("skipped (dangling or filtered)\n");+ for (name, n) in &self.skipped {+ s.push_str(&format!(" {name:<38} {n:>12}\n"));+ }+ }+ s.push_str("sections\n");+ for (name, len) in &self.sections {+ if *len > 0 {+ s.push_str(&format!(" {name:<38} {:>12.1} MB\n", mb(*len)));+ }+ }+ s.push_str(&format!(" {:<38} {:>12.1} MB\n", "TOTAL", mb(self.total_bytes)));+ s.push_str("measured ratios (design doc R2 -- these were estimates)\n");+ s.push_str(&format!(+ " {:<38} {:>11.1}% ({} of {})\n",+ "distinct recording titles",+ pct(self.distinct_recording_titles, self.recording_titles),+ self.distinct_recording_titles,+ self.recording_titles+ ));+ let tracks = self.rows.iter().find(|(n, _)| *n == "track").map(|(_, n)| *n).unwrap_or(0);+ s.push_str(&format!(+ " {:<38} {:>11.1}%\n",+ "tracks whose title == recording's",+ pct(self.tracks_title_same, tracks)+ ));+ s.push_str(&format!(+ " {:<38} {:>11.1}%\n",+ "tracks whose credit == recording's",+ pct(self.tracks_credit_same, tracks)+ ));+ s.push_str(&format!(+ " {:<38} {:>11.1}%\n",+ "tracks whose length == recording's",+ pct(self.tracks_length_same, tracks)+ ));+ let recs =+ self.rows.iter().find(|(n, _)| *n == "recording").map(|(_, n)| *n).unwrap_or(0);+ s.push_str(&format!(+ " {:<38} {:>11.1}% ({})\n",+ "recordings with no track (standalone)",+ pct(self.standalone_recordings, recs),+ self.standalone_recordings+ ));+ s.push_str("build cost\n");+ s.push_str(&format!(+ " {:<38} {:>12.1} MB\n",+ "string pool (raw)",+ mb(self.string_pool_bytes as u64)+ ));+ s.push_str(&format!(" {:<38} {:>12}\n", "distinct strings", self.distinct_strings));+ s.push_str(&format!(" {:<38} {:>12}\n", "search postings", self.search_postings));+ s.push_str(&format!(+ " {:<38} {:>12.1} MB\n",+ "track sort buffer (peak, transient)",+ mb(self.track_sort_buffer_bytes)+ ));+ s.push_str(&format!(+ " {:<38} {:>12.1} MB\n",+ "dense id -> index maps",+ mb(self.dense_map_bytes)+ ));+ if self.isrc_rejects > 0 {+ s.push_str(&format!(" {:<38} {:>12}\n", "malformed ISRCs dropped", self.isrc_rejects));+ }+ s+ }+}++/// A dense `primary key -> index` map.+struct DenseMap {+ v: Vec<u32>,+}++impl DenseMap {+ fn new() -> DenseMap {+ DenseMap { v: Vec::new() }+ }++ fn set(&mut self, id: u32, val: u32) -> io::Result<()> {+ if id > MAX_ID {+ return Err(other_err(format!("primary key {id} exceeds the sanity ceiling {MAX_ID}")));+ }+ if self.v.len() <= id as usize {+ self.v.resize(id as usize + 1, pack::NONE);+ }+ self.v[id as usize] = val;+ Ok(())+ }++ fn get(&self, id: u32) -> Option<u32> {+ match self.v.get(id as usize) {+ Some(&v) if v != pack::NONE => Some(v),+ _ => None,+ }+ }++ fn bytes(&self) -> u64 {+ (self.v.len() * 4) as u64+ }+}++// --- intermediate rows ---++struct ArtistBuild {+ gid: Mbid,+ name_off: u32,+ disamb_off: u32,+ area_off: u32,+ begin_date: u32,+ kind: u16,+ country: u16,+ id: u32,+}++struct RgBuild {+ gid: Mbid,+ title_off: u32,+ first_date: u32,+ credit_id: u32,+ primary: u16,+ secondary: u16,+ secondary_src_id: u32,+ id: u32,+}++struct ReleaseBuild {+ gid: Mbid,+ title_off: u32,+ rg_id: u32,+ credit_id: u32,+ date: u32,+ disamb_off: u32,+ status: u16,+ status_rank: u8,+ country: u16,+ id: u32,+}++struct MediumBuild {+ id: u32,+ release_idx: u32,+ position: i32,+ format: u16,+ track_count: u32,+}++#[derive(Clone, Copy)]+struct TrackBuild {+ medium_idx: u32,+ /// `i32`, not `i64`: `track.position` is a Postgres INTEGER, and the wider+ /// field would push this record from 28 to 32 bytes, which is 240 MB of peak+ /// RSS across 57.4 M rows.+ position: i32,+ recording_id: u32,+ title_off: u32,+ credit_id: u32,+ length_s: u16,+ /// Index into `track_gids`, which is only populated for tier A. Kept out of+ /// this record so a tier B build does not carry 16 B x 57 M of MBIDs it is+ /// never going to write.+ gid_slot: u32,+}++#[derive(Clone, Copy, Default)]+struct RecBuild {+ title_off: u32,+ credit_id: u32,+ dur_s: u16,+}++/// Build a pack from `input` and write it to `out`.+pub fn build<W: Write + Seek>(+ input: &Input,+ out: W,+ opts: &BuildOptions,+ log: &mut dyn Write,+) -> io::Result<BuildStats> {+ let mut st = BuildStats::default();+ let mut pool = StringPool::new();+ let mut enums = EnumPool::new();+ macro_rules! step {+ ($($arg:tt)*) => { if opts.verbose { writeln!(log, $($arg)*)?; } };+ }++ // --- areas and the small enumerations -------------------------------------+ step!("pass 1: areas, country codes, enumerations");+ let mut area_name: HashMap<u32, u32> = HashMap::new();+ let n = require(+ input,+ "area",+ Shape { table: "area", min_fields: 14, ints: &[0], uuids: &[1] },+ |row| {+ if let Some(id) = row.u32(0) {+ let off = pool.intern(&row.str(2));+ area_name.insert(id, off);+ }+ Ok(())+ },+ )?;+ st.rows.push(("area", n));++ let mut area_country: HashMap<u32, u16> = HashMap::new();+ let n = require(+ input,+ "iso_3166_1",+ Shape { table: "iso_3166_1", min_fields: 2, ints: &[0], uuids: &[] },+ |row| {+ if let Some(area) = row.u32(0) {+ let code = row.str(1);+ let code = code.trim();+ if !code.is_empty() {+ let e = enums.intern(&mut pool, code);+ area_country.insert(area, e);+ }+ }+ Ok(())+ },+ )?;+ st.rows.push(("iso_3166_1", n));++ let artist_types = read_enum_table(input, "artist_type", &mut pool, &mut enums)?;+ let rg_primary = read_enum_table(input, "release_group_primary_type", &mut pool, &mut enums)?;+ let rg_secondary =+ read_enum_table(input, "release_group_secondary_type", &mut pool, &mut enums)?;+ let statuses = read_enum_table(input, "release_status", &mut pool, &mut enums)?;+ let formats = read_enum_table(input, "medium_format", &mut pool, &mut enums)?;++ // --- artist credits -------------------------------------------------------+ // A credit is stored as one pre-rendered display string ("A feat. B"), because+ // nothing in the app reads the per-artist breakdown -- only+ // MbArtistCredit.display(), which concatenates name + joinphrase. MusicBrainz+ // already stores exactly that string as `artist_credit.name`, so we take it+ // rather than re-deriving it from artist_credit_name and risking a different+ // join order. artist_credit_name is still needed, for the artist -> release+ // group links.+ step!("pass 2: artist credits");+ let mut credits_off: Vec<u32> = Vec::new();+ let n = require(+ input,+ "artist_credit",+ Shape { table: "artist_credit", min_fields: 7, ints: &[0, 2], uuids: &[6] },+ |row| {+ let Some(id) = row.u32(0) else { return Ok(()) };+ if id > MAX_ID {+ return Err(other_err(format!("artist_credit id {id} exceeds {MAX_ID}")));+ }+ let i = id as usize;+ if credits_off.len() <= i {+ credits_off.resize(i + 1, 0);+ }+ credits_off[i] = pool.intern(&row.str(1));+ Ok(())+ },+ )?;+ st.rows.push(("artist_credit", n));+ let credit_count = credits_off.len() as u32;++ let mut credit_artists: Vec<Vec<u32>> = vec![Vec::new(); credits_off.len()];+ let n = require(+ input,+ "artist_credit_name",+ Shape { table: "artist_credit_name", min_fields: 5, ints: &[0, 1, 2], uuids: &[] },+ |row| {+ let (Some(cid), Some(artist)) = (row.u32(0), row.u32(2)) else { return Ok(()) };+ if let Some(slot) = credit_artists.get_mut(cid as usize) {+ slot.push(artist);+ }+ Ok(())+ },+ )?;+ st.rows.push(("artist_credit_name", n));++ // --- artists --------------------------------------------------------------+ step!("pass 3: artists");+ let mut artists: Vec<ArtistBuild> = Vec::new();+ let mut bad_gids = 0u64;+ let n = require(+ input,+ "artist",+ Shape { table: "artist", min_fields: 19, ints: &[0], uuids: &[1] },+ |row| {+ let Some(id) = row.u32(0) else { return Ok(()) };+ let Some(gid) = parse_mbid(&row.str(1)) else {+ bad_gids += 1;+ return Ok(());+ };+ let area = row.u32(11);+ artists.push(ArtistBuild {+ gid,+ name_off: pool.intern(&row.str(2)),+ disamb_off: pool.intern(&row.str(13)),+ area_off: area.and_then(|a| area_name.get(&a).copied()).unwrap_or(0),+ begin_date: pack_date(row.i64(4), row.i64(5), row.i64(6)),+ kind: row+ .u32(10)+ .and_then(|t| artist_types.get(&t).copied())+ .unwrap_or(EnumPool::NONE_ENUM),+ country: area+ .and_then(|a| area_country.get(&a).copied())+ .unwrap_or(EnumPool::NONE_ENUM),+ id,+ });+ Ok(())+ },+ )?;+ st.rows.push(("artist", n));+ if bad_gids > 0 {+ st.skipped.push(("artist rows with an unparseable gid", bad_gids));+ }+ drop(area_name);++ artists.sort_unstable_by_key(|a| a.gid);+ let mut artist_idx = DenseMap::new();+ for (i, a) in artists.iter().enumerate() {+ artist_idx.set(a.id, i as u32)?;+ }++ // --- release groups -------------------------------------------------------+ step!("pass 4: release groups");+ let mut rgs: Vec<RgBuild> = Vec::new();+ let n = require(+ input,+ "release_group",+ Shape { table: "release_group", min_fields: 8, ints: &[0, 3], uuids: &[1] },+ |row| {+ let Some(id) = row.u32(0) else { return Ok(()) };+ let Some(gid) = parse_mbid(&row.str(1)) else { return Ok(()) };+ rgs.push(RgBuild {+ gid,+ title_off: pool.intern(&row.str(2)),+ first_date: 0,+ credit_id: row.u32(3).unwrap_or(pack::NONE),+ primary: row+ .u32(4)+ .and_then(|t| rg_primary.get(&t).copied())+ .unwrap_or(EnumPool::NONE_ENUM),+ secondary: EnumPool::NONE_ENUM,+ secondary_src_id: u32::MAX,+ id,+ });+ Ok(())+ },+ )?;+ st.rows.push(("release_group", n));+ let mut rg_slot = DenseMap::new();+ for (i, r) in rgs.iter().enumerate() {+ rg_slot.set(r.id, i as u32)?;+ }+ let n = require(+ input,+ "release_group_meta",+ Shape { table: "release_group_meta", min_fields: 7, ints: &[0], uuids: &[] },+ |row| {+ if let Some(slot) = row.u32(0).and_then(|id| rg_slot.get(id)) {+ rgs[slot as usize].first_date = pack_date(row.i64(2), row.i64(3), row.i64(4));+ }+ Ok(())+ },+ )?;+ st.rows.push(("release_group_meta", n));+ let n = require(+ input,+ "release_group_secondary_type_join",+ Shape {+ table: "release_group_secondary_type_join",+ min_fields: 2,+ ints: &[0, 1],+ uuids: &[],+ },+ |row| {+ let (Some(rg), Some(ty)) = (row.u32(0), row.u32(1)) else { return Ok(()) };+ if let Some(slot) = rg_slot.get(rg) {+ let r = &mut rgs[slot as usize];+ // The app only ever renders secondaryTypes[0]; pick the lowest type+ // id so the choice is deterministic across rebuilds.+ if ty < r.secondary_src_id {+ if let Some(&e) = rg_secondary.get(&ty) {+ r.secondary = e;+ r.secondary_src_id = ty;+ }+ }+ }+ Ok(())+ },+ )?;+ st.rows.push(("release_group_secondary_type_join", n));+ drop(rg_slot);++ rgs.sort_unstable_by_key(|r| r.gid);+ let mut rg_idx = DenseMap::new();+ for (i, r) in rgs.iter().enumerate() {+ rg_idx.set(r.id, i as u32)?;+ }++ // ARTIST_RGS: artist -> release groups, via the release group's credit.+ let mut artist_rg_pairs: Vec<(u32, u32)> = Vec::new();+ for (i, r) in rgs.iter().enumerate() {+ let Some(artists_of) = credit_artists.get(r.credit_id as usize) else { continue };+ for a in artists_of {+ if let Some(ai) = artist_idx.get(*a) {+ artist_rg_pairs.push((ai, i as u32));+ }+ }+ }+ // Newest first: the discography order MusicBrainzViewModel.kt:207 sorts into.+ artist_rg_pairs.sort_unstable_by(|x, y| {+ x.0.cmp(&y.0)+ .then(rgs[y.1 as usize].first_date.cmp(&rgs[x.1 as usize].first_date))+ .then(x.1.cmp(&y.1))+ });+ artist_rg_pairs.dedup();+ let (artist_rgs, artist_rgs_idx) = to_csr(&artist_rg_pairs, artists.len());+ drop(artist_rg_pairs);+ drop(credit_artists);++ // --- releases -------------------------------------------------------------+ step!("pass 5: releases");+ let mut releases: Vec<ReleaseBuild> = Vec::new();+ let mut filtered_status = 0u64;+ let n = require(+ input,+ "release",+ Shape { table: "release", min_fields: 14, ints: &[0, 3, 4], uuids: &[1] },+ |row| {+ let Some(id) = row.u32(0) else { return Ok(()) };+ let Some(gid) = parse_mbid(&row.str(1)) else { return Ok(()) };+ let Some(rg) = row.u32(4) else { return Ok(()) };+ let status_id = row.u32(5);+ if opts.official_only && status_id != Some(1) {+ filtered_status += 1;+ return Ok(());+ }+ releases.push(ReleaseBuild {+ gid,+ title_off: pool.intern(&row.str(2)),+ rg_id: rg,+ credit_id: row.u32(3).unwrap_or(pack::NONE),+ date: 0,+ disamb_off: pool.intern(&row.str(10)),+ status: status_id+ .and_then(|s| statuses.get(&s).copied())+ .unwrap_or(EnumPool::NONE_ENUM),+ // Official (id 1) first, then anything with a status, then none:+ // the edition-list sort key of MusicBrainzViewModel.kt:238.+ status_rank: match status_id {+ Some(1) => 0,+ Some(_) => 1,+ None => 2,+ },+ country: EnumPool::NONE_ENUM,+ id,+ });+ Ok(())+ },+ )?;+ st.rows.push(("release", n));+ if filtered_status > 0 {+ st.skipped.push(("non-Official releases (--official-only)", filtered_status));+ }+ let mut release_slot = DenseMap::new();+ for (i, r) in releases.iter().enumerate() {+ release_slot.set(r.id, i as u32)?;+ }+ // release_country.country is an *area* id, not a country code, so it resolves+ // through the same iso_3166_1 mapping the artists used; a release can carry+ // several countries, and we keep the earliest-dated one.+ let n = require(+ input,+ "release_country",+ Shape { table: "release_country", min_fields: 5, ints: &[0, 1], uuids: &[] },+ |row| {+ let Some(slot) = row.u32(0).and_then(|id| release_slot.get(id)) else { return Ok(()) };+ let d = pack_date(row.i64(2), row.i64(3), row.i64(4));+ let r = &mut releases[slot as usize];+ if r.date == 0 || (d != 0 && d < r.date) {+ r.date = d;+ if let Some(&c) = row.u32(1).and_then(|a| area_country.get(&a)) {+ r.country = c;+ }+ }+ Ok(())+ },+ )?;+ st.rows.push(("release_country", n));+ let n = require(+ input,+ "release_unknown_country",+ Shape { table: "release_unknown_country", min_fields: 4, ints: &[0], uuids: &[] },+ |row| {+ let Some(slot) = row.u32(0).and_then(|id| release_slot.get(id)) else { return Ok(()) };+ let d = pack_date(row.i64(1), row.i64(2), row.i64(3));+ let r = &mut releases[slot as usize];+ if r.date == 0 || (d != 0 && d < r.date) {+ r.date = d;+ }+ Ok(())+ },+ )?;+ st.rows.push(("release_unknown_country", n));+ drop(release_slot);+ drop(area_country);++ releases.sort_unstable_by_key(|r| r.gid);+ let mut release_idx = DenseMap::new();+ for (i, r) in releases.iter().enumerate() {+ release_idx.set(r.id, i as u32)?;+ }+ let mut dangling_rg = 0u64;+ let mut rg_release_pairs: Vec<(u32, u32)> = Vec::with_capacity(releases.len());+ for (i, r) in releases.iter().enumerate() {+ match rg_idx.get(r.rg_id) {+ Some(g) => rg_release_pairs.push((g, i as u32)),+ None => dangling_rg += 1,+ }+ }+ if dangling_rg > 0 {+ st.skipped.push(("releases whose release group is missing", dangling_rg));+ }+ rg_release_pairs.sort_unstable_by(|x, y| {+ let (a, b) = (&releases[x.1 as usize], &releases[y.1 as usize]);+ x.0.cmp(&y.0)+ .then(a.status_rank.cmp(&b.status_rank))+ .then(a.date.cmp(&b.date))+ .then(x.1.cmp(&y.1))+ });+ let (rg_releases, rg_releases_idx) = to_csr(&rg_release_pairs, rgs.len());+ drop(rg_release_pairs);++ // --- media ----------------------------------------------------------------+ step!("pass 6: media");+ let mut media: Vec<MediumBuild> = Vec::new();+ let mut dangling_media = 0u64;+ let n = require(+ input,+ "medium",+ Shape { table: "medium", min_fields: 9, ints: &[0, 1, 2], uuids: &[8] },+ |row| {+ let (Some(id), Some(rel)) = (row.u32(0), row.u32(1)) else { return Ok(()) };+ let Some(ri) = release_idx.get(rel) else {+ dangling_media += 1;+ return Ok(());+ };+ media.push(MediumBuild {+ id,+ release_idx: ri,+ position: clamp_position(row.i64(2)),+ format: row+ .u32(3)+ .and_then(|f| formats.get(&f).copied())+ .unwrap_or(EnumPool::NONE_ENUM),+ track_count: row.u32(7).unwrap_or(0),+ });+ Ok(())+ },+ )?;+ st.rows.push(("medium", n));+ if dangling_media > 0 {+ st.skipped.push(("media whose release was filtered or missing", dangling_media));+ }+ media.sort_unstable_by(|a, b| {+ a.release_idx.cmp(&b.release_idx).then(a.position.cmp(&b.position)).then(a.id.cmp(&b.id))+ });+ let mut medium_idx = DenseMap::new();+ for (i, m) in media.iter().enumerate() {+ medium_idx.set(m.id, i as u32)?;+ }+ let mut media_idx_csr = vec![0u32; releases.len() + 1];+ for m in &media {+ media_idx_csr[m.release_idx as usize + 1] += 1;+ }+ for i in 0..releases.len() {+ media_idx_csr[i + 1] += media_idx_csr[i];+ }++ // --- recordings -----------------------------------------------------------+ step!("pass 7: recordings");+ let mut rec_rows: Vec<RecBuild> = Vec::new();+ let mut rec_gids: Vec<Mbid> = Vec::new();+ let mut rec_present: Vec<bool> = Vec::new();+ let mut distinct_titles: std::collections::HashSet<u32> = std::collections::HashSet::new();+ let n = require(+ input,+ "recording",+ Shape { table: "recording", min_fields: 9, ints: &[0, 3], uuids: &[1] },+ |row| {+ let Some(id) = row.u32(0) else { return Ok(()) };+ let Some(gid) = parse_mbid(&row.str(1)) else { return Ok(()) };+ if id > MAX_ID {+ return Err(other_err(format!("recording id {id} exceeds {MAX_ID}")));+ }+ let i = id as usize;+ if rec_rows.len() <= i {+ rec_rows.resize(i + 1, RecBuild::default());+ rec_gids.resize(i + 1, [0u8; 16]);+ rec_present.resize(i + 1, false);+ }+ let title_off = pool.intern(&row.str(2));+ distinct_titles.insert(title_off);+ rec_rows[i] = RecBuild {+ title_off,+ credit_id: row.u32(3).unwrap_or(pack::NONE),+ dur_s: ms_to_secs(row.i64(4)),+ };+ rec_gids[i] = gid;+ rec_present[i] = true;+ Ok(())+ },+ )?;+ st.rows.push(("recording", n));+ st.recording_titles = n;+ st.distinct_recording_titles = distinct_titles.len() as u64;+ drop(distinct_titles);++ // --- tracks ---------------------------------------------------------------+ // The dump is in track-id order but TRACKS must be grouped by medium, so the+ // rows are buffered and sorted once. This is the only large transient buffer.+ step!("pass 8: tracks");+ let mut tracks: Vec<TrackBuild> = Vec::new();+ let mut track_gids: Vec<Mbid> = Vec::new();+ let mut dangling_tracks = 0u64;+ let mut bad_track_gids = 0u64;+ let n = require(+ input,+ "track",+ Shape { table: "track", min_fields: 12, ints: &[0, 2, 3, 4, 7], uuids: &[1] },+ |row| {+ let (Some(rec), Some(med)) = (row.u32(2), row.u32(3)) else { return Ok(()) };+ let Some(mi) = medium_idx.get(med) else {+ dangling_tracks += 1;+ return Ok(());+ };+ let gid_slot = if opts.include_track_mbids {+ match parse_mbid(&row.str(1)) {+ Some(g) => {+ track_gids.push(g);+ track_gids.len() as u32 - 1+ }+ None => {+ bad_track_gids += 1;+ return Ok(());+ }+ }+ } else {+ 0+ };+ tracks.push(TrackBuild {+ medium_idx: mi,+ position: clamp_position(row.i64(4)),+ recording_id: rec,+ title_off: pool.intern(&row.str(6)),+ credit_id: row.u32(7).unwrap_or(pack::NONE),+ length_s: ms_to_secs(row.i64(8)),+ gid_slot,+ });+ Ok(())+ },+ )?;+ st.rows.push(("track", n));+ if dangling_tracks > 0 {+ st.skipped.push(("tracks whose medium was filtered or missing", dangling_tracks));+ }+ if bad_track_gids > 0 {+ st.skipped.push(("tracks with an unparseable gid", bad_track_gids));+ }+ st.track_sort_buffer_bytes = (tracks.len() * std::mem::size_of::<TrackBuild>()) as u64;+ tracks.sort_unstable_by(|a, b| {+ a.medium_idx.cmp(&b.medium_idx).then(a.position.cmp(&b.position))+ });++ // Assign recording indices in first-appearance order (design doc §4.3): a+ // tracklist then references consecutive recordings, so d_recording is mostly+ // 1 and TRACKS stays around 2 B a track.+ let mut rec_new: Vec<u32> = vec![pack::NONE; rec_rows.len()];+ let mut rec_order: Vec<u32> = Vec::new();+ let mut rec_first_release: Vec<u32> = Vec::new();+ let mut tracks_stream: Vec<u8> = Vec::new();+ let mut track_mbids: Vec<u8> = Vec::new();+ let mut track_idx: Vec<u32> = vec![0u32; media.len() + 1];+ let mut track_count = 0u32;+ let mut cursor = 0usize;+ let mut missing_recordings = 0u64;+ for m in 0..media.len() {+ track_idx[m] = tracks_stream.len() as u32;+ let mut ordinal = 0u32;+ let mut prev_rec: i64 = 0;+ while cursor < tracks.len() && tracks[cursor].medium_idx as usize == m {+ let t = tracks[cursor];+ cursor += 1;+ let rid = t.recording_id as usize;+ if rid >= rec_rows.len() || !rec_present[rid] {+ missing_recordings += 1;+ continue;+ }+ let new_idx = if rec_new[rid] != pack::NONE {+ rec_new[rid]+ } else {+ let i = rec_order.len() as u32;+ rec_new[rid] = i;+ rec_order.push(t.recording_id);+ rec_first_release.push(media[m].release_idx);+ i+ };+ let rec = rec_rows[rid];+ let title_differs = t.title_off != rec.title_off;+ let credit_differs = t.credit_id != rec.credit_id;+ let pos_differs = t.position != (ordinal as i32 + 1);+ let len_differs = t.length_s != 0 && t.length_s != rec.dur_s;+ if !title_differs {+ st.tracks_title_same += 1;+ }+ if !credit_differs {+ st.tracks_credit_same += 1;+ }+ if !len_differs {+ st.tracks_length_same += 1;+ }+ let flags = (title_differs as u64)+ | ((credit_differs as u64) << 1)+ | ((pos_differs as u64) << 2)+ | ((len_differs as u64) << 3);+ pack::write_uvarint(&mut tracks_stream, flags);+ if ordinal == 0 {+ pack::write_uvarint(&mut tracks_stream, new_idx as u64);+ } else {+ pack::write_zigzag(&mut tracks_stream, new_idx as i64 - prev_rec);+ }+ prev_rec = new_idx as i64;+ if title_differs {+ pack::write_uvarint(&mut tracks_stream, t.title_off as u64);+ }+ if credit_differs {+ pack::write_uvarint(&mut tracks_stream, t.credit_id as u64);+ }+ if pos_differs {+ pack::write_uvarint(&mut tracks_stream, t.position.max(0) as u64);+ }+ if len_differs {+ pack::write_uvarint(&mut tracks_stream, t.length_s as u64);+ }+ if opts.include_track_mbids {+ track_mbids.extend_from_slice(&track_gids[t.gid_slot as usize]);+ }+ ordinal += 1;+ track_count += 1;+ }+ // The stored track_count must match what a decode of the run yields, or+ // TRACKTOTAL and the tracklist disagree.+ media[m].track_count = ordinal;+ }+ track_idx[media.len()] = tracks_stream.len() as u32;+ if missing_recordings > 0 {+ st.skipped.push(("tracks whose recording is missing", missing_recordings));+ }+ drop(tracks);+ drop(track_gids);++ // Standalone recordings (no track anywhere) are appended so recording search+ // can still reach them.+ let tracked = rec_order.len() as u64;+ for id in 0..rec_rows.len() {+ if rec_present[id] && rec_new[id] == pack::NONE {+ rec_new[id] = rec_order.len() as u32;+ rec_order.push(id as u32);+ rec_first_release.push(pack::NONE);+ }+ }+ st.standalone_recordings = rec_order.len() as u64 - tracked;++ // --- ISRCs ----------------------------------------------------------------+ step!("pass 9: ISRCs");+ let mut isrcs: Vec<(u32, [u8; 7])> = Vec::new();+ if opts.include_isrcs {+ let mut rejects = 0u64;+ let n = require(+ input,+ "isrc",+ Shape { table: "isrc", min_fields: 5, ints: &[0, 1], uuids: &[] },+ |row| {+ let Some(rec) = row.u32(1) else { return Ok(()) };+ let Some(&new) = rec_new.get(rec as usize) else { return Ok(()) };+ if new == pack::NONE {+ return Ok(());+ }+ match pack_isrc(row.str(2).trim().as_bytes()) {+ Some(p) => isrcs.push((new, p)),+ None => rejects += 1,+ }+ Ok(())+ },+ )?;+ st.rows.push(("isrc", n));+ st.isrc_rejects = rejects;+ isrcs.sort_unstable();+ isrcs.dedup();+ }++ // --- search index ---------------------------------------------------------+ step!("pass 10: search index");+ let mut term_dict: HashMap<String, u32> = HashMap::new();+ let mut postings: Vec<(u32, u32)> = Vec::new();+ let mut terms_buf: Vec<String> = Vec::new();+ let mut add = |text: &str, refv: u32, dict: &mut HashMap<String, u32>, post: &mut Vec<(u32, u32)>| {+ terms_buf.clear();+ search_terms(text, &mut terms_buf);+ for t in &terms_buf {+ let next = dict.len() as u32;+ let id = *dict.entry(t.clone()).or_insert(next);+ post.push((id, refv));+ }+ };+ for (i, a) in artists.iter().enumerate() {+ let name = str_from_pool(&pool, a.name_off);+ check_searchable(i as u32)?;+ add(&name, (pack::KIND_ARTIST << pack::KIND_SHIFT) | i as u32, &mut term_dict, &mut postings);+ }+ for (i, r) in rgs.iter().enumerate() {+ let title = str_from_pool(&pool, r.title_off);+ check_searchable(i as u32)?;+ add(+ &title,+ (pack::KIND_RELEASE_GROUP << pack::KIND_SHIFT) | i as u32,+ &mut term_dict,+ &mut postings,+ );+ }+ if opts.include_recording_search {+ for (i, id) in rec_order.iter().enumerate() {+ let title = str_from_pool(&pool, rec_rows[*id as usize].title_off);+ check_searchable(i as u32)?;+ add(+ &title,+ (pack::KIND_RECORDING << pack::KIND_SHIFT) | i as u32,+ &mut term_dict,+ &mut postings,+ );+ }+ }+ st.search_postings = postings.len() as u64;+ // Sort the dictionary so the reader can binary search it, then renumber.+ let mut sorted_terms: Vec<(String, u32)> = term_dict.into_iter().collect();+ sorted_terms.sort_unstable_by(|a, b| a.0.cmp(&b.0));+ let mut remap = vec![0u32; sorted_terms.len()];+ for (new, (_, old)) in sorted_terms.iter().enumerate() {+ remap[*old as usize] = new as u32;+ }+ for p in postings.iter_mut() {+ p.0 = remap[p.0 as usize];+ }+ drop(remap);+ postings.sort_unstable();+ postings.dedup();+ let term_count = sorted_terms.len();+ let mut search_terms_bytes: Vec<u8> = Vec::new();+ let mut postings_bytes: Vec<u8> = Vec::new();+ let mut term_index: Vec<u8> = Vec::with_capacity((term_count + 1) * 8);+ let mut p = 0usize;+ for (new_id, (t, _)) in sorted_terms.iter().enumerate() {+ term_index.extend_from_slice(&(search_terms_bytes.len() as u32).to_le_bytes());+ term_index.extend_from_slice(&(postings_bytes.len() as u32).to_le_bytes());+ search_terms_bytes.extend_from_slice(t.as_bytes());+ search_terms_bytes.push(0);+ let start = p;+ while p < postings.len() && postings[p].0 == new_id as u32 {+ p += 1;+ }+ pack::write_uvarint(&mut postings_bytes, (p - start) as u64);+ let mut prev = 0u32;+ for &(_, refv) in &postings[start..p] {+ pack::write_uvarint(&mut postings_bytes, (refv - prev) as u64);+ prev = refv;+ }+ }+ term_index.extend_from_slice(&(search_terms_bytes.len() as u32).to_le_bytes());+ term_index.extend_from_slice(&(postings_bytes.len() as u32).to_le_bytes());+ drop(postings);++ // --- assemble -------------------------------------------------------------+ step!("pass 11: writing");+ let mut w = PackWriter::new(out)?;+ w.section_u32(pack::S_ENUM_POOL, enums.offsets())?;+ w.section_u32(pack::S_CREDITS, &credits_off)?;++ let mut buf: Vec<u8> = Vec::new();+ buf.clear();+ for a in &artists {+ buf.extend_from_slice(&a.name_off.to_le_bytes());+ buf.extend_from_slice(&a.disamb_off.to_le_bytes());+ buf.extend_from_slice(&a.area_off.to_le_bytes());+ buf.extend_from_slice(&a.begin_date.to_le_bytes());+ buf.extend_from_slice(&a.kind.to_le_bytes());+ buf.extend_from_slice(&a.country.to_le_bytes());+ }+ w.section(pack::S_ARTISTS, &buf)?;+ let gids: Vec<Mbid> = artists.iter().map(|a| a.gid).collect();+ let (recs, hi) = build_mbid_table(&gids);+ w.section(pack::S_ARTIST_MBID, &recs)?;+ w.section_u32(pack::S_ARTIST_MBID_HI, &hi)?;+ drop(gids);++ buf.clear();+ for r in &rgs {+ buf.extend_from_slice(&r.title_off.to_le_bytes());+ buf.extend_from_slice(&r.first_date.to_le_bytes());+ buf.extend_from_slice(&credit_idx_of(r.credit_id, credit_count).to_le_bytes());+ buf.extend_from_slice(&r.primary.to_le_bytes());+ buf.extend_from_slice(&r.secondary.to_le_bytes());+ }+ w.section(pack::S_RELEASE_GROUPS, &buf)?;+ let gids: Vec<Mbid> = rgs.iter().map(|r| r.gid).collect();+ let (recs, hi) = build_mbid_table(&gids);+ w.section(pack::S_RG_MBID, &recs)?;+ w.section_u32(pack::S_RG_MBID_HI, &hi)?;+ drop(gids);+ w.section_u32(pack::S_ARTIST_RGS, &artist_rgs)?;+ w.section_u32(pack::S_ARTIST_RGS_IDX, &artist_rgs_idx)?;++ buf.clear();+ for r in &releases {+ buf.extend_from_slice(&r.title_off.to_le_bytes());+ buf.extend_from_slice(&rg_idx.get(r.rg_id).unwrap_or(pack::NONE).to_le_bytes());+ buf.extend_from_slice(&credit_idx_of(r.credit_id, credit_count).to_le_bytes());+ buf.extend_from_slice(&r.date.to_le_bytes());+ buf.extend_from_slice(&r.disamb_off.to_le_bytes());+ buf.extend_from_slice(&r.status.to_le_bytes());+ buf.extend_from_slice(&r.country.to_le_bytes());+ }+ w.section(pack::S_RELEASES, &buf)?;+ let gids: Vec<Mbid> = releases.iter().map(|r| r.gid).collect();+ let (recs, hi) = build_mbid_table(&gids);+ w.section(pack::S_RELEASE_MBID, &recs)?;+ w.section_u32(pack::S_RELEASE_MBID_HI, &hi)?;+ drop(gids);+ w.section_u32(pack::S_RG_RELEASES, &rg_releases)?;+ w.section_u32(pack::S_RG_RELEASES_IDX, &rg_releases_idx)?;++ w.section_u32(pack::S_MEDIA_IDX, &media_idx_csr)?;+ buf.clear();+ for m in &media {+ buf.extend_from_slice(&m.format.to_le_bytes());+ buf.extend_from_slice(&(m.track_count.min(u16::MAX as u32) as u16).to_le_bytes());+ }+ w.section(pack::S_MEDIA, &buf)?;+ w.section_u32(pack::S_TRACK_IDX, &track_idx)?;+ assert!(+ tracks_stream.len() <= u32::MAX as usize,+ "TRACKS is {} bytes, past the u32 ceiling TRACK_IDX addresses it with",+ tracks_stream.len()+ );+ w.section(pack::S_TRACKS, &tracks_stream)?;+ drop(tracks_stream);+ if opts.include_track_mbids {+ w.section(pack::S_TRACK_MBID, &track_mbids)?;+ }+ drop(track_mbids);++ buf.clear();+ for id in &rec_order {+ let r = rec_rows[*id as usize];+ let (lo, hi) = encode_recording_credit(credit_idx_of(r.credit_id, credit_count));+ buf.extend_from_slice(&r.title_off.to_le_bytes());+ buf.extend_from_slice(&r.dur_s.to_le_bytes());+ buf.extend_from_slice(&lo.to_le_bytes());+ buf.push(hi);+ }+ w.section(pack::S_RECORDINGS, &buf)?;+ if opts.include_recording_mbids {+ buf.clear();+ for id in &rec_order {+ buf.extend_from_slice(&rec_gids[*id as usize]);+ }+ w.section(pack::S_RECORDING_MBID, &buf)?;+ }+ w.section_u32(pack::S_REC_FIRST_RELEASE, &rec_first_release)?;++ if opts.include_isrcs {+ buf.clear();+ for (rec, packed) in &isrcs {+ buf.extend_from_slice(&rec.to_le_bytes());+ buf.extend_from_slice(packed);+ }+ w.section(pack::S_ISRCS, &buf)?;+ }++ w.section(pack::S_SEARCH_TERMS, &search_terms_bytes)?;+ w.section(pack::S_SEARCH_POSTINGS, &postings_bytes)?;+ w.section(pack::S_SEARCH_TERM_IDX, &term_index)?;+ w.section(pack::S_STRINGS, pool.bytes())?;++ let counts = HeaderCounts {+ artists: artists.len() as u32,+ credits: credit_count,+ release_groups: rgs.len() as u32,+ releases: releases.len() as u32,+ media: media.len() as u32,+ tracks: track_count,+ recordings: rec_order.len() as u32,+ isrcs: isrcs.len() as u32,+ search_terms: term_count as u32,+ enums: enums.offsets().len() as u32,+ };+ w.set_header(&counts, opts.flags(), input.dump_date());+ st.sections = w+ .section_sizes()+ .into_iter()+ .map(|(i, len)| (pack::SECTION_NAMES[i], len))+ .collect();+ st.distinct_strings = pool.distinct();+ st.string_pool_bytes = pool.bytes().len();+ st.dense_map_bytes =+ artist_idx.bytes() + rg_idx.bytes() + release_idx.bytes() + medium_idx.bytes();+ st.total_bytes = w.finish()?;+ Ok(st)+}++fn check_searchable(idx: u32) -> io::Result<()> {+ if idx > pack::MAX_SEARCHABLE_IDX {+ return Err(other_err(format!(+ "entity index {idx} exceeds the {} a search posting can address; the two kind \+ bits would silently corrupt it",+ pack::MAX_SEARCHABLE_IDX+ )));+ }+ Ok(())+}++/// `medium.position` and `track.position` are Postgres INTEGERs. Anything outside+/// that range is corrupt input, not a wider position.+fn clamp_position(v: Option<i64>) -> i32 {+ match v {+ Some(v) => v.clamp(i32::MIN as i64, i32::MAX as i64) as i32,+ None => 0,+ }+}++fn credit_idx_of(credit_id: u32, credit_count: u32) -> u32 {+ if credit_id == pack::NONE || credit_id >= credit_count {+ pack::NONE+ } else {+ credit_id+ }+}++fn str_from_pool(pool: &StringPool, off: u32) -> String {+ let bytes = pool.bytes();+ let start = off as usize;+ if start >= bytes.len() {+ return String::new();+ }+ let end = bytes[start..].iter().position(|&b| b == 0).map_or(bytes.len(), |n| start + n);+ String::from_utf8_lossy(&bytes[start..end]).into_owned()+}++/// MusicBrainz stores lengths in milliseconds; the pack stores seconds because+/// the UI renders m:ss, Tidal matching uses a ±3 s tolerance and LRCLIB takes+/// seconds. Clamped rather than wrapped: an 18-hour recording is rare but real.+fn ms_to_secs(ms: Option<i64>) -> u16 {+ match ms {+ Some(ms) if ms > 0 => (ms.saturating_add(500) / 1000).min(u16::MAX as i64) as u16,+ _ => 0,+ }+}++fn to_csr(pairs: &[(u32, u32)], parents: usize) -> (Vec<u32>, Vec<u32>) {+ let mut idx = vec![0u32; parents + 1];+ for &(p, _) in pairs {+ idx[p as usize + 1] += 1;+ }+ for i in 0..parents {+ idx[i + 1] += idx[i];+ }+ (pairs.iter().map(|&(_, c)| c).collect(), idx)+}++fn read_enum_table(+ input: &Input,+ table: &'static str,+ pool: &mut StringPool,+ enums: &mut EnumPool,+) -> io::Result<HashMap<u32, u16>> {+ let mut out = HashMap::new();+ require(input, table, Shape { table, min_fields: 2, ints: &[0], uuids: &[] }, |row| {+ if let Some(id) = row.u32(0) {+ out.insert(id, enums.intern(pool, &row.str(1)));+ }+ Ok(())+ })?;+ Ok(out)+}++/// Read a table that must be present, checking its shape on the first row.+fn require<F>(input: &Input, table: &'static str, shape: Shape, mut f: F) -> io::Result<u64>+where+ F: FnMut(&Row<'_>) -> io::Result<()>,+{+ let mut first = true;+ let rows = input.each_row(table, |row| {+ if first {+ shape.check(row)?;+ first = false;+ }+ f(row)+ })?;+ match rows {+ Some(n) => Ok(n),+ None => Err(other_err(format!(+ "table `{table}` is missing from {}. The core mbdump.tar.bz2 contains it as \+ `mbdump/{table}`; a derived or partial dump does not.",+ input.describe()+ ))),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn track_build_stays_small() {+ // 57.4 M of these are resident while the track pass sorts, so every byte+ // here is 57 MB of peak RSS. The README quotes this number.+ assert_eq!(std::mem::size_of::<TrackBuild>(), 28);+ }++ #[test]+ fn positions_clamp_instead_of_wrapping() {+ assert_eq!(clamp_position(None), 0);+ assert_eq!(clamp_position(Some(0)), 0);+ assert_eq!(clamp_position(Some(-1)), -1);+ assert_eq!(clamp_position(Some(i64::MAX)), i32::MAX);+ assert_eq!(clamp_position(Some(i64::MIN)), i32::MIN);+ }++ #[test]+ fn ms_round_to_nearest_second_and_clamp() {+ assert_eq!(ms_to_secs(None), 0);+ assert_eq!(ms_to_secs(Some(0)), 0);+ assert_eq!(ms_to_secs(Some(499)), 0);+ assert_eq!(ms_to_secs(Some(500)), 1);+ assert_eq!(ms_to_secs(Some(67_000)), 67);+ assert_eq!(ms_to_secs(Some(i64::MAX)), u16::MAX, "an 18-hour recording clamps");+ }++ #[test]+ fn csr_is_a_prefix_sum() {+ let (vals, idx) = to_csr(&[(0, 7), (0, 8), (2, 9)], 3);+ assert_eq!(vals, [7, 8, 9]);+ assert_eq!(idx, [0, 2, 2, 3]);+ }++ #[test]+ fn dense_map_rejects_absurd_keys() {+ let mut m = DenseMap::new();+ m.set(5, 1).unwrap();+ assert_eq!(m.get(5), Some(1));+ assert_eq!(m.get(4), None);+ assert_eq!(m.get(9_999), None);+ assert!(m.set(MAX_ID + 1, 0).is_err());+ }+}
scripts/musicbrainz/mb_ingest/src/copy.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/copy.rs b/scripts/musicbrainz/mb_ingest/src/copy.rsnew file mode 100644index 0000000000..7c44924849--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/src/copy.rs@@ -0,0 +1,387 @@+//! Read the tables of a MusicBrainz full export.+//!+//! The tables in `mbdump.tar.bz2` are PostgreSQL `COPY ... TO` output in the+//! default TEXT format: one row per line, columns separated by TAB, `\N` for+//! NULL, and backslash escapes (`\\`, `\t`, `\n`, `\r`, `\b`, `\f`, `\v`) for the+//! characters that would otherwise break the framing. Real MusicBrainz titles do+//! contain tabs and newlines, so unescaping is not optional.+//!+//! Verified against the live export rather than assumed:+//! * the archive member names in `mbdump.tar.bz2` are `mbdump/<table>` with no+//! schema prefix (`mbdump/area`, `mbdump/artist`, ...), in ASCII order, after+//! the leading `TIMESTAMP`, `COPYING`, `README`, `REPLICATION_SEQUENCE` and+//! `SCHEMA_SEQUENCE` members. The non-`musicbrainz`-schema dumps use+//! `mbdump/<schema>.<table>` instead (confirmed on+//! `mbdump-documentation.tar.bz2`), so both spellings are accepted.+//! * `TIMESTAMP` holds e.g. `2026-08-19 00:25:41.835127+00`.+//!+//! Two input shapes are supported. A directory is the fast path for repeated+//! builds and the only one the tests use. A `.tar.bz2` is streamed through the+//! system `tar`, so a full build never materialises the ~40 GB of extracted+//! tables; the cost is one decompression pass per table read.++use std::borrow::Cow;+use std::fs::File;+use std::io::{self, BufRead, BufReader, Read};+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};++/// One row of a COPY dump, borrowing the line buffer.+pub struct Row<'a> {+ line: &'a [u8],+ fields: &'a [(u32, u32)],+}++impl<'a> Row<'a> {+ pub fn len(&self) -> usize {+ self.fields.len()+ }++ pub fn is_empty(&self) -> bool {+ self.fields.is_empty()+ }++ pub fn raw(&self, i: usize) -> &'a [u8] {+ match self.fields.get(i) {+ Some(&(a, b)) => &self.line[a as usize..b as usize],+ None => &[],+ }+ }++ pub fn is_null(&self, i: usize) -> bool {+ self.raw(i) == b"\\N"+ }++ /// The field with COPY escapes resolved. NULL reads as `""`; callers that+ /// care about the difference ask `is_null` first.+ pub fn str(&self, i: usize) -> Cow<'a, str> {+ let raw = self.raw(i);+ if raw == b"\\N" {+ return Cow::Borrowed("");+ }+ if !raw.contains(&b'\\') {+ return String::from_utf8_lossy(raw);+ }+ let mut out = Vec::with_capacity(raw.len());+ let mut it = raw.iter().copied();+ while let Some(b) = it.next() {+ if b != b'\\' {+ out.push(b);+ continue;+ }+ match it.next() {+ Some(b'n') => out.push(b'\n'),+ Some(b't') => out.push(b'\t'),+ Some(b'r') => out.push(b'\r'),+ Some(b'b') => out.push(8),+ Some(b'f') => out.push(12),+ Some(b'v') => out.push(11),+ Some(b'\\') => out.push(b'\\'),+ Some(other) => {+ out.push(b'\\');+ out.push(other);+ }+ None => out.push(b'\\'),+ }+ }+ Cow::Owned(String::from_utf8_lossy(&out).into_owned())+ }++ pub fn i64(&self, i: usize) -> Option<i64> {+ let raw = self.raw(i);+ if raw.is_empty() || raw == b"\\N" {+ return None;+ }+ let (neg, digits) = match raw[0] {+ b'-' => (true, &raw[1..]),+ _ => (false, raw),+ };+ if digits.is_empty() {+ return None;+ }+ let mut v: i64 = 0;+ for &c in digits {+ if !c.is_ascii_digit() {+ return None;+ }+ v = v.checked_mul(10)?.checked_add((c - b'0') as i64)?;+ }+ Some(if neg { -v } else { v })+ }++ pub fn u32(&self, i: usize) -> Option<u32> {+ match self.i64(i) {+ Some(v) if (0..=u32::MAX as i64).contains(&v) => Some(v as u32),+ _ => None,+ }+ }++ /// Does the field look like a bare (unhyphenated or hyphenated) UUID?+ pub fn looks_like_uuid(&self, i: usize) -> bool {+ let raw = self.raw(i);+ let hex = raw.iter().filter(|c| c.is_ascii_hexdigit()).count();+ let dashes = raw.iter().filter(|&&c| c == b'-').count();+ hex == 32 && hex + dashes == raw.len()+ }+}++/// A table's byte stream plus, for the archive path, the `tar` process feeding it.+type TableStream = (Box<dyn Read>, Option<Child>);++/// Where the tables come from.+pub enum Input {+ /// A directory holding the table files, either `<dir>/<table>` or+ /// `<dir>/mbdump/<table>` (i.e. an extracted archive works unchanged).+ Dir(PathBuf),+ /// An `mbdump*.tar.bz2`, streamed through the system `tar`.+ Archive(PathBuf),+}++impl Input {+ /// Classify by extension so the CLI takes either without a flag.+ pub fn detect(path: &Path) -> Input {+ let s = path.to_string_lossy().to_ascii_lowercase();+ if s.ends_with(".tar.bz2") || s.ends_with(".tbz2") || s.ends_with(".tar") {+ Input::Archive(path.to_path_buf())+ } else {+ Input::Dir(path.to_path_buf())+ }+ }++ pub fn describe(&self) -> String {+ match self {+ Input::Dir(p) => format!("directory {}", p.display()),+ Input::Archive(p) => format!("archive {}", p.display()),+ }+ }++ /// The dump's `TIMESTAMP` as `YYYYMMDD`, or 0 when it is not readable.+ pub fn dump_date(&self) -> u32 {+ let text = match self {+ Input::Dir(p) => {+ std::fs::read_to_string(p.join("TIMESTAMP")).ok()+ }+ Input::Archive(p) => {+ let out = Command::new("tar").arg("-xOf").arg(p).arg("TIMESTAMP").output().ok();+ out.and_then(|o| String::from_utf8(o.stdout).ok())+ }+ };+ let text = match text {+ Some(t) => t,+ None => return 0,+ };+ let d: Vec<u8> = text.bytes().filter(|c| c.is_ascii_digit()).take(8).collect();+ if d.len() < 8 {+ return 0;+ }+ std::str::from_utf8(&d).ok().and_then(|s| s.parse().ok()).unwrap_or(0)+ }++ fn open_reader(&self, table: &str) -> io::Result<Option<TableStream>> {+ match self {+ Input::Dir(dir) => {+ for cand in [dir.join("mbdump").join(table), dir.join(table)] {+ if cand.is_file() {+ return Ok(Some((Box::new(File::open(cand)?), None)));+ }+ }+ Ok(None)+ }+ Input::Archive(path) => {+ // `tar` picks the decompressor from the magic bytes, so this works+ // for .tar, .tar.bz2 and .tar.gz alike, and streams: nothing is+ // written to disk. bsdtar (Windows) and GNU tar both support it.+ let member = format!("mbdump/{table}");+ let mut child = Command::new("tar")+ .arg("-xOf")+ .arg(path)+ .arg(&member)+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .map_err(|e| {+ io::Error::new(+ e.kind(),+ format!(+ "could not run `tar` to stream {member} out of {}: {e}. \+ Archive input needs tar on PATH; extract the archive and \+ pass the directory instead.",+ path.display()+ ),+ )+ })?;+ let out = child.stdout.take().expect("piped stdout");+ Ok(Some((Box::new(out), Some(child))))+ }+ }+ }++ /// Call `f` once per row of `table`. Returns the number of rows, or `None` if+ /// the table is not in this input at all.+ ///+ /// Rows are handed out as borrowed slices and never accumulated, so this is+ /// safe on `track` (57 M rows) as long as the caller does not accumulate+ /// either.+ pub fn each_row<F>(&self, table: &str, mut f: F) -> io::Result<Option<u64>>+ where+ F: FnMut(&Row<'_>) -> io::Result<()>,+ {+ let Some((reader, child)) = self.open_reader(table)? else {+ return Ok(None);+ };+ let mut reader = BufReader::with_capacity(1 << 20, reader);+ let mut line: Vec<u8> = Vec::with_capacity(4096);+ let mut fields: Vec<(u32, u32)> = Vec::with_capacity(32);+ let mut rows = 0u64;+ loop {+ line.clear();+ let n = reader.read_until(b'\n', &mut line)?;+ if n == 0 {+ break;+ }+ while matches!(line.last(), Some(b'\n') | Some(b'\r')) {+ line.pop();+ }+ if line.is_empty() {+ continue;+ }+ fields.clear();+ let mut start = 0u32;+ for (i, &c) in line.iter().enumerate() {+ if c == b'\t' {+ fields.push((start, i as u32));+ start = i as u32 + 1;+ }+ }+ fields.push((start, line.len() as u32));+ f(&Row { line: &line, fields: &fields })?;+ rows += 1;+ }+ if let Some(mut child) = child {+ // A non-zero tar exit means the member was missing or the stream was+ // truncated; treating that as an empty table would silently produce a+ // wrong pack.+ let status = child.wait()?;+ if !status.success() && rows == 0 {+ return Ok(None);+ }+ if !status.success() {+ return Err(other_err(format!(+ "tar failed after {rows} rows of {table}; the archive is truncated"+ )));+ }+ }+ Ok(Some(rows))+ }+}++/// A table's expected shape, checked on the first row.+///+/// The column order of a COPY dump is the table's physical column order, which+/// this crate hard-codes from `admin/sql/CreateTables.sql`. If MusicBrainz ever+/// reorders or inserts a column, silently reading the wrong field would produce a+/// plausible-looking but wrong pack, so every table asserts its arity and spot+/// checks the columns whose types are distinctive.+pub struct Shape {+ pub table: &'static str,+ pub min_fields: usize,+ /// Column indices that must parse as integers.+ pub ints: &'static [usize],+ /// Column indices that must look like UUIDs.+ pub uuids: &'static [usize],+}++impl Shape {+ pub fn check(&self, row: &Row<'_>) -> io::Result<()> {+ if row.len() < self.min_fields {+ return Err(other_err(format!(+ "table `{}`: expected at least {} columns, found {}. The dump's schema \+ does not match what this build was written against; check \+ SCHEMA_SEQUENCE and admin/sql/CreateTables.sql before trusting any pack.",+ self.table,+ self.min_fields,+ row.len()+ )));+ }+ for &i in self.ints {+ if !row.is_null(i) && row.i64(i).is_none() {+ return Err(other_err(format!(+ "table `{}`: column {i} should be an integer but is {:?}. Column order \+ has almost certainly changed upstream.",+ self.table,+ String::from_utf8_lossy(row.raw(i))+ )));+ }+ }+ for &i in self.uuids {+ if !row.looks_like_uuid(i) {+ return Err(other_err(format!(+ "table `{}`: column {i} should be a UUID but is {:?}. Column order has \+ almost certainly changed upstream.",+ self.table,+ String::from_utf8_lossy(row.raw(i))+ )));+ }+ }+ Ok(())+ }+}++pub fn other_err(msg: String) -> io::Error {+ io::Error::new(io::ErrorKind::InvalidData, msg)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn row_of(line: &str) -> (Vec<u8>, Vec<(u32, u32)>) {+ let bytes = line.as_bytes().to_vec();+ let mut fields = Vec::new();+ let mut start = 0u32;+ for (i, &c) in bytes.iter().enumerate() {+ if c == b'\t' {+ fields.push((start, i as u32));+ start = i as u32 + 1;+ }+ }+ fields.push((start, bytes.len() as u32));+ (bytes, fields)+ }++ #[test]+ fn parses_copy_text_format() {+ let (line, fields) = row_of("42\tPink Floyd\t\\N\t\\N\t1965\t");+ let r = Row { line: &line, fields: &fields };+ assert_eq!(r.len(), 6);+ assert_eq!(r.u32(0), Some(42));+ assert_eq!(&*r.str(1), "Pink Floyd");+ assert!(r.is_null(2));+ assert_eq!(&*r.str(2), "");+ assert_eq!(r.i64(2), None);+ assert_eq!(r.u32(4), Some(1965));+ assert_eq!(&*r.str(5), "", "trailing empty field is an empty string, not NULL");+ assert!(!r.is_null(5));+ }++ #[test]+ fn unescapes_titles_that_would_break_framing() {+ let (line, fields) = row_of("1\tA\\tB\\nC\\\\D\t2");+ let r = Row { line: &line, fields: &fields };+ assert_eq!(&*r.str(1), "A\tB\nC\\D");+ assert_eq!(r.u32(2), Some(2));+ }++ #[test]+ fn rejects_bad_integers_and_detects_uuids() {+ let (line, fields) = row_of("x\tf27ec8db-af05-4f36-916e-3d57f91ecf5e\tnope");+ let r = Row { line: &line, fields: &fields };+ assert_eq!(r.i64(0), None);+ assert!(r.looks_like_uuid(1));+ assert!(!r.looks_like_uuid(2));+ let shape = Shape { table: "t", min_fields: 3, ints: &[0], uuids: &[1] };+ assert!(shape.check(&r).is_err(), "a non-integer id must be caught, not ignored");+ let shape = Shape { table: "t", min_fields: 4, ints: &[], uuids: &[] };+ assert!(shape.check(&r).is_err(), "too few columns must be caught");+ }+}
scripts/musicbrainz/mb_ingest/src/fixture.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/fixture.rs b/scripts/musicbrainz/mb_ingest/src/fixture.rsnew file mode 100644index 0000000000..5c1046bce3--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/src/fixture.rs@@ -0,0 +1,268 @@+//! A small synthetic mbdump, in the exact shape of the real one.+//!+//! Column counts and orders match `admin/sql/CreateTables.sql` for schema+//! sequence 31 exactly, so the ingest passes exercised here are the same code+//! paths a 7 GB run takes. The fixture deliberately includes the awkward cases:+//! NULL columns (`\N`), a title containing an escaped tab and newline, accented+//! text (search folding), a track whose title differs from its recording's, a+//! track whose credit differs, a pregap track at position 0, a track whose length+//! differs from its recording's, a multi-medium release, recordings reused across+//! releases (so `d_recording` is not always 1), a standalone recording with no+//! track, a release with no status, a release group with a secondary type, and a+//! malformed ISRC that must be rejected rather than stored.++use std::fs;+use std::io::{self, Write};+use std::path::Path;++fn table(dir: &Path, name: &str, rows: &[&[&str]]) -> io::Result<()> {+ let mut f = fs::File::create(dir.join(name))?;+ for row in rows {+ f.write_all(row.join("\t").as_bytes())?;+ f.write_all(b"\n")?;+ }+ Ok(())+}++/// Artist / release-group / release / recording MBIDs the round-trip test asserts+/// against. Chosen so the MBID sort order is the obvious one.+pub const ARTIST_PINK_FLOYD: &str = "11111111-1111-1111-1111-111111111111";+pub const ARTIST_BJORK: &str = "22222222-2222-2222-2222-222222222222";+pub const ARTIST_VARIOUS: &str = "33333333-3333-3333-3333-333333333333";+pub const RG_DARK_SIDE: &str = "a1000000-0000-0000-0000-000000000001";+pub const RG_HOMOGENIC: &str = "a2000000-0000-0000-0000-000000000002";+pub const RG_ECHOES: &str = "a3000000-0000-0000-0000-000000000003";+pub const RG_WEIRD: &str = "a4000000-0000-0000-0000-000000000004";+pub const REL_DARK_SIDE: &str = "b1000000-0000-0000-0000-000000000001";+pub const REL_DARK_SIDE_BOOT: &str = "b2000000-0000-0000-0000-000000000002";+pub const REL_HOMOGENIC: &str = "b3000000-0000-0000-0000-000000000003";+pub const REL_ECHOES: &str = "b4000000-0000-0000-0000-000000000004";+pub const REL_WEIRD: &str = "b5000000-0000-0000-0000-000000000005";+pub const REC_SPEAK_TO_ME: &str = "c1000000-0000-0000-0000-000000000001";+pub const REC_BREATHE: &str = "c2000000-0000-0000-0000-000000000002";+pub const REC_TIME: &str = "c3000000-0000-0000-0000-000000000003";+pub const REC_JOGA: &str = "c4000000-0000-0000-0000-000000000004";+pub const REC_BACHELORETTE: &str = "c5000000-0000-0000-0000-000000000005";+pub const REC_WISH: &str = "c6000000-0000-0000-0000-000000000006";+pub const REC_STANDALONE: &str = "c7000000-0000-0000-0000-000000000007";++/// The title that carries escaped control characters. The dump spells it+/// `Untitled\tWeird\nTitle`; the reader must hand back the real characters.+pub const WEIRD_TITLE: &str = "Untitled\tWeird\nTitle";++const N: &str = "\\N";+const T: &str = "t";+const F: &str = "f";+const TS: &str = "2026-08-19 00:00:00+00";++pub fn write_fixture(dir: &Path) -> io::Result<()> {+ fs::create_dir_all(dir)?;+ fs::write(dir.join("TIMESTAMP"), "2026-08-19 00:25:41.835127+00\n")?;+ fs::write(dir.join("SCHEMA_SEQUENCE"), "31\n")?;++ // area: id, gid, name, type, edits_pending, last_updated, begin y/m/d,+ // end y/m/d, ended, comment+ table(+ dir,+ "area",+ &[+ &["1", "e0000000-0000-0000-0000-000000000001", "United Kingdom", "1", "0", TS, N, N, N, N, N, N, F, ""],+ &["2", "e0000000-0000-0000-0000-000000000002", "United States", "1", "0", TS, N, N, N, N, N, N, F, ""],+ &["3", "e0000000-0000-0000-0000-000000000003", "Berlin", "3", "0", TS, N, N, N, N, N, N, F, ""],+ ],+ )?;+ // iso_3166_1: area, code+ table(dir, "iso_3166_1", &[&["1", "GB"], &["2", "US"]])?;++ // <enum>: id, name, parent, child_order, description, gid+ let enum_row = |id: &'static str, name: &'static str| -> Vec<&'static str> {+ vec![id, name, N, "0", N, "f0000000-0000-0000-0000-000000000000"]+ };+ let artist_types = [enum_row("1", "Person"), enum_row("2", "Group")];+ table(dir, "artist_type", &artist_types.iter().map(|r| r.as_slice()).collect::<Vec<_>>())?;+ let rg_primary = [enum_row("1", "Album"), enum_row("2", "Single")];+ table(+ dir,+ "release_group_primary_type",+ &rg_primary.iter().map(|r| r.as_slice()).collect::<Vec<_>>(),+ )?;+ let rg_secondary = [enum_row("1", "Compilation"), enum_row("3", "Live")];+ table(+ dir,+ "release_group_secondary_type",+ &rg_secondary.iter().map(|r| r.as_slice()).collect::<Vec<_>>(),+ )?;+ let statuses = [enum_row("1", "Official"), enum_row("3", "Bootleg")];+ table(dir, "release_status", &statuses.iter().map(|r| r.as_slice()).collect::<Vec<_>>())?;+ // medium_format: id, name, parent, child_order, year, has_discids, description, gid+ table(+ dir,+ "medium_format",+ &[+ &["1", "CD", N, "0", "1982", T, N, "f1000000-0000-0000-0000-000000000001"],+ &["7", "12\" Vinyl", N, "0", N, F, N, "f1000000-0000-0000-0000-000000000007"],+ ],+ )?;++ // artist: id, gid, name, sort_name, begin y/m/d, end y/m/d, type, area,+ // gender, comment, edits_pending, last_updated, ended,+ // begin_area, end_area+ table(+ dir,+ "artist",+ &[+ &["1", ARTIST_PINK_FLOYD, "Pink Floyd", "Pink Floyd", "1965", "1", "1", N, N, N, "2", "1", N, "British rock band", "0", TS, F, N, N],+ &["2", ARTIST_BJORK, "Björk", "Björk", "1965", "11", "21", N, N, N, "1", N, "2", "", "0", TS, F, N, N],+ &["3", ARTIST_VARIOUS, "Various Artists", "Various Artists", N, N, N, N, N, N, N, N, N, "", "0", TS, F, N, N],+ ],+ )?;++ // artist_credit: id, name, artist_count, ref_count, created, edits_pending, gid+ table(+ dir,+ "artist_credit",+ &[+ &["1", "Pink Floyd", "1", "10", TS, "0", "a0000000-0000-0000-0000-000000000001"],+ &["2", "Björk", "1", "5", TS, "0", "a0000000-0000-0000-0000-000000000002"],+ &["3", "Pink Floyd feat. Björk", "2", "1", TS, "0", "a0000000-0000-0000-0000-000000000003"],+ &["4", "Various Artists", "1", "3", TS, "0", "a0000000-0000-0000-0000-000000000004"],+ ],+ )?;+ // artist_credit_name: artist_credit, position, artist, name, join_phrase+ table(+ dir,+ "artist_credit_name",+ &[+ &["1", "0", "1", "Pink Floyd", ""],+ &["2", "0", "2", "Björk", ""],+ &["3", "0", "1", "Pink Floyd", " feat. "],+ &["3", "1", "2", "Björk", ""],+ &["4", "0", "3", "Various Artists", ""],+ ],+ )?;++ // release_group: id, gid, name, artist_credit, type, comment,+ // edits_pending, last_updated+ table(+ dir,+ "release_group",+ &[+ &["1", RG_DARK_SIDE, "The Dark Side of the Moon", "1", "1", "", "0", TS],+ &["2", RG_HOMOGENIC, "Homogenic", "2", "1", "", "0", TS],+ &["3", RG_ECHOES, "Echoes: The Best of Pink Floyd", "1", "1", "", "0", TS],+ &["4", RG_WEIRD, "Untitled\\tWeird\\nTitle", "3", N, "", "0", TS],+ ],+ )?;+ // release_group_meta: id, release_count, first y/m/d, rating, rating_count+ table(+ dir,+ "release_group_meta",+ &[+ &["1", "2", "1973", "3", "1", N, N],+ &["2", "1", "1997", "9", "22", N, N],+ &["3", "1", "2001", "11", "5", N, N],+ &["4", "1", N, N, N, N, N],+ ],+ )?;+ // release_group_secondary_type_join: release_group, secondary_type, created+ table(dir, "release_group_secondary_type_join", &[&["3", "1", TS], &["3", "3", TS]])?;++ // release: id, gid, name, artist_credit, release_group, status, packaging,+ // language, script, barcode, comment, edits_pending, quality,+ // last_updated+ table(+ dir,+ "release",+ &[+ &["1", REL_DARK_SIDE, "The Dark Side of the Moon", "1", "1", "1", N, "120", "28", "5099902988603", "", "0", "2", TS],+ &["2", REL_DARK_SIDE_BOOT, "The Dark Side of the Moon", "1", "1", "3", N, N, N, N, "vinyl bootleg", "0", "-1", TS],+ &["3", REL_HOMOGENIC, "Homogenic", "2", "2", "1", N, N, N, N, "", "0", "1", TS],+ &["4", REL_ECHOES, "Echoes: The Best of Pink Floyd", "1", "3", "1", N, N, N, N, "", "0", "1", TS],+ &["5", REL_WEIRD, "Untitled\\tWeird\\nTitle", "3", "4", N, N, N, N, N, "", "0", "-1", TS],+ ],+ )?;+ // release_country: release, country(area id), date y/m/d+ table(dir, "release_country", &[&["1", "1", "1973", "3", "1"], &["3", "2", "1997", "9", "22"]])?;+ // release_unknown_country: release, date y/m/d+ table(+ dir,+ "release_unknown_country",+ &[&["2", "2011", N, N], &["4", "2001", "11", "5"]],+ )?;++ // medium: id, release, position, format, name, edits_pending, last_updated,+ // track_count, gid+ // Medium 1 claims 10 tracks but carries 3: the pack must publish the count it+ // can actually serve, not the dump's.+ table(+ dir,+ "medium",+ &[+ &["1", "1", "1", "1", "", "0", TS, "10", "d0000000-0000-0000-0000-000000000001"],+ &["2", "2", "1", "7", "", "0", TS, "2", "d0000000-0000-0000-0000-000000000002"],+ &["3", "3", "1", "1", "", "0", TS, "2", "d0000000-0000-0000-0000-000000000003"],+ &["4", "4", "1", "1", "", "0", TS, "2", "d0000000-0000-0000-0000-000000000004"],+ &["5", "4", "2", "1", "", "0", TS, "1", "d0000000-0000-0000-0000-000000000005"],+ &["6", "5", "1", N, "", "0", TS, "2", "d0000000-0000-0000-0000-000000000006"],+ ],+ )?;++ // recording: id, gid, name, artist_credit, length(ms), comment,+ // edits_pending, last_updated, video+ table(+ dir,+ "recording",+ &[+ &["1", REC_SPEAK_TO_ME, "Speak to Me", "1", "67000", "", "0", TS, F],+ &["2", REC_BREATHE, "Breathe", "1", "163000", "", "0", TS, F],+ &["3", REC_TIME, "Time", "1", "421000", "", "0", TS, F],+ &["4", REC_JOGA, "Jóga", "2", "305000", "", "0", TS, F],+ &["5", REC_BACHELORETTE, "Bachelorette", "2", "340000", "", "0", TS, F],+ &["6", REC_WISH, "Wish You Were Here", "1", "334000", "", "0", TS, F],+ &["7", REC_STANDALONE, "Untitled Demo", "1", N, "unreleased", "0", TS, F],+ ],+ )?;++ // track: id, gid, recording, medium, position, number, name, artist_credit,+ // length(ms), edits_pending, last_updated, is_data_track+ let g = |n: u32| -> String { format!("d1000000-0000-0000-0000-{n:012}") };+ let gids: Vec<String> = (1..=12).map(g).collect();+ table(+ dir,+ "track",+ &[+ // medium 1: track 2's title differs, track 3's length differs+ &["1", &gids[0], "1", "1", "1", "1", "Speak to Me", "1", "67000", "0", TS, F],+ &["2", &gids[1], "2", "1", "2", "2", "Breathe (In the Air)", "1", "163000", "0", TS, F],+ &["3", &gids[2], "3", "1", "3", "3", "Time", "1", "425000", "0", TS, F],+ // medium 2: a pregap track at position 0+ &["4", &gids[3], "1", "2", "0", "0", "Speak to Me", "1", N, "0", TS, F],+ &["5", &gids[4], "2", "2", "1", "1", "Breathe", "1", N, "0", TS, F],+ // medium 3+ &["6", &gids[5], "4", "3", "1", "1", "Jóga", "2", "305000", "0", TS, F],+ &["7", &gids[6], "5", "3", "2", "2", "Bachelorette", "2", "340000", "0", TS, F],+ // medium 4: track 2's credit differs from its recording's+ &["8", &gids[7], "3", "4", "1", "1", "Time", "1", "421000", "0", TS, F],+ &["9", &gids[8], "6", "4", "2", "2", "Wish You Were Here", "3", "334000", "0", TS, F],+ // medium 5+ &["10", &gids[9], "1", "5", "1", "1", "Speak to Me", "1", "67000", "0", TS, F],+ // medium 6: recordings out of clustered order, so d_recording is negative+ &["11", &gids[10], "6", "6", "1", "1", "Wish You Were Here", "1", "334000", "0", TS, F],+ &["12", &gids[11], "2", "6", "2", "2", "Breathe", "1", "163000", "0", TS, F],+ ],+ )?;++ // isrc: id, recording, isrc, edits_pending, created+ table(+ dir,+ "isrc",+ &[+ &["1", "1", "GBAYE0601498", "0", TS],+ &["2", "2", "GBAYE0601499", "0", TS],+ &["3", "4", "ISABC1200001", "0", TS],+ &["4", "2", "not-an-isrc!", "0", TS],+ ],+ )?;++ Ok(())+}
scripts/musicbrainz/mb_ingest/src/lib.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/lib.rs b/scripts/musicbrainz/mb_ingest/src/lib.rsnew file mode 100644index 0000000000..714edfc8ff--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/src/lib.rs@@ -0,0 +1,24 @@+//! MusicBrainz offline pack: build one from an mbdump full export, and read one+//! back.+//!+//! The format spec lives on `pack` (the producer is the source of truth); `reader`+//! is the consumer the server uses and must stay in sync with it.+//!+//! ```no_run+//! use mb_ingest::{build, copy::Input, reader::MbPack};+//! let input = Input::detect(std::path::Path::new("mbdump.tar.bz2"));+//! let mut out = std::fs::File::create("musicbrainz.pack")?;+//! let stats = build::build(&input, &mut out, &build::BuildOptions::default(),+//! &mut std::io::stderr())?;+//! print!("{}", stats.report());+//! # Ok::<(), std::io::Error>(())+//! ```++pub mod build;+pub mod copy;+pub mod fixture;+pub mod pack;+pub mod reader;++pub use pack::{format_mbid, parse_mbid, Mbid};+pub use reader::{MbPack, PackError};
scripts/musicbrainz/mb_ingest/src/main.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/main.rs b/scripts/musicbrainz/mb_ingest/src/main.rsnew file mode 100644index 0000000000..75405a5c47--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/src/main.rs@@ -0,0 +1,153 @@+//! CLI wrapper. All the logic is in the library so the server can call the same+//! ingest code in-process instead of shelling out to this binary.+//!+//! ```text+//! mb_ingest build <mbdump.tar.bz2 | dir> <out.pack> [--tier-a] [--official-only]+//! [--no-isrcs] [--no-recording-search]+//! [--no-recording-mbids] [-q]+//! mb_ingest fixture <dir> write the synthetic test dump+//! mb_ingest inspect <out.pack> header, section sizes and a smoke query+//! ```++use std::io::{self, Write};+use std::path::{Path, PathBuf};+use std::process::ExitCode;++use mb_ingest::build::{build, BuildOptions};+use mb_ingest::copy::Input;+use mb_ingest::fixture::write_fixture;+use mb_ingest::pack::format_mbid;+use mb_ingest::reader::MbPack;++fn main() -> ExitCode {+ match run() {+ Ok(()) => ExitCode::SUCCESS,+ Err(e) => {+ eprintln!("mb_ingest: {e}");+ ExitCode::FAILURE+ }+ }+}++fn usage() -> io::Error {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ "usage:\n \+ mb_ingest build <mbdump.tar.bz2|dir> <out.pack> [--tier-a] [--official-only] \+ [--no-isrcs] [--no-recording-search] [--no-recording-mbids] [-q]\n \+ mb_ingest fixture <dir>\n \+ mb_ingest inspect <pack>",+ )+}++fn run() -> io::Result<()> {+ let args: Vec<String> = std::env::args().skip(1).collect();+ match args.first().map(String::as_str) {+ Some("build") => cmd_build(&args[1..]),+ Some("fixture") => {+ let dir = args.get(1).ok_or_else(usage)?;+ write_fixture(Path::new(dir))?;+ println!("wrote synthetic mbdump to {dir}");+ Ok(())+ }+ Some("inspect") => cmd_inspect(args.get(1).ok_or_else(usage)?),+ _ => Err(usage()),+ }+}++fn cmd_build(args: &[String]) -> io::Result<()> {+ let mut positional: Vec<&String> = Vec::new();+ let mut opts = BuildOptions { verbose: true, ..BuildOptions::default() };+ for a in args {+ match a.as_str() {+ "--tier-a" => opts.include_track_mbids = true,+ "--official-only" => opts.official_only = true,+ "--no-isrcs" => opts.include_isrcs = false,+ "--no-recording-search" => opts.include_recording_search = false,+ "--no-recording-mbids" => opts.include_recording_mbids = false,+ "-q" | "--quiet" => opts.verbose = false,+ other if other.starts_with('-') => {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("unknown flag {other}"),+ ))+ }+ _ => positional.push(a),+ }+ }+ if positional.len() != 2 {+ return Err(usage());+ }+ let input = Input::detect(Path::new(positional[0]));+ // Write to a .tmp and rename, so a crashed build never leaves a half-written+ // pack where the server will mmap it (the sb_build.sh:90-92 convention).+ let final_path = PathBuf::from(positional[1]);+ let tmp_path = final_path.with_extension("pack.tmp");+ let started = std::time::Instant::now();+ let stats = {+ let mut file = std::fs::File::create(&tmp_path)?;+ let stats = build(&input, &mut file, &opts, &mut io::stderr())?;+ file.flush()?;+ stats+ };+ std::fs::rename(&tmp_path, &final_path)?;+ print!("{}", stats.report());+ println!(+ "wrote {} ({:.2} GB) in {:.1}s",+ final_path.display(),+ stats.total_bytes as f64 / 1e9,+ started.elapsed().as_secs_f64()+ );+ Ok(())+}++fn cmd_inspect(path: &str) -> io::Result<()> {+ let bytes = std::fs::read(path)?;+ let pack = MbPack::open(&bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;+ let c = pack.counts();+ println!("dump date {}", pack.dump_date());+ println!("flags {:#08b}", pack.flags());+ println!(" track MBIDs {}", pack.has_track_mbids());+ println!(" recording MBIDs {}", pack.has_recording_mbids());+ println!(" ISRCs {}", pack.has_isrcs());+ println!(" recording search {}", pack.has_recording_search());+ println!(" official only {}", pack.official_only());+ println!(+ "counts artists {} credits {} rgs {} releases {} media {} tracks {} \+ recordings {} isrcs {} terms {}",+ c.artists, c.credits, c.release_groups, c.releases, c.media, c.tracks, c.recordings,+ c.isrcs, c.search_terms+ );+ for (name, len) in pack.section_sizes() {+ if len > 0 {+ println!(" {name:<20} {:>12.3} MB", len as f64 / 1e6);+ }+ }+ // Smoke query: walk the first release end to end, which touches every section+ // an /api/mb/release/:mbid request would.+ if c.releases > 0 {+ let mbid = pack.release_mbid(0).expect("release 0 has an MBID");+ let rel = pack.release(0).expect("release 0");+ println!("\nfirst release {} \"{}\" [{}]", format_mbid(&mbid), rel.title, rel.status);+ for (medium, tracks) in pack.release_tracklist(0) {+ println!(" medium {} {} ({} tracks)", medium.position, medium.format, medium.track_count);+ for t in tracks {+ let isrcs: Vec<String> = pack+ .recording_isrcs(t.recording_idx)+ .iter()+ .map(|i| String::from_utf8_lossy(i).into_owned())+ .collect();+ println!(+ " {:>3}. {} — {} ({}s) rec {} {}",+ t.position,+ t.title,+ t.credit,+ t.length_secs,+ pack.recording_mbid(t.recording_idx).map(|m| format_mbid(&m)).unwrap_or_default(),+ isrcs.join(",")+ );+ }+ }+ }+ Ok(())+}
scripts/musicbrainz/mb_ingest/src/pack.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/pack.rs b/scripts/musicbrainz/mb_ingest/src/pack.rsnew file mode 100644index 0000000000..0698835a92--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/src/pack.rs@@ -0,0 +1,908 @@+//! Serialize the offline MusicBrainz catalogue to the on-disk `.pack` format and+//! provide the writer primitives (string pool, enum pool, varints, section+//! directory) the ingest passes in `build.rs` are built out of.+//!+//! ON-DISK FORMAT v1 ("MBP1", little-endian, mmap-friendly, read via+//! `read_unaligned`). THIS LAYOUT MUST STAY IN SYNC WITH+//! `scripts/musicbrainz/mb_ingest/src/reader.rs`, which is the consumer copied+//! into / path-depended on by `location_share_server`.+//!+//! Design provenance: `c:\Users\Vayun\.llms\plans\mb_pack.plan.md` (pack-designer,+//! team `mb-offline`, task 2). Section numbering below is that document's §2.3+//! numbering, preserved even where a section is now unused, so the two can be+//! read side by side. Conventions are lifted from `scripts/maps/gtfs_ingest/src/index.rs`+//! ("TRX2"): fixed header, `{u64 offset, u64 len}` section directory, 8-byte+//! aligned sections, an interning string pool, CSR child lists, and a varint+//! stream for the innermost high-cardinality table.+//!+//! # The trap this format exists to avoid+//!+//! `index.rs:15-27` records the v1 GTFS failure: a fixed-size record *per stop+//! per trip* made a world pack 10-20 GB and overflowed a u32 ceiling. `track` is+//! this format's `stop_time` -- 57.4 M rows, always read as a contiguous run per+//! medium. So tracks are never a fixed-size record and never a `Vec<TrackRec>`+//! in the writer: they are a varint stream (§ TRACKS) addressed by a per-medium+//! byte offset, factored against their recording so the common track costs ~2 B.+//! Section offsets and lengths are **u64**, so the file may exceed 4 GB.+//!+//! # Header (64 bytes)+//!+//! ```text+//! 0x00 u32 magic = 0x3150424D ("MBP1")+//! 0x04 u32 version = 1+//! 0x08 u32 section_count= 32+//! 0x0C u32 artist_count+//! 0x10 u32 credit_count+//! 0x14 u32 release_group_count+//! 0x18 u32 release_count+//! 0x1C u32 medium_count+//! 0x20 u32 track_count+//! 0x24 u32 recording_count+//! 0x28 u32 isrc_count+//! 0x2C u32 search_term_count+//! 0x30 u32 enum_count+//! 0x34 u32 flags+//! 0x38 u32 dump_date // YYYYMMDD of the source mbdump, 0 if unknown+//! 0x3C u32 _reserved+//! ```+//!+//! Then the section directory: `section_count * { u64 offset, u64 len }`,+//! absolute byte offsets from file start, every section 8-byte aligned. Absent+//! sections are present in the directory with `len == 0` rather than renumbered,+//! so one reader serves every tier of the design doc's §2.4 without a version+//! bump; `flags` says which capabilities are really there.+//!+//! `flags` bits: 0 track MBIDs present, 1 recording MBIDs present, 2 ISRCs+//! present, 3 recording search present, 4 official-releases-only, 5 string pool+//! block-compressed (**not implemented**; a reader that sees it must refuse the+//! file rather than return garbage).+//!+//! String pool offset 0 is the empty string. Dates pack into a u32 as+//! `year<<9 | month<<5 | day`, 0 meaning unknown.+//!+//! # Sections+//!+//! ```text+//! 0 STRINGS NUL-terminated UTF-8 pool; offsets are byte offsets into it.+//! 1 STRINGS_BLKIDX unused (len 0). Reserved for flags bit 5.+//! 2 ARTISTS ArtistRec[artist_count], 20 B, ordered by MBID ascending.+//! 3 ARTIST_MBID artist_count * 14 B: bytes 2..16 of the MBID. The top two+//! bytes are implied by the bucket (see ARTIST_MBID_HI), so a+//! lookup is bucket -> binary search, and the full MBID is+//! reconstructable from (bucket, record).+//! 4 ARTIST_MBID_HI u32[65537] prefix offsets: bucket b (the MBID's first two+//! bytes big-endian) occupies [HI[b], HI[b+1]).+//! 5 CREDITS u32[credit_count] STRINGS offsets of pre-rendered artist+//! credit display strings ("A feat. B"). Rendered at build+//! time because nothing reads the per-artist breakdown.+//! 6 RELEASE_GROUPS ReleaseGroupRec[release_group_count], 16 B, MBID order.+//! 7 RG_MBID as ARTIST_MBID.+//! 8 RG_MBID_HI as ARTIST_MBID_HI.+//! 9 ARTIST_RGS u32[] release-group indices, CSR values, already sorted+//! newest-first by first-release-date (the discography order+//! of MusicBrainzViewModel.kt:207) so the server sorts nothing.+//! 10 ARTIST_RGS_IDX u32[artist_count + 1] prefix offsets into ARTIST_RGS.+//! 11 RELEASES ReleaseRec[release_count], 24 B, MBID order.+//! 12 RELEASE_MBID as ARTIST_MBID.+//! 13 RELEASE_MBID_HI as ARTIST_MBID_HI.+//! 14 RG_RELEASES u32[] release indices, CSR values, already sorted by+//! (status, date) per MusicBrainzViewModel.kt:238.+//! 15 RG_RELEASES_IDX u32[release_group_count + 1] prefix offsets.+//! 16 MEDIA_IDX u32[release_count + 1] prefix offsets into MEDIA.+//! 17 MEDIA MediumRec[medium_count], 4 B. `position` is implicit: the+//! ordinal within the release's MEDIA range, +1, except where+//! the source positions are irregular, in which case the+//! medium's tracks carry it (see TRACKS bit 2 for tracks;+//! medium positions are renumbered densely, which is what the+//! UI shows as DISCNUMBER).+//! 18 TRACK_IDX u32[medium_count + 1] **byte** offsets into TRACKS, so a+//! medium's tracks are one contiguous varint run. Byte, not+//! row, exactly as ROUTE_TRIPS is addressed in index.rs:50-54.+//! 19 TRACKS varint stream, per track:+//! uvarint flags+//! bit 0 title differs from the recording's+//! bit 1 credit differs from the recording's+//! bit 2 position is not (ordinal + 1)+//! bit 3 length differs from the recording's+//! recording reference: the **first** track of a medium+//! carries `uvarint recording_idx` absolute; every later+//! track carries `zigzag varint d_recording` relative to+//! the previous track of the same medium. Absolute-per-+//! medium is what makes a medium decodable on its own,+//! which random access requires; it costs ~22 MB at full+//! scale and buys back the whole point of TRACK_IDX.+//! [bit 0] uvarint title_off (STRINGS offset)+//! [bit 1] uvarint credit_idx (CREDITS index)+//! [bit 2] uvarint position+//! [bit 3] uvarint length_secs+//! Overrides are INLINE rather than in the side tables the+//! design doc's §4.4 proposed: inline only widens the ~12% of+//! tracks that actually differ, costs ~46 MB less than+//! TRACK_TITLE_EXC + TRACK_CREDIT_EXC, and removes a binary+//! search from the hot path. Sections 20 and 21 are therefore+//! unused.+//! 20 (unused) reserved; was TRACK_TITLE_EXC.+//! 21 (unused) reserved; was TRACK_CREDIT_EXC.+//! 22 TRACK_MBID track_count * 16 B raw MBIDs in TRACKS order. **Absent+//! (len 0) in tier B**, which is the whole of tier B: 57.4 M+//! x 16 B = 918 MB, the largest single section in the format.+//! flags bit 0 is clear when it is absent.+//! 23 RECORDINGS RecordingRec[recording_count], 9 B, in the clustered order+//! described below.+//! 24 RECORDING_MBID recording_count * 16 B raw MBIDs, **unsorted**, same order+//! as RECORDINGS. Deliberate: nothing looks a recording up by+//! MBID (the WS/2 `recording/<mbid>` endpoint is dead code+//! with no callers), so recordings are instead ordered by+//! first appearance in release -> medium -> track order. That+//! makes a tracklist's `d_recording` deltas mostly 1, which is+//! what keeps TRACKS at ~2 B/track. Sorting these MBIDs would+//! buy a 14 B truncation and cost more than it saves.+//! 25 REC_FIRST_RELEASE u32[recording_count] release index of the recording's+//! first appearance, or NONE. Only used to fill the+//! `releases[0]` field of a recording search hit.+//! 26 ISRCS IsrcRec[isrc_count], 11 B, sorted by recording index:+//! u32 recording index + 7 B packed ISRC (50 bits: 2 letters,+//! 3 base-36 chars, 7 digits -- the shape the schema's own+//! CHECK constraint enforces). Binary search by recording.+//! 27 (unused) reserved; was ISRC_BLKIDX.+//! 28 SEARCH_TERMS NUL-terminated normalised search terms, sorted ascending.+//! 29 SEARCH_POSTINGS per term, a varint block: uvarint n, then n ascending+//! Δ-varint entity refs. A ref is `kind << 30 | index` with+//! kind 0 artist, 1 release group, 2 recording.+//! 30 SEARCH_TERM_IDX TermIdxRec[search_term_count + 1], 8 B: byte offset into+//! SEARCH_TERMS and byte offset into SEARCH_POSTINGS. The+//! trailing sentinel gives the last term's extents.+//! 31 ENUM_POOL u32[enum_count] STRINGS offsets for the small enumerations+//! (artist type, release-group primary/secondary type,+//! release status, medium format, country code). Records hold+//! a u16 index into this table instead of a 4 B pool offset,+//! which is worth ~56 MB across ARTISTS/RELEASE_GROUPS/+//! RELEASES/MEDIA at full scale.+//! ```+//!+//! # Reproducibility+//!+//! Byte-for-byte reproducible for a given mbdump: artist / release-group /+//! release order is MBID ascending, recording order is release -> medium -> track+//! first appearance with standalone recordings appended in source id order, the+//! search dictionary is sorted, and no hash-map iteration order reaches the+//! output.++use std::collections::HashMap;+use std::io::{self, Seek, SeekFrom, Write};++pub const MAGIC: u32 = 0x3150_424D; // "MBP1"+pub const VERSION: u32 = 1;+pub const SECTION_COUNT: usize = 32;+pub const HEADER_LEN: u64 = 64;+pub const NONE: u32 = 0xFFFF_FFFF;++pub const S_STRINGS: usize = 0;+pub const S_STRINGS_BLKIDX: usize = 1;+pub const S_ARTISTS: usize = 2;+pub const S_ARTIST_MBID: usize = 3;+pub const S_ARTIST_MBID_HI: usize = 4;+pub const S_CREDITS: usize = 5;+pub const S_RELEASE_GROUPS: usize = 6;+pub const S_RG_MBID: usize = 7;+pub const S_RG_MBID_HI: usize = 8;+pub const S_ARTIST_RGS: usize = 9;+pub const S_ARTIST_RGS_IDX: usize = 10;+pub const S_RELEASES: usize = 11;+pub const S_RELEASE_MBID: usize = 12;+pub const S_RELEASE_MBID_HI: usize = 13;+pub const S_RG_RELEASES: usize = 14;+pub const S_RG_RELEASES_IDX: usize = 15;+pub const S_MEDIA_IDX: usize = 16;+pub const S_MEDIA: usize = 17;+pub const S_TRACK_IDX: usize = 18;+pub const S_TRACKS: usize = 19;+pub const S_TRACK_MBID: usize = 22;+pub const S_RECORDINGS: usize = 23;+pub const S_RECORDING_MBID: usize = 24;+pub const S_REC_FIRST_RELEASE: usize = 25;+pub const S_ISRCS: usize = 26;+pub const S_SEARCH_TERMS: usize = 28;+pub const S_SEARCH_POSTINGS: usize = 29;+pub const S_SEARCH_TERM_IDX: usize = 30;+pub const S_ENUM_POOL: usize = 31;++pub const FLAG_TRACK_MBIDS: u32 = 1 << 0;+pub const FLAG_RECORDING_MBIDS: u32 = 1 << 1;+pub const FLAG_ISRCS: u32 = 1 << 2;+pub const FLAG_RECORDING_SEARCH: u32 = 1 << 3;+pub const FLAG_OFFICIAL_ONLY: u32 = 1 << 4;+pub const FLAG_STRINGS_COMPRESSED: u32 = 1 << 5;++/// Record widths, duplicated in the reader; the round-trip test pins them.+pub const ARTIST_REC_LEN: usize = 20;+pub const RG_REC_LEN: usize = 16;+pub const RELEASE_REC_LEN: usize = 24;+pub const MEDIUM_REC_LEN: usize = 4;+pub const RECORDING_REC_LEN: usize = 9;+pub const MBID_TRUNC_LEN: usize = 14;+pub const ISRC_REC_LEN: usize = 11;+pub const TERM_IDX_REC_LEN: usize = 8;++/// Search entity kinds, encoded in the top two bits of a posting.+pub const KIND_ARTIST: u32 = 0;+pub const KIND_RELEASE_GROUP: u32 = 1;+pub const KIND_RECORDING: u32 = 2;+pub const KIND_SHIFT: u32 = 30;+pub const IDX_MASK: u32 = (1 << KIND_SHIFT) - 1;++/// The largest entity index a search posting can name. Checked at build time+/// because silently truncating here is the modern version of the u32 stop-time+/// overflow recorded in `index.rs:15-27`.+pub const MAX_SEARCHABLE_IDX: u32 = IDX_MASK;++pub type Mbid = [u8; 16];++// --- varints (unsigned LEB128, as index.rs:106-117) ---++pub fn write_uvarint(out: &mut Vec<u8>, mut x: u64) {+ loop {+ let b = (x & 0x7f) as u8;+ x >>= 7;+ if x != 0 {+ out.push(b | 0x80);+ } else {+ out.push(b);+ break;+ }+ }+}++pub fn write_zigzag(out: &mut Vec<u8>, x: i64) {+ write_uvarint(out, ((x << 1) ^ (x >> 63)) as u64);+}++/// Decode a uvarint at `bytes[*pos]`, advancing `pos`. `None` on a truncated or+/// over-long encoding rather than a panic or a wrapped value.+pub fn read_uvarint(bytes: &[u8], pos: &mut usize) -> Option<u64> {+ let mut out: u64 = 0;+ let mut shift = 0;+ loop {+ let b = *bytes.get(*pos)?;+ *pos += 1;+ if shift >= 64 {+ return None;+ }+ out |= ((b & 0x7f) as u64) << shift;+ if b & 0x80 == 0 {+ return Some(out);+ }+ shift += 7;+ }+}++pub fn read_zigzag(bytes: &[u8], pos: &mut usize) -> Option<i64> {+ let u = read_uvarint(bytes, pos)?;+ Some(((u >> 1) as i64) ^ -((u & 1) as i64))+}++// --- dates ---++/// Pack a partial date into a u32 as `year<<9 | month<<5 | day`. 0 = unknown.+/// Out-of-range components are dropped rather than corrupting the neighbours.+pub fn pack_date(year: Option<i64>, month: Option<i64>, day: Option<i64>) -> u32 {+ let y = match year {+ Some(y) if (1..=9999).contains(&y) => y as u32,+ _ => return 0,+ };+ let m = match month {+ Some(m) if (1..=12).contains(&m) => m as u32,+ _ => 0,+ };+ let d = if m == 0 {+ 0+ } else {+ match day {+ Some(d) if (1..=31).contains(&d) => d as u32,+ _ => 0,+ }+ };+ (y << 9) | (m << 5) | d+}++// --- MBIDs ---++pub fn parse_mbid(s: &str) -> Option<Mbid> {+ let mut out = [0u8; 16];+ let mut nibble = 0usize;+ for c in s.chars() {+ if c == '-' {+ continue;+ }+ let v = match c {+ '0'..='9' => c as u8 - b'0',+ 'a'..='f' => c as u8 - b'a' + 10,+ 'A'..='F' => c as u8 - b'A' + 10,+ _ => return None,+ };+ if nibble >= 32 {+ return None;+ }+ if nibble.is_multiple_of(2) {+ out[nibble / 2] = v << 4;+ } else {+ out[nibble / 2] |= v;+ }+ nibble += 1;+ }+ if nibble == 32 {+ Some(out)+ } else {+ None+ }+}++pub fn format_mbid(m: &Mbid) -> String {+ const HEX: &[u8; 16] = b"0123456789abcdef";+ let mut s = String::with_capacity(36);+ for (i, b) in m.iter().enumerate() {+ if i == 4 || i == 6 || i == 8 || i == 10 {+ s.push('-');+ }+ s.push(HEX[(b >> 4) as usize] as char);+ s.push(HEX[(b & 0xf) as usize] as char);+ }+ s+}++// --- ISRC packing (2 letters, 3 base-36, 7 digits = 50 bits -> 7 bytes) ---++/// Pack a 12-character ISRC into 7 bytes. `None` for anything that does not+/// match the shape the MusicBrainz schema's own CHECK constraint enforces,+/// `^[A-Z]{2}[A-Z0-9]{3}[0-9]{7}$`; callers count and report rejects rather than+/// writing a corrupt record.+pub fn pack_isrc(s: &[u8]) -> Option<[u8; 7]> {+ if s.len() != 12 {+ return None;+ }+ let mut v: u64 = 0;+ for &c in &s[0..2] {+ if !c.is_ascii_uppercase() {+ return None;+ }+ v = v * 26 + (c - b'A') as u64;+ }+ for &c in &s[2..5] {+ let d = match c {+ b'0'..=b'9' => (c - b'0') as u64,+ b'A'..=b'Z' => (c - b'A') as u64 + 10,+ _ => return None,+ };+ v = v * 36 + d;+ }+ let mut n: u64 = 0;+ for &c in &s[5..12] {+ if !c.is_ascii_digit() {+ return None;+ }+ n = n * 10 + (c - b'0') as u64;+ }+ // 26*26 = 676 (10 bits), 36^3 = 46656 (16 bits), 10^7 (24 bits) = 50 bits.+ let packed = (v << 24) | n;+ let mut out = [0u8; 7];+ for (i, o) in out.iter_mut().enumerate() {+ *o = (packed >> (8 * i)) as u8;+ }+ Some(out)+}++pub fn unpack_isrc(b: &[u8; 7]) -> [u8; 12] {+ let mut packed: u64 = 0;+ for (i, &x) in b.iter().enumerate() {+ packed |= (x as u64) << (8 * i);+ }+ let n = packed & 0xFF_FFFF;+ let mut v = packed >> 24;+ let mut out = [b'0'; 12];+ let mut digits = n;+ for i in (5..12).rev() {+ out[i] = b'0' + (digits % 10) as u8;+ digits /= 10;+ }+ for i in (2..5).rev() {+ let d = (v % 36) as u8;+ out[i] = if d < 10 { b'0' + d } else { b'A' + d - 10 };+ v /= 36;+ }+ for i in (0..2).rev() {+ out[i] = b'A' + (v % 26) as u8;+ v /= 26;+ }+ out+}++// --- string pool ---++/// Interning pool producing byte offsets into STRINGS.+///+/// The index is open-addressed over u32 pool offsets rather than a+/// `HashMap<String, u32>`: at full scale there are ~23 M distinct strings, and a+/// `HashMap<String, u32>` costs well over a gigabyte of resident memory on its+/// own, while this costs 4 bytes per slot. That matters because peak RSS is the+/// binding constraint on this whole tool.+pub struct StringPool {+ bytes: Vec<u8>,+ /// Slot values are `offset + 1`; 0 means empty.+ slots: Vec<u32>,+ len: usize,+}++impl Default for StringPool {+ fn default() -> Self {+ Self::new()+ }+}++impl StringPool {+ pub fn new() -> StringPool {+ // Byte 0 is a lone NUL so offset 0 is a valid empty string.+ StringPool { bytes: vec![0], slots: vec![0; 1024], len: 0 }+ }++ pub fn bytes(&self) -> &[u8] {+ &self.bytes+ }++ pub fn distinct(&self) -> usize {+ self.len+ }++ fn hash(s: &[u8]) -> u64 {+ // FNV-1a: cheap, no dependency, good enough for short titles.+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;+ for &b in s {+ h ^= b as u64;+ h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+ h+ }++ fn at(&self, off: u32) -> &[u8] {+ let start = off as usize;+ let end = self.bytes[start..].iter().position(|&b| b == 0).unwrap() + start;+ &self.bytes[start..end]+ }++ fn grow(&mut self) {+ let mut slots = vec![0u32; self.slots.len() * 2];+ let mask = slots.len() - 1;+ for i in 0..self.slots.len() {+ let v = self.slots[i];+ if v == 0 {+ continue;+ }+ let off = v - 1;+ let mut j = (Self::hash(self.at(off)) as usize) & mask;+ while slots[j] != 0 {+ j = (j + 1) & mask;+ }+ slots[j] = v;+ }+ self.slots = slots;+ }++ /// Intern `s`, returning its byte offset. The empty string is always 0.+ pub fn intern(&mut self, s: &str) -> u32 {+ if s.is_empty() {+ return 0;+ }+ if self.len * 4 >= self.slots.len() * 3 {+ self.grow();+ }+ let mask = self.slots.len() - 1;+ let mut j = (Self::hash(s.as_bytes()) as usize) & mask;+ loop {+ let v = self.slots[j];+ if v == 0 {+ let off = self.bytes.len();+ assert!(+ off + s.len() < u32::MAX as usize,+ "STRINGS exceeded the u32 offset ceiling at {off} bytes; the pool \+ is the first field in this format that would overflow (design doc §4.7)"+ );+ self.bytes.extend_from_slice(s.as_bytes());+ self.bytes.push(0);+ self.slots[j] = off as u32 + 1;+ self.len += 1;+ return off as u32;+ }+ if self.at(v - 1) == s.as_bytes() {+ return v - 1;+ }+ j = (j + 1) & mask;+ }+ }+}++/// The small enumerations (artist type, RG types, release status, medium format,+/// country code) share one table of STRINGS offsets so records can hold a u16+/// index instead of a 4 B pool offset.+pub struct EnumPool {+ offsets: Vec<u32>,+ map: HashMap<String, u16>,+}++impl Default for EnumPool {+ fn default() -> Self {+ Self::new()+ }+}++impl EnumPool {+ pub fn new() -> EnumPool {+ EnumPool { offsets: Vec::new(), map: HashMap::new() }+ }++ /// `None` is represented by `NONE_ENUM`, which resolves to the empty string.+ pub const NONE_ENUM: u16 = u16::MAX;++ pub fn intern(&mut self, pool: &mut StringPool, s: &str) -> u16 {+ if s.is_empty() {+ return Self::NONE_ENUM;+ }+ if let Some(&i) = self.map.get(s) {+ return i;+ }+ assert!(+ self.offsets.len() < u16::MAX as usize,+ "ENUM_POOL overflowed 65535 entries; a genuinely large vocabulary does not \+ belong in this table"+ );+ let i = self.offsets.len() as u16;+ let off = pool.intern(s);+ self.offsets.push(off);+ self.map.insert(s.to_string(), i);+ i+ }++ pub fn offsets(&self) -> &[u32] {+ &self.offsets+ }+}++// --- section writer ---++/// Streams sections to the pack file, patching the directory at the end.+///+/// Sections are streamed rather than assembled into one `Vec<u8>` because at full+/// scale the sections total more than 2 GB; buffering them all is the memory+/// failure this format is designed around.+pub struct PackWriter<W: Write + Seek> {+ w: W,+ dir: Vec<(u64, u64)>,+ pos: u64,+ open: Option<(usize, u64)>,+ header: [u8; HEADER_LEN as usize],+}++impl<W: Write + Seek> PackWriter<W> {+ pub fn new(mut w: W) -> io::Result<PackWriter<W>> {+ let dir_len = (SECTION_COUNT * 16) as u64;+ let zeros = vec![0u8; (HEADER_LEN + dir_len) as usize];+ w.write_all(&zeros)?;+ Ok(PackWriter {+ w,+ dir: vec![(0, 0); SECTION_COUNT],+ pos: HEADER_LEN + dir_len,+ open: None,+ header: [0u8; HEADER_LEN as usize],+ })+ }++ fn align(&mut self) -> io::Result<()> {+ let pad = (8 - (self.pos % 8)) % 8;+ if pad != 0 {+ self.w.write_all(&[0u8; 8][..pad as usize])?;+ self.pos += pad;+ }+ Ok(())+ }++ pub fn begin(&mut self, index: usize) -> io::Result<()> {+ assert!(self.open.is_none(), "section {index} begun while another is open");+ assert!(index < SECTION_COUNT, "section index {index} out of range");+ assert!(self.dir[index] == (0, 0), "section {index} written twice");+ self.align()?;+ self.open = Some((index, self.pos));+ Ok(())+ }++ pub fn write(&mut self, bytes: &[u8]) -> io::Result<()> {+ assert!(self.open.is_some(), "write with no section open");+ self.w.write_all(bytes)?;+ self.pos += bytes.len() as u64;+ Ok(())+ }++ pub fn end(&mut self) -> io::Result<u64> {+ let (index, start) = self.open.take().expect("end with no section open");+ let len = self.pos - start;+ self.dir[index] = (start, len);+ Ok(len)+ }++ /// Write a whole section from one buffer.+ pub fn section(&mut self, index: usize, bytes: &[u8]) -> io::Result<u64> {+ self.begin(index)?;+ self.write(bytes)?;+ self.end()+ }++ pub fn section_u32(&mut self, index: usize, vals: &[u32]) -> io::Result<u64> {+ self.begin(index)?;+ // Chunked so a 65 M-entry index does not need a second full-size buffer.+ let mut buf = Vec::with_capacity(4 * 4096);+ for chunk in vals.chunks(4096) {+ buf.clear();+ for v in chunk {+ buf.extend_from_slice(&v.to_le_bytes());+ }+ self.write(&buf)?;+ }+ self.end()+ }++ #[allow(clippy::too_many_arguments)]+ pub fn set_header(&mut self, counts: &HeaderCounts, flags: u32, dump_date: u32) {+ let mut h = [0u8; HEADER_LEN as usize];+ let mut put = |off: usize, v: u32| h[off..off + 4].copy_from_slice(&v.to_le_bytes());+ put(0x00, MAGIC);+ put(0x04, VERSION);+ put(0x08, SECTION_COUNT as u32);+ put(0x0C, counts.artists);+ put(0x10, counts.credits);+ put(0x14, counts.release_groups);+ put(0x18, counts.releases);+ put(0x1C, counts.media);+ put(0x20, counts.tracks);+ put(0x24, counts.recordings);+ put(0x28, counts.isrcs);+ put(0x2C, counts.search_terms);+ put(0x30, counts.enums);+ put(0x34, flags);+ put(0x38, dump_date);+ self.header = h;+ }++ /// Patch the header and directory. Returns the total file length.+ pub fn finish(mut self) -> io::Result<u64> {+ assert!(self.open.is_none(), "finish with a section still open");+ let total = self.pos;+ self.w.seek(SeekFrom::Start(0))?;+ self.w.write_all(&self.header)?;+ let mut dir = Vec::with_capacity(SECTION_COUNT * 16);+ for &(off, len) in &self.dir {+ dir.extend_from_slice(&off.to_le_bytes());+ dir.extend_from_slice(&len.to_le_bytes());+ }+ self.w.write_all(&dir)?;+ self.w.flush()?;+ Ok(total)+ }++ pub fn section_sizes(&self) -> Vec<(usize, u64)> {+ self.dir.iter().enumerate().map(|(i, &(_, len))| (i, len)).collect()+ }+}++#[derive(Default, Clone, Copy)]+pub struct HeaderCounts {+ pub artists: u32,+ pub credits: u32,+ pub release_groups: u32,+ pub releases: u32,+ pub media: u32,+ pub tracks: u32,+ pub recordings: u32,+ pub isrcs: u32,+ pub search_terms: u32,+ pub enums: u32,+}++/// Human-readable names, only for the build report.+pub const SECTION_NAMES: [&str; SECTION_COUNT] = [+ "STRINGS",+ "STRINGS_BLKIDX",+ "ARTISTS",+ "ARTIST_MBID",+ "ARTIST_MBID_HI",+ "CREDITS",+ "RELEASE_GROUPS",+ "RG_MBID",+ "RG_MBID_HI",+ "ARTIST_RGS",+ "ARTIST_RGS_IDX",+ "RELEASES",+ "RELEASE_MBID",+ "RELEASE_MBID_HI",+ "RG_RELEASES",+ "RG_RELEASES_IDX",+ "MEDIA_IDX",+ "MEDIA",+ "TRACK_IDX",+ "TRACKS",+ "(unused 20)",+ "(unused 21)",+ "TRACK_MBID",+ "RECORDINGS",+ "RECORDING_MBID",+ "REC_FIRST_RELEASE",+ "ISRCS",+ "(unused 27)",+ "SEARCH_TERMS",+ "SEARCH_POSTINGS",+ "SEARCH_TERM_IDX",+ "ENUM_POOL",+];++/// Build the `{bucket -> [start, end)}` prefix table for a sorted MBID list and+/// the truncated 14-byte records that go with it.+pub fn build_mbid_table(sorted: &[Mbid]) -> (Vec<u8>, Vec<u32>) {+ let mut recs = Vec::with_capacity(sorted.len() * MBID_TRUNC_LEN);+ let mut hi = vec![0u32; 65537];+ for m in sorted {+ recs.extend_from_slice(&m[2..]);+ let bucket = ((m[0] as usize) << 8) | m[1] as usize;+ hi[bucket + 1] += 1;+ }+ for i in 0..65536 {+ hi[i + 1] += hi[i];+ }+ (recs, hi)+}++/// Normalise a string for the search index: lowercase, strip accents on the+/// Latin-1 range, and split on anything that is not alphanumeric.+///+/// Deliberately not a full Unicode normaliser: this crate has no dependencies,+/// and the app's current behaviour is Lucene's, which we cannot reproduce+/// anyway (design doc R7). CJK text yields one term per run of ideographs, which+/// makes it prefix-searchable as a whole title but not per character.+pub fn search_terms(s: &str, out: &mut Vec<String>) {+ let mut cur = String::new();+ for ch in s.chars() {+ let c = fold_char(ch);+ if c.is_alphanumeric() {+ for l in c.to_lowercase() {+ cur.push(l);+ }+ } else if !cur.is_empty() {+ out.push(std::mem::take(&mut cur));+ }+ }+ if !cur.is_empty() {+ out.push(cur);+ }+}++fn fold_char(c: char) -> char {+ match c {+ 'à'..='å' | 'À'..='Å' => 'a',+ 'è'..='ë' | 'È'..='Ë' => 'e',+ 'ì'..='ï' | 'Ì'..='Ï' => 'i',+ 'ò'..='ö' | 'Ò'..='Ö' => 'o',+ 'ù'..='ü' | 'Ù'..='Ü' => 'u',+ 'ç' | 'Ç' => 'c',+ 'ñ' | 'Ñ' => 'n',+ 'ý' | 'ÿ' | 'Ý' => 'y',+ 'ø' | 'Ø' => 'o',+ 'æ' | 'Æ' => 'a',+ 'ß' => 's',+ other => other,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn uvarint_round_trips() {+ for v in [0u64, 1, 127, 128, 300, 16383, 16384, u32::MAX as u64, u64::MAX] {+ let mut buf = Vec::new();+ write_uvarint(&mut buf, v);+ let mut pos = 0;+ assert_eq!(read_uvarint(&buf, &mut pos), Some(v), "value {v}");+ assert_eq!(pos, buf.len());+ }+ }++ #[test]+ fn zigzag_round_trips() {+ for v in [0i64, 1, -1, 63, -64, 1000, -1000, i32::MIN as i64, i32::MAX as i64] {+ let mut buf = Vec::new();+ write_zigzag(&mut buf, v);+ let mut pos = 0;+ assert_eq!(read_zigzag(&buf, &mut pos), Some(v), "value {v}");+ }+ }++ #[test]+ fn truncated_uvarint_is_none_not_panic() {+ assert_eq!(read_uvarint(&[0x80], &mut 0), None);+ assert_eq!(read_uvarint(&[], &mut 0), None);+ }++ #[test]+ fn mbid_round_trips() {+ let s = "f27ec8db-af05-4f36-916e-3d57f91ecf5e";+ let m = parse_mbid(s).unwrap();+ assert_eq!(format_mbid(&m), s);+ assert_eq!(parse_mbid("F27EC8DB-AF05-4F36-916E-3D57F91ECF5E"), Some(m));+ assert_eq!(parse_mbid("f27ec8dbaf054f36916e3d57f91ecf5e"), Some(m));+ assert_eq!(parse_mbid("not-a-mbid"), None);+ assert_eq!(parse_mbid(""), None);+ assert_eq!(parse_mbid("f27ec8db-af05-4f36-916e-3d57f91ecf5e-extra"), None);+ }++ #[test]+ fn isrc_round_trips() {+ for s in ["GBAYE0601498", "USRC17607839", "ZZZ990000000", "AAA000000000"] {+ let p = pack_isrc(s.as_bytes()).unwrap_or_else(|| panic!("pack {s}"));+ assert_eq!(&unpack_isrc(&p), s.as_bytes(), "isrc {s}");+ }+ assert_eq!(pack_isrc(b"TOOSHORT"), None);+ assert_eq!(pack_isrc(b"gbaye0601498"), None, "lowercase must be rejected");+ assert_eq!(pack_isrc(b"GBAYE060149X"), None, "non-digit designation");+ }++ #[test]+ fn string_pool_dedups_and_keeps_zero_empty() {+ let mut p = StringPool::new();+ assert_eq!(p.intern(""), 0);+ let a = p.intern("Pink Floyd");+ let b = p.intern("Pink Floyd");+ assert_eq!(a, b);+ assert_ne!(a, p.intern("Pink Floyd "));+ assert_eq!(p.distinct(), 2);+ // Force several table growths.+ for i in 0..5000 {+ p.intern(&format!("title {i}"));+ }+ assert_eq!(p.intern("title 4999"), p.intern("title 4999"));+ assert_eq!(p.distinct(), 5002);+ }++ #[test]+ fn dates_pack() {+ assert_eq!(pack_date(None, None, None), 0);+ let d = pack_date(Some(1973), Some(3), Some(1));+ assert_eq!(d >> 9, 1973);+ assert_eq!((d >> 5) & 0xf, 3);+ assert_eq!(d & 0x1f, 1);+ // A day without a month is meaningless; drop it rather than store a lie.+ assert_eq!(pack_date(Some(1973), None, Some(4)) & 0x1f, 0);+ assert_eq!(pack_date(Some(1973), Some(13), None) >> 5 & 0xf, 0);+ }++ #[test]+ fn search_terms_split_and_fold() {+ let mut t = Vec::new();+ search_terms("The Dark Side of the Moon", &mut t);+ assert_eq!(t, ["the", "dark", "side", "of", "the", "moon"]);+ t.clear();+ search_terms("Björk — Homogénic (Remastered)", &mut t);+ assert_eq!(t, ["bjork", "homogenic", "remastered"]);+ t.clear();+ search_terms("!!!", &mut t);+ assert!(t.is_empty());+ }++ #[test]+ fn mbid_buckets_are_prefix_sums() {+ let a = parse_mbid("0000ffff-0000-0000-0000-000000000001").unwrap();+ let b = parse_mbid("0000ffff-0000-0000-0000-000000000002").unwrap();+ let c = parse_mbid("ffff0000-0000-0000-0000-000000000003").unwrap();+ let (recs, hi) = build_mbid_table(&[a, b, c]);+ assert_eq!(recs.len(), 3 * MBID_TRUNC_LEN);+ assert_eq!(hi[0], 0);+ assert_eq!(hi[1] - hi[0], 2, "both 0x0000-prefixed MBIDs land in bucket 0");+ assert_eq!(hi[0xffff + 1] - hi[0xffff], 1);+ assert_eq!(hi[65536], 3);+ }+}
scripts/musicbrainz/mb_ingest/src/reader.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/reader.rs b/scripts/musicbrainz/mb_ingest/src/reader.rsnew file mode 100644index 0000000000..885d8fabff--- /dev/null+++ b/scripts/musicbrainz/mb_ingest/src/reader.rs@@ -0,0 +1,1163 @@+//! Read an offline MusicBrainz pack ("MBP1").+//!+//! THIS LAYOUT MUST STAY IN SYNC WITH+//! `scripts/musicbrainz/mb_ingest/src/pack.rs`, which is the producer and the+//! authoritative spec. Every constant here is duplicated there and pinned by the+//! round-trip test in `tests/round_trip.rs`.+//!+//! Written to be copied into / path-depended on by `location_share_server`:+//!+//! * it has **no dependencies** and does not own the mapping. `MbPack::open`+//! takes a `&[u8]`, so the caller keeps using memmap2 exactly as it does for+//! `traffic_edges.bin` (`main.rs:391-405`, `state.rs:26-28`) and hands the+//! slice in. `open` only validates the header and directory, so calling it+//! per request is cheap and avoids a self-referential `AppState` field.+//! * every accessor is bounds-checked and returns `Option`/empty rather than+//! panicking, in the style of `openlr/graph.rs:371-390`. It deliberately does+//! *not* copy `handlers/maps/traffic.rs:285-292`, where `mmap.len() - 259200`+//! underflows on a truncated file.+//! * strings come back as `Cow<'a, str>`. Today the pool is uncompressed so+//! they are always borrowed and free; the type is `Cow` so that turning on the+//! compressed pool later does not break callers.++use std::borrow::Cow;+use std::collections::HashMap;+use std::fmt;++use crate::pack::{+ self, read_uvarint, read_zigzag, Mbid, IDX_MASK, KIND_ARTIST, KIND_RECORDING,+ KIND_RELEASE_GROUP, KIND_SHIFT, MAGIC, SECTION_COUNT, VERSION,+};++// --- errors ---++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum PackError {+ TooSmall { len: usize },+ BadMagic { found: u32 },+ BadVersion { found: u32, expected: u32 },+ BadSectionCount { found: u32, expected: u32 },+ SectionOutOfBounds { index: usize, offset: u64, len: u64, file_len: u64 },+ SectionMisaligned { index: usize, offset: u64 },+ SectionTruncated { index: usize, need: u64, have: u64 },+ UnsupportedPoolCodec,+}++impl fmt::Display for PackError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ PackError::TooSmall { len } => {+ write!(f, "pack is {len} bytes, too small to hold a header and directory")+ }+ PackError::BadMagic { found } => {+ write!(f, "bad magic {found:#010x}, expected {MAGIC:#010x} (\"MBP1\")")+ }+ PackError::BadVersion { f
Diff truncated.