Modern Apps git

← Modern-Apps.git

musicbrainz revert

Commit
97e7168375f58f64aea5e063feeaa738897643f7
Author
vayun-mathur <[email protected]>
When
2026-08-21 01:25 UTC (3 months ago)
Parents
4e5901a

Diff

musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.ktindex 68bed8a444..d2f26f0edd 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt@@ -1,67 +1,36 @@ package com.vayunmathur.musicbrainz.network.api  import com.vayunmathur.library.network.NetworkClient-import kotlinx.serialization.Serializable+import kotlinx.coroutines.delay+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock import kotlinx.serialization.json.Json import java.io.IOException-import java.net.HttpURLConnection import java.net.URLEncoder -/** The 503 body the server sends when it has no catalogue to answer from. */-@Serializable-internal data class NotReadyBody(-    val error: String = "",-    val state: String = "",-    val progress: Float? = null,-    val detail: String? = null,-    /** Whether waiting and asking again will ever produce a catalogue. */-    val retryable: Boolean? = null,-)- /**- * The server has a catalogue to serve, but not yet: either the data pack was never- * imported or an import is still running. The server signals both as HTTP 503 with an- * `{"error":"not_ready"}` body, and reserves other statuses for genuine faults.- *- * Kept apart from an ordinary failure because the user can do nothing about it and it is not- * a fault at their end.+ * Client for the MusicBrainz WS/2 API.  *- * [reason] is the server's own explanation, carried only for [ABSENT] - a catalogue that is- * absent may never arrive, and [BUILDING] needs no explanation because it resolves on its own.- *- * [retryable] is the server's word on whether asking again will ever help, and it is NOT the- * same question as whether a catalogue is absent: a first boot before the scheduler has run,- * and a failed build queued for the next check, are both absent yet worth retrying, while a- * host that cannot fit a build never will be. It is reported rather than inferred because only- * the server knows which of those it is.- */-class CatalogueNotReadyException(-    message: String,-    val state: String? = null,-    val reason: String? = null,-    val retryable: Boolean = true,-) : IOException(message) {-    companion object {-        const val ABSENT = "absent"-        const val BUILDING = "building"-    }-}--/**- * Client for the self-hosted MusicBrainz mirror.+ * MusicBrainz allows one request per second per client and blocks callers that ignore+ * that, so every request funnels through [gate]. It also rejects requests without an+ * identifying User-Agent, which is why [USER_AGENT] names the app and links the source.  *- * The mirror speaks WS/2's URL grammar and JSON shapes, so the requests below are the same- * ones the public API takes. What it does not have is the public API's one-request-per-second- * limit, so requests go straight out and callers are free to run them concurrently.+ * That one request per second is a hard ceiling, so the app's job is to spend it well:+ * deduplication and caching live above this object, in+ * [com.vayunmathur.musicbrainz.domain.cache.ResponseCache].  */ object MusicBrainzApi { -    private const val BASE = "https://api.vayunmathur.com/api/mb/ws/2"--    /** Named so the mirror's own logs can tell this client apart from anything else. */+    private const val BASE = "https://musicbrainz.org/ws/2"     private const val USER_AGENT =         "ModernAppsMusicBrainz/1.0 ( https://ma.vayunmathur.com/apps/musicbrainz )" +    /** A little over a second, so clock jitter cannot round two requests into one second. */+    internal const val MIN_REQUEST_SPACING_MS = 1_100L++    private val rateLimit = Mutex()+    private var lastRequestAt = 0L+     private val headers = mapOf(         "User-Agent" to USER_AGENT,         "Accept" to "application/json",@@ -73,11 +42,10 @@ object MusicBrainzApi {      * applies to a key that is ABSENT - a `null` on one of the non-nullable fields would      * otherwise turn one unset value into a blank screen.      *-     * The server guarantees it never emits `null` anywhere, enforced on its side by-     * `skip_serializing_if` plus a test, so this is defence in depth rather than something the-     * current contract relies on. It is here because the failure it prevents is invisible-     * until it happens against the live server, and `MbTrack.id` - the field the catalogue-     * stopped carrying - is the one most likely to arrive that way if the guarantee ever slips.+     * WS/2 does emit `null` for absent values rather than omitting the key, so this is load+     * bearing rather than defensive. It can only turn a decode that would have thrown into one+     * that succeeds with the declared default, so it cannot change how a response that already+     * decodes is read.      *      * Internal rather than private so `MusicBrainzModelsTest` decodes through the real      * configuration instead of a copy of it.@@ -91,38 +59,38 @@ object MusicBrainzApi {     /**      * The failure for a non-2xx status, or null when the response is fine.      *-     * 503 is the server saying it has no catalogue loaded yet, which is a wait rather than a-     * fault. The server uses 503 EXCLUSIVELY for that and 500 exclusively for a real failure,-     * with no overlap, so the STATUS alone decides which kind of failure this is. The body is-     * parsed only to carry the server's explanation through to the screen, and a body that does-     * not parse costs nothing but that explanation.+     * Split out from [get] so `MusicBrainzApiErrorTest` can pin the mapping without a server.+     * WS/2 answers 503 when a client outruns the rate limit, which [gate] exists to prevent;+     * it is reported like any other failure because there is nothing extra for the user to do+     * about it.+     */+    internal fun failureFor(status: Int, body: String): IOException? =+        if (status in 200..299) null else IOException("HTTP $status: ${body.take(500)}")++    /**+     * How long to wait before sending, given when the last request was SENT.      *-     * Split out from [get] so `MusicBrainzApiErrorTest` can pin the mapping without a server;-     * it is the one place the contract with the server is encoded.+     * Pure and internal so `RateLimitTest` can pin the spacing rule without a clock or a+     * network.      */-    internal fun failureFor(status: Int, body: String): IOException? = when {-        status == HttpURLConnection.HTTP_UNAVAILABLE -> {-            val parsed = runCatching { json.decodeFromString<NotReadyBody>(body) }.getOrNull()-            val reason = parsed?.detail?.ifBlank { null }-                ?.takeIf { parsed.state == CatalogueNotReadyException.ABSENT }-            CatalogueNotReadyException(-                message = "HTTP 503: ${body.take(200)}",-                state = parsed?.state?.ifBlank { null },-                reason = reason,-                // Falls back to inferring it from the reason when the server does not say, so a-                // body without the field behaves as it did before the field existed rather than-                // offering a retry that cannot work.-                retryable = parsed?.retryable ?: (reason == null),-            )-        }-        status in 200..299 -> null-        else -> IOException("HTTP $status: ${body.take(500)}")+    internal fun waitBeforeSending(now: Long, sentAt: Long): Long =+        (MIN_REQUEST_SPACING_MS - (now - sentAt)).coerceAtLeast(0L)++    /** Serialises requests and spaces them out so the shared rate limit is respected. */+    private suspend fun <T> gate(block: suspend () -> T): T = rateLimit.withLock {+        delay(waitBeforeSending(System.currentTimeMillis(), lastRequestAt))+        // Stamped before the call rather than after it. The limit is on how often requests are+        // SENT, so the cooldown belongs alongside the round trip, not after it: stamping on+        // completion charged every caller the spacing PLUS the latency, which roughly doubled+        // the cost of each request and made a two-request screen take seconds.+        lastRequestAt = System.currentTimeMillis()+        block()     } -    private suspend inline fun <reified T> get(path: String): T {+    private suspend inline fun <reified T> get(path: String): T = gate {         val response = NetworkClient.performRequest("$BASE/$path", headers = headers)         failureFor(response.status, response.body)?.let { throw it }-        return json.decodeFromString<T>(response.body)+        json.decodeFromString<T>(response.body)     }      private fun encode(value: String): String = URLEncoder.encode(value, "UTF-8")
scripts/musicbrainz/mb_ingest/.gitignore
diff --git a/scripts/musicbrainz/mb_ingest/.gitignore b/scripts/musicbrainz/mb_ingest/.gitignoredeleted file mode 100644index ea8c4bf7f3..0000000000--- a/scripts/musicbrainz/mb_ingest/.gitignore+++ /dev/null@@ -1 +0,0 @@-/target
scripts/musicbrainz/mb_ingest/Cargo.lock
diff --git a/scripts/musicbrainz/mb_ingest/Cargo.lock b/scripts/musicbrainz/mb_ingest/Cargo.lockdeleted file mode 100644index f7d2f94da0..0000000000--- a/scripts/musicbrainz/mb_ingest/Cargo.lock+++ /dev/null@@ -1,107 +0,0 @@-# This file is automatically @generated by Cargo.-# 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.tomldeleted file mode 100644index d68fc564e7..0000000000--- a/scripts/musicbrainz/mb_ingest/Cargo.toml+++ /dev/null@@ -1,44 +0,0 @@-# Host-side MusicBrainz ingest tool for the offline MusicBrainz pack ("MBP1").-#-# 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 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 (it takes a &[u8], so the caller owns the mmap and this crate-#     needs no memmap dependency).-[package]-name = "mb_ingest"-version = "0.1.0"-edition = "2021"-publish = false-license = "GPL-2.0-only"-description = "MusicBrainz mbdump -> compact offline pack for the musicbrainz app"--[lib]-name = "mb_ingest"-path = "src/lib.rs"--[[bin]]-name = "mb_ingest"-path = "src/main.rs"--[dependencies]-zstd = "0.13"--[profile.release]-opt-level = 3--# 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.mddeleted file mode 100644index 62a30c0988..0000000000--- a/scripts/musicbrainz/mb_ingest/README.md+++ /dev/null@@ -1,362 +0,0 @@-# `mb_ingest` — MusicBrainz offline pack builder and reader--Turns a MusicBrainz full export into one mmap-able `.pack` file, and reads it-back. The point is to delete the `musicbrainz` app's dependence on the WS/2 API,-whose 1 req/s client-side rate limiter (`MusicBrainzApi.kt:21-40`) is what makes-the artist screen take 3-5 seconds — two serialised calls, not network latency.--Design: `c:\Users\Vayun\.llms\plans\mb_pack.plan.md` (pack-designer, task 2).-Format spec: the `//!` header of `src/pack.rs`, which is the source of truth.-Reader: `src/reader.rs`, which must stay in sync with it.--Detached from the repo-root Cargo workspace, 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--# The real 7.45 GB export: extract the 19 tables this crate reads (one bz2 pass,-# ~9 min, ~15 GB of scratch), then build from the directory. The server's-# single-traversal spill is the production equivalent.-tar -xf mbdump.tar.bz2 -C /scratch/mbdump TIMESTAMP mbdump/artist mbdump/track ...-./target/release/mb_ingest build /scratch/mbdump musicbrainz.pack --work-dir /scratch/spill--# 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 /tmp/musicbrainz.pack-./target/release/mb_ingest inspect /tmp/musicbrainz.pack-./target/release/mb_ingest query  /tmp/musicbrainz.pack "dark side"--cargo test          # 48 tests, including a full round trip through the reader-                    # and three that prove the reader cannot panic on corrupt input-```--Flags: `--tier-a` adds track MBIDs, `--official-only` drops the 9.4% of releases-that are not Official, `--raw-strings` leaves the string pool uncompressed-(+578 MB, but strings become zero-copy), `--work-dir <dir>` places the 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`** is needed (7,451,072,390 bytes for 20260819-002541).-Verified against the live export by extracting it, not by reading the schema:--* core-dump members are `mbdump/<table>`, unprefixed, in ASCII order, after-  `TIMESTAMP`, `COPYING`, `README`, `REPLICATION_SEQUENCE`, `SCHEMA_SEQUENCE`.-  The non-`musicbrainz`-schema dumps use `mbdump/<schema>.<table>` instead.-* tables are PostgreSQL `COPY` TEXT: TAB-separated, `\N` for NULL, backslash-  escapes for embedded tabs and newlines. Real titles contain both, so the-  unescaping in `src/copy.rs` is load-bearing.--**`release_group_meta` is NOT in the core dump**, despite being marked-`-- replicate` in `admin/sql/CreateTables.sql` — that marker governs replication-packets, not the dump split. Its `first_release_date_*` is therefore derived as-the earliest date across a group's releases, which is how upstream materialises it.-This is what keeps the crate off `mbdump-derived.tar.bz2`.--The comparison uses `pack::date_rank`, not the raw packed date: a year-only date-packs with month and day zero, so a raw `<` makes `1973` beat `1973-03-24` and the-group loses the precise date. Spot-checked against musicbrainz.org after the fix —-*The Dark Side of the Moon* `1973-03-24`, *Homogenic* `1997-09-20`, *Nevermind*-`1991-09-24`, all three exact matches.--Tables read (19), and `build::TABLES` is the authoritative list — import it rather-than duplicating it: `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_secondary_type_join`, `release`,-`release_country`, `release_unknown_country`, `medium`, `recording`, `track`,-`isrc`.--Measured uncompressed sizes of the 19 tables read (total ~14.8 GB):-`track` 7409 MB, `recording` 4319, `release` 739, `medium` 560,-`release_group` 459, `artist` 416, `artist_credit` 396, `isrc` 368,-`release_country` 273, `artist_credit_name` 227,-`release_group_secondary_type_join` 35, `area` 13,-`release_unknown_country` 8, and six enum tables under 1 MB each.--Deflate-compressed, measured rather than assumed, the same 19 tables are-**6.24 GB — an overall ratio of 2.37x, not 3x**. `isrc` (5.12x) and-`release_country` (3.48x) beat it because they are nearly pure digits; `track`-(2.52x) and `recording` (2.13x) are ordinary text and are 79% of the volume.--**`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 `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`. 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 — MEASURED--Built from the `20260819-002541` full export (SHA256 verified). These are real-numbers from a completed run, not projections. `MB` means 10⁶ bytes.--| section | MB |-|---|---|-| `RECORDING_MBID` | 638.1 |-| `RECORDINGS` | 358.9 |-| `SEARCH_POSTINGS` | 299.0 |-| `STRINGS` (zstd, sorted, from 805.4 raw — **3.53x**) | 227.8 |-| `TRACKS` (varint, overrides inline) | 196.4 |-| `REC_FIRST_RELEASE` | 159.5 |-| `RELEASES` + `RELEASE_MBID` | 217.2 |-| `RELEASE_GROUPS` + `RG_MBID` | 134.1 |-| `ARTISTS` + `ARTIST_MBID` | 100.7 |-| `SEARCH_TERMS` + `SEARCH_TERM_IDX` | 86.2 |-| `ISRCS` | 69.1 |-| CSR indexes, `MEDIA`, `CREDITS`, buckets | 168.0 |-| **total, tier B** | **2 655.0** |--**2,801,472,608 bytes = 2.801 GB**, built in 6.9 min on Windows / 10m48s under WSL2-(the difference is reading 14.9 GB of tables over `/mnt/c` at 205 MB/s, not the-build). **Peak `RssAnon` on Linux: 2.85 GB** (see below).--SHA256 `5beccbf5ab267643b4adeefb12d373c4dc6ff4a49f847e3e7854f3e29920d170` for the-Linux build of `5f243c765`. Byte-for-byte reproducibility was proven on two-consecutive Windows runs of an earlier commit; it has **not** been re-proven for-this commit, and cross-platform byte-identity is unverified.--### Where the +145 MB over projection went--This compares the projection (2,510 MB) against the first measured pack-(2,655 MB), before artist-credit terms were folded into the search indexes.--| section | projected | measured | delta |-|---|---|---|---|-| `SEARCH_POSTINGS` | 173 | **299.0** | **+126** |-| `STRINGS` | 181 | **227.8** | **+47** |-| `CREDITS` | 12.4 | **20.3** | +8 |-| `SEARCH_TERMS` | 44 | **51.5** | +8 |-| `SEARCH_TERM_IDX` | 44 | **34.7** | −9 |-| `TRACKS` | 235 | **196.4** | **−39** |-| everything else | — | — | ~0 |--Two misses and one win. The postings miss dominates: the design doc estimated-78.8 M postings and there are **157,118,254**, exactly 2x. `STRINGS` missed-because the raw pool is 805 MB rather than the estimated 635 MB — the-distinct-recording-title fraction is 49.9%, not 40%. `TRACKS` came in 39 MB-*under* projection, so the inline-override design paid off more than claimed.-`CREDITS` is sized to max `artist_credit` id (5,083,674) rather than live rows-(3,830,114), a 1.33x id gap.--### Then artist-credit terms were folded in: +146 MB--| section | before | after |-|---|---|---|-| `SEARCH_POSTINGS` | 299.0 MB | **444.5 MB** |-| `SEARCH_TERMS` | 51.5 MB | **52.1 MB** |-| `SEARCH_TERM_IDX` | 34.7 MB | **35.0 MB** |-| postings | 157,118,254 | **266,307,161** |-| **pack total** | 2,655,030,016 B | **2,801,472,608 B** |--Almost all of it is the recording half: a credit attached to each of 39.88 M-recordings is where the 109 M extra postings come from. Release groups alone-would have cost ~20 MB. Peak memory is unaffected — the postings are spilled and-streamed, so this costs pack size only.--Row counts in the pack: 2,962,348 artists / 4,468,998 release groups /-5,714,674 releases / 6,274,550 media / 57,404,909 tracks / 39,881,298 recordings-/ 6,278,039 ISRCs / 4,332,477 search terms / 29,153,704 distinct strings.--### The design doc's estimates against reality--| ratio | doc estimate | measured |-|---|---|---|-| distinct recording titles | 40% | **49.9%** |-| tracks whose title == recording's | 88% | **92.8%** |-| tracks whose credit == recording's | 92% | **91.5%** |-| tracks whose length == recording's | not estimated | **89.9%** |-| standalone recordings | 5% | **0.4%** |-| search postings | 78.8 M | **157,118,254** |-| string pool, raw | 635 MB | **805.4 MB** |-| id-map gap (max id / live rows) | 1.6x | **1.03-1.19x** |--The standalone-recording figure being 12x over-estimated makes lever L5 worth-~3 MB rather than 36 MB. The postings count being exactly 2x the estimate is the-main reason the pack came in above projection.--Deliberate layout differences from the doc's §2.3, each one because the doc's-version does not fit or does not work:--* `ReleaseRec` is 24 B, not 20. The doc packs "status+country" into one byte; a u8-  cannot hold an ISO-3166-1 alpha-2 code.-* `ReleaseGroupRec` 16 B not 14, `ArtistRec` 20 B not 18: the small enumerations-  and the ~250 country codes share one table and need u16 indices.-* `MEDIA` 4 B not 1, so per-medium track counts need no tracklist decode. A-  release-group page renders up to 100 editions.-* `ISRCS` 69 MB not 25: plain 11 B records sorted for binary search rather than-  delta-varint in compressed blocks. Recoverable later.-* `SEARCH_TERM_IDX` needs two offsets per term, one into the dictionary and one-  into the postings; the doc budgeted one.-* `TRACKS` carries title, credit, position **and length** overrides inline rather-  than in `TRACK_TITLE_EXC` / `TRACK_CREDIT_EXC` side arrays. Inline only widens-  the ~7% of tracks that differ, is cheaper than the two side tables, and removes-  a binary search from the hot path. Doc L8 discarded per-track lengths, wrongly:-  `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. Without that a medium-  cannot be decoded on its own and `TRACK_IDX`'s byte offset buys nothing.--Tier A (add track MBIDs) would be ~3.57 GB.--## Where the memory goes--Peak memory is the binding constraint: the ingest runs in-process alongside the-live server on a box with 5-7 GB free, and the target is stated on **anonymous**-memory because that is what causes OOM kills — clean file-backed pages cost query-latency, not availability.--**Measured on real Linux (WSL2), polling `/proc/<pid>/status` every 200 ms:**--    max RssAnon    2.85 GB     <-- the figure the target is stated on-    max RssFile    0.00 GB-    max RssShmem   0.00 GB-    VmHWM          2.85 GB--The build is effectively **all anonymous** — buffered reads go through the page-cache without entering process RSS, and no old pack is mapped during a first-build. `max(RssAnon+RssFile+RssShmem) / VmHWM = 1.000`, so the sampling interval-did not miss the spike. Nothing swapped.--Note that Windows `WorkingSetSize` for the same build reads **2.64 GB** — *lower*-than Linux `RssAnon`. A Windows figure is not an upper bound on Linux anonymous-memory (different allocator: glibc retains freed memory in per-thread arenas), so-do not substitute one for the other.--Getting there took cutting 6.14 GB to 2.85 GB, and the itemisation is what made it-possible — the peak was **accumulation**, not one allocation, because nothing was-freed between pass 2 and the write phase:--| phase | peak RSS | delta |-|---|---|---|-| pass 2-6 artists, credits, RGs, releases, media | 1.23 GB | |-| pass 7 recordings | 2.56 GB | **+1.33** |-| pass 8-9 track spill, pool sort | 2.44 GB | −0.12 |-| pass 10 TRACKS | 3.05 GB | +0.61 |-| pass 13 search index | 3.33 GB | +0.21 |-| pass 14 writing | **3.49 GB** | +0.16 |--That was the 3.49 GB profile. The two changes that took it to 2.64 GB came-straight off it: emitting the artist/release-group/release sections **before** the-track pass and dropping those vectors (−571 MB, keeping only their 30 MB of-name/title symbols for the search index), and streaming `TRACKS` into the pack-rather than buffering the whole varint stream (−196 MB).--The peak is accumulation, not one allocation — nothing was freed between pass 2-and the write. Six rules the code follows, each worth a measured amount:--* **`TRACKS` is never a `Vec<TrackRec>`** and is now streamed. 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.**-  mbdump foreign keys are integer row ids (`track.recording INTEGER`), not gids.-  Measured: **83 MB** for all six, against ~1.4 GB for a `HashMap<[u8;16], u32>`-  over recording gids alone. Measured id gaps are 1.03-1.19x, not the 1.6x assumed.-* **track rows are bucket-sorted through spill files** — 64 medium-keyed buckets,-  1.38 GB on disk, ~25 MB resident.-* **the search dictionary is a symbol pool, not `HashMap<String,u32>`**, and-  postings are spilled to 64 rank-keyed buckets and streamed. Together ~3 GB: the-  map plus the `Vec<(String,u32)>` it was drained into held ~4.3 M duplicated-  `String` allocations at once, and 157 M postings as `Vec<(u32,u32)>` is 1.26 GB.-* **entity vectors go to disk before the track pass** and are dropped.-* **every remaining buffer is dropped as soon as its section is on disk**, and the-  638 MB recording-MBID pass runs immediately before its own write.--Disk: 1.38 GB of scratch for the track spill plus ~1.26 GB for the postings spill-(`--work-dir`), and the pack itself.--## 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--Track MBIDs, and therefore the `MUSICBRAINZ_RELEASETRACKID` Vorbis tag. Nothing-else. `LibrarySnapshot.hasTrack` (`data/library/LibraryIndex.kt:30-42`) is a-four-tier cascade with every parameter nullable; dropping the tag removes tier 1-only, and recording MBIDs — tier 2, also exact — are in the pack. The precision-that tag adds is already absent for most of a real library, because-`MatchKeys.trackKey` is release-agnostic by construction.--Also given up, deliberately:--* **there is no `recording_by_mbid` and no `track_by_mbid`.** Recordings are-  stored in tracklist-clustered order, which is what makes the `TRACKS` deltas-  cheap; a sorted MBID index would cost more than it saves. The WS/2 endpoint-  that would have needed it is dead code with no callers.-* **search is word-prefix, not substring and not Lucene.** "dark side" finds-  "The Dark Side of the Moon"; "loitude" does not find "Solitude". Query words-  are ANDed. Measured latency on the full catalogue: 0.1-0.9 ms typical,-  19 ms worst seen.-* **artist-credit terms ARE indexed** for release groups and recordings, so-  "radiohead" in the albums tab finds Radiohead's albums — parity with WS/2's-  `release-group?query=`, which matches artist names. This costs **146 MB**-  (+109 M postings), almost all of it from attaching credits to 39.88 M-  recordings; release groups alone would be ~20 MB. Artist search remains-  name-only, which is what WS/2 does.-* 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--`mbdump-cover-art-archive.tar.bz2` (158 MB) records which releases actually have-cover art. The app currently builds coverartarchive.org URLs blindly and absorbs-the 404s. A presence bitmap over the 5.7 M releases is ~0.7 MB in the pack and-would remove those wasted round trips.
scripts/musicbrainz/mb_ingest/src/build.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/build.rs b/scripts/musicbrainz/mb_ingest/src/build.rsdeleted file mode 100644index 0b194ed16b..0000000000--- a/scripts/musicbrainz/mb_ingest/src/build.rs+++ /dev/null@@ -1,1964 +0,0 @@-//! The ingest passes: mbdump tables in, one `.pack` out.-//!-//! Column orders are hard-coded from the MusicBrainz schema's-//! `admin/sql/CreateTables.sql` and every table's arity and distinctive columns-//! are checked on the first row (see `copy::Shape`), because a silently shifted-//! column would produce a plausible-looking but wrong pack.-//!-//! 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, 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. 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::fs::File;-use std::io::{self, BufWriter, Read, Seek, Write};-use std::path::{Path, PathBuf};--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, FinalPool,-    HeaderCounts, Mbid, PackWriter, StringBlockWriter, StringPool, Sym, SYM_EMPTY,-};-use crate::reader::encode_recording_credit;--/// Guard against a hostile or corrupt dump asking us to allocate a dense map for-/// an absurd primary key.-const MAX_ID: u32 = 400_000_000;--/// Every table this crate reads.-///-/// All of these are present in the core `mbdump.tar.bz2` — **verified by actually-/// extracting them**, which is not the same as what the schema suggests. Note the-/// absence of `release_group_meta`: it is marked `-- replicate` in-/// `admin/sql/CreateTables.sql`, but that marker controls replication packets, not-/// the dump split, and the table is NOT in the core dump. Its-/// `first_release_date_*` is derived here instead (see `derive_first_release_dates`),-/// which is what keeps this crate off `mbdump-derived.tar.bz2`.-pub const TABLES: &[&str] = &[-    "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_secondary_type_join",-    "release",-    "release_country",-    "release_unknown_country",-    "medium",-    "recording",-    "track",-    "isrc",-];--#[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,-}--impl Default for BuildOptions {-    /// Tier B of the design doc's §2.4: everything except track MBIDs, which is-    /// the single 918 MB section and the only thing tier B gives up.-    fn default() -> Self {-        BuildOptions {-            include_track_mbids: false,-            include_recording_mbids: true,-            include_isrcs: true,-            include_recording_search: true,-            official_only: false,-            compress_strings: true,-            work_dir: None,-            verbose: false,-        }-    }-}--impl BuildOptions {-    pub fn tier_a() -> Self {-        BuildOptions { include_track_mbids: true, ..Self::default() }-    }--    fn flags(&self) -> u32 {-        let mut f = 0;-        if self.include_track_mbids {-            f |= pack::FLAG_TRACK_MBIDS;-        }-        if self.include_recording_mbids {-            f |= pack::FLAG_RECORDING_MBIDS;-        }-        if self.include_isrcs {-            f |= pack::FLAG_ISRCS;-        }-        if self.include_recording_search {-            f |= pack::FLAG_RECORDING_SEARCH;-        }-        if self.official_only {-            f |= pack::FLAG_OFFICIAL_ONLY;-        }-        if self.compress_strings {-            f |= pack::FLAG_STRINGS_COMPRESSED;-        }-        f-    }-}--/// The measured numbers a build prints. The four ratios were estimates in the-/// design doc (its R2, ~285 MB of budget between them); a real run closes them.-#[derive(Default)]-pub struct BuildStats {-    pub rows: Vec<(&'static str, u64)>,-    pub sections: Vec<(&'static str, u64)>,-    pub total_bytes: u64,-    pub distinct_strings: usize,-    pub string_pool_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,-    pub tracks_credit_same: u64,-    pub tracks_length_same: u64,-    pub standalone_recordings: u64,-    pub skipped: Vec<(&'static str, u64)>,-    pub isrc_rejects: u64,-    pub track_spill_bytes: u64,-    pub dense_map_bytes: u64,-    pub search_postings: u64,-    /// Per table: (name, max row id seen, live row count). The flat `Vec<u32>` id-    /// maps are sized to the MAX ID, not the live count, so the gap between them is-    /// a direct multiplier on resident memory and the last unmeasured input to the-    /// memory model.-    pub max_ids: Vec<(&'static str, u64, u64)>,-}--impl BuildStats {-    pub fn report(&self) -> String {-        let mb = |b: u64| b as f64 / 1_000_000.0;-        let pct = |a: u64, b: u64| if b == 0 { 0.0 } else { 100.0 * a as f64 / b as f64 };-        let mut s = String::new();-        s.push_str("input rows\n");-        for (name, n) in &self.rows {-            s.push_str(&format!("  {name:<38} {n:>12}\n"));-        }-        if !self.skipped.is_empty() {-            s.push_str("skipped (dangling or filtered)\n");-            for (name, n) in &self.skipped {-                s.push_str(&format!("  {name:<38} {n:>12}\n"));-            }-        }-        s.push_str("sections\n");-        for (name, len) in &self.sections {-            if *len > 0 {-                s.push_str(&format!("  {name:<38} {:>12.1} MB\n", mb(*len)));-            }-        }-        s.push_str(&format!("  {:<38} {:>12.1} MB\n", "TOTAL", mb(self.total_bytes)));-        s.push_str("measured ratios (design doc R2 -- these were estimates)\n");-        s.push_str(&format!(-            "  {:<38} {:>11.1}%  ({} of {})\n",-            "distinct recording titles",-            pct(self.distinct_recording_titles, self.recording_titles),-            self.distinct_recording_titles,-            self.recording_titles-        ));-        let tracks = self.rows.iter().find(|(n, _)| *n == "track").map(|(_, n)| *n).unwrap_or(0);-        s.push_str(&format!(-            "  {:<38} {:>11.1}%\n",-            "tracks whose title == recording's",-            pct(self.tracks_title_same, tracks)-        ));-        s.push_str(&format!(-            "  {:<38} {:>11.1}%\n",-            "tracks whose credit == recording's",-            pct(self.tracks_credit_same, tracks)-        ));-        s.push_str(&format!(-            "  {:<38} {:>11.1}%\n",-            "tracks whose length == recording's",-            pct(self.tracks_length_same, tracks)-        ));-        let recs = self.rows.iter().find(|(n, _)| *n == "recording").map(|(_, n)| *n).unwrap_or(0);-        s.push_str(&format!(-            "  {:<38} {:>11.1}%  ({})\n",-            "recordings with no track (standalone)",-            pct(self.standalone_recordings, recs),-            self.standalone_recordings-        ));-        s.push_str("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  ({} 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("id density (flat maps are sized to max id, not live count)\n");-        for (name, max_id, live) in &self.max_ids {-            let gap = if *live == 0 { 0.0 } else { (*max_id + 1) as f64 / *live as f64 };-            s.push_str(&format!(-                "  {name:<24} max id {max_id:>11}  live {live:>11}  gap {gap:>5.2}x\n"-            ));-        }-        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 spill (disk, not memory)",-            mb(self.track_spill_bytes)-        ));-        s.push_str(&format!(-            "  {:<38} {:>12.1} MB\n",-            "dense id -> index maps",-            mb(self.dense_map_bytes)-        ));-        if self.isrc_rejects > 0 {-            s.push_str(&format!("  {:<38} {:>12}\n", "malformed ISRCs dropped", self.isrc_rejects));-        }-        s-    }-}--/// A dense `primary key -> index` map.-struct DenseMap {-    v: Vec<u32>,-}--impl DenseMap {-    fn new() -> DenseMap {-        DenseMap { v: Vec::new() }-    }--    fn set(&mut self, id: u32, val: u32) -> io::Result<()> {-        if id > MAX_ID {-            return Err(other_err(format!("primary key {id} exceeds the sanity ceiling {MAX_ID}")));-        }-        if self.v.len() <= id as usize {-            self.v.resize(id as usize + 1, pack::NONE);-        }-        self.v[id as usize] = val;-        Ok(())-    }--    fn get(&self, id: u32) -> Option<u32> {-        match self.v.get(id as usize) {-            Some(&v) if v != pack::NONE => Some(v),-            _ => None,-        }-    }--    fn bytes(&self) -> u64 {-        (self.v.len() * 4) as u64-    }--    /// The largest primary key seen, which is what the allocation is sized to.-    fn max_id(&self) -> u64 {-        self.v.len().saturating_sub(1) as u64-    }--    fn live(&self) -> u64 {-        self.v.iter().filter(|&&v| v != pack::NONE).count() as u64-    }-}--// --- 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);-    }-}--/// Bucket-sorts search postings by term rank through files on disk.-///-/// 157 M postings held as `Vec<(u32, u32)>` is 1.26 GB, which was the single-/// largest contributor to a measured 6.14 GB peak. Bucketing by rank means only-/// one bucket (~20 MB) is resident while it is sorted and emitted, and the ranks-/// are known before this runs so the buckets come out in output order.-struct PostingSpill {-    dir: PathBuf,-    writers: Vec<BufWriter<File>>,-    buckets: usize,-    terms: u32,-    written: u64,-}--impl PostingSpill {-    fn new(work_dir: Option<&Path>, terms: u32) -> io::Result<PostingSpill> {-        let buckets = if terms < 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_postings_{}_{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!("p{b:03}")))?,-            ));-        }-        Ok(PostingSpill { dir, writers, buckets, terms, written: 0 })-    }--    fn bucket_of(&self, rank: u32) -> usize {-        if self.buckets == 1 || self.terms == 0 {-            return 0;-        }-        ((rank as u64 * self.buckets as u64) / self.terms as u64).min(self.buckets as u64 - 1)-            as usize-    }--    /// First rank NOT in bucket `b`. Must be the exact inverse of `bucket_of`.-    fn bucket_end(&self, b: usize) -> u32 {-        if self.buckets == 1 {-            return self.terms;-        }-        if b + 1 >= self.buckets {-            return self.terms;-        }-        let t = self.terms as u64;-        let n = self.buckets as u64;-        (((b as u64 + 1) * t).div_ceil(n)).min(t) as u32-    }--    fn push(&mut self, rank: u32, refv: u32) -> io::Result<()> {-        let b = self.bucket_of(rank);-        let mut rec = [0u8; 8];-        rec[0..4].copy_from_slice(&rank.to_le_bytes());-        rec[4..8].copy_from_slice(&refv.to_le_bytes());-        self.writers[b].write_all(&rec)?;-        self.written += 8;-        Ok(())-    }--    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!("p{b:03}"))).collect())-    }-}--impl Drop for PostingSpill {-    fn drop(&mut self) {-        self.writers.clear();-        let _ = std::fs::remove_dir_all(&self.dir);-    }-}--/// The display-string symbol for a credit id, or `SYM_EMPTY` when there is none.-fn credit_sym_of(credit_syms: &[Sym], credit_id: u32) -> Sym {-    if credit_id == pack::NONE {-        return SYM_EMPTY;-    }-    credit_syms.get(credit_id as usize).copied().unwrap_or(SYM_EMPTY)-}--/// Tokenise an entity's indexable text and spill one posting per term.-///-/// The terms come from `pack::indexable_terms`, which the reader's verification-/// path also calls. That sharing is the point: two implementations of "what does-/// this entity contribute to the index" is precisely the bug that shipped.-fn emit_postings(-    primary: &str,-    credit: &str,-    refv: u32,-    terms: &StringPool,-    ranks: &[u32],-    buf: &mut Vec<String>,-    spill: &mut PostingSpill,-) -> io::Result<()> {-    pack::indexable_terms(primary, credit, buf);-    for t in buf.iter() {-        let Some(sym) = terms.lookup(t) else {-            return Err(other_err(format!(-                "search term {t:?} was not interned in the dictionary pass; the two search \-                 passes disagree, which would silently corrupt the index"-            )));-        };-        spill.push(ranks[sym as usize], refv)?;-    }-    Ok(())-}--#[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: Sym,-    disamb: Sym,-    area: Sym,-    begin_date: u32,-    kind: u16,-    country: u16,-    id: u32,-}--struct RgBuild {-    gid: Mbid,-    title: Sym,-    first_date: u32,-    credit_id: u32,-    primary: u16,-    secondary: u16,-    secondary_src_id: u32,-    id: u32,-}--struct ReleaseBuild {-    gid: Mbid,-    title: Sym,-    rg_id: u32,-    credit_id: u32,-    date: u32,-    disamb: Sym,-    status: u16,-    status_rank: u8,-    country: u16,-    id: u32,-}--struct MediumBuild {-    id: u32,-    release_idx: u32,-    position: i32,-    format: u16,-    track_count: u32,-}--/// Build a pack from `source` and write it to `out`.-pub fn build<W: Write + Seek>(-    source: &dyn TableSource,-    out: W,-    opts: &BuildOptions,-    log: &mut dyn Write,-) -> io::Result<BuildStats> {-    let mut st = BuildStats::default();-    let mut pool = StringPool::new();-    let mut enums = EnumPool::new();-    // Phase lines carry elapsed seconds so an external RSS sampler can be joined-    // against them. Peak memory per phase is measured that way rather than-    // modelled: the one time it was modelled, the estimate was wrong by 3x.-    let started = std::time::Instant::now();-    macro_rules! step {-        ($($arg:tt)*) => {-            if opts.verbose {-                write!(log, "[{:8.2}s] ", started.elapsed().as_secs_f64())?;-                writeln!(log, $($arg)*)?;-                log.flush()?;-            }-        };-    }--    // --- areas and the small enumerations --------------------------------------    step!("pass 1: areas, country codes, enumerations");-    let mut area_name: HashMap<u32, Sym> = HashMap::new();-    let n = require(-        source,-        "area",-        Shape { table: "area", min_fields: 14, ints: &[0], uuids: &[1] },-        |row| {-            if let Some(id) = row.u32(0) {-                let sym = pool.intern(&row.str(2));-                area_name.insert(id, sym);-            }-            Ok(())-        },-    )?;-    st.rows.push(("area", n));--    let mut area_country: HashMap<u32, u16> = HashMap::new();-    let n = require(-        source,-        "iso_3166_1",-        Shape { table: "iso_3166_1", min_fields: 2, ints: &[0], uuids: &[] },-        |row| {-            if let Some(area) = row.u32(0) {-                let code = row.str(1);-                let code = code.trim();-                if !code.is_empty() {-                    let e = enums.intern(&mut pool, code);-                    area_country.insert(area, e);-                }-            }-            Ok(())-        },-    )?;-    st.rows.push(("iso_3166_1", n));--    let artist_types = read_enum_table(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(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-    // nothing in the app reads the per-artist breakdown -- only-    // MbArtistCredit.display(), which concatenates name + joinphrase. MusicBrainz-    // already stores exactly that string as `artist_credit.name`, so we take it-    // rather than re-deriving it from artist_credit_name and risking a different-    // join order. artist_credit_name is still needed, for the artist -> release-    // group links.-    step!("pass 2: artist credits");-    let mut credit_syms: Vec<Sym> = Vec::new();-    let n = require(-        source,-        "artist_credit",-        Shape { table: "artist_credit", min_fields: 7, ints: &[0, 2], uuids: &[6] },-        |row| {-            let Some(id) = row.u32(0) else { return Ok(()) };-            if id > MAX_ID {-                return Err(other_err(format!("artist_credit id {id} exceeds {MAX_ID}")));-            }-            let i = id as usize;-            if credit_syms.len() <= i {-                credit_syms.resize(i + 1, SYM_EMPTY);-            }-            credit_syms[i] = pool.intern(&row.str(1));-            Ok(())-        },-    )?;-    st.rows.push(("artist_credit", n));-    let credit_count = credit_syms.len() as u32;--    let mut credit_artists: Vec<Vec<u32>> = vec![Vec::new(); credit_syms.len()];-    let n = require(-        source,-        "artist_credit_name",-        Shape { table: "artist_credit_name", min_fields: 5, ints: &[0, 1, 2], uuids: &[] },-        |row| {-            let (Some(cid), Some(artist)) = (row.u32(0), row.u32(2)) else { return Ok(()) };-            if let Some(slot) = credit_artists.get_mut(cid as usize) {-                slot.push(artist);-            }-            Ok(())-        },-    )?;-    st.rows.push(("artist_credit_name", n));--    // --- artists ---------------------------------------------------------------    step!("pass 3: artists");-    let mut artists: Vec<ArtistBuild> = Vec::new();-    let mut bad_gids = 0u64;-    let n = require(-        source,-        "artist",-        Shape { table: "artist", min_fields: 19, ints: &[0], uuids: &[1] },-        |row| {-            let Some(id) = row.u32(0) else { return Ok(()) };-            let Some(gid) = parse_mbid(&row.str(1)) else {-                bad_gids += 1;-                return Ok(());-            };-            let area = row.u32(11);-            artists.push(ArtistBuild {-                gid,-                name: 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)-                    .and_then(|t| artist_types.get(&t).copied())-                    .unwrap_or(EnumPool::NONE_ENUM),-                country: area-                    .and_then(|a| area_country.get(&a).copied())-                    .unwrap_or(EnumPool::NONE_ENUM),-                id,-            });-            Ok(())-        },-    )?;-    st.rows.push(("artist", n));-    if bad_gids > 0 {-        st.skipped.push(("artist rows with an unparseable gid", bad_gids));-    }-    drop(area_name);--    artists.sort_unstable_by_key(|a| a.gid);-    let mut artist_idx = DenseMap::new();-    for (i, a) in artists.iter().enumerate() {-        artist_idx.set(a.id, i as u32)?;-    }--    // --- release groups --------------------------------------------------------    step!("pass 4: release groups");-    let mut rgs: Vec<RgBuild> = Vec::new();-    let n = require(-        source,-        "release_group",-        Shape { table: "release_group", min_fields: 8, ints: &[0, 3], uuids: &[1] },-        |row| {-            let Some(id) = row.u32(0) else { return Ok(()) };-            let Some(gid) = parse_mbid(&row.str(1)) else { return Ok(()) };-            rgs.push(RgBuild {-                gid,-                title: pool.intern(&row.str(2)),-                first_date: 0,-                credit_id: row.u32(3).unwrap_or(pack::NONE),-                primary: row-                    .u32(4)-                    .and_then(|t| rg_primary.get(&t).copied())-                    .unwrap_or(EnumPool::NONE_ENUM),-                secondary: EnumPool::NONE_ENUM,-                secondary_src_id: u32::MAX,-                id,-            });-            Ok(())-        },-    )?;-    st.rows.push(("release_group", n));-    let mut rg_slot = DenseMap::new();-    for (i, r) in rgs.iter().enumerate() {-        rg_slot.set(r.id, i as u32)?;-    }-    let n = require(-        source,-        "release_group_secondary_type_join",-        Shape {-            table: "release_group_secondary_type_join",-            min_fields: 2,-            ints: &[0, 1],-            uuids: &[],-        },-        |row| {-            let (Some(rg), Some(ty)) = (row.u32(0), row.u32(1)) else { return Ok(()) };-            if let Some(slot) = rg_slot.get(rg) {-                let r = &mut rgs[slot as usize];-                // The app only ever renders secondaryTypes[0]; pick the lowest type-                // id so the choice is deterministic across rebuilds.-                if ty < r.secondary_src_id {-                    if let Some(&e) = rg_secondary.get(&ty) {-                        r.secondary = e;-                        r.secondary_src_id = ty;-                    }-                }-            }-            Ok(())-        },-    )?;-    st.rows.push(("release_group_secondary_type_join", n));-    drop(rg_slot);--    rgs.sort_unstable_by_key(|r| r.gid);-    let mut rg_idx = DenseMap::new();-    for (i, r) in rgs.iter().enumerate() {-        rg_idx.set(r.id, i as u32)?;-    }--    // --- releases --------------------------------------------------------------    step!("pass 5: releases");-    let mut releases: Vec<ReleaseBuild> = Vec::new();-    let mut filtered_status = 0u64;-    let n = require(-        source,-        "release",-        Shape { table: "release", min_fields: 14, ints: &[0, 3, 4], uuids: &[1] },-        |row| {-            let Some(id) = row.u32(0) else { return Ok(()) };-            let Some(gid) = parse_mbid(&row.str(1)) else { return Ok(()) };-            let Some(rg) = row.u32(4) else { return Ok(()) };-            let status_id = row.u32(5);-            if opts.official_only && status_id != Some(1) {-                filtered_status += 1;-                return Ok(());-            }-            releases.push(ReleaseBuild {-                gid,-                title: pool.intern(&row.str(2)),-                rg_id: rg,-                credit_id: row.u32(3).unwrap_or(pack::NONE),-                date: 0,-                disamb: pool.intern(&row.str(10)),-                status: status_id-                    .and_then(|s| statuses.get(&s).copied())-                    .unwrap_or(EnumPool::NONE_ENUM),-                // Official (id 1) first, then anything with a status, then none:-                // the edition-list sort key of MusicBrainzViewModel.kt:238.-                status_rank: match status_id {-                    Some(1) => 0,-                    Some(_) => 1,-                    None => 2,-                },-                country: EnumPool::NONE_ENUM,-                id,-            });-            Ok(())-        },-    )?;-    st.rows.push(("release", n));-    if filtered_status > 0 {-        st.skipped.push(("non-Official releases (--official-only)", filtered_status));-    }-    let mut release_slot = DenseMap::new();-    for (i, r) in releases.iter().enumerate() {-        release_slot.set(r.id, i as u32)?;-    }-    // release_country.country is an *area* id, not a country code, so it resolves-    // through the same iso_3166_1 mapping the artists used; a release can carry-    // several countries, and we keep the earliest-dated one.-    let n = require(-        source,-        "release_country",-        Shape { table: "release_country", min_fields: 5, ints: &[0, 1], uuids: &[] },-        |row| {-            let Some(slot) = row.u32(0).and_then(|id| release_slot.get(id)) else { return Ok(()) };-            let d = pack_date(row.i64(2), row.i64(3), row.i64(4));-            let r = &mut releases[slot as usize];-            if pack::date_rank(d) < pack::date_rank(r.date) {-                r.date = d;-                if let Some(&c) = row.u32(1).and_then(|a| area_country.get(&a)) {-                    r.country = c;-                }-            }-            Ok(())-        },-    )?;-    st.rows.push(("release_country", n));-    let n = require(-        source,-        "release_unknown_country",-        Shape { table: "release_unknown_country", min_fields: 4, ints: &[0], uuids: &[] },-        |row| {-            let Some(slot) = row.u32(0).and_then(|id| release_slot.get(id)) else { return Ok(()) };-            let d = pack_date(row.i64(1), row.i64(2), row.i64(3));-            let r = &mut releases[slot as usize];-            if pack::date_rank(d) < pack::date_rank(r.date) {-                r.date = d;-            }-            Ok(())-        },-    )?;-    st.rows.push(("release_unknown_country", n));-    drop(release_slot);-    drop(area_country);--    releases.sort_unstable_by_key(|r| r.gid);-    let mut release_idx = DenseMap::new();-    for (i, r) in releases.iter().enumerate() {-        release_idx.set(r.id, i as u32)?;-    }-    let mut dangling_rg = 0u64;-    let mut rg_release_pairs: Vec<(u32, u32)> = Vec::with_capacity(releases.len());-    for (i, r) in releases.iter().enumerate() {-        match rg_idx.get(r.rg_id) {-            Some(g) => rg_release_pairs.push((g, i as u32)),-            None => dangling_rg += 1,-        }-    }-    if dangling_rg > 0 {-        st.skipped.push(("releases whose release group is missing", dangling_rg));-    }--    // A release group's first release date. MusicBrainz materialises this in-    // `release_group_meta`, which is NOT in the core dump, so it is derived here as-    // the earliest known date across the group's releases -- which is how upstream-    // computes it in the first place.-    //-    // The comparison goes through `date_rank`, NOT the packed value: a year-only-    // date packs with month and day zero, so a raw `<` would make `1973` beat-    // `1973-03-24` and the group would lose the precise date. Spot-checked against-    // musicbrainz.org: release group f5093c06-23e3-404f-aeaa-40f72885ee3a (The Dark-    // Side of the Moon) is 1973-03-24 there, and a raw comparison derived `1973`.-    //-    // Load-bearing: the RG screen header, the discography sort-    // (MusicBrainzViewModel.kt:207) and the release-date fallback (:475-476).-    for &(g, ri) in &rg_release_pairs {-        let d = releases[ri as usize].date;-        if d == 0 {-            continue;-        }-        let cur = &mut rgs[g as usize].first_date;-        if pack::date_rank(d) < pack::date_rank(*cur) {-            *cur = d;-        }-    }--    // ARTIST_RGS: artist -> release groups, via the release group's credit. Built-    // after the dates are derived, because it is sorted on them.-    let mut artist_rg_pairs: Vec<(u32, u32)> = Vec::new();-    for (i, r) in rgs.iter().enumerate() {-        let Some(artists_of) = credit_artists.get(r.credit_id as usize) else { continue };-        for a in artists_of {-            if let Some(ai) = artist_idx.get(*a) {-                artist_rg_pairs.push((ai, i as u32));-            }-        }-    }-    // Newest first: the discography order MusicBrainzViewModel.kt:207 sorts into.-    artist_rg_pairs.sort_unstable_by(|x, y| {-        x.0.cmp(&y.0)-            .then(rgs[y.1 as usize].first_date.cmp(&rgs[x.1 as usize].first_date))-            .then(x.1.cmp(&y.1))-    });-    artist_rg_pairs.dedup();-    let (artist_rgs, artist_rgs_idx) = to_csr(&artist_rg_pairs, artists.len());-    drop(artist_rg_pairs);-    drop(credit_artists);--    rg_release_pairs.sort_unstable_by(|x, y| {-        let (a, b) = (&releases[x.1 as usize], &releases[y.1 as usize]);-        x.0.cmp(&y.0)-            .then(a.status_rank.cmp(&b.status_rank))-            .then(pack::date_rank(a.date).cmp(&pack::date_rank(b.date)))-            .then(x.1.cmp(&y.1))-    });-    let (rg_releases, rg_releases_idx) = to_csr(&rg_release_pairs, rgs.len());-    drop(rg_release_pairs);--    // --- media -----------------------------------------------------------------    step!("pass 6: media");-    let mut media: Vec<MediumBuild> = Vec::new();-    let mut dangling_media = 0u64;-    let n = require(-        source,-        "medium",-        Shape { table: "medium", min_fields: 9, ints: &[0, 1, 2], uuids: &[8] },-        |row| {-            let (Some(id), Some(rel)) = (row.u32(0), row.u32(1)) else { return Ok(()) };-            let Some(ri) = release_idx.get(rel) else {-                dangling_media += 1;-                return Ok(());-            };-            media.push(MediumBuild {-                id,-                release_idx: ri,-                position: clamp_position(row.i64(2)),-                format: row-                    .u32(3)-                    .and_then(|f| formats.get(&f).copied())-                    .unwrap_or(EnumPool::NONE_ENUM),-                track_count: row.u32(7).unwrap_or(0),-            });-            Ok(())-        },-    )?;-    st.rows.push(("medium", n));-    if dangling_media > 0 {-        st.skipped.push(("media whose release was filtered or missing", dangling_media));-    }-    media.sort_unstable_by(|a, b| {-        a.release_idx.cmp(&b.release_idx).then(a.position.cmp(&b.position)).then(a.id.cmp(&b.id))-    });-    let mut medium_idx = DenseMap::new();-    for (i, m) in media.iter().enumerate() {-        medium_idx.set(m.id, i as u32)?;-    }-    let mut media_idx_csr = vec![0u32; releases.len() + 1];-    for m in &media {-        media_idx_csr[m.release_idx as usize + 1] += 1;-    }-    for i in 0..releases.len() {-        media_idx_csr[i + 1] += media_idx_csr[i];-    }--    // --- recordings ------------------------------------------------------------    // 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_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<Sym> = std::collections::HashSet::new();-    let n = require(-        source,-        "recording",-        Shape { table: "recording", min_fields: 9, ints: &[0, 3], uuids: &[1] },-        |row| {-            let Some(id) = row.u32(0) 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_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 = 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(())-        },-    )?;-    st.rows.push(("recording", n));-    st.recording_titles = n;-    st.distinct_recording_titles = distinct_titles.len() as u64;-    drop(distinct_titles);--    // --- 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(-        source,-        "track",-        Shape { table: "track", min_fields: 12, ints: &[0, 2, 3, 4, 7], uuids: &[1] },-        |row| {-            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 = if opts.include_track_mbids {-                match parse_mbid(&row.str(1)) {-                    Some(g) => g,-                    None => {-                        bad_track_gids += 1;-                        return Ok(());-                    }-                }-            } else {-                [0u8; 16]-            };-            TrackRow {-                medium_idx: mi,-                position: clamp_position(row.i64(4)),-                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)),-            }-            .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));-    if dangling_tracks > 0 {-        st.skipped.push(("tracks whose medium was filtered or missing", dangling_tracks));-    }-    if bad_track_gids > 0 {-        st.skipped.push(("tracks with an unparseable gid", bad_track_gids));-    }-    st.track_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;--    // --- emit everything that is already final ---------------------------------    // The pack writer opens HERE, before the track pass, so the artist,-    // release-group and release vectors can go to disk and be dropped rather than-    // sitting resident until the end. Measured: they are 571 MB of a 3.49 GB peak,-    // and nothing after this point needs more than their name/title symbols.-    // Section order in the file is irrelevant; the directory holds absolute offsets.-    step!("pass 9b: artists, release groups, releases");-    let artist_count = artists.len() as u32;-    let rg_count = rgs.len() as u32;-    let release_count = releases.len() as u32;-    let credit_live = credit_syms.iter().filter(|&&s| s != SYM_EMPTY).count() as u64;-    let mut w = PackWriter::new(out)?;--    let enum_offsets: Vec<u32> = enums.syms().iter().map(|&s| pool.offset(s)).collect();-    let enum_count = enum_offsets.len() as u32;-    w.section_u32(pack::S_ENUM_POOL, &enum_offsets)?;-    drop(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_offsets);-    // `credit_syms` survives to the search pass: artist-credit terms are folded into-    // the release-group and recording indexes so that typing an artist name into the-    // albums tab finds their albums. WS/2's `release-group?query=` matches artist-    // names, so a title-only index would be a REGRESSION against the live API the-    // pack replaces -- "radiohead" would return nothing rather than fewer results.-    // 20 MB to keep, and dropped as soon as the index is built.--    let mut buf: Vec<u8> = Vec::new();-    for a in &artists {-        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());-    }-    w.section(pack::S_ARTISTS, &buf)?;-    let gids: Vec<Mbid> = artists.iter().map(|a| a.gid).collect();-    let (recs, hi) = build_mbid_table(&gids);-    w.section(pack::S_ARTIST_MBID, &recs)?;-    w.section_u32(pack::S_ARTIST_MBID_HI, &hi)?;-    drop(gids);-    drop(recs);-    drop(hi);-    // Only the name symbols survive, for the search index: 12 MB instead of 118.-    let artist_name_syms: Vec<Sym> = artists.iter().map(|a| a.name).collect();-    drop(artists);--    buf.clear();-    for r in &rgs {-        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());-        buf.extend_from_slice(&r.secondary.to_le_bytes());-    }-    w.section(pack::S_RELEASE_GROUPS, &buf)?;-    let gids: Vec<Mbid> = rgs.iter().map(|r| r.gid).collect();-    let (recs, hi) = build_mbid_table(&gids);-    w.section(pack::S_RG_MBID, &recs)?;-    w.section_u32(pack::S_RG_MBID_HI, &hi)?;-    drop(gids);-    drop(recs);-    drop(hi);-    let rg_title_syms: Vec<Sym> = rgs.iter().map(|r| r.title).collect();-    let rg_credit_syms: Vec<Sym> = rgs-        .iter()-        .map(|r| credit_sym_of(&credit_syms, r.credit_id))-        .collect();-    drop(rgs);--    w.section_u32(pack::S_ARTIST_RGS, &artist_rgs)?;-    drop(artist_rgs);-    w.section_u32(pack::S_ARTIST_RGS_IDX, &artist_rgs_idx)?;-    drop(artist_rgs_idx);--    buf.clear();-    for r in &releases {-        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(&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());-    }-    w.section(pack::S_RELEASES, &buf)?;-    let gids: Vec<Mbid> = releases.iter().map(|r| r.gid).collect();-    let (recs, hi) = build_mbid_table(&gids);-    w.section(pack::S_RELEASE_MBID, &recs)?;-    w.section_u32(pack::S_RELEASE_MBID_HI, &hi)?;-    drop(gids);-    drop(recs);-    drop(hi);-    drop(releases);--    w.section_u32(pack::S_RG_RELEASES, &rg_releases)?;-    drop(rg_releases);-    w.section_u32(pack::S_RG_RELEASES_IDX, &rg_releases_idx)?;-    drop(rg_releases_idx);-    w.section_u32(pack::S_MEDIA_IDX, &media_idx_csr)?;-    drop(media_idx_csr);-    buf.clear();-    buf.shrink_to_fit();--    // --- 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();-    // TRACKS is streamed straight into the pack rather than buffered: the full-    // varint stream is 196 MB, and it would otherwise stay resident until the very-    // end. `chunk` is flushed every 64 KB, so only that much is ever held.-    let mut chunk: Vec<u8> = Vec::with_capacity(1 << 17);-    let mut tracks_len: u64 = 0;-    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 missing_recordings = 0u64;-    let mut next_medium = 0usize;-    w.begin(pack::S_TRACKS)?;-    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 {-                let mut g = [0u8; 16];-                g.copy_from_slice(&chunk[TRACK_SPILL_LEN..TRACK_SPILL_LEN_A]);-                gids.push(g);-            }-        }-        let mut order: Vec<u32> = (0..rows.len() as u32).collect();-        // The trailing `i` matters: MusicBrainz does contain more than one track at-        // the same position on the same medium, and without a total order-        // `sort_unstable_by_key` may order those two arbitrarily between runs. That-        // produced two same-sized but byte-different packs from identical input, and-        // the fixture never caught it because it has no tied positions.-        order.sort_unstable_by_key(|&i| {-            (rows[i as usize].medium_idx, rows[i as usize].position, i)-        });-        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_len + chunk.len() as u64) 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 chunk, 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 chunk, new_idx as u64);-                } else {-                    pack::write_zigzag(&mut chunk, new_idx as i64 - prev_rec);-                }-                prev_rec = new_idx as i64;-                if title_differs {-                    pack::write_uvarint(&mut chunk, pool.offset(t.title) as u64);-                }-                if credit_differs {-                    pack::write_uvarint(&mut chunk, t.credit_id as u64);-                }-                if pos_differs {-                    pack::write_uvarint(&mut chunk, t.position.max(0) as u64);-                }-                if len_differs {-                    pack::write_uvarint(&mut chunk, 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;-            // Flushed at medium boundaries, so a medium's run is never split across-            // the boundary bookkeeping and only ~64 KB is ever resident.-            if chunk.len() >= (1 << 16) {-                w.write(&chunk)?;-                tracks_len += chunk.len() as u64;-                chunk.clear();-            }-        }-    }-    // Trailing media with no tracks.-    while next_medium < media.len() {-        track_idx[next_medium] = (tracks_len + chunk.len() as u64) as u32;-        media[next_medium].track_count = 0;-        next_medium += 1;-    }-    track_idx[media.len()] = (tracks_len + chunk.len() as u64) as u32;-    w.write(&chunk)?;-    tracks_len += chunk.len() as u64;-    chunk.clear();-    chunk.shrink_to_fit();-    let tracks_section_len = w.end()?;-    assert_eq!(tracks_section_len, tracks_len, "TRACKS length bookkeeping drifted");-    assert!(-        tracks_len <= u32::MAX as u64,-        "TRACKS is {tracks_len} bytes, past the u32 ceiling TRACK_IDX addresses it with"-    );-    if missing_recordings > 0 {-        st.skipped.push(("tracks whose recording is missing", missing_recordings));-    }-    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_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);-            rec_first_release.push(pack::NONE);-        }-    }-    st.standalone_recordings = rec_order.len() as u64 - tracked;--    // --- 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(-            source,-            "isrc",-            Shape { table: "isrc", min_fields: 5, ints: &[0, 1], uuids: &[] },-            |row| {-                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(());-                }-                match pack_isrc(row.str(2).trim().as_bytes()) {-                    Some(p) => isrcs.push((new, p)),-                    None => rejects += 1,-                }-                Ok(())-            },-        )?;-        st.rows.push(("isrc", n));-        st.isrc_rejects = rejects;-        isrcs.sort_unstable();-        isrcs.dedup();-    }--    // --- search index ----------------------------------------------------------    // Two passes over the in-memory entity texts rather than one, because the-    // one-pass version was the peak of the whole build: a `HashMap<String, u32>`-    // dictionary plus the `Vec<(String, u32)>` it is drained into cost ~1.5 GB of-    // duplicated allocations, and 157 M postings held as `Vec<(u32, u32)>` cost-    // another 1.26 GB. Pass A interns terms into a symbol pool (the same-    // open-addressed structure the string pool uses); pass B emits postings with-    // their final sorted term ranks straight into rank-keyed spill buckets. The-    // texts are already in memory, so the second pass costs CPU and no I/O.-    step!("pass 13a: search dictionary");-    let mut terms = StringPool::new();-    let mut terms_buf: Vec<String> = Vec::new();-    for &sym in artist_name_syms.iter() {-        let text = String::from_utf8_lossy(pool.get(sym)).into_owned();-        terms_buf.clear();-        search_terms(&text, &mut terms_buf);-        for t in terms_buf.iter() {-            terms.intern(t);-        }-    }-    for &sym in rg_title_syms.iter() {-        let text = String::from_utf8_lossy(pool.get(sym)).into_owned();-        terms_buf.clear();-        search_terms(&text, &mut terms_buf);-        for t in terms_buf.iter() {-            terms.intern(t);-        }-    }-    // Every artist-credit display string, interned once. That covers the credits of-    // both release groups and recordings without walking 39.9 M recordings here ---    // 5.08 M strings instead. The postings pass below attaches them per entity.-    for &sym in credit_syms.iter() {-        if sym == SYM_EMPTY {-            continue;-        }-        let text = String::from_utf8_lossy(pool.get(sym)).into_owned();-        terms_buf.clear();-        search_terms(&text, &mut terms_buf);-        for t in terms_buf.iter() {-            terms.intern(t);-        }-    }-    if opts.include_recording_search {-        for id in rec_order.iter() {-            let text = String::from_utf8_lossy(pool.get(rec_title[*id as usize])).into_owned();-            terms_buf.clear();-            search_terms(&text, &mut terms_buf);-            for t in terms_buf.iter() {-                terms.intern(t);-            }-        }-    }-    // `finalize` would consume the pool, and pass B still needs to look terms up,-    // so the sorted order is taken without consuming it. Alphabetical order is-    // exactly what SEARCH_TERMS needs for the reader's binary search.-    let term_count = terms.distinct();-    let term_order = terms.sorted_order();-    let mut term_ranks = vec![0u32; term_count];-    for (rank, &sym) in term_order.iter().enumerate() {-        term_ranks[sym as usize] = rank as u32;-    }--    step!("pass 13b: search postings ({term_count} terms)");-    let mut post_spill = PostingSpill::new(opts.work_dir.as_deref(), term_count as u32)?;-    {-        for (i, &sym) in artist_name_syms.iter().enumerate() {-            check_searchable(i as u32)?;-            let text = String::from_utf8_lossy(pool.get(sym)).into_owned();-            emit_postings(-                &text,-                "",-                (pack::KIND_ARTIST << pack::KIND_SHIFT) | i as u32,-                &terms,-                &term_ranks,-                &mut terms_buf,-                &mut post_spill,-            )?;-        }-        for (i, &sym) in rg_title_syms.iter().enumerate() {-            check_searchable(i as u32)?;-            let refv = (pack::KIND_RELEASE_GROUP << pack::KIND_SHIFT) | i as u32;-            let title = String::from_utf8_lossy(pool.get(sym)).into_owned();-            let credit = match rg_credit_syms[i] {-                SYM_EMPTY => String::new(),-                csym => String::from_utf8_lossy(pool.get(csym)).into_owned(),-            };-            emit_postings(-                &title,-                &credit,-                refv,-                &terms,-                &term_ranks,-                &mut terms_buf,-                &mut post_spill,-            )?;-        }-        if opts.include_recording_search {-            for (i, id) in rec_order.iter().enumerate() {-                check_searchable(i as u32)?;-                let refv = (pack::KIND_RECORDING << pack::KIND_SHIFT) | i as u32;-                let title =-                    String::from_utf8_lossy(pool.get(rec_title[*id as usize])).into_owned();-                let credit = match credit_sym_of(&credit_syms, rec_credit[*id as usize]) {-                    SYM_EMPTY => String::new(),-                    csym => String::from_utf8_lossy(pool.get(csym)).into_owned(),-                };-                emit_postings(-                    &title,-                    &credit,-                    refv,-                    &terms,-                    &term_ranks,-                    &mut terms_buf,-                    &mut post_spill,-                )?;-            }-        }-    }-    drop(term_ranks);-    drop(artist_name_syms);-    drop(rg_title_syms);-    drop(rg_credit_syms);-    drop(credit_syms);-    st.search_postings = post_spill.written / 8;-    let post_buckets = post_spill.finish()?;--    // The pack writer opens here rather than after the search index, so-    // SEARCH_POSTINGS can be STREAMED bucket by bucket instead of accumulating a-    // ~300 MB buffer while the string pool is still resident. Section order in the-    // file is irrelevant -- the directory carries absolute offsets.-    step!("pass 14: writing");-    // Captured before the sources are dropped further down.-    let rec_max_id = rec_present.len().saturating_sub(1) as u64;-    let rec_live = rec_present.iter().filter(|&&p| p).count() as u64;--    // SEARCH_TERMS, streamed straight out of the term pool in rank order.-    w.begin(pack::S_SEARCH_TERMS)?;-    let mut chunk: Vec<u8> = Vec::with_capacity(1 << 16);-    for &sym in &term_order {-        chunk.extend_from_slice(terms.get(sym));-        chunk.push(0);-        if chunk.len() >= (1 << 16) {-            w.write(&chunk)?;-            chunk.clear();-        }-    }-    w.write(&chunk)?;-    w.end()?;--    // SEARCH_POSTINGS, streamed; SEARCH_TERM_IDX accumulates the two offsets per-    // term as we go, which is only 8 bytes a term.-    let mut term_index: Vec<u8> = Vec::with_capacity((term_count + 1) * 8);-    let mut term_off = 0u32;-    let mut post_off = 0u32;-    let mut rank = 0u32;-    let mut spill_buf: Vec<u8> = Vec::new();-    w.begin(pack::S_SEARCH_POSTINGS)?;-    for (b, bucket) in post_buckets.iter().enumerate() {-        spill_buf.clear();-        File::open(bucket)?.read_to_end(&mut spill_buf)?;-        let mut pairs: Vec<(u32, u32)> = spill_buf-            .chunks_exact(8)-            .map(|c| {-                (-                    u32::from_le_bytes([c[0], c[1], c[2], c[3]]),-                    u32::from_le_bytes([c[4], c[5], c[6], c[7]]),-                )-            })-            .collect();-        pairs.sort_unstable();-        pairs.dedup();-        let bucket_end = post_spill.bucket_end(b);-        let mut out_bytes: Vec<u8> = Vec::new();-        let mut p = 0usize;-        while rank < bucket_end {-            term_index.extend_from_slice(&term_off.to_le_bytes());-            term_index.extend_from_slice(&post_off.to_le_bytes());-            term_off += terms.get(term_order[rank as usize]).len() as u32 + 1;-            let start = p;-            while p < pairs.len() && pairs[p].0 == rank {-                p += 1;-            }-            let before = out_bytes.len();-            pack::write_uvarint(&mut out_bytes, (p - start) as u64);-            let mut prev = 0u32;-            for &(_, refv) in &pairs[start..p] {-                pack::write_uvarint(&mut out_bytes, (refv - prev) as u64);-                prev = refv;-            }-            post_off += (out_bytes.len() - before) as u32;-            rank += 1;-        }-        w.write(&out_bytes)?;-    }-    w.end()?;-    term_index.extend_from_slice(&term_off.to_le_bytes());-    term_index.extend_from_slice(&post_off.to_le_bytes());-    w.section(pack::S_SEARCH_TERM_IDX, &term_index)?;-    drop(term_index);-    drop(post_spill);-    drop(spill_buf);-    drop(term_order);-    drop(terms);--    // --- assemble --------------------------------------------------------------    // Everything not already on disk. The entity vectors went out in pass 9b and-    // are gone; what remains is keyed off the recording clustering, which only-    // exists after the track pass.-    let media_count = media.len() as u32;-    let counts = HeaderCounts {-        artists: artist_count,-        credits: credit_count,-        release_groups: rg_count,-        releases: release_count,-        media: media_count,-        tracks: track_count,-        recordings: rec_order.len() as u32,-        isrcs: isrcs.len() as u32,-        search_terms: term_count as u32,-        enums: enum_count,-    };-    let mut buf: Vec<u8> = Vec::new();-    buf.clear();-    for m in &media {-        buf.extend_from_slice(&m.format.to_le_bytes());-        buf.extend_from_slice(&(m.track_count.min(u16::MAX as u32) as u16).to_le_bytes());-    }-    w.section(pack::S_MEDIA, &buf)?;-    drop(media);-    w.section_u32(pack::S_TRACK_IDX, &track_idx)?;-    drop(track_idx);-    if opts.include_track_mbids {-        w.section(pack::S_TRACK_MBID, &track_mbids)?;-    }-    drop(track_mbids);--    buf.clear();-    for id in &rec_order {-        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)?;-    buf.clear();-    buf.shrink_to_fit();-    // Dead from here: RECORDINGS was their only remaining consumer, and the search-    // index is already written.-    drop(rec_title);-    drop(rec_credit);-    drop(rec_dur);-    drop(rec_present);-    let recording_count = rec_order.len();-    drop(rec_order);-    if opts.include_recording_mbids {-        // Deliberately built HERE rather than earlier: this is a 638 MB buffer, and-        // running the pass at its natural place in the order would have kept it-        // resident alongside the search index. A second scan of `recording` is far-        // cheaper than that overlap -- and cheaper still than holding 16 B per-        // recording id (~760 MB) through the whole build, which is what scattering-        // into this buffer avoids.-        step!("pass 14b: recording MBIDs");-        let mut recording_mbids = vec![0u8; recording_count * 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(())-            },-        )?;-        w.section(pack::S_RECORDING_MBID, &recording_mbids)?;-    }-    w.section_u32(pack::S_REC_FIRST_RELEASE, &rec_first_release)?;-    drop(rec_first_release);-    drop(rec_new);--    if opts.include_isrcs {-        buf.clear();-        for (recording, packed) in &isrcs {-            buf.extend_from_slice(&recording.to_le_bytes());-            buf.extend_from_slice(packed);-        }-        w.section(pack::S_ISRCS, &buf)?;-    }-    let isrc_count = isrcs.len();-    let _ = isrc_count;-    drop(isrcs);-    buf.clear();-    buf.shrink_to_fit();--    // STRINGS goes last: it is only complete now, and streaming it here means the-    // sorted pool is never materialised as a second buffer.-    step!("pass 15: STRINGS ({} MB raw)", pool.raw_len() / 1_000_000);-    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()?;-    }--    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.dense_map_bytes =-        artist_idx.bytes() + rg_idx.bytes() + release_idx.bytes() + medium_idx.bytes();-    st.max_ids = vec![-        ("artist", artist_idx.max_id(), artist_idx.live()),-        ("artist_credit", credit_count.saturating_sub(1) as u64, credit_live),-        ("release_group", rg_idx.max_id(), rg_idx.live()),-        ("release", release_idx.max_id(), release_idx.live()),-        ("medium", medium_idx.max_id(), medium_idx.live()),-        ("recording", rec_max_id, rec_live),-    ];-    st.total_bytes = w.finish()?;-    Ok(st)-}--fn check_searchable(idx: u32) -> io::Result<()> {-    if idx > pack::MAX_SEARCHABLE_IDX {-        return Err(other_err(format!(-            "entity index {idx} exceeds the {} a search posting can address; the two kind \-             bits would silently corrupt it",-            pack::MAX_SEARCHABLE_IDX-        )));-    }-    Ok(())-}--/// `medium.position` and `track.position` are Postgres INTEGERs. Anything outside-/// that range is corrupt input, not a wider position.-fn clamp_position(v: Option<i64>) -> i32 {-    match v {-        Some(v) => v.clamp(i32::MIN as i64, i32::MAX as i64) as i32,-        None => 0,-    }-}--fn credit_idx_of(credit_id: u32, credit_count: u32) -> u32 {-    if credit_id == pack::NONE || credit_id >= credit_count {-        pack::NONE-    } else {-        credit_id-    }-}--/// MusicBrainz stores lengths in milliseconds; the pack stores seconds because-/// the UI renders m:ss, Tidal matching uses a ±3 s tolerance and LRCLIB takes-/// seconds. Clamped rather than wrapped: an 18-hour recording is rare but real.-fn ms_to_secs(ms: Option<i64>) -> u16 {-    match ms {-        Some(ms) if ms > 0 => (ms.saturating_add(500) / 1000).min(u16::MAX as i64) as u16,-        _ => 0,-    }-}--fn to_csr(pairs: &[(u32, u32)], parents: usize) -> (Vec<u32>, Vec<u32>) {-    let mut idx = vec![0u32; parents + 1];-    for &(p, _) in pairs {-        idx[p as usize + 1] += 1;-    }-    for i in 0..parents {-        idx[i + 1] += idx[i];-    }-    (pairs.iter().map(|&(_, c)| c).collect(), idx)-}--fn read_enum_table(-    source: &dyn TableSource,-    table: &'static str,-    pool: &mut StringPool,-    enums: &mut EnumPool,-) -> io::Result<HashMap<u32, u16>> {-    let mut out = HashMap::new();-    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)));-        }-        Ok(())-    })?;-    Ok(out)-}--/// Read a table that must be present, checking its shape on the first row.-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;-    each_row(reader, |row| {-        if first {-            shape.check(row)?;-            first = false;-        }-        f(row)-    })-}--#[cfg(test)]-mod tests {-    use super::*;--    #[test]-    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]-    fn positions_clamp_instead_of_wrapping() {-        assert_eq!(clamp_position(None), 0);-        assert_eq!(clamp_position(Some(0)), 0);-        assert_eq!(clamp_position(Some(-1)), -1);-        assert_eq!(clamp_position(Some(i64::MAX)), i32::MAX);-        assert_eq!(clamp_position(Some(i64::MIN)), i32::MIN);-    }--    #[test]-    fn ms_round_to_nearest_second_and_clamp() {-        assert_eq!(ms_to_secs(None), 0);-        assert_eq!(ms_to_secs(Some(0)), 0);-        assert_eq!(ms_to_secs(Some(499)), 0);-        assert_eq!(ms_to_secs(Some(500)), 1);-        assert_eq!(ms_to_secs(Some(67_000)), 67);-        assert_eq!(ms_to_secs(Some(i64::MAX)), u16::MAX, "an 18-hour recording clamps");-    }--    #[test]-    fn csr_is_a_prefix_sum() {-        let (vals, idx) = to_csr(&[(0, 7), (0, 8), (2, 9)], 3);-        assert_eq!(vals, [7, 8, 9]);-        assert_eq!(idx, [0, 2, 2, 3]);-    }--    #[test]-    fn dense_map_rejects_absurd_keys() {-        let mut m = DenseMap::new();-        m.set(5, 1).unwrap();-        assert_eq!(m.get(5), Some(1));-        assert_eq!(m.get(4), None);-        assert_eq!(m.get(9_999), None);-        assert!(m.set(MAX_ID + 1, 0).is_err());-    }--    #[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 posting_buckets_and_ends_are_exact_inverses() {-        // If `bucket_of` and `bucket_end` disagree by even one rank, the emit loop-        // either skips a term's postings or attributes them to the wrong term.-        for terms in [1u32, 2, 63, 64, 65, 100_000, 4_332_477] {-            let s = PostingSpill::new(None, terms).unwrap();-            let mut expected = 0u32;-            for b in 0..s.buckets {-                let end = s.bucket_end(b);-                assert!(end >= expected, "bucket ends must not go backwards");-                for rank in expected..end {-                    assert_eq!(-                        s.bucket_of(rank),-                        b,-                        "terms={terms} rank={rank} belongs in bucket {b}"-                    );-                }-                expected = end;-            }-            assert_eq!(expected, terms, "buckets must cover every rank exactly once");-        }-    }--    #[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.rsdeleted file mode 100644index 83ad312ef0..0000000000--- a/scripts/musicbrainz/mb_ingest/src/copy.rs+++ /dev/null@@ -1,446 +0,0 @@-//! Read the tables of a MusicBrainz full export.-//!-//! The tables in `mbdump.tar.bz2` are PostgreSQL `COPY ... TO` output in the-//! default TEXT format: one row per line, columns separated by TAB, `\N` for-//! NULL, and backslash escapes (`\\`, `\t`, `\n`, `\r`, `\b`, `\f`, `\v`) for the-//! characters that would otherwise break the framing. Real MusicBrainz titles do-//! contain tabs and newlines, so unescaping is not optional.-//!-//! Verified against the live export rather than assumed:-//!   * the archive member names in `mbdump.tar.bz2` are `mbdump/<table>` with no-//!     schema prefix (`mbdump/area`, `mbdump/artist`, ...), in ASCII order, after-//!     the leading `TIMESTAMP`, `COPYING`, `README`, `REPLICATION_SEQUENCE` and-//!     `SCHEMA_SEQUENCE` members. The non-`musicbrainz`-schema dumps use-//!     `mbdump/<schema>.<table>` instead (confirmed on-//!     `mbdump-documentation.tar.bz2`), so both spellings are accepted.-//!   * `TIMESTAMP` holds e.g. `2026-08-19 00:25:41.835127+00`.-//!-//! Two input shapes are supported. A directory is the fast path for repeated-//! builds and the only one the tests use. A `.tar.bz2` is streamed through the-//! system `tar`, so a full build never materialises the ~40 GB of extracted-//! tables; the cost is one decompression pass per table read.--use std::borrow::Cow;-use std::fs::File;-use std::io::{self, BufRead, BufReader, Read};-use std::path::{Path, PathBuf};-use std::process::{Child, Command, Stdio};--/// One row of a COPY dump, borrowing the line buffer.-pub struct Row<'a> {-    line: &'a [u8],-    fields: &'a [(u32, u32)],-}--impl<'a> Row<'a> {-    pub fn len(&self) -> usize {-        self.fields.len()-    }--    pub fn is_empty(&self) -> bool {-        self.fields.is_empty()-    }--    pub fn raw(&self, i: usize) -> &'a [u8] {-        match self.fields.get(i) {-            Some(&(a, b)) => &self.line[a as usize..b as usize],-            None => &[],-        }-    }--    pub fn is_null(&self, i: usize) -> bool {-        self.raw(i) == b"\\N"-    }--    /// The field with COPY escapes resolved. NULL reads as `""`; callers that-    /// care about the difference ask `is_null` first.-    pub fn str(&self, i: usize) -> Cow<'a, str> {-        let raw = self.raw(i);-        if raw == b"\\N" {-            return Cow::Borrowed("");-        }-        if !raw.contains(&b'\\') {-            return String::from_utf8_lossy(raw);-        }-        let mut out = Vec::with_capacity(raw.len());-        let mut it = raw.iter().copied();-        while let Some(b) = it.next() {-            if b != b'\\' {-                out.push(b);-                continue;-            }-            match it.next() {-                Some(b'n') => out.push(b'\n'),-                Some(b't') => out.push(b'\t'),-                Some(b'r') => out.push(b'\r'),-                Some(b'b') => out.push(8),-                Some(b'f') => out.push(12),-                Some(b'v') => out.push(11),-                Some(b'\\') => out.push(b'\\'),-                Some(other) => {-                    out.push(b'\\');-                    out.push(other);-                }-                None => out.push(b'\\'),-            }-        }-        Cow::Owned(String::from_utf8_lossy(&out).into_owned())-    }--    pub fn i64(&self, i: usize) -> Option<i64> {-        let raw = self.raw(i);-        if raw.is_empty() || raw == b"\\N" {-            return None;-        }-        let (neg, digits) = match raw[0] {-            b'-' => (true, &raw[1..]),-            _ => (false, raw),-        };-        if digits.is_empty() {-            return None;-        }-        let mut v: i64 = 0;-        for &c in digits {-            if !c.is_ascii_digit() {-                return None;-            }-            v = v.checked_mul(10)?.checked_add((c - b'0') as i64)?;-        }-        Some(if neg { -v } else { v })-    }--    pub fn u32(&self, i: usize) -> Option<u32> {-        match self.i64(i) {-            Some(v) if (0..=u32::MAX as i64).contains(&v) => Some(v as u32),-            _ => None,-        }-    }--    /// Does the field look like a bare (unhyphenated or hyphenated) UUID?-    pub fn looks_like_uuid(&self, i: usize) -> bool {-        let raw = self.raw(i);-        let hex = raw.iter().filter(|c| c.is_ascii_hexdigit()).count();-        let dashes = raw.iter().filter(|&&c| c == b'-').count();-        hex == 32 && hex + dashes == raw.len()-    }-}--/// A table's byte stream plus, for the archive path, the `tar` process feeding it.-type TableStream = (Box<dyn Read + 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).-    Dir(PathBuf),-    /// An `mbdump*.tar.bz2`, streamed through the system `tar`.-    Archive(PathBuf),-}--impl Input {-    /// Classify by extension so the CLI takes either without a flag.-    pub fn detect(path: &Path) -> Input {-        let s = path.to_string_lossy().to_ascii_lowercase();-        if s.ends_with(".tar.bz2") || s.ends_with(".tbz2") || s.ends_with(".tar") {-            Input::Archive(path.to_path_buf())-        } else {-            Input::Dir(path.to_path_buf())-        }-    }--    pub fn describe(&self) -> String {-        match self {-            Input::Dir(p) => format!("directory {}", p.display()),-            Input::Archive(p) => format!("archive {}", p.display()),-        }-    }--    /// The dump's `TIMESTAMP` as `YYYYMMDD`, or 0 when it is not readable.-    pub fn dump_date(&self) -> u32 {-        let text = match self {-            Input::Dir(p) => {-                std::fs::read_to_string(p.join("TIMESTAMP")).ok()-            }-            Input::Archive(p) => {-                let out = Command::new("tar").arg("-xOf").arg(p).arg("TIMESTAMP").output().ok();-                out.and_then(|o| String::from_utf8(o.stdout).ok())-            }-        };-        let text = match text {-            Some(t) => t,-            None => return 0,-        };-        let d: Vec<u8> = text.bytes().filter(|c| c.is_ascii_digit()).take(8).collect();-        if d.len() < 8 {-            return 0;-        }-        std::str::from_utf8(&d).ok().and_then(|s| s.parse().ok()).unwrap_or(0)-    }--    fn open_reader(&self, table: &str) -> io::Result<Option<TableStream>> {-        match self {-            Input::Dir(dir) => {-                for cand in [dir.join("mbdump").join(table), dir.join(table)] {-                    if cand.is_file() {-                        return Ok(Some((Box::new(File::open(cand)?), None)));-                    }-                }-                Ok(None)-            }-            Input::Archive(path) => {-                // `tar` picks the decompressor from the magic bytes, so this works for-                // .tar, .tar.bz2 and .tar.gz alike, and streams: nothing is written to-                // disk. bsdtar (Windows) and GNU tar both support it.-                let member = format!("mbdump/{table}");-                let mut child = Command::new("tar")-                    .arg("-xOf")-                    .arg(path)-                    .arg(&member)-                    .stdout(Stdio::piped())-                    .stderr(Stdio::null())-                    .spawn()-                    .map_err(|e| {-                        io::Error::new(-                            e.kind(),-                            format!(-                                "could not run `tar` to stream {member} out of {}: {e}. \-                                 Archive input needs tar on PATH; pass an extracted \-                                 directory instead.",-                                path.display()-                            ),-                        )-                    })?;-                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))))-            }-        }-    }-}---/// 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;-        }-        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;-    }-    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();-        }-    }-}--/// A table's expected shape, checked on the first row.-///-/// The column order of a COPY dump is the table's physical column order, which-/// this crate hard-codes from `admin/sql/CreateTables.sql`. If MusicBrainz ever-/// reorders or inserts a column, silently reading the wrong field would produce a-/// plausible-looking but wrong pack, so every table asserts its arity and spot-/// checks the columns whose types are distinctive.-pub struct Shape {-    pub table: &'static str,-    pub min_fields: usize,-    /// Column indices that must parse as integers.-    pub ints: &'static [usize],-    /// Column indices that must look like UUIDs.-    pub uuids: &'static [usize],-}--impl Shape {-    pub fn check(&self, row: &Row<'_>) -> io::Result<()> {-        if row.len() < self.min_fields {-            return Err(other_err(format!(-                "table `{}`: expected at least {} columns, found {}. The dump's schema \-                 does not match what this build was written against; check \-                 SCHEMA_SEQUENCE and admin/sql/CreateTables.sql before trusting any pack.",-                self.table,-                self.min_fields,-                row.len()-            )));-        }-        for &i in self.ints {-            if !row.is_null(i) && row.i64(i).is_none() {-                return Err(other_err(format!(-                    "table `{}`: column {i} should be an integer but is {:?}. Column order \-                     has almost certainly changed upstream.",-                    self.table,-                    String::from_utf8_lossy(row.raw(i))-                )));-            }-        }-        for &i in self.uuids {-            if !row.looks_like_uuid(i) {-                return Err(other_err(format!(-                    "table `{}`: column {i} should be a UUID but is {:?}. Column order has \-                     almost certainly changed upstream.",-                    self.table,-                    String::from_utf8_lossy(row.raw(i))-                )));-            }-        }-        Ok(())-    }-}--pub fn other_err(msg: String) -> io::Error {-    io::Error::new(io::ErrorKind::InvalidData, msg)-}--#[cfg(test)]-mod tests {-    use super::*;--    fn row_of(line: &str) -> (Vec<u8>, Vec<(u32, u32)>) {-        let bytes = line.as_bytes().to_vec();-        let mut fields = Vec::new();-        let mut start = 0u32;-        for (i, &c) in bytes.iter().enumerate() {-            if c == b'\t' {-                fields.push((start, i as u32));-                start = i as u32 + 1;-            }-        }-        fields.push((start, bytes.len() as u32));-        (bytes, fields)-    }--    #[test]-    fn parses_copy_text_format() {-        let (line, fields) = row_of("42\tPink Floyd\t\\N\t\\N\t1965\t");-        let r = Row { line: &line, fields: &fields };-        assert_eq!(r.len(), 6);-        assert_eq!(r.u32(0), Some(42));-        assert_eq!(&*r.str(1), "Pink Floyd");-        assert!(r.is_null(2));-        assert_eq!(&*r.str(2), "");-        assert_eq!(r.i64(2), None);-        assert_eq!(r.u32(4), Some(1965));-        assert_eq!(&*r.str(5), "", "trailing empty field is an empty string, not NULL");-        assert!(!r.is_null(5));-    }--    #[test]-    fn unescapes_titles_that_would_break_framing() {-        let (line, fields) = row_of("1\tA\\tB\\nC\\\\D\t2");-        let r = Row { line: &line, fields: &fields };-        assert_eq!(&*r.str(1), "A\tB\nC\\D");-        assert_eq!(r.u32(2), Some(2));-    }--    #[test]-    fn rejects_bad_integers_and_detects_uuids() {-        let (line, fields) = row_of("x\tf27ec8db-af05-4f36-916e-3d57f91ecf5e\tnope");-        let r = Row { line: &line, fields: &fields };-        assert_eq!(r.i64(0), None);-        assert!(r.looks_like_uuid(1));-        assert!(!r.looks_like_uuid(2));-        let shape = Shape { table: "t", min_fields: 3, ints: &[0], uuids: &[1] };-        assert!(shape.check(&r).is_err(), "a non-integer id must be caught, not ignored");-        let shape = Shape { table: "t", min_fields: 4, ints: &[], uuids: &[] };-        assert!(shape.check(&r).is_err(), "too few columns must be caught");-    }-}
scripts/musicbrainz/mb_ingest/src/fixture.rs
diff --git a/scripts/musicbrainz/mb_ingest/src/fixture.rs b/scripts/musicbrainz/mb_ingest/src/fixture.rsdeleted file mode 100644index 715c7d07a5..0000000000--- a/scripts/musicbrainz/mb_ingest/src/fixture.rs+++ /dev/null@@ -1,266 +0,0 @@-//! A small synthetic mbdump, in the exact shape of the real one.-//!-//! Column counts and orders match `admin/sql/CreateTables.sql` for schema-//! sequence 31 exactly, so the ingest passes exercised here are the same code-//! paths a 7 GB run takes. The fixture deliberately includes the awkward cases:-//! NULL columns (`\N`), a title containing an escaped tab and newline, accented-//! text (search folding), a track whose title differs from its recording's, a-//! track whose credit differs, a pregap track at position 0, a track whose length-//! differs from its recording's, a multi-medium release, recordings reused across-//! releases (so `d_recording` is not always 1), a standalone recording with no-//! track, a release with no status, a release group with a secondary type, and a-//! malformed ISRC that must be rejected rather than stored.-//!-//! There is deliberately **no `release_group_meta`**: that table is not in the-//! core dump, so first-release dates are derived from release dates. The fixture-//! therefore also exercises that derivation, including a release group whose only-//! release has no date at all.--use std::fs;-use std::io::{self, Write};-use std::path::Path;--fn table(dir: &Path, name: &str, rows: &[&[&str]]) -> io::Result<()> {-    let mut f = fs::File::create(dir.join(name))?;-    for row in rows {-        f.write_all(row.join("\t").as_bytes())?;-        f.write_all(b"\n")?;-    }-    Ok(())-}--/// Artist / release-group / release / recording MBIDs the round-trip test asserts-/// against. Chosen so the MBID sort order is the obvious one.-pub const ARTIST_PINK_FLOYD: &str = "11111111-1111-1111-1111-111111111111";-pub const ARTIST_BJORK: &str = "22222222-2222-2222-2222-222222222222";-pub const ARTIST_VARIOUS: &str = "33333333-3333-3333-3333-333333333333";-pub const RG_DARK_SIDE: &str = "a1000000-0000-0000-0000-000000000001";-pub const RG_HOMOGENIC: &str = "a2000000-0000-0000-0000-000000000002";-pub const RG_ECHOES: &str = "a3000000-0000-0000-0000-000000000003";-pub const RG_WEIRD: &str = "a4000000-0000-0000-0000-000000000004";-pub const REL_DARK_SIDE: &str = "b1000000-0000-0000-0000-000000000001";-pub const REL_DARK_SIDE_BOOT: &str = "b2000000-0000-0000-0000-000000000002";-pub const REL_HOMOGENIC: &str = "b3000000-0000-0000-0000-000000000003";-pub const REL_ECHOES: &str = "b4000000-0000-0000-0000-000000000004";-pub const REL_WEIRD: &str = "b5000000-0000-0000-0000-000000000005";-pub const REC_SPEAK_TO_ME: &str = "c1000000-0000-0000-0000-000000000001";-pub const REC_BREATHE: &str = "c2000000-0000-0000-0000-000000000002";-pub const REC_TIME: &str = "c3000000-0000-0000-0000-000000000003";-pub const REC_JOGA: &str = "c4000000-0000-0000-0000-000000000004";-pub const REC_BACHELORETTE: &str = "c5000000-0000-0000-0000-000000000005";-pub const REC_WISH: &str = "c6000000-0000-0000-0000-000000000006";-pub const REC_STANDALONE: &str = "c7000000-0000-0000-0000-000000000007";--/// The title that carries escaped control characters. The dump spells it-/// `Untitled\tWeird\nTitle`; the reader must hand back the real characters.-pub const WEIRD_TITLE: &str = "Untitled\tWeird\nTitle";--const N: &str = "\\N";-const T: &str = "t";-const F: &str = "f";-const TS: &str = "2026-08-19 00:00:00+00";--pub fn write_fixture(dir: &Path) -> io::Result<()> {-    fs::create_dir_all(dir)?;-    fs::write(dir.join("TIMESTAMP"), "2026-08-19 00:25:41.835127+00\n")?;-    fs::write(dir.join("SCHEMA_SEQUENCE"), "31\n")?;--    // area: id, gid, name, type, edits_pending, last_updated, begin y/m/d,-    //       end y/m/d, ended, comment-    table(-        dir,-        "area",-        &[-            &["1", "e0000000-0000-0000-0000-000000000001", "United Kingdom", "1", "0", TS, N, N, N, N, N, N, F, ""],-            &["2", "e0000000-0000-0000-0000-000000000002", "United States", "1", "0", TS, N, N, N, N, N, N, F, ""],-            &["3", "e0000000-0000-0000-0000-000000000003", "Berlin", "3", "0", TS, N, N, N, N, N, N, F, ""],-        ],-    )?;-    // iso_3166_1: area, code-    table(dir, "iso_3166_1", &[&["1", "GB"], &["2", "US"]])?;--    // <enum>: id, name, parent, child_order, description, gid-    let enum_row = |id: &'static str, name: &'static str| -> Vec<&'static str> {-        vec![id, name,

Diff truncated.