Modern Apps git

← Modern-Apps.git

musicbrainz: zstd string pool, spill sort, TableSource seam

Commit
cc150a4830accd483bacecd92cfe7ccc18e99ce5
Author
vayun-mathur <[email protected]>
When
2026-08-20 21:26 UTC (3 months ago)
Parents
32870db

Diff

scripts/musicbrainz/mb_ingest/Cargo.lock
diff --git a/scripts/musicbrainz/mb_ingest/Cargo.lock b/scripts/musicbrainz/mb_ingest/Cargo.lockindex 4a863f7f3a..f7d2f94da0 100644--- a/scripts/musicbrainz/mb_ingest/Cargo.lock+++ b/scripts/musicbrainz/mb_ingest/Cargo.lock@@ -2,6 +2,106 @@ # It is not intended for manual editing. version = 4 +[[package]]+name = "cc"+version = "1.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d"+dependencies = [+ "find-msvc-tools",+ "jobserver",+ "libc",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "find-msvc-tools"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+]++[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom",+ "libc",+]++[[package]]+name = "libc"+version = "0.2.189"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"+ [[package]] name = "mb_ingest" version = "0.1.0"+dependencies = [+ "zstd",+]++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "zstd"+version = "0.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"+dependencies = [+ "zstd-safe",+]++[[package]]+name = "zstd-safe"+version = "7.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"+dependencies = [+ "zstd-sys",+]++[[package]]+name = "zstd-sys"+version = "2.0.16+zstd.1.5.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"+dependencies = [+ "cc",+ "pkg-config",+]
scripts/musicbrainz/mb_ingest/Cargo.toml
diff --git a/scripts/musicbrainz/mb_ingest/Cargo.toml b/scripts/musicbrainz/mb_ingest/Cargo.tomlindex 875161bab4..d68fc564e7 100644--- a/scripts/musicbrainz/mb_ingest/Cargo.toml+++ b/scripts/musicbrainz/mb_ingest/Cargo.toml@@ -1,15 +1,23 @@ # 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.+# Detached from the repo-root Rust workspace (the empty [workspace] table below),+# as scripts/maps/gtfs_ingest is, so `cargo build` here never pulls the+# aarch64-android toolchain or the app crates' lints.+#+# gtfs_ingest is deliberately dependency-free; this crate is not, and the reason+# is worth recording. The server pipeline that feeds it already needs a C+# compiler (bzip2-sys for the archive, and zstd-sys transitively through+# `zip 8.6.0`), so zstd is not a new CLASS of dependency here -- and it buys+# ~450 MB, about 15% of the pack, by block-compressing the string pool. See the+# "Why the string pool is sorted" section of README.md. # # 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::build` turns mbdump tables into a `.pack`, reading them through+#     `mb_ingest::copy::TableSource` -- this crate never touches the archive,+#     bzip2 or tar, which the server owns; #   * `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).+#     in-process (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"@@ -27,9 +35,10 @@ name = "mb_ingest" path = "src/main.rs"  [dependencies]+zstd = "0.13"  [profile.release] opt-level = 3 -# Detach from the repo-root workspace so this host tool builds standalone/offline.+# Detach from the repo-root workspace so this host tool builds standalone. [workspace]
scripts/musicbrainz/mb_ingest/README.md
diff --git a/scripts/musicbrainz/mb_ingest/README.md b/scripts/musicbrainz/mb_ingest/README.mdindex 67b1c78396..ecfcf9d705 100644--- a/scripts/musicbrainz/mb_ingest/README.md+++ b/scripts/musicbrainz/mb_ingest/README.md@@ -9,38 +9,59 @@ 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`.+Detached from the repo-root Cargo workspace, as `scripts/maps/gtfs_ingest` is.+One dependency, `zstd`, for the compressed string pool; `location_share_server`+already pulls it in transitively through `zip 8.6.0`.++## Where the boundaries are++This crate does **not** download anything and does not touch bzip2 or tar.+`location_share_server` owns the download, does one bzip2 traversal of the+archive, demuxes the tar, spills the 20 tables named in `build::TABLES`, and+implements `copy::TableSource` over them. That matters because bz2 is not+seekable: one traversal of the 7.45 GB archive is ~8.5 minutes at the measured+14.7 MB/s, so a pass-per-table design would spend over an hour just inflating the+same bytes.++The trait is small, and **tables must be re-openable**:++```rust+pub trait TableSource {+    fn open_table(&self, table: &str) -> io::Result<Option<Box<dyn BufRead + Send>>>;+    fn dump_date(&self) -> u32 { 0 }+    fn describe(&self) -> String { .. }+}+```++`copy::Input` implements it over a directory or a `.tar.bz2` (through the system+`tar`). Those exist so the fixture and the CLI work without the server's+pipeline; they are not the production path.  ## Use  ```sh cargo build --release -# Recommended for the real 7 GB export: extract only the 20 tables this crate-# reads (one bz2 pass, ~13 GB of disk), then build from the directory.-./target/release/mb_ingest extract mbdump.tar.bz2 /scratch/mbdump-./target/release/mb_ingest build /scratch/mbdump musicbrainz.pack--# Also works, and streams with nothing extracted -- but costs one bz2-# decompression pass PER TABLE, so it is for small archives and fixtures.-./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+./target/release/mb_ingest build /tmp/mb /tmp/musicbrainz.pack+./target/release/mb_ingest inspect /tmp/musicbrainz.pack -cargo test          # 36 tests, including a full round trip through the reader+cargo test          # 42 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`,+drops the 9.4% of releases that are not Official, `--raw-strings` leaves the+string pool uncompressed (+454 MB, but strings become zero-copy),+`--work-dir <dir>` places the track spill buckets, `--no-isrcs`, `--no-recording-search`, `--no-recording-mbids`. +`build` writes `<out>.pack.tmp` and renames, so a crashed build never leaves a+half-written pack where the server would mmap it.+ ## Input -Only **`mbdump.tar.bz2`** (7 GB) is needed. Verified against the live export+Only **`mbdump.tar.bz2`** is needed. Verified against the live export (`20260819-002541`), not assumed:  * core-dump members are `mbdump/<table>`, unprefixed, in ASCII order, after@@ -50,106 +71,135 @@ Only **`mbdump.tar.bz2`** (7 GB) is needed. Verified against the live export   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`.+All 20 tables read are marked `-- replicate` in `admin/sql/CreateTables.sql`,+which is what puts a table in the core dump — including `release_group_meta`, the+source of `first_release_date_*`, which is a core table despite ratings being a+derived-dump concern.  **`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+Column order is hard-coded from `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.+The export directory publishes `SHA256SUMS` and `SHA256SUMS.asc`. SHA256 against+the published sums is the agreed bar: they arrive over the same authenticated TLS+channel as the archive, so PGP's marginal gain is protection against a+compromised origin, which is not the threat model for a personal server ingesting+a public dataset. The stronger option, if that ever changes, is verifying+`SHA256SUMS.asc` against MusicBrainz's key `C777580F` (fingerprint+`D5E6 3B4B DCCE 1956 4294 8684 B8FC 2375 C777 580F`).  ## 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.+**projections from the measured row counts, not from a completed full run.**  | section | MB | |---|---|-| `STRINGS` (uncompressed) | 635 | | `RECORDING_MBID` | 638 | | `RECORDINGS` | 359 | | `TRACKS` (varint, overrides inline) | ~235 |+| `STRINGS` (zstd, sorted, from 635 raw) | ~181 | | `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 |+| `ISRCS` | 69 | | 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`.+| **total, tier B** | **~2 510** |++**~2.51 GB.** The design doc's 2,409.5 MB differs by ~100 MB of deliberate+layout corrections, itemised here so the gap is not a mystery:++* `ReleaseRec` is 24 B, not 20 (+23 MB). The doc packs "status+country" into one+  byte; a u8 cannot hold an ISO-3166-1 alpha-2 code.+* `ReleaseGroupRec` 16 B not 14 (+9), `ArtistRec` 20 B not 18 (+6): the small+  enumerations and the ~250 country codes share one table and need u16 indices.+* `MEDIA` 4 B not 1 (+19). The doc's medium record holds only a format byte, so+  per-medium track counts would have to be derived by decoding tracklists — on a+  release-group page with up to 100 editions, thousands of varint runs per+  request. Storing the count makes `TRACKTOTAL` O(1).+* `ISRCS` 69 MB not 25 (+44). Plain 11 B records sorted for binary search rather+  than delta-varint in compressed blocks. Recoverable later.+* `SEARCH_TERM_IDX` 44 MB not 22 (+22). A term needs two offsets, one into the+  dictionary and one into the postings; the doc budgeted one.+* `TRACKS` −24 MB, *and* it keeps a field the doc dropped. Title and credit+  overrides are inline in the varint stream rather than in `TRACK_TITLE_EXC` /+  `TRACK_CREDIT_EXC` side arrays: inline only widens the ~12% of tracks that+  differ, is 46 MB cheaper, and removes a binary search from the hot path. The+  room that freed up now carries per-track length overrides, which doc L8+  discarded — wrongly, because `track.length ?: recording.length`+  (`MusicBrainzViewModel.kt:503`) makes the track's length the primary source.+* the first track of each medium carries an **absolute** recording index rather+  than a delta from the previous medium's last track (+22 MB, inside the ~235).+  Without that a medium cannot be decoded on its own and `TRACK_IDX`'s byte+  offset buys nothing.++Tier A (add track MBIDs) is ~3.43 GB.  ## Where the memory goes -Peak RSS, not wall time, is the binding constraint. Two rules the code follows:+Peak RSS is the binding constraint, not wall time: the ingest runs in-process+alongside the live server on an 11 GB box, so the budget is 4 GB. Four 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:+* **id maps are dense `Vec<u32>` keyed by the dump's integer primary key.**+  mbdump foreign keys are integer row ids (`track.recording INTEGER`), not gids,+  so all six maps together are ~400 MB rather than the ~1.4 GB a+  `HashMap<[u8;16], u32>` over recording gids alone would cost.+* **track rows are bucket-sorted through spill files.** The dump is in track-id+  order and `TRACKS` needs medium order; buffering all 57.4 M rows to sort would+  be ~1.4 GB. Instead 24-byte records go out to 64 medium-keyed buckets and each+  bucket (~25 MB) is sorted in memory. This needs the table to be re-openable.+* **`RECORDING_MBID` is filled by a second pass over `recording`** that scatters+  gids into the output buffer, rather than holding 16 B per recording id (~800 MB)+  through the whole build.++Projected peak, largest phase governing — a projection, 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, which is why-`extract` exists: one pass over the archive rather than one per table. The build-itself is a sort plus linear scans. Output is written to `<out>.pack.tmp` and-renamed, so a crashed build never leaves a half-written pack where the server-would mmap it.--The same pack is produced byte for byte whether the input is the archive or an-extracted directory; the round-trip test asserts reproducibility.+| string pool staging bytes | ~635 |+| recording title/credit/duration arrays | ~500 |+| dense id -> index maps | ~400 |+| string pool interning index | ~130 |+| `TRACKS` output buffer | ~235 |+| one track bucket | ~25 |+| **peak** | **~2 100** |++The string pool's interning index is open-addressed over u32 symbol ids, not a+`HashMap<String, u32>`: the latter is ~1.84 GB steady with a ~2.3 GB transient+spike at its final resize, which does not fit.++Disk: ~1.4 GB of scratch for the track spill (`--work-dir`), plus the pack.++## Why the string pool is sorted++`intern` returns a dense **symbol id**, not a byte offset. Offsets are assigned+only by `finalize`, after sorting every distinct string alphabetically. zstd over+64 KB blocks of sorted short text gets ~3.5x where the same text in interning+order gets ~2.5-3x, and the offsets cannot be reordered afterwards because they+are baked into the inline overrides of the `TRACKS` varint stream, where changing+an offset changes the varint's width. Deferring costs nothing: every table is+read before any offset is needed.++Blocks break at exact multiples of 64 KiB so a pool offset names its block by+division rather than a search. A string may straddle a boundary; the reader+continues into the next block when it does not find the terminating NUL.  ## What tier B gives up @@ -167,11 +217,12 @@ Also given up, deliberately:   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+  "The Dark Side of the Moon"; "loitude" does not find "Solitude". Query words+  are ANDed. Results will differ from musicbrainz.org.+* durations are **seconds, not milliseconds** — the UI renders m:ss, Tidal   matching uses a ±3 s tolerance and LRCLIB takes seconds.+* strings are `Cow<'a, str>`: owned when the pool is compressed, borrowed when+  `--raw-strings` is used. Do not assume they are free.  ## Possible follow-up, not in scope here 
scripts/musicbrainz/mb_ingest/src/build.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/build.rs b/scripts/musicbrainz/mb_ingest/src/build.rsindex 1424c35534..e4ca128a13 100644--- a/scripts/musicbrainz/mb_ingest/src/build.rs+++ b/scripts/musicbrainz/mb_ingest/src/build.rs@@ -5,32 +5,42 @@ //! are checked on the first row (see `copy::Shape`), because a silently shifted //! column would produce a plausible-looking but wrong pack. //!+//! Tables arrive through [`crate::copy::TableSource`]. This crate never touches+//! the archive, bzip2 or tar — `location_share_server` owns the download and does+//! one traversal, spilling the 20 tables named in [`TABLES`]. It matters that the+//! spilled tables are **re-openable**: the track pass reads `track` once to spill+//! it into medium-keyed buckets and then reads the buckets back, which is what+//! keeps 57.4 M track rows out of memory.+//! //! # Memory //!-//! Peak RSS is the binding constraint, not wall time. Two rules:+//! Peak RSS, not wall time, is the binding constraint: the ingest runs in-process+//! alongside the live server on an 11 GB box, so the budget is 4 GB. Four 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.+//!     key, not `HashMap<[u8;16], u32>` keyed by MBID. mbdump foreign keys are+//!     integer row ids (`track.recording INTEGER`), so the recording map is+//!     ~180 MB rather than the ~1.4 GB a UUID-keyed hash map would cost.+//!   * the track rows are **bucket-sorted through spill files**, not sorted in+//!     memory. The dump is in track-id order and `TRACKS` needs medium order;+//!     buffering all 57.4 M rows to sort would be ~1.4 GB.+//!   * `RECORDING_MBID` is filled by a second pass over `recording` that scatters+//!     gids into the output buffer, rather than holding 16 B per recording id+//!     (~800 MB) through the whole build.  use std::collections::HashMap;-use std::io::{self, Seek, Write};+use std::fs::File;+use std::io::{self, BufWriter, Read, Seek, Write};+use std::path::{Path, PathBuf}; -use crate::copy::{other_err, Input, Row, Shape};+use crate::copy::{each_row, other_err, Row, Shape, TableSource}; use crate::pack::{-    self, build_mbid_table, pack_date, pack_isrc, parse_mbid, search_terms, EnumPool, HeaderCounts,-    Mbid, PackWriter, StringPool,+    self, build_mbid_table, pack_date, pack_isrc, parse_mbid, search_terms, EnumPool, FinalPool,+    HeaderCounts, Mbid, PackWriter, StringBlockWriter, StringPool, Sym, SYM_EMPTY, }; use crate::reader::encode_recording_credit; @@ -38,8 +48,9 @@ use crate::reader::encode_recording_credit; /// an absurd primary key. const MAX_ID: u32 = 400_000_000; -/// Every table this crate reads, in the order the passes want them. All of these-/// live in the core `mbdump.tar.bz2`; none needs `mbdump-derived.tar.bz2`.+/// Every table this crate reads. All of these live in the core `mbdump.tar.bz2`+/// (each is marked `-- replicate` in `admin/sql/CreateTables.sql`, which is what+/// puts a table in that dump); none needs `mbdump-derived.tar.bz2`. pub const TABLES: &[&str] = &[     "area",     "iso_3166_1",@@ -63,13 +74,18 @@ pub const TABLES: &[&str] = &[     "isrc", ]; -#[derive(Clone, Copy)]+#[derive(Clone)] 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,+    /// Compress the string pool with zstd. Worth ~450 MB of the ~2.9 GB pack.+    pub compress_strings: bool,+    /// Where the track bucket files go. Defaults to the system temp directory.+    /// Needs room for ~1.4 GB at full scale.+    pub work_dir: Option<PathBuf>,     pub verbose: bool, } @@ -83,6 +99,8 @@ impl Default for BuildOptions {             include_isrcs: true,             include_recording_search: true,             official_only: false,+            compress_strings: true,+            work_dir: None,             verbose: false,         }     }@@ -110,6 +128,9 @@ impl BuildOptions {         if self.official_only {             f |= pack::FLAG_OFFICIAL_ONLY;         }+        if self.compress_strings {+            f |= pack::FLAG_STRINGS_COMPRESSED;+        }         f     } }@@ -122,7 +143,9 @@ pub struct BuildStats {     pub sections: Vec<(&'static str, u64)>,     pub total_bytes: u64,     pub distinct_strings: usize,-    pub string_pool_bytes: usize,+    pub string_pool_raw: u64,+    pub string_pool_stored: u64,+    pub string_blocks: u32,     pub recording_titles: u64,     pub distinct_recording_titles: u64,     pub tracks_title_same: u64,@@ -131,7 +154,7 @@ pub struct BuildStats {     pub standalone_recordings: u64,     pub skipped: Vec<(&'static str, u64)>,     pub isrc_rejects: u64,-    pub track_sort_buffer_bytes: u64,+    pub track_spill_bytes: u64,     pub dense_map_bytes: u64,     pub search_postings: u64, }@@ -182,26 +205,33 @@ impl BuildStats {             "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);+        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("string pool\n");+        s.push_str(&format!("  {:<38} {:>12}\n", "distinct strings", self.distinct_strings));+        s.push_str(&format!("  {:<38} {:>12.1} MB\n", "raw", mb(self.string_pool_raw)));         s.push_str(&format!(-            "  {:<38} {:>12.1} MB\n",-            "string pool (raw)",-            mb(self.string_pool_bytes as u64)+            "  {:<38} {:>12.1} MB  ({} blocks, {:.2}x)\n",+            "stored",+            mb(self.string_pool_stored),+            self.string_blocks,+            if self.string_pool_stored == 0 {+                0.0+            } else {+                self.string_pool_raw as f64 / self.string_pool_stored as f64+            }         ));-        s.push_str(&format!("  {:<38} {:>12}\n", "distinct strings", self.distinct_strings));+        s.push_str("build cost\n");         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)+            "track spill (disk, not memory)",+            mb(self.track_spill_bytes)         ));         s.push_str(&format!(             "  {:<38} {:>12.1} MB\n",@@ -248,13 +278,129 @@ impl DenseMap {     } } +// --- track bucket spill ---++/// Fixed-width track record written to the bucket files. 24 bytes, or 40 with a+/// track MBID appended for tier A.+const TRACK_SPILL_LEN: usize = 24;+const TRACK_SPILL_LEN_A: usize = 40;++/// Bucket-sorts track rows by medium through files on disk.+///+/// The alternative is buffering all 57.4 M rows to sort, ~1.4 GB, which does not+/// fit the memory budget. Trading wall time and ~1.4 GB of scratch disk for that+/// is the explicit instruction.+struct TrackSpill {+    dir: PathBuf,+    writers: Vec<BufWriter<File>>,+    buckets: usize,+    rec_len: usize,+    media: u32,+    written: u64,+}++/// Distinguishes concurrent builds inside one process. Without it two builds in+/// the same process share a spill directory and delete each other's buckets --+/// which is exactly what the parallel test runner does.+static SPILL_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);++impl TrackSpill {+    fn new(work_dir: Option<&Path>, media: u32, rec_len: usize) -> io::Result<TrackSpill> {+        // One bucket is plenty for a fixture; a full run wants each bucket to be a+        // few tens of MB so sorting one is cheap.+        let buckets = if media < 100_000 { 1 } else { 64 };+        let base = match work_dir {+            Some(p) => p.to_path_buf(),+            None => std::env::temp_dir(),+        };+        let seq = SPILL_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+        let dir = base.join(format!("mb_ingest_tracks_{}_{seq}", std::process::id()));+        let _ = std::fs::remove_dir_all(&dir);+        std::fs::create_dir_all(&dir)?;+        let mut writers = Vec::with_capacity(buckets);+        for b in 0..buckets {+            writers.push(BufWriter::with_capacity(+                1 << 16,+                File::create(dir.join(format!("b{b:03}")))?,+            ));+        }+        Ok(TrackSpill { dir, writers, buckets, rec_len, media, written: 0 })+    }++    fn bucket_of(&self, medium_idx: u32) -> usize {+        if self.buckets == 1 || self.media == 0 {+            return 0;+        }+        ((medium_idx as u64 * self.buckets as u64) / self.media as u64)+            .min(self.buckets as u64 - 1) as usize+    }++    fn push(&mut self, medium_idx: u32, rec: &[u8]) -> io::Result<()> {+        debug_assert_eq!(rec.len(), self.rec_len);+        let b = self.bucket_of(medium_idx);+        self.writers[b].write_all(rec)?;+        self.written += rec.len() as u64;+        Ok(())+    }++    /// Flush and return the bucket paths, in medium order.+    fn finish(&mut self) -> io::Result<Vec<PathBuf>> {+        for w in self.writers.iter_mut() {+            w.flush()?;+        }+        self.writers.clear();+        Ok((0..self.buckets).map(|b| self.dir.join(format!("b{b:03}"))).collect())+    }+}++impl Drop for TrackSpill {+    fn drop(&mut self) {+        self.writers.clear();+        let _ = std::fs::remove_dir_all(&self.dir);+    }+}++#[derive(Clone, Copy)]+struct TrackRow {+    medium_idx: u32,+    position: i32,+    recording_id: u32,+    title: Sym,+    credit_id: u32,+    length_s: u16,+}++impl TrackRow {+    fn encode(&self, out: &mut [u8]) {+        out[0..4].copy_from_slice(&self.medium_idx.to_le_bytes());+        out[4..8].copy_from_slice(&self.position.to_le_bytes());+        out[8..12].copy_from_slice(&self.recording_id.to_le_bytes());+        out[12..16].copy_from_slice(&self.title.to_le_bytes());+        out[16..20].copy_from_slice(&self.credit_id.to_le_bytes());+        out[20..22].copy_from_slice(&self.length_s.to_le_bytes());+        out[22..24].copy_from_slice(&0u16.to_le_bytes());+    }++    fn decode(b: &[u8]) -> TrackRow {+        let u32_at = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);+        TrackRow {+            medium_idx: u32_at(0),+            position: i32::from_le_bytes([b[4], b[5], b[6], b[7]]),+            recording_id: u32_at(8),+            title: u32_at(12),+            credit_id: u32_at(16),+            length_s: u16::from_le_bytes([b[20], b[21]]),+        }+    }+}+ // --- intermediate rows ---  struct ArtistBuild {     gid: Mbid,-    name_off: u32,-    disamb_off: u32,-    area_off: u32,+    name: Sym,+    disamb: Sym,+    area: Sym,     begin_date: u32,     kind: u16,     country: u16,@@ -263,7 +409,7 @@ struct ArtistBuild {  struct RgBuild {     gid: Mbid,-    title_off: u32,+    title: Sym,     first_date: u32,     credit_id: u32,     primary: u16,@@ -274,11 +420,11 @@ struct RgBuild {  struct ReleaseBuild {     gid: Mbid,-    title_off: u32,+    title: Sym,     rg_id: u32,     credit_id: u32,     date: u32,-    disamb_off: u32,+    disamb: Sym,     status: u16,     status_rank: u8,     country: u16,@@ -293,33 +439,9 @@ struct MediumBuild {     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`.+/// Build a pack from `source` and write it to `out`. pub fn build<W: Write + Seek>(-    input: &Input,+    source: &dyn TableSource,     out: W,     opts: &BuildOptions,     log: &mut dyn Write,@@ -333,15 +455,15 @@ pub fn build<W: Write + Seek>(      // --- areas and the small enumerations -------------------------------------     step!("pass 1: areas, country codes, enumerations");-    let mut area_name: HashMap<u32, u32> = HashMap::new();+    let mut area_name: HashMap<u32, Sym> = HashMap::new();     let n = require(-        input,+        source,         "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);+                let sym = pool.intern(&row.str(2));+                area_name.insert(id, sym);             }             Ok(())         },@@ -350,7 +472,7 @@ pub fn build<W: Write + Seek>(      let mut area_country: HashMap<u32, u16> = HashMap::new();     let n = require(-        input,+        source,         "iso_3166_1",         Shape { table: "iso_3166_1", min_fields: 2, ints: &[0], uuids: &[] },         |row| {@@ -367,12 +489,12 @@ pub fn build<W: Write + Seek>(     )?;     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 artist_types = read_enum_table(source, "artist_type", &mut pool, &mut enums)?;+    let rg_primary = read_enum_table(source, "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)?;+        read_enum_table(source, "release_group_secondary_type", &mut pool, &mut enums)?;+    let statuses = read_enum_table(source, "release_status", &mut pool, &mut enums)?;+    let formats = read_enum_table(source, "medium_format", &mut pool, &mut enums)?;      // --- artist credits -------------------------------------------------------     // A credit is stored as one pre-rendered display string ("A feat. B"), because@@ -383,9 +505,9 @@ pub fn build<W: Write + Seek>(     // 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 mut credit_syms: Vec<Sym> = Vec::new();     let n = require(-        input,+        source,         "artist_credit",         Shape { table: "artist_credit", min_fields: 7, ints: &[0, 2], uuids: &[6] },         |row| {@@ -394,19 +516,19 @@ pub fn build<W: Write + Seek>(                 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);+            if credit_syms.len() <= i {+                credit_syms.resize(i + 1, SYM_EMPTY);             }-            credits_off[i] = pool.intern(&row.str(1));+            credit_syms[i] = pool.intern(&row.str(1));             Ok(())         },     )?;     st.rows.push(("artist_credit", n));-    let credit_count = credits_off.len() as u32;+    let credit_count = credit_syms.len() as u32; -    let mut credit_artists: Vec<Vec<u32>> = vec![Vec::new(); credits_off.len()];+    let mut credit_artists: Vec<Vec<u32>> = vec![Vec::new(); credit_syms.len()];     let n = require(-        input,+        source,         "artist_credit_name",         Shape { table: "artist_credit_name", min_fields: 5, ints: &[0, 1, 2], uuids: &[] },         |row| {@@ -424,7 +546,7 @@ pub fn build<W: Write + Seek>(     let mut artists: Vec<ArtistBuild> = Vec::new();     let mut bad_gids = 0u64;     let n = require(-        input,+        source,         "artist",         Shape { table: "artist", min_fields: 19, ints: &[0], uuids: &[1] },         |row| {@@ -436,9 +558,9 @@ pub fn build<W: Write + Seek>(             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),+                name: pool.intern(&row.str(2)),+                disamb: pool.intern(&row.str(13)),+                area: area.and_then(|a| area_name.get(&a).copied()).unwrap_or(SYM_EMPTY),                 begin_date: pack_date(row.i64(4), row.i64(5), row.i64(6)),                 kind: row                     .u32(10)@@ -468,7 +590,7 @@ pub fn build<W: Write + Seek>(     step!("pass 4: release groups");     let mut rgs: Vec<RgBuild> = Vec::new();     let n = require(-        input,+        source,         "release_group",         Shape { table: "release_group", min_fields: 8, ints: &[0, 3], uuids: &[1] },         |row| {@@ -476,7 +598,7 @@ pub fn build<W: Write + Seek>(             let Some(gid) = parse_mbid(&row.str(1)) else { return Ok(()) };             rgs.push(RgBuild {                 gid,-                title_off: pool.intern(&row.str(2)),+                title: pool.intern(&row.str(2)),                 first_date: 0,                 credit_id: row.u32(3).unwrap_or(pack::NONE),                 primary: row@@ -496,7 +618,7 @@ pub fn build<W: Write + Seek>(         rg_slot.set(r.id, i as u32)?;     }     let n = require(-        input,+        source,         "release_group_meta",         Shape { table: "release_group_meta", min_fields: 7, ints: &[0], uuids: &[] },         |row| {@@ -508,7 +630,7 @@ pub fn build<W: Write + Seek>(     )?;     st.rows.push(("release_group_meta", n));     let n = require(-        input,+        source,         "release_group_secondary_type_join",         Shape {             table: "release_group_secondary_type_join",@@ -567,7 +689,7 @@ pub fn build<W: Write + Seek>(     let mut releases: Vec<ReleaseBuild> = Vec::new();     let mut filtered_status = 0u64;     let n = require(-        input,+        source,         "release",         Shape { table: "release", min_fields: 14, ints: &[0, 3, 4], uuids: &[1] },         |row| {@@ -581,11 +703,11 @@ pub fn build<W: Write + Seek>(             }             releases.push(ReleaseBuild {                 gid,-                title_off: pool.intern(&row.str(2)),+                title: 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)),+                disamb: pool.intern(&row.str(10)),                 status: status_id                     .and_then(|s| statuses.get(&s).copied())                     .unwrap_or(EnumPool::NONE_ENUM),@@ -614,7 +736,7 @@ pub fn build<W: Write + Seek>(     // 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,+        source,         "release_country",         Shape { table: "release_country", min_fields: 5, ints: &[0, 1], uuids: &[] },         |row| {@@ -632,7 +754,7 @@ pub fn build<W: Write + Seek>(     )?;     st.rows.push(("release_country", n));     let n = require(-        input,+        source,         "release_unknown_country",         Shape { table: "release_unknown_country", min_fields: 4, ints: &[0], uuids: &[] },         |row| {@@ -680,7 +802,7 @@ pub fn build<W: Write + Seek>(     let mut media: Vec<MediumBuild> = Vec::new();     let mut dangling_media = 0u64;     let n = require(-        input,+        source,         "medium",         Shape { table: "medium", min_fields: 9, ints: &[0, 1, 2], uuids: &[8] },         |row| {@@ -722,35 +844,38 @@ pub fn build<W: Write + Seek>(     }      // --- recordings -----------------------------------------------------------+    // Struct-of-arrays keyed by recording id: no padding, and the gids are NOT+    // held (that would be ~800 MB); RECORDING_MBID is filled by a second pass.     step!("pass 7: recordings");-    let mut rec_rows: Vec<RecBuild> = Vec::new();-    let mut rec_gids: Vec<Mbid> = Vec::new();+    let mut rec_title: Vec<Sym> = Vec::new();+    let mut rec_credit: Vec<u32> = Vec::new();+    let mut rec_dur: Vec<u16> = Vec::new();     let mut rec_present: Vec<bool> = Vec::new();-    let mut distinct_titles: std::collections::HashSet<u32> = std::collections::HashSet::new();+    let mut distinct_titles: std::collections::HashSet<Sym> = std::collections::HashSet::new();     let n = require(-        input,+        source,         "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 !row.looks_like_uuid(1) {+                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]);+            if rec_title.len() <= i {+                rec_title.resize(i + 1, SYM_EMPTY);+                rec_credit.resize(i + 1, pack::NONE);+                rec_dur.resize(i + 1, 0);                 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;+            let title = pool.intern(&row.str(2));+            distinct_titles.insert(title);+            rec_title[i] = title;+            rec_credit[i] = row.u32(3).unwrap_or(pack::NONE);+            rec_dur[i] = ms_to_secs(row.i64(4));             rec_present[i] = true;             Ok(())         },@@ -760,48 +885,48 @@ pub fn build<W: Write + Seek>(     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();+    // --- tracks, phase 1: spill to medium-keyed buckets ------------------------+    step!("pass 8: tracks -> spill buckets");+    let spill_len =+        if opts.include_track_mbids { TRACK_SPILL_LEN_A } else { TRACK_SPILL_LEN };+    let mut spill = TrackSpill::new(opts.work_dir.as_deref(), media.len() as u32, spill_len)?;     let mut dangling_tracks = 0u64;     let mut bad_track_gids = 0u64;+    let mut rec = vec![0u8; spill_len];     let n = require(-        input,+        source,         "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(recording), 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 {+            let gid = if opts.include_track_mbids {                 match parse_mbid(&row.str(1)) {-                    Some(g) => {-                        track_gids.push(g);-                        track_gids.len() as u32 - 1-                    }+                    Some(g) => g,                     None => {                         bad_track_gids += 1;                         return Ok(());                     }                 }             } else {-                0+                [0u8; 16]             };-            tracks.push(TrackBuild {+            TrackRow {                 medium_idx: mi,                 position: clamp_position(row.i64(4)),-                recording_id: rec,-                title_off: pool.intern(&row.str(6)),+                recording_id: recording,+                title: 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(())+            }+            .encode(&mut rec);+            if opts.include_track_mbids {+                rec[TRACK_SPILL_LEN..TRACK_SPILL_LEN_A].copy_from_slice(&gid);+            }+            spill.push(mi, &rec)         },     )?;     st.rows.push(("track", n));@@ -811,102 +936,141 @@ pub fn build<W: Write + Seek>(     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))-    });+    st.track_spill_bytes = spill.written;+    let buckets = spill.finish()?;++    // --- finalise the string pool ---------------------------------------------+    // Every table has now been read, so the pool is complete and can be sorted.+    // Nothing before this point knows a byte offset; everything after uses one.+    step!("pass 9: sorting the string pool ({} distinct)", pool.distinct());+    st.distinct_strings = pool.distinct();+    let pool: FinalPool = pool.finalize();+    st.string_pool_raw = pool.raw_len() as u64; -    // 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()];+    // --- tracks, phase 2: cluster recordings and emit TRACKS -------------------+    step!("pass 10: tracks -> TRACKS varint stream");+    let mut rec_new: Vec<u32> = vec![pack::NONE; rec_title.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);-            }+    let mut next_medium = 0usize;+    let mut buf: Vec<u8> = Vec::new();+    for bucket in &buckets {+        let mut rows: Vec<TrackRow> = Vec::new();+        let mut gids: Vec<Mbid> = Vec::new();+        buf.clear();+        File::open(bucket)?.read_to_end(&mut buf)?;+        for chunk in buf.chunks_exact(spill_len) {+            rows.push(TrackRow::decode(chunk));             if opts.include_track_mbids {-                track_mbids.extend_from_slice(&track_gids[t.gid_slot as usize]);+                let mut g = [0u8; 16];+                g.copy_from_slice(&chunk[TRACK_SPILL_LEN..TRACK_SPILL_LEN_A]);+                gids.push(g);             }-            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;+        let mut order: Vec<u32> = (0..rows.len() as u32).collect();+        order.sort_unstable_by_key(|&i| (rows[i as usize].medium_idx, rows[i as usize].position));+        let mut cursor = 0usize;+        // Every medium up to the last one in this bucket gets its offset written,+        // including the ones with no tracks at all.+        let bucket_last = order+            .last()+            .map(|&i| rows[i as usize].medium_idx as usize)+            .unwrap_or(next_medium.saturating_sub(1));+        while next_medium <= bucket_last && next_medium < media.len() {+            let m = next_medium;+            track_idx[m] = tracks_stream.len() as u32;+            let mut ordinal = 0u32;+            let mut prev_rec: i64 = 0;+            while cursor < order.len() && rows[order[cursor] as usize].medium_idx as usize == m {+                let i = order[cursor] as usize;+                let t = rows[i];+                cursor += 1;+                let rid = t.recording_id as usize;+                if rid >= rec_present.len() || !rec_present[rid] {+                    missing_recordings += 1;+                    continue;+                }+                let new_idx = if rec_new[rid] != pack::NONE {+                    rec_new[rid]+                } else {+                    let idx = rec_order.len() as u32;+                    rec_new[rid] = idx;+                    rec_order.push(t.recording_id);+                    rec_first_release.push(media[m].release_idx);+                    idx+                };+                let title_differs = t.title != rec_title[rid];+                let credit_differs = t.credit_id != rec_credit[rid];+                let pos_differs = t.position != (ordinal as i32 + 1);+                let len_differs = t.length_s != 0 && t.length_s != rec_dur[rid];+                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);+                // The first track of a medium carries an ABSOLUTE recording index so+                // the medium is decodable on its own; TRACK_IDX's byte offset would+                // be useless otherwise.+                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, pool.offset(t.title) 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(&gids[i]);+                }+                ordinal += 1;+                track_count += 1;+            }+            // The published count must match what a decode of the run yields, or+            // TRACKTOTAL and the tracklist disagree.+            media[m].track_count = ordinal;+            next_medium += 1;+        }+    }+    // Trailing media with no tracks.+    while next_medium < media.len() {+        track_idx[next_medium] = tracks_stream.len() as u32;+        media[next_medium].track_count = 0;+        next_medium += 1;     }     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);+    drop(spill);      // 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() {+    for id in 0..rec_present.len() {         if rec_present[id] && rec_new[id] == pack::NONE {             rec_new[id] = rec_order.len() as u32;             rec_order.push(id as u32);@@ -915,18 +1079,42 @@ pub fn build<W: Write + Seek>(     }     st.standalone_recordings = rec_order.len() as u64 - tracked; +    // --- recording MBIDs, scattered in clustered order ------------------------+    let mut recording_mbids: Vec<u8> = Vec::new();+    if opts.include_recording_mbids {+        step!("pass 11: recording MBIDs");+        recording_mbids = vec![0u8; rec_order.len() * 16];+        require(+            source,+            "recording",+            Shape { table: "recording", min_fields: 9, ints: &[0, 3], uuids: &[1] },+            |row| {+                let Some(id) = row.u32(0) else { return Ok(()) };+                let Some(&new) = rec_new.get(id as usize) else { return Ok(()) };+                if new == pack::NONE {+                    return Ok(());+                }+                if let Some(gid) = parse_mbid(&row.str(1)) {+                    let at = new as usize * 16;+                    recording_mbids[at..at + 16].copy_from_slice(&gid);+                }+                Ok(())+            },+        )?;+    }+     // --- ISRCs -----------------------------------------------------------------    step!("pass 9: ISRCs");     let mut isrcs: Vec<(u32, [u8; 7])> = Vec::new();     if opts.include_isrcs {+        step!("pass 12: ISRCs");         let mut rejects = 0u64;         let n = require(-            input,+            source,             "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(()) };+                let Some(recording) = row.u32(1) else { return Ok(()) };+                let Some(&new) = rec_new.get(recording as usize) else { return Ok(()) };                 if new == pack::NONE {                     return Ok(());                 }@@ -944,58 +1132,70 @@ pub fn build<W: Write + Seek>(     }      // --- search index ----------------------------------------------------------    step!("pass 10: search index");+    step!("pass 13: 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));+    {+        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.iter() {+                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() {+            check_searchable(i as u32)?;+            let text = String::from_utf8_lossy(pool.get(a.name)).into_owned();+            add(+                &text,+                (pack::KIND_ARTIST << pack::KIND_SHIFT) | i as u32,+                &mut term_dict,+                &mut postings,+            );         }-    };-    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);+        for (i, r) in rgs.iter().enumerate() {             check_searchable(i as u32)?;+            let text = String::from_utf8_lossy(pool.get(r.title)).into_owned();             add(-                &title,-                (pack::KIND_RECORDING << pack::KIND_SHIFT) | i as u32,+                &text,+                (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() {+                check_searchable(i as u32)?;+                let text =+                    String::from_utf8_lossy(pool.get(rec_title[*id as usize])).into_owned();+                add(+                    &text,+                    (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];+    {+        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();@@ -1022,19 +1222,22 @@ pub fn build<W: Write + Seek>(     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);+    drop(sorted_terms);      // --- assemble --------------------------------------------------------------    step!("pass 11: writing");+    step!("pass 14: 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 enum_offsets: Vec<u32> = enums.syms().iter().map(|&s| pool.offset(s)).collect();+    w.section_u32(pack::S_ENUM_POOL, &enum_offsets)?;+    let credit_offsets: Vec<u32> = credit_syms.iter().map(|&s| pool.offset(s)).collect();+    w.section_u32(pack::S_CREDITS, &credit_offsets)?;+    drop(credit_syms); -    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(&pool.offset(a.name).to_le_bytes());+        buf.extend_from_slice(&pool.offset(a.disamb).to_le_bytes());+        buf.extend_from_slice(&pool.offset(a.area).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());@@ -1048,7 +1251,7 @@ pub fn build<W: Write + Seek>(      buf.clear();     for r in &rgs {-        buf.extend_from_slice(&r.title_off.to_le_bytes());+        buf.extend_from_slice(&pool.offset(r.title).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());@@ -1065,11 +1268,11 @@ pub fn build<W: Write + Seek>(      buf.clear();     for r in &releases {-        buf.extend_from_slice(&r.title_off.to_le_bytes());+        buf.extend_from_slice(&pool.offset(r.title).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(&pool.offset(r.disamb).to_le_bytes());         buf.extend_from_slice(&r.status.to_le_bytes());         buf.extend_from_slice(&r.country.to_le_bytes());     }@@ -1104,27 +1307,24 @@ pub fn build<W: Write + Seek>(      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());+        let i = *id as usize;+        let (lo, hi) = encode_recording_credit(credit_idx_of(rec_credit[i], credit_count));+        buf.extend_from_slice(&pool.offset(rec_title[i]).to_le_bytes());+        buf.extend_from_slice(&rec_dur[i].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(pack::S_RECORDING_MBID, &recording_mbids)?;     }+    drop(recording_mbids);     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());+        for (recording, packed) in &isrcs {+            buf.extend_from_slice(&recording.to_le_bytes());             buf.extend_from_slice(packed);         }         w.section(pack::S_ISRCS, &buf)?;@@ -1133,7 +1333,34 @@ pub fn build<W: Write + Seek>(     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())?;++    // STRINGS goes last: it is only complete now, and streaming it here means the+    // sorted pool is never materialised as a second buffer.+    let mut string_blocks = 0u32;+    if opts.compress_strings {+        let mut bw = StringBlockWriter::new();+        pool.write_strings(|s| bw.push(s))?;+        let (compressed, block_offsets) = bw.finish()?;+        st.string_pool_stored = compressed.len() as u64;+        string_blocks = (block_offsets.len() - 1) as u32;+        w.section(pack::S_STRINGS, &compressed)?;+        w.section_u32(pack::S_STRINGS_BLKIDX, &block_offsets)?;+    } else {+        w.begin(pack::S_STRINGS)?;+        let mut chunk: Vec<u8> = Vec::with_capacity(1 << 16);+        pool.write_strings(|s| {+            chunk.extend_from_slice(s);+            if chunk.len() >= (1 << 16) {+                let taken = std::mem::take(&mut chunk);+                w.write(&taken)?;+                chunk = taken;+                chunk.clear();+            }+            Ok(())+        })?;+        w.write(&chunk)?;+        st.string_pool_stored = w.end()?;+    }      let counts = HeaderCounts {         artists: artists.len() as u32,@@ -1145,16 +1372,15 @@ pub fn build<W: Write + Seek>(         recordings: rec_order.len() as u32,         isrcs: isrcs.len() as u32,         search_terms: term_count as u32,-        enums: enums.offsets().len() as u32,+        enums: enum_offsets.len() as u32,     };-    w.set_header(&counts, opts.flags(), input.dump_date());+    w.set_header(&counts, opts.flags(), source.dump_date(), string_blocks);+    st.string_blocks = string_blocks;     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()?;@@ -1189,16 +1415,6 @@ fn credit_idx_of(credit_id: u32, credit_count: u32) -> u32 {     } } -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.@@ -1221,13 +1437,13 @@ fn to_csr(pairs: &[(u32, u32)], parents: usize) -> (Vec<u32>, Vec<u32>) { }  fn read_enum_table(-    input: &Input,+    source: &dyn TableSource,     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| {+    require(source, 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)));         }@@ -1237,26 +1453,30 @@ fn read_enum_table( }  /// 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>+fn require<F>(+    source: &dyn TableSource,+    table: &'static str,+    shape: Shape,+    mut f: F,+) -> io::Result<u64> where     F: FnMut(&Row<'_>) -> io::Result<()>, {+    let Some(reader) = source.open_table(table)? else {+        return 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.",+            source.describe()+        )));+    };     let mut first = true;-    let rows = input.each_row(table, |row| {+    each_row(reader, |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)]@@ -1264,10 +1484,31 @@ 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);+    fn track_spill_record_stays_small() {+        // 57.4 M of these go through the spill; the README quotes this width.+        assert_eq!(TRACK_SPILL_LEN, 24);+        assert_eq!(TRACK_SPILL_LEN_A, TRACK_SPILL_LEN + 16);+    }++    #[test]+    fn track_rows_round_trip_through_the_spill_encoding() {+        let t = TrackRow {+            medium_idx: 1_234_567,+            position: -3,+            recording_id: 39_881_257,+            title: 99,+            credit_id: pack::NONE,+            length_s: 425,+        };+        let mut b = [0u8; TRACK_SPILL_LEN];+        t.encode(&mut b);+        let d = TrackRow::decode(&b);+        assert_eq!(d.medium_idx, t.medium_idx);+        assert_eq!(d.position, t.position);+        assert_eq!(d.recording_id, t.recording_id);+        assert_eq!(d.title, t.title);+        assert_eq!(d.credit_id, t.credit_id);+        assert_eq!(d.length_s, t.length_s);     }      #[test]@@ -1305,4 +1546,24 @@ mod tests {         assert_eq!(m.get(9_999), None);         assert!(m.set(MAX_ID + 1, 0).is_err());     }++    #[test]+    fn spill_buckets_are_monotonic_in_medium() {+        let s = TrackSpill::new(Some(&std::env::temp_dir()), 640_000, TRACK_SPILL_LEN).unwrap();+        assert!(s.buckets > 1, "a full-scale medium count must use many buckets");+        let mut prev = 0usize;+        for m in [0u32, 1, 10_000, 320_000, 639_999] {+            let b = s.bucket_of(m);+            assert!(b >= prev, "buckets must not go backwards: medium {m} -> {b}");+            assert!(b < s.buckets);+            prev = b;+        }+    }++    #[test]+    fn concurrent_spills_do_not_share_a_directory() {+        let a = TrackSpill::new(None, 10, TRACK_SPILL_LEN).unwrap();+        let b = TrackSpill::new(None, 10, TRACK_SPILL_LEN).unwrap();+        assert_ne!(a.dir, b.dir, "two builds in one process must not collide");+    } }
scripts/musicbrainz/mb_ingest/src/copy.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/copy.rs b/scripts/musicbrainz/mb_ingest/src/copy.rsindex 1d7e37b11b..83ad312ef0 100644--- a/scripts/musicbrainz/mb_ingest/src/copy.rs+++ b/scripts/musicbrainz/mb_ingest/src/copy.rs@@ -126,9 +126,14 @@ impl<'a> Row<'a> { }  /// A table's byte stream plus, for the archive path, the `tar` process feeding it.-type TableStream = (Box<dyn Read>, Option<Child>);+type TableStream = (Box<dyn Read + Send>, Option<Child>);  /// Where the tables come from.+///+/// The production path is neither of these: `location_share_server` owns the+/// download, the bzip2 stream and the tar demux, spills the 20 tables it needs,+/// and implements [`TableSource`] over them. These two exist so the fixture tests+/// and the CLI work without that pipeline. pub enum Input {     /// A directory holding the table files, either `<dir>/<table>` or     /// `<dir>/mbdump/<table>` (i.e. an extracted archive works unchanged).@@ -177,42 +182,6 @@ impl Input {         std::str::from_utf8(&d).ok().and_then(|s| s.parse().ok()).unwrap_or(0)     } -    /// Extract just `tables` (plus `TIMESTAMP`) into `dir` in ONE pass.-    ///-    /// Reading tables straight out of the archive costs one full bz2 decompression-    /// per table, because `tar` has to stream to the member it wants. That is fine-    /// for a fixture and badly wrong for the real 7 GB dump: ~20 tables means ~20-    /// passes over ~40 GB of decompressed output. Extracting the tables this crate-    /// actually reads costs one pass and ~13 GB of disk, versus ~40 GB for the-    /// whole archive.-    pub fn extract_to(&self, dir: &Path, tables: &[&str]) -> io::Result<()> {-        let Input::Archive(path) = self else {-            return Err(other_err(format!(-                "{} is already a directory; nothing to extract",-                self.describe()-            )));-        };-        std::fs::create_dir_all(dir)?;-        let mut cmd = Command::new("tar");-        cmd.arg("-xf").arg(path).arg("-C").arg(dir).arg("TIMESTAMP");-        for t in tables {-            cmd.arg(format!("mbdump/{t}"));-        }-        let status = cmd.status().map_err(|e| {-            io::Error::new(-                e.kind(),-                format!("could not run `tar` to extract {}: {e}", path.display()),-            )-        })?;-        if !status.success() {-            return Err(other_err(format!(-                "tar failed extracting {}; is it the core mbdump.tar.bz2?",-                path.display()-            )));-        }-        Ok(())-    }-     fn open_reader(&self, table: &str) -> io::Result<Option<TableStream>> {         match self {             Input::Dir(dir) => {@@ -224,9 +193,9 @@ impl Input {                 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.+                // `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")@@ -240,74 +209,128 @@ impl Input {                             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.",+                                 Archive input needs tar on PATH; pass an extracted \+                                 directory instead.",                                 path.display()                             ),                         )                     })?;-                let out = child.stdout.take().expect("piped stdout");-                Ok(Some((Box::new(out), Some(child))))+                let mut out = child.stdout.take().expect("piped stdout");+                // Probe one byte so a missing member is reported as an absent table+                // rather than as an empty one -- silently building a pack with no+                // artists because a member name was wrong would be much worse.+                let mut probe = [0u8; 1];+                let n = out.read(&mut probe)?;+                if n == 0 {+                    let _ = child.wait();+                    return Ok(None);+                }+                let head = io::Cursor::new(probe[..n].to_vec());+                Ok(Some((Box::new(head.chain(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;++/// A source of mbdump tables, by name.+///+/// This is the seam with `location_share_server`: it does one bzip2 traversal of+/// the archive, demuxes the tar and spills each table, then implements this trait.+/// This crate never touches the archive, bzip2 or tar.+///+/// **Tables must be re-openable.** The ingest calls `open("track")` more than+/// once, which is what lets it bucket-sort 57.4 M track rows through spill files+/// instead of holding ~1.6 GB of them in memory to sort.+pub trait TableSource {+    /// A fresh sequential reader over the table's COPY-format bytes, or `None` if+    /// this source does not have that table.+    fn open_table(&self, table: &str) -> io::Result<Option<Box<dyn BufRead + Send>>>;++    /// The dump's date as `YYYYMMDD`, or 0 when unknown.+    fn dump_date(&self) -> u32 {+        0+    }++    fn describe(&self) -> String {+        "table source".to_string()+    }+}++/// Call `f` once per row of a COPY-format stream. 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>(reader: Box<dyn BufRead + Send>, mut f: F) -> io::Result<u64>+where+    F: FnMut(&Row<'_>) -> io::Result<()>,+{+    let mut reader = 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;         }-        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"-                )));+        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;             }         }-        Ok(Some(rows))+        fields.push((start, line.len() as u32));+        f(&Row { line: &line, fields: &fields })?;+        rows += 1;+    }+    Ok(rows)+}++impl TableSource for Input {+    fn open_table(&self, table: &str) -> io::Result<Option<Box<dyn BufRead + Send>>> {+        match self.open_reader(table)? {+            None => Ok(None),+            Some((reader, child)) => Ok(Some(Box::new(BufReader::with_capacity(+                1 << 20,+                ChildReader { inner: reader, child },+            )))),+        }+    }++    fn dump_date(&self) -> u32 {+        Input::dump_date(self)+    }++    fn describe(&self) -> String {+        Input::describe(self)+    }+}++struct ChildReader {+    inner: Box<dyn Read + Send>,+    child: Option<Child>,+}++impl Read for ChildReader {+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {+        self.inner.read(buf)+    }+}++impl Drop for ChildReader {+    fn drop(&mut self) {+        if let Some(child) = self.child.as_mut() {+            let _ = child.wait();+        }     } } 
scripts/musicbrainz/mb_ingest/src/main.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/main.rs b/scripts/musicbrainz/mb_ingest/src/main.rsindex 52b3405934..ec19b827e3 100644--- a/scripts/musicbrainz/mb_ingest/src/main.rs+++ b/scripts/musicbrainz/mb_ingest/src/main.rs@@ -4,8 +4,8 @@ //! ```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 extract <mbdump.tar.bz2> <dir>   one-pass extract of just the tables needed+//!                                                   [--no-recording-mbids] [--raw-strings]+//!                                                   [--work-dir <dir>] [-q] //! mb_ingest fixture <dir>          write the synthetic test dump //! mb_ingest inspect <out.pack>     header, section sizes and a smoke query //! ```@@ -16,7 +16,6 @@ use std::process::ExitCode;  use mb_ingest::build::{build, BuildOptions, TABLES}; use mb_ingest::copy::Input;-use mb_ingest::fixture::write_fixture; use mb_ingest::pack::format_mbid; use mb_ingest::reader::MbPack; @@ -35,8 +34,8 @@ fn usage() -> io::Error {         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 extract <mbdump.tar.bz2> <dir>\n  \+         [--no-isrcs] [--no-recording-search] [--no-recording-mbids] [--raw-strings] \+         [--work-dir <dir>] [-q]\n  \          mb_ingest fixture <dir>\n  \          mb_ingest inspect <pack>",     )@@ -46,21 +45,9 @@ 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("extract") => {-            let (archive, dir) = (args.get(1).ok_or_else(usage)?, args.get(2).ok_or_else(usage)?);-            let input = Input::detect(Path::new(archive));-            let started = std::time::Instant::now();-            input.extract_to(Path::new(dir), TABLES)?;-            println!(-                "extracted {} tables to {dir} in {:.1}s",-                TABLES.len(),-                started.elapsed().as_secs_f64()-            );-            Ok(())-        }         Some("fixture") => {             let dir = args.get(1).ok_or_else(usage)?;-            write_fixture(Path::new(dir))?;+            mb_ingest::fixture::write_fixture(Path::new(dir))?;             println!("wrote synthetic mbdump to {dir}");             Ok(())         }@@ -72,13 +59,19 @@ fn run() -> io::Result<()> { 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 {+    let mut args_iter = args.iter();+    while let Some(a) = args_iter.next() {         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,+            "--raw-strings" => opts.compress_strings = false,+            "--work-dir" => {+                let dir = args_iter.next().ok_or_else(usage)?;+                opts.work_dir = Some(PathBuf::from(dir));+            }             "-q" | "--quiet" => opts.verbose = false,             other if other.starts_with('-') => {                 return Err(io::Error::new(@@ -96,10 +89,10 @@ fn cmd_build(args: &[String]) -> io::Result<()> {     if matches!(input, Input::Archive(_)) {         eprintln!(             "note: reading tables straight out of an archive costs one bz2 decompression \-             pass per table ({} of them). For the 7 GB full export, run `mb_ingest extract \-             {} <dir>` once (~13 GB of disk) and build from <dir> instead.",-            TABLES.len(),-            positional[0]+             pass per table ({} of them), because bz2 is not seekable. That is fine for a \+             fixture; for the 7 GB full export the server's single-traversal spill is the \+             production path.",+            TABLES.len()         );     }     // Write to a .tmp and rename, so a crashed build never leaves a half-written@@ -135,6 +128,7 @@ fn cmd_inspect(path: &str) -> io::Result<()> {     println!("  ISRCs              {}", pack.has_isrcs());     println!("  recording search   {}", pack.has_recording_search());     println!("  official only      {}", pack.official_only());+    println!("  strings compressed {}", pack.strings_compressed());     println!(         "counts               artists {} credits {} rgs {} releases {} media {} tracks {} \          recordings {} isrcs {} terms {}",
scripts/musicbrainz/mb_ingest/src/pack.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/pack.rs b/scripts/musicbrainz/mb_ingest/src/pack.rsindex 0698835a92..9184232abd 100644--- a/scripts/musicbrainz/mb_ingest/src/pack.rs+++ b/scripts/musicbrainz/mb_ingest/src/pack.rs@@ -43,7 +43,7 @@ //! 0x30 u32 enum_count //! 0x34 u32 flags //! 0x38 u32 dump_date    // YYYYMMDD of the source mbdump, 0 if unknown-//! 0x3C u32 _reserved+//! 0x3C u32 string_block_count //! ``` //! //! Then the section directory: `section_count * { u64 offset, u64 len }`,@@ -54,8 +54,7 @@ //! //! `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).+//! block-compressed with zstd. //! //! String pool offset 0 is the empty string. Dates pack into a u32 as //! `year<<9 | month<<5 | day`, 0 meaning unknown.@@ -63,8 +62,17 @@ //! # 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.+//!  0 STRINGS          The string pool. Offsets are byte offsets into the+//!                     UNCOMPRESSED pool. Strings are sorted alphabetically, which+//!                     is worth ~0.5 MB per MB to zstd and is free because offsets+//!                     are assigned after the sort. When flags bit 5 is set this+//!                     section holds zstd blocks, each covering exactly+//!                     STRING_BLOCK_SIZE (64 KiB) of uncompressed pool, so a pool+//!                     offset names its block by division. A string may straddle a+//!                     block boundary; a reader that does not find the terminating+//!                     NUL continues into the next block.+//!  1 STRINGS_BLKIDX   u32[string_block_count + 1] byte offsets into STRINGS of+//!                     each compressed block. Empty when the pool is raw. //!  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@@ -418,20 +426,34 @@ pub fn unpack_isrc(b: &[u8; 7]) -> [u8; 12] {  // --- string pool --- -/// Interning pool producing byte offsets into STRINGS.+/// Interning pool. ///-/// The index is open-addressed over u32 pool offsets rather than a+/// `intern` returns a dense **symbol id**, not a byte offset. Byte offsets are+/// only assigned by [`StringPool::finalize`], which first sorts every distinct+/// string alphabetically. That deferral is what makes the compressed pool worth+/// having: zstd over 64 KB blocks of *sorted* short text gets ~3.5x, where the+/// same text in interning order gets ~2.5-3x, and the offsets cannot be reordered+/// after the fact because they are baked into the inline overrides of the TRACKS+/// varint stream, where changing an offset changes the varint's width.+///+/// The index is open-addressed over u32 symbol ids 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.+/// `HashMap<String, u32>` costs ~1.84 GB steady with a ~2.3 GB transient spike at+/// its final resize, against a 4 GB budget for the whole build. This costs 4 bytes+/// per slot. pub struct StringPool {+    /// Staging bytes in interning order, each string NUL-terminated.     bytes: Vec<u8>,-    /// Slot values are `offset + 1`; 0 means empty.+    /// Symbol id -> start offset in `bytes`.+    starts: Vec<u32>,+    /// Open-addressed index; slot values are `sym + 1`, 0 means empty.     slots: Vec<u32>,-    len: usize, } +/// A dense string id handed out during the build. `SYM_EMPTY` is the empty string.+pub type Sym = u32;+pub const SYM_EMPTY: Sym = 0;+ impl Default for StringPool {     fn default() -> Self {         Self::new()@@ -440,16 +462,16 @@ impl Default for StringPool {  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 }+        // Symbol 0 is the empty string, so a missing value needs no sentinel.+        StringPool { bytes: vec![0], starts: vec![0], slots: vec![0; 1024] }     } -    pub fn bytes(&self) -> &[u8] {-        &self.bytes+    pub fn distinct(&self) -> usize {+        self.starts.len()     } -    pub fn distinct(&self) -> usize {-        self.len+    pub fn staging_bytes(&self) -> usize {+        self.bytes.len()     }      fn hash(s: &[u8]) -> u64 {@@ -462,8 +484,9 @@ impl StringPool {         h     } -    fn at(&self, off: u32) -> &[u8] {-        let start = off as usize;+    /// The bytes of a symbol, without its NUL.+    pub fn get(&self, sym: Sym) -> &[u8] {+        let start = self.starts[sym as usize] as usize;         let end = self.bytes[start..].iter().position(|&b| b == 0).unwrap() + start;         &self.bytes[start..end]     }@@ -476,8 +499,7 @@ impl StringPool {             if v == 0 {                 continue;             }-            let off = v - 1;-            let mut j = (Self::hash(self.at(off)) as usize) & mask;+            let mut j = (Self::hash(self.get(v - 1)) as usize) & mask;             while slots[j] != 0 {                 j = (j + 1) & mask;             }@@ -486,12 +508,11 @@ impl StringPool {         self.slots = slots;     } -    /// Intern `s`, returning its byte offset. The empty string is always 0.-    pub fn intern(&mut self, s: &str) -> u32 {+    pub fn intern(&mut self, s: &str) -> Sym {         if s.is_empty() {-            return 0;+            return SYM_EMPTY;         }-        if self.len * 4 >= self.slots.len() * 3 {+        if self.starts.len() * 4 >= self.slots.len() * 3 {             self.grow();         }         let mask = self.slots.len() - 1;@@ -502,28 +523,178 @@ impl StringPool {                 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)"+                    "the string pool passed the u32 offset ceiling at {off} bytes; it is the \+                     first field in this format that would overflow (design doc §4.7 / R8)"                 );                 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;+                let sym = self.starts.len() as u32;+                self.starts.push(off as u32);+                self.slots[j] = sym + 1;+                return sym;             }-            if self.at(v - 1) == s.as_bytes() {+            if self.get(v - 1) == s.as_bytes() {                 return v - 1;             }             j = (j + 1) & mask;         }     }++    /// Sort the distinct strings alphabetically and assign final byte offsets.+    ///+    /// The sorted bytes are deliberately **not** materialised — that would need a+    /// second 635 MB buffer. Offsets are computed from the sorted order, and+    /// [`FinalPool::write_strings`] later streams the strings out of the staging+    /// buffer in that order.+    pub fn finalize(mut self) -> FinalPool {+        // The index is dead weight from here on.+        self.slots = Vec::new();+        self.slots.shrink_to_fit();+        let n = self.starts.len();+        let mut order: Vec<u32> = (0..n as u32).collect();+        {+            let bytes = &self.bytes;+            let starts = &self.starts;+            let key = |sym: &u32| -> &[u8] {+                let start = starts[*sym as usize] as usize;+                let end = bytes[start..].iter().position(|&b| b == 0).unwrap() + start;+                &bytes[start..end]+            };+            order.sort_unstable_by(|a, b| key(a).cmp(key(b)));+        }+        let mut offsets = vec![0u32; n];+        let mut off: u64 = 0;+        for &sym in &order {+            offsets[sym as usize] = off as u32;+            let len = {+                let start = self.starts[sym as usize] as usize;+                self.bytes[start..].iter().position(|&b| b == 0).unwrap()+            };+            off += len as u64 + 1;+        }+        assert!(+            off <= u32::MAX as u64,+            "the string pool is {off} bytes, past the u32 offset ceiling (design doc R8)"+        );+        FinalPool { bytes: self.bytes, starts: self.starts, order, offsets, total: off as u32 }+    }+}++/// A finalised pool: symbols resolve to byte offsets into the alphabetically+/// sorted pool that `write_strings` emits.+pub struct FinalPool {+    bytes: Vec<u8>,+    starts: Vec<u32>,+    order: Vec<u32>,+    offsets: Vec<u32>,+    total: u32,+}++impl FinalPool {+    pub fn offset(&self, sym: Sym) -> u32 {+        self.offsets[sym as usize]+    }++    pub fn get(&self, sym: Sym) -> &[u8] {+        let start = self.starts[sym as usize] as usize;+        let end = self.bytes[start..].iter().position(|&b| b == 0).unwrap() + start;+        &self.bytes[start..end]+    }++    pub fn distinct(&self) -> usize {+        self.offsets.len()+    }++    /// Uncompressed size of the pool.+    pub fn raw_len(&self) -> u32 {+        self.total+    }++    /// Stream the pool in sorted order through `sink`, one string (with its NUL)+    /// at a time. Never builds a second copy of the pool.+    pub fn write_strings<F: FnMut(&[u8]) -> io::Result<()>>(&self, mut sink: F) -> io::Result<()> {+        for &sym in &self.order {+            let start = self.starts[sym as usize] as usize;+            let end = self.bytes[start..].iter().position(|&b| b == 0).unwrap() + start;+            sink(&self.bytes[start..=end])?;+        }+        Ok(())+    }+}++/// Uncompressed span covered by one block of the compressed string pool. A pool+/// offset's block is `off / STRING_BLOCK_SIZE`, so the mapping needs no lookup.+pub const STRING_BLOCK_SIZE: usize = 64 * 1024;++/// zstd level for the pool. The pack is built once and read forever, and the+/// user's stated goal is the smallest possible file, so this is deliberately at+/// the expensive end.+pub const STRING_ZSTD_LEVEL: i32 = 19;++/// Compresses the string pool into `STRING_BLOCK_SIZE` blocks and records where+/// each block landed.+///+/// Blocks break at exact multiples of `STRING_BLOCK_SIZE`, so a string may+/// straddle two blocks; the reader continues into the next block when it does not+/// find the terminating NUL. Keeping the boundaries exact is what lets a pool+/// offset name its block by division instead of a binary search.+pub struct StringBlockWriter {+    pending: Vec<u8>,+    out: Vec<u8>,+    block_offsets: Vec<u32>,+}++impl Default for StringBlockWriter {+    fn default() -> Self {+        Self::new()+    }+}++impl StringBlockWriter {+    pub fn new() -> StringBlockWriter {+        StringBlockWriter {+            pending: Vec::with_capacity(STRING_BLOCK_SIZE * 2),+            out: Vec::new(),+            block_offsets: vec![0],+        }+    }++    pub fn push(&mut self, bytes: &[u8]) -> io::Result<()> {+        self.pending.extend_from_slice(bytes);+        while self.pending.len() >= STRING_BLOCK_SIZE {+            self.flush_block(STRING_BLOCK_SIZE)?;+        }+        Ok(())+    }++    fn flush_block(&mut self, len: usize) -> io::Result<()> {+        let block = zstd::bulk::compress(&self.pending[..len], STRING_ZSTD_LEVEL)?;+        self.out.extend_from_slice(&block);+        assert!(+            self.out.len() <= u32::MAX as usize,+            "the compressed string pool passed the u32 block-offset ceiling"+        );+        self.block_offsets.push(self.out.len() as u32);+        self.pending.drain(..len);+        Ok(())+    }++    /// Returns the compressed bytes and the block offset index.+    pub fn finish(mut self) -> io::Result<(Vec<u8>, Vec<u32>)> {+        if !self.pending.is_empty() {+            let len = self.pending.len();+            self.flush_block(len)?;+        }+        Ok((self.out, self.block_offsets))+    } }  /// 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.+/// country code) share one table so records can hold a u16 index instead of a 4 B+/// pool offset, which is worth ~56 MB across ARTISTS / RELEASE_GROUPS / RELEASES /+/// MEDIA at full scale. pub struct EnumPool {-    offsets: Vec<u32>,+    syms: Vec<Sym>,     map: HashMap<String, u16>, } @@ -535,7 +706,7 @@ impl Default for EnumPool {  impl EnumPool {     pub fn new() -> EnumPool {-        EnumPool { offsets: Vec::new(), map: HashMap::new() }+        EnumPool { syms: Vec::new(), map: HashMap::new() }     }      /// `None` is represented by `NONE_ENUM`, which resolves to the empty string.@@ -549,19 +720,19 @@ impl EnumPool {             return i;         }         assert!(-            self.offsets.len() < u16::MAX as usize,+            self.syms.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);+        let i = self.syms.len() as u16;+        let sym = pool.intern(s);+        self.syms.push(sym);         self.map.insert(s.to_string(), i);         i     } -    pub fn offsets(&self) -> &[u32] {-        &self.offsets+    pub fn syms(&self) -> &[Sym] {+        &self.syms     } } @@ -648,7 +819,13 @@ impl<W: Write + Seek> PackWriter<W> {     }      #[allow(clippy::too_many_arguments)]-    pub fn set_header(&mut self, counts: &HeaderCounts, flags: u32, dump_date: u32) {+    pub fn set_header(+        &mut self,+        counts: &HeaderCounts,+        flags: u32,+        dump_date: u32,+        string_block_count: 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);@@ -666,6 +843,7 @@ impl<W: Write + Seek> PackWriter<W> {         put(0x30, counts.enums);         put(0x34, flags);         put(0x38, dump_date);+        put(0x3C, string_block_count);         self.header = h;     } @@ -852,20 +1030,103 @@ mod tests {     }      #[test]-    fn string_pool_dedups_and_keeps_zero_empty() {+    fn string_pool_dedups_and_sorts_at_finalize() {         let mut p = StringPool::new();-        assert_eq!(p.intern(""), 0);+        assert_eq!(p.intern(""), SYM_EMPTY);         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);+        let zebra = p.intern("zebra");+        let apple = p.intern("apple");         // 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);+        let again = p.intern("title 4999");+        assert_eq!(p.distinct(), 5005, "empty + 2 floyds + zebra + apple + 5000 titles");++        let f = p.finalize();+        assert_eq!(f.offset(SYM_EMPTY), 0, "the empty string must stay at offset 0");+        assert_eq!(f.get(a), b"Pink Floyd");+        assert_eq!(f.get(again), b"title 4999");+        assert!(+            f.offset(apple) < f.offset(zebra),+            "finalize must sort alphabetically, or the compressed pool loses its ratio"+        );++        // The streamed pool is NUL-terminated, sorted, and exactly raw_len bytes.+        let mut out = Vec::new();+        f.write_strings(|s| {+            out.extend_from_slice(s);+            Ok(())+        })+        .unwrap();+        assert_eq!(out.len(), f.raw_len() as usize);+        assert_eq!(out[0], 0, "offset 0 is the empty string's terminator");+        let at = |off: u32| {+            let s = off as usize;+            let e = out[s..].iter().position(|&b| b == 0).unwrap() + s;+            String::from_utf8(out[s..e].to_vec()).unwrap()+        };+        assert_eq!(at(f.offset(a)), "Pink Floyd");+        assert_eq!(at(f.offset(zebra)), "zebra");+        assert_eq!(at(f.offset(again)), "title 4999");+    }++    #[test]+    fn string_blocks_round_trip_including_a_straddling_string() {+        let mut p = StringPool::new();+        // Enough text to cross several 64 KiB block boundaries, plus one string long+        // enough that it cannot sit inside a single block.+        let mut syms = Vec::new();+        for i in 0..20_000 {+            syms.push(p.intern(&format!("recording title number {i}")));+        }+        let huge = "x".repeat(STRING_BLOCK_SIZE + 1234);+        let huge_sym = p.intern(&huge);+        let f = p.finalize();+        let mut w = StringBlockWriter::new();+        f.write_strings(|s| w.push(s)).unwrap();+        let (compressed, blocks) = w.finish().unwrap();+        assert!(blocks.len() >= 3, "expected several blocks, got {}", blocks.len());+        assert_eq!(*blocks.last().unwrap() as usize, compressed.len());+        assert!(+            compressed.len() < f.raw_len() as usize,+            "compression must actually shrink the pool"+        );++        // Decode exactly as the reader does: locate the block by division, then+        // continue into later blocks until the NUL is found.+        let read = |off: u32| -> String {+            let mut block = off as usize / STRING_BLOCK_SIZE;+            let mut pos = off as usize % STRING_BLOCK_SIZE;+            let mut out: Vec<u8> = Vec::new();+            loop {+                let (a, b) = (blocks[block] as usize, blocks[block + 1] as usize);+                let raw =+                    zstd::bulk::decompress(&compressed[a..b], STRING_BLOCK_SIZE).unwrap();+                let slice = &raw[pos.min(raw.len())..];+                match slice.iter().position(|&c| c == 0) {+                    Some(n) => {+                        out.extend_from_slice(&slice[..n]);+                        break;+                    }+                    None => {+                        out.extend_from_slice(slice);+                        block += 1;+                        pos = 0;+                        if block + 1 >= blocks.len() {+                            break;+                        }+                    }+                }+            }+            String::from_utf8(out).unwrap()+        };+        assert_eq!(read(f.offset(syms[0])), "recording title number 0");+        assert_eq!(read(f.offset(syms[19_999])), "recording title number 19999");+        assert_eq!(read(f.offset(huge_sym)), huge, "a string spanning blocks must survive");     }      #[test]
scripts/musicbrainz/mb_ingest/src/reader.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/reader.rs b/scripts/musicbrainz/mb_ingest/src/reader.rsindex 885d8fabff..9e28caa859 100644--- a/scripts/musicbrainz/mb_ingest/src/reader.rs+++ b/scripts/musicbrainz/mb_ingest/src/reader.rs@@ -5,20 +5,21 @@ //! 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`:+//! Written to be consumed 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.+//!   * it 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.+//!   * its only dependency is `zstd`, for the compressed string pool, which the+//!     server already pulls in transitively through `zip 8.6.0`. //!   * 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.+//!   * strings come back as `Cow<'a, str>`: borrowed and free when the pool is+//!     raw, owned when it is compressed. Do not assume they are free.  use std::borrow::Cow; use std::collections::HashMap;@@ -40,7 +41,9 @@ pub enum PackError {     SectionOutOfBounds { index: usize, offset: u64, len: u64, file_len: u64 },     SectionMisaligned { index: usize, offset: u64 },     SectionTruncated { index: usize, need: u64, have: u64 },-    UnsupportedPoolCodec,+    /// The pool claims to be compressed but its block index is missing or+    /// inconsistent, so no offset can be resolved.+    BadStringBlockIndex { blocks: u32, index_len: u64 }, }  impl fmt::Display for PackError {@@ -70,10 +73,10 @@ impl fmt::Display for PackError {                 f,                 "section {index} needs {need} bytes for the row count in the header but has {have}"             ),-            PackError::UnsupportedPoolCodec => write!(+            PackError::BadStringBlockIndex { blocks, index_len } => write!(                 f,-                "pack uses a compressed string pool, which this reader cannot decode; \-                 refusing rather than returning garbage"+                "string pool claims {blocks} compressed blocks but STRINGS_BLKIDX is \+                 {index_len} bytes; refusing rather than returning garbage"             ),         }     }@@ -272,6 +275,7 @@ pub struct MbPack<'a> {     counts: Counts,     flags: u32,     dump_date: u32,+    string_blocks: u32, }  impl fmt::Debug for MbPack<'_> {@@ -281,6 +285,7 @@ impl fmt::Debug for MbPack<'_> {             .field("counts", &self.counts)             .field("flags", &self.flags)             .field("dump_date", &self.dump_date)+            .field("string_blocks", &self.string_blocks)             .finish()     } }@@ -322,10 +327,8 @@ impl<'a> MbPack<'a> {             enums: g(0x30),         };         let flags = g(0x34);-        if flags & pack::FLAG_STRINGS_COMPRESSED != 0 {-            return Err(PackError::UnsupportedPoolCodec);-        }         let dump_date = g(0x38);+        let string_blocks = g(0x3C);          let mut dir = [(0u64, 0u64); SECTION_COUNT];         let file_len = bytes.len() as u64;@@ -351,7 +354,19 @@ impl<'a> MbPack<'a> {             *slot = (off, len);         } -        let me = MbPack { bytes, dir, counts, flags, dump_date };+        let me = MbPack { bytes, dir, counts, flags, dump_date, string_blocks };+        if me.strings_compressed() {+            // The index needs one offset per block plus a trailing sentinel; without+            // it, no pool offset can be resolved at all.+            let need = (string_blocks as u64 + 1) * 4;+            let have = me.dir[pack::S_STRINGS_BLKIDX].1;+            if string_blocks == 0 || have < need {+                return Err(PackError::BadStringBlockIndex {+                    blocks: string_blocks,+                    index_len: have,+                });+            }+        }         me.check_capacity(pack::S_ARTISTS, counts.artists, pack::ARTIST_REC_LEN)?;         me.check_capacity(pack::S_ARTIST_MBID, counts.artists, pack::MBID_TRUNC_LEN)?;         me.check_capacity(pack::S_ARTIST_MBID_HI, 65537, 4)?;@@ -426,6 +441,9 @@ impl<'a> MbPack<'a> {     pub fn official_only(&self) -> bool {         self.flags & pack::FLAG_OFFICIAL_ONLY != 0     }+    pub fn strings_compressed(&self) -> bool {+        self.flags & pack::FLAG_STRINGS_COMPRESSED != 0+    }      /// Section byte lengths, for a build report or a `/status` handler.     pub fn section_sizes(&self) -> Vec<(&'static str, u64)> {@@ -438,7 +456,25 @@ impl<'a> MbPack<'a> {      // --- strings --- +    /// Decompress one block of the compressed pool.+    fn string_block(&self, block: usize) -> Option<Vec<u8>> {+        if block >= self.string_blocks as usize {+            return None;+        }+        let idx = self.sec(pack::S_STRINGS_BLKIDX);+        let (start, end) = (u32_at(idx, block)?, u32_at(idx, block + 1)?);+        if start > end {+            return None;+        }+        let pool = self.sec(pack::S_STRINGS);+        let src = pool.get(start as usize..end as usize)?;+        zstd::bulk::decompress(src, pack::STRING_BLOCK_SIZE).ok()+    }+     fn str_at(&self, off: u32) -> Cow<'a, str> {+        if self.strings_compressed() {+            return Cow::Owned(self.compressed_str_at(off));+        }         let pool = self.sec(pack::S_STRINGS);         let start = off as usize;         if start >= pool.len() {@@ -451,6 +487,33 @@ impl<'a> MbPack<'a> {         String::from_utf8_lossy(&pool[start..end])     } +    /// Blocks cover exactly `STRING_BLOCK_SIZE` of uncompressed pool, so the block+    /// is a division rather than a search. A string may straddle a boundary, in+    /// which case we continue into the next block.+    fn compressed_str_at(&self, off: u32) -> String {+        let mut block = off as usize / pack::STRING_BLOCK_SIZE;+        let mut pos = off as usize % pack::STRING_BLOCK_SIZE;+        let mut out: Vec<u8> = Vec::new();+        while let Some(raw) = self.string_block(block) {+            if pos >= raw.len() {+                break;+            }+            let slice = &raw[pos..];+            match slice.iter().position(|&b| b == 0) {+                Some(n) => {+                    out.extend_from_slice(&slice[..n]);+                    break;+                }+                None => {+                    out.extend_from_slice(slice);+                    block += 1;+                    pos = 0;+                }+            }+        }+        String::from_utf8_lossy(&out).into_owned()+    }+     fn enum_str(&self, idx: u16) -> Cow<'a, str> {         if idx == u16::MAX {             return Cow::Borrowed("");@@ -1135,13 +1198,17 @@ mod tests {     }      #[test]-    fn refuses_a_compressed_pool_rather_than_guessing() {+    fn refuses_a_compressed_pool_with_no_block_index() {         let mut buf = vec![0u8; 64 + SECTION_COUNT * 16];         buf[0..4].copy_from_slice(&MAGIC.to_le_bytes());         buf[4..8].copy_from_slice(&VERSION.to_le_bytes());         buf[8..12].copy_from_slice(&(SECTION_COUNT as u32).to_le_bytes());         buf[0x34..0x38].copy_from_slice(&pack::FLAG_STRINGS_COMPRESSED.to_le_bytes());-        assert_eq!(MbPack::open(&buf).unwrap_err(), PackError::UnsupportedPoolCodec);+        buf[0x3C..0x40].copy_from_slice(&7u32.to_le_bytes());+        assert!(matches!(+            MbPack::open(&buf).unwrap_err(),+            PackError::BadStringBlockIndex { blocks: 7, index_len: 0 }+        ));     }      #[test]
scripts/musicbrainz/mb_ingest/tests/round_trip.rs
diff --git a/scripts/musicbrainz/mb_ingest/tests/round_trip.rs b/scripts/musicbrainz/mb_ingest/tests/round_trip.rsindex eac9a139f5..8fa4d27c2d 100644--- a/scripts/musicbrainz/mb_ingest/tests/round_trip.rs+++ b/scripts/musicbrainz/mb_ingest/tests/round_trip.rs@@ -439,6 +439,90 @@ fn report_measures_the_ratios_the_design_doc_only_estimated() {     } } +#[test]+fn compressed_and_raw_pools_read_back_identically() {+    let compressed = build_fixture(BuildOptions::default());+    let raw = build_fixture(BuildOptions { compress_strings: false, ..BuildOptions::default() });+    let pc = MbPack::open(&compressed.bytes).expect("open compressed");+    let pr = MbPack::open(&raw.bytes).expect("open raw");+    assert!(pc.strings_compressed());+    assert!(!pr.strings_compressed());++    // Every string-bearing field must agree between the two encodings, including+    // the title carrying an escaped tab and newline.+    for i in 0..pc.counts().artists {+        let (a, b) = (pc.artist(i).unwrap(), pr.artist(i).unwrap());+        assert_eq!(a.name, b.name);+        assert_eq!(a.disambiguation, b.disambiguation);+        assert_eq!(a.area, b.area);+        assert_eq!(a.kind, b.kind);+        assert_eq!(a.country, b.country);+    }+    for i in 0..pc.counts().release_groups {+        let (a, b) = (pc.release_group(i).unwrap(), pr.release_group(i).unwrap());+        assert_eq!(a.title, b.title);+        assert_eq!(a.credit, b.credit);+        assert_eq!(a.primary_type, b.primary_type);+        assert_eq!(a.secondary_type, b.secondary_type);+    }+    for i in 0..pc.counts().releases {+        let (a, b) = (pc.release(i).unwrap(), pr.release(i).unwrap());+        assert_eq!(a.title, b.title);+        assert_eq!(a.status, b.status);+        assert_eq!(a.country, b.country);+        assert_eq!(a.disambiguation, b.disambiguation);+        let (ta, tb) = (pc.release_tracklist(i), pr.release_tracklist(i));+        assert_eq!(ta.len(), tb.len());+        for ((ma, tsa), (mb_, tsb)) in ta.iter().zip(tb.iter()) {+            assert_eq!(ma.format, mb_.format);+            assert_eq!(tsa.len(), tsb.len());+            for (x, y) in tsa.iter().zip(tsb.iter()) {+                assert_eq!(x.title, y.title);+                assert_eq!(x.credit, y.credit);+                assert_eq!(x.length_secs, y.length_secs);+                assert_eq!(x.position, y.position);+            }+        }+    }+    let rg = pc.release_group_by_mbid(&mb(fixture::RG_WEIRD)).unwrap();+    assert_eq!(+        &*pc.release_group(rg).unwrap().title,+        fixture::WEIRD_TITLE,+        "escaped control characters must survive compression too"+    );+    // Search is unaffected: SEARCH_TERMS is its own uncompressed dictionary.+    assert_eq!(+        pc.search_release_groups("dark side", 25),+        pr.search_release_groups("dark side", 25)+    );+}++#[test]+fn the_string_pool_is_sorted_so_compression_can_work() {+    // Offsets are assigned after an alphabetical sort. On a fixture this is only+    // an ordering check -- the ratio itself needs real data -- but if the sort+    // regresses, the compressed pool quietly loses ~15% of the whole pack.+    let built = build_fixture(BuildOptions { compress_strings: false, ..BuildOptions::default() });+    let pack = MbPack::open(&built.bytes).expect("open");+    let mut titles: Vec<(u32, String)> = Vec::new();+    for i in 0..pack.counts().release_groups {+        let g = pack.release_group(i).unwrap();+        titles.push((i, g.title.into_owned()));+    }+    // "Echoes..." < "Homogenic" < "The Dark Side..." < "Untitled\tWeird\nTitle"+    let mut sorted = titles.clone();+    sorted.sort_by(|a, b| a.1.cmp(&b.1));+    assert_eq!(+        sorted.iter().map(|t| t.1.as_str()).collect::<Vec<_>>(),+        [+            "Echoes: The Best of Pink Floyd",+            "Homogenic",+            "The Dark Side of the Moon",+            fixture::WEIRD_TITLE,+        ]+    );+}+ #[test] fn truncated_pack_is_rejected_not_read() {     let built = build_fixture(BuildOptions::default());