maps: run real-archive and live tests on a synthetic fixture (#tests)
- Commit
17c3a505c876662ebdefc049fa7bffff48e9929f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-15 17:18 UTC (20 days ago)
- Parents
740f2df
Eight tests skipped in CI: PoiArchiveRealFileTest (6) needed a 50-80 GB planet .mamaps via MAMAPS_REAL_ARCHIVE, PoiPlanetParityTest needed two of them, and MapOverlayLiveTest needed network to data.maproj.org. OfflineRouter Slice3 tests (5) also Assume-guarded the native lib. New PoiSyntheticArchive builds a small .mamaps in the exact section formats the production readers validate (index/names, attrs with rating+review count+summary, CSR spatial grid, word index, region links, admin hierarchy: kinds 8-12, 15, 16) with six bay-area records. PoiArchiveRealFileTest and PoiPlanetParityTest now run their reader assertions (sections, nearest/viewport, name search incl. type-51 place labels, attributes, boundary links, locality) against it by default, and keep the original planet-scale assertions when the env vars name real archives. Parity compares raw vs DEFLATE-ZSEC block-compressed attrs/region - the planet5 format change it exists to pin. MapOverlayLiveTest parses a captured copy of the published planet5 manifest (same build id/length/empty overlay stack) and only fetches the live file under MAMAPS_LIVE=1. OfflineRouter guards now assert the cargoBuildHost-produced libofflinerouter, like vpn. Verified: :maps:testDevUnitTest / createMergedCoverageReport green, 1062 tests, 0 skipped (was 8 skipped locally, 13 guarded in total).
Diff
maps/src/test/java/com/vayunmathur/maps/util/MapOverlayLiveTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayLiveTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayLiveTest.ktindex 3b88501b43..6561ae95a9 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayLiveTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayLiveTest.kt@@ -5,21 +5,29 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue-import org.junit.Assume /**- * The LIVE `planet5.manifest.json` through [MapOverlay.parse], checked against what the app- * downloads ([MapTileCache.BASEMAP_ARCHIVE_URL]) and what a planet4 install will do with it.- * Skipped unless `MAMAPS_LIVE=1` (network to data.maproj.org).+ * The `planet5.manifest.json` shape through [MapOverlay.parse], checked+ * against what the app downloads ([MapTileCache.BASEMAP_ARCHIVE_URL]) and+ * what a planet4 install will do with it.+ *+ * By default this parses a captured copy of the published manifest (same+ * build id, length and empty overlay stack), so it runs hermetically in CI+ * instead of skipping. With `MAMAPS_LIVE=1` it additionally fetches the+ * live manifest and requires it to still match the pinned planet5 build. */ class MapOverlayLiveTest { @Test fun `live planet5 manifest parses and pins the archive the app downloads`() {- Assume.assumeTrue("MAMAPS_LIVE not set; live test skipped", System.getenv("MAMAPS_LIVE") == "1")- val text = URI(MapOverlay.MANIFEST_URL).toURL().readText()- println("live manifest (${text.length} B): $text")- val m = assertNotNull(MapOverlay.parse(text), "the client refuses the live manifest")+ val live = System.getenv("MAMAPS_LIVE") == "1"+ val text = if (live) {+ URI(MapOverlay.MANIFEST_URL).toURL().readText()+ } else {+ CAPTURED_MANIFEST+ }+ println("manifest (${text.length} B): $text")+ val m = assertNotNull(MapOverlay.parse(text), "the client refuses the planet5 manifest") assertEquals(MapTileCache.BASEMAP_MANIFEST_URL, MapOverlay.MANIFEST_URL) assertEquals(MapTileCache.BASEMAP_ARCHIVE_URL, m.baseUrl) assertEquals(PLANET5_BUILD_ID, m.baseBuildId)@@ -37,5 +45,20 @@ class MapOverlayLiveTest { // a5ba63230: header v11 superblocks, v12 bodies, graph v9). Replaces the 63 GB build. const val PLANET5_BUILD_ID = -0x768935f835da84c7L // 0x8976ca07ca257b39 as a signed Long const val PLANET5_LEN = 49_990_890_888L++ /** Captured shape of the published manifest (build id as unsigned hex, as served). */+ const val CAPTURED_MANIFEST = """+ {+ "version": 1, "min_client": 1, "overlay_seq": 0,+ "overlay_build_id": "0x8976ca07ca257b39",+ "base": {+ "url": "https://data.maproj.org/planet5.mamaps",+ "build_id": "0x8976ca07ca257b39",+ "len": 49990890888+ },+ "segments": [],+ "tombstones": []+ }+ """ } }
maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterSlice3ExtraTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterSlice3ExtraTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterSlice3ExtraTest.ktindex cc2b2854e2..14a2c81543 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterSlice3ExtraTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterSlice3ExtraTest.kt@@ -8,7 +8,6 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking-import org.junit.Assume import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config@@ -27,7 +26,7 @@ class OfflineRouterSlice3ExtraTest { } catch (_: Throwable) { false } @Test fun getRouteWithoutGraphThrowsNoRoute() { runBlocking {- Assume.assumeTrue("host offlinerouter lib unavailable", nativeAvailable())+ assertTrue(nativeAvailable(), "host offlinerouter lib unavailable: cargoBuildHost must produce libofflinerouter for JVM tests") OfflineRouterLifecycle.isInitialized = false // No archive was ever downloaded in the sandbox: native finds no route // and getRoute surfaces that as IllegalStateException, which routing@@ -39,7 +38,7 @@ class OfflineRouterSlice3ExtraTest { } } @Test fun trafficNativeSurfaceWithoutGraph() {- Assume.assumeTrue("host offlinerouter lib unavailable", nativeAvailable())+ assertTrue(nativeAvailable(), "host offlinerouter lib unavailable: cargoBuildHost must produce libofflinerouter for JVM tests") // Tile queries against an uninitialized graph answer deterministically // (null or an empty tile - either is a valid no-data answer, never a throw) val tile1 = OfflineRouter.getTrafficTileNative(14, 2600, 6500)@@ -57,7 +56,7 @@ class OfflineRouterSlice3ExtraTest { } @Test fun lifecycleInitializeAndReload() { runBlocking {- Assume.assumeTrue("host offlinerouter lib unavailable", nativeAvailable())+ assertTrue(nativeAvailable(), "host offlinerouter lib unavailable: cargoBuildHost must produce libofflinerouter for JVM tests") OfflineRouterLifecycle.isInitialized = false val base = OfflineRouterLifecycle.transitBase(ctx) // Sandbox external dir exists; graph init against it simply reports false
maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterTransitSlice3ExtraTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterTransitSlice3ExtraTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterTransitSlice3ExtraTest.ktindex 4753bdebd9..b8e608f5c9 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterTransitSlice3ExtraTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/OfflineRouterTransitSlice3ExtraTest.kt@@ -10,7 +10,6 @@ import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking-import org.junit.Assume import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config@@ -44,7 +43,7 @@ class OfflineRouterTransitSlice3ExtraTest { } @Test fun noPackEntryPointsDegrade() { runBlocking {- Assume.assumeTrue("host offlinerouter lib unavailable", nativeAvailable())+ assertTrue(nativeAvailable(), "host offlinerouter lib unavailable: cargoBuildHost must produce libofflinerouter for JVM tests") // Force re-init against the sandbox external dir (no packs were ever downloaded) OfflineRouterLifecycle.isInitialized = false OfflineRouterTransit.onReload()@@ -61,7 +60,7 @@ class OfflineRouterTransitSlice3ExtraTest { } } @Test fun fakeFeedFileDegradesThroughNative() { runBlocking {- Assume.assumeTrue("host offlinerouter lib unavailable", nativeAvailable())+ assertTrue(nativeAvailable(), "host offlinerouter lib unavailable: cargoBuildHost must produce libofflinerouter for JVM tests") val base = OfflineRouterLifecycle.transitBase(ctx) assertNotNull(base) // A zero-byte sidecar pack makes transitFeeds report this feed; every native
maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveRealFileTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveRealFileTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveRealFileTest.ktindex 73f013db75..a7ff0b29e0 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveRealFileTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveRealFileTest.kt@@ -5,69 +5,91 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue-import org.junit.Assume /**- * The app's POI reader against a REAL planet archive (`planet4.mamaps` or its- * byte-identical local build). Skipped unless `MAMAPS_REAL_ARCHIVE` names the- * file, so CI and normal unit-test runs never need the 80 GB input:+ * The app's POI reader against a real `.mamaps` archive, through exactly the+ * production entry point ([PoiIndex.reloadArchive] -> [PoiArchive]): every+ * POI section the app reads — index + names (kinds 8/9), attributes incl.+ * rating / review count / summary (10), the spatial grid (11), the word+ * index (12), the boundary links (15) and the admin hierarchy (16).+ *+ * By default the archive is the small synthetic fixture+ * ([PoiSyntheticArchive]: the same section formats, a handful of bay-area+ * records), so the test runs hermetically in CI instead of skipping. When+ * `MAMAPS_REAL_ARCHIVE` names a planet archive the same test methods run+ * their original planet-scale assertions against it: * * ``` * MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps ./gradlew :maps:testDevUnitTest \ * --tests '*PoiArchiveRealFileTest*' * ```- *- * It goes through exactly the production entry point ([PoiIndex.reloadArchive]- * -> [PoiArchive]) and checks every POI section the app reads: index + names- * (kinds 8/9), attributes incl. rating / review count / summary (10), the- * spatial grid (11), the word index (12) and the boundary links (15). */ class PoiArchiveRealFileTest { - private fun archive(): File {- val path = System.getenv(ENV)- Assume.assumeTrue("$ENV not set; real-archive test skipped", !path.isNullOrBlank())- val file = File(path!!)- Assume.assumeTrue("$ENV=$path does not exist", file.isFile)- return file+ private var temp: File? = null++ private fun planetFile(): File? {+ val path = System.getenv(ENV)?.takeIf { it.isNotBlank() } ?: return null+ return File(path).takeIf { it.isFile } } private fun load(): PoiIndex.Mapped {- val file = archive()+ val planet = planetFile()+ val file = planet ?: PoiSyntheticArchive.write().also { temp = it.parentFile } assertTrue(PoiIndex.reloadArchive(file), "the app could not map POI sections from $file") return assertNotNull(PoiIndex.mappedForQuery()) } + private val isPlanet: Boolean get() = planetFile() != null+ @Test fun `every POI section maps and agrees on the record count`() { val m = load() println("POI records=${m.count} names=${m.namesLen}B cells=${m.cellCount} words=${m.entryCount}")- assertTrue(m.count > MIN_PLANET_RECORDS, "only ${m.count} records: not a planet index")+ if (isPlanet) {+ assertTrue(m.count > MIN_PLANET_RECORDS, "only ${m.count} records: not a planet index")+ } else {+ assertEquals(PoiSyntheticArchive.RECORDS.size, m.count)+ } assertNotNull(m.attrs, "attrs section (kind 10) refused") assertNotNull(m.spatial, "spatial section (kind 11) refused") assertTrue(m.cellCount > 0) assertNotNull(m.nameIdx, "word index (kind 12) refused") assertTrue(m.entryCount > m.count, "word index should hold >1 word per record on average") assertNotNull(m.region, "region section (kind 15) refused")+ assertNotNull(m.admin, "admin section (kind 16) refused") } @Test fun `nearest and viewport queries answer in four cities`() { load()- for ((city, lat, lon) in CITIES) {+ val places = if (isPlanet) {+ CITIES+ } else {+ PoiSyntheticArchive.RECORDS.take(4).map { Triple(it.name, it.lat, it.lon) }+ }+ for ((city, lat, lon) in places) { val near = PoiIndex.nearest(lat, lon, limit = 20, maxMeters = 500.0) val box = PoiIndex.inViewport(lon - 0.01, lat - 0.01, lon + 0.01, lat + 0.01) println("$city nearest=${near.size} first=${near.firstOrNull()?.name} viewport=${box.size}") assertTrue(near.isNotEmpty(), "$city: no POI within 500 m") assertTrue(box.isNotEmpty(), "$city: empty viewport") assertTrue(near.all { it.name.isNotEmpty() }, "$city: a nearest hit has no name")+ if (!isPlanet) {+ assertEquals(city, near.first().name, "$city: nearest hit is not the record at that point")+ } } } @Test fun `name search finds landmarks and the new type-51 place labels`() { load()- for ((query, lat, lon) in LANDMARKS) {+ val landmarks = if (isPlanet) LANDMARKS else listOf(+ Triple("Golden Gate Bridge", 37.8199, -122.4783),+ Triple("Tartine Bakery", 37.7614, -122.4241),+ Triple("Golden Gate Park", 37.7694, -122.4862),+ )+ for ((query, lat, lon) in landmarks) { val hits = PoiIndex.searchByName(query, lat, lon, limit = 10) println("search '$query' -> ${hits.take(3).map { "${it.name}(${it.type})" }}") assertTrue(hits.isNotEmpty(), "no hit for '$query'")@@ -75,7 +97,8 @@ class PoiArchiveRealFileTest { assertTrue(d < NEAR_DEG_SQ, "top hit for '$query' is far away: ${hits[0]}") } // Place labels became searchable records (type 51) in planet4.- for ((query, lat, lon) in PLACES) {+ val places = if (isPlanet) PLACES else listOf(Triple("Oakland", 37.8044, -122.2712))+ for ((query, lat, lon) in places) { val hits = PoiIndex.searchByName(query, lat, lon, limit = 20) val place = hits.firstOrNull { it.type == TYPE_PLACE && it.name.equals(query, ignoreCase = true) } println("place '$query' -> $place")@@ -85,6 +108,10 @@ class PoiArchiveRealFileTest { // Tagged OSM id: low 2 bits are the id space (2 = way, 3 = relation). assertTrue((place.regionId and SPACE_MASK) in 2L..3L, "bad tagged id ${place.regionId}") }+ if (!isPlanet) {+ // The admin hierarchy gives every fixture record its locality line.+ assertEquals("Paris, France", PoiIndex.localityAt(0, english = true))+ } } @Test@@ -120,6 +147,12 @@ class PoiArchiveRealFileTest { assertTrue(rated > 0, "no rating (KEY_RATING) decoded") assertTrue(counted > 0, "no review count (KEY_REVIEW_COUNT) decoded") assertTrue(summarised > 0, "no review summary (KEY_REVIEW_SUMMARY) decoded")+ if (!isPlanet) {+ val tartine = PoiIndex.attributesAt(1)+ assertEquals(4.6, tartine?.rating)+ assertEquals(157, tartine?.reviewCount)+ assertTrue(tartine?.reviewSummary?.contains("Tartine Bakery") == true)+ } } @Test@@ -127,7 +160,12 @@ class PoiArchiveRealFileTest { load() var rated = 0 var summarised = 0- for ((query, lat, lon) in FAMOUS) {+ val famous = if (isPlanet) FAMOUS else listOf(+ Triple("Tartine Bakery", 37.7614, -122.4241),+ Triple("Golden Gate Park", 37.7694, -122.4862),+ Triple("Golden Gate Bridge", 37.8199, -122.4783),+ )+ for ((query, lat, lon) in famous) { val hit = PoiIndex.searchByName(query, lat, lon, limit = 5).firstOrNull() val attrs = hit?.let { PoiIndex.attributesAt(it.ordinal) } println(@@ -139,7 +177,7 @@ class PoiArchiveRealFileTest { } // Coverage depends on the review table (reviews_archive.tsv); decoding is what is // pinned here, so a couple of fully reviewed landmarks are enough.- assertTrue(rated >= 2, "only $rated of ${FAMOUS.size} famous places carry an archive rating")+ assertTrue(rated >= 2, "only $rated of ${famous.size} famous places carry an archive rating") assertTrue(summarised >= 1, "no famous place carries rating + count + summary") } @@ -157,6 +195,7 @@ class PoiArchiveRealFileTest { } println("region links $linked/$sampled sampled") assertTrue(linked * 2 > sampled, "fewer than half the sampled POIs link to a boundary")+ if (!isPlanet) assertEquals(sampled, linked, "every fixture record links to Paris") } private companion object {
maps/src/test/java/com/vayunmathur/maps/util/PoiPlanetParityTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiPlanetParityTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiPlanetParityTest.ktindex 33104ae56a..75ab22e2d9 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiPlanetParityTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiPlanetParityTest.kt@@ -5,34 +5,31 @@ import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue-import org.junit.Assume /**- * planet5 POI parity and speed on REAL archives: the same queries through the production- * reader ([PoiIndex.reloadArchive] -> [PoiArchive]) against a baseline archive and a- * candidate, which must answer identically -- search hits, nearest/viewport hits, boundary- * links, the "City, State, Country" locality line and place attributes -- and the time each- * query path takes on both.+ * POI parity: the same queries through the production reader+ * ([PoiIndex.reloadArchive] -> [PoiArchive]) against a baseline archive and+ * a candidate must answer identically — search hits, nearest/viewport hits,+ * boundary links, the "City, State, Country" locality line and place+ * attributes. *- * Skipped unless both are named (the inputs are 60-80 GB files):+ * By default both archives are the small synthetic fixture+ * ([PoiSyntheticArchive]), the candidate with its attrs/region sections+ * block-compressed (DEFLATE ZSEC) and the baseline raw — the planet5 format+ * change this test exists to pin — so it runs hermetically in CI instead of+ * skipping. When both env vars name real archives the same comparison runs+ * against them at planet scale: * * ``` * MAMAPS_BASELINE_ARCHIVE=planet5-rawpoi.mamaps MAMAPS_REAL_ARCHIVE=planet5.mamaps \ * ./gradlew :maps:testDevUnitTest --tests '*PoiPlanetParityTest*' * ```- *- * Use the same POI data in both (a raw-POI and a block-POI pack of one build), so any- * difference is the reader's. Timings are host JVM, mapped files in the page cache, block- * caches cold on the first pass and warm on the second. */ class PoiPlanetParityTest { - private fun file(env: String): File {- val path = System.getenv(env)- Assume.assumeTrue("$env not set; planet parity test skipped", !path.isNullOrBlank())- val f = File(path!!)- Assume.assumeTrue("$env=$path does not exist", f.isFile)- return f+ private fun envFile(env: String): File? {+ val path = System.getenv(env)?.takeIf { it.isNotBlank() } ?: return null+ return File(path).takeIf { it.isFile } } /** Everything a user sees from the POI index for the fixed query set, plus timings. */@@ -56,29 +53,41 @@ class PoiPlanetParityTest { private fun answers(file: File): Answers { assertTrue(PoiIndex.reloadArchive(file), "the app could not map POI sections from $file") val m = kotlin.test.assertNotNull(PoiIndex.mappedForQuery())+ val planet = m.count > 1_000 val lines = ArrayList<String>() val timings = LinkedHashMap<String, Pair<Double, Double>>() fun row(r: PoiIndex.PoiRecord) = "${r.ordinal}|${r.name}|${r.latE7},${r.lonE7}|t${r.type}|reg${r.regionId}|" + "${PoiIndex.localityAt(r.ordinal, english = true)}" + val cities = if (planet) CITIES else PoiSyntheticArchive.RECORDS.take(4)+ .map { Triple(it.name, it.lat, it.lon) }+ val queries = if (planet) QUERIES else listOf(+ Triple("Golden Gate Bridge", 37.8199, -122.4783),+ Triple("Tartine Bakery", 37.7614, -122.4241),+ Triple("Golden Gate Park", 37.7694, -122.4862),+ Triple("Oakland", 37.8044, -122.2712),+ Triple("Cafe", 37.7749, -122.4194),+ )+ // Name search, City/State/Country line and attributes of each hit.- fun searchPass(): Unit = QUERIES.forEach { (q, lat, lon) ->+ fun searchPass(): Unit = queries.forEach { (q, lat, lon) -> PoiIndex.searchByName(q, lat, lon, limit = 10).forEach { lines.add("search $q: ${row(it)}") } }- timings["search (us/query)"] = timedPair(lines, QUERIES.size) { searchPass() }+ timings["search (us/query)"] = timedPair(lines, queries.size) { searchPass() } // Spatial: nearest + viewport in each city (each record carries its regionId).- fun spatialPass(): Unit = CITIES.forEach { (c, lat, lon) ->+ fun spatialPass(): Unit = cities.forEach { (c, lat, lon) -> PoiIndex.nearest(lat, lon, limit = 20, maxMeters = 500.0).forEach { lines.add("near $c: ${row(it)}") } val box = PoiIndex.inViewport(lon - 0.01, lat - 0.01, lon + 0.01, lat + 0.01) lines.add("viewport $c: ${box.size} regionsum ${box.sumOf { it.regionId }}") }- timings["nearest+viewport (us/city)"] = timedPair(lines, CITIES.size) { spatialPass() }+ timings["nearest+viewport (us/city)"] = timedPair(lines, cities.size) { spatialPass() } // Place sheet: attributes of random ordinals (each one a different block when cold). val rnd = Random(SEED)- val ords = IntArray(ATTR_PROBES) { rnd.nextInt(m.count) }+ val probes = if (planet) ATTR_PROBES else m.count+ val ords = IntArray(probes) { if (planet) rnd.nextInt(m.count) else it } fun attrPass(): Unit = ords.forEach { o -> lines.add("attrs $o: ${PoiIndex.attributesAt(o)}") } val attrCold = nanosPer(ords.size) { attrPass() } val keep3 = lines.size@@ -87,7 +96,8 @@ class PoiPlanetParityTest { timings["attributesAt random (us/call)"] = attrCold to attrWarm // Boundary link + locality of random ordinals (search rows of far-apart places).- val ords2 = IntArray(REGION_PROBES) { rnd.nextInt(m.count) }+ val regionProbes = if (planet) REGION_PROBES else m.count+ val ords2 = IntArray(regionProbes) { if (planet) rnd.nextInt(m.count) else it } fun regionPass(): Unit = ords2.forEach { o -> lines.add("region $o: ${m.regionId(o)} ${PoiIndex.localityAt(o, english = true)}") }@@ -101,8 +111,10 @@ class PoiPlanetParityTest { @Test fun `block compressed POI sections answer exactly like raw ones`() {- val baseline = file(BASELINE_ENV)- val candidate = file(CANDIDATE_ENV)+ val baselineFile = envFile(BASELINE_ENV)+ val candidateFile = envFile(CANDIDATE_ENV)+ val baseline = baselineFile ?: PoiSyntheticArchive.write("poibase", blockCompressed = false)+ val candidate = candidateFile ?: PoiSyntheticArchive.write("poicand", blockCompressed = true) val a = answers(baseline) val b = answers(candidate) println("POI parity: ${a.lines.size} answer lines")@@ -117,7 +129,12 @@ class PoiPlanetParityTest { val diff = a.lines.indices.firstOrNull { a.lines[it] != b.lines.getOrNull(it) } assertEquals(a.lines.size, b.lines.size, "answer counts differ") assertEquals(null, diff, "first difference: ${diff?.let { a.lines[it] + " vs " + b.lines[it] }}")- assertTrue(a.lines.any { it.contains("United States") }, "no City/State/Country line resolved")+ if (baselineFile != null && candidateFile != null) {+ assertTrue(a.lines.any { it.contains("United States") }, "no City/State/Country line resolved")+ } else {+ // Fixture admin hierarchy: Paris under France for every record.+ assertTrue(a.lines.any { it.contains("Paris, France") }, "no locality line resolved: ${a.lines.take(5)}")+ } } private companion object {
maps/src/test/java/com/vayunmathur/maps/util/PoiSyntheticArchive.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiSyntheticArchive.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiSyntheticArchive.ktnew file mode 100644index 0000000000..d8e1b53ee2--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiSyntheticArchive.kt@@ -0,0 +1,236 @@+package com.vayunmathur.maps.util++import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.file.Files++/**+ * A small synthetic `.mamaps` archive holding a handful of POI records with+ * every POI section the app reads (index, names, attrs, spatial grid, word+ * index, region links and the admin hierarchy), built in the exact on-disk+ * formats the production readers validate.+ *+ * This is the hermetic stand-in for the 50-80 GB planet archive: the reader+ * paths under test ([PoiIndex.reloadArchive] -> [PoiArchive], nearest /+ * viewport / name search / attributes / locality) are the production ones,+ * only the input size differs. Real-archive tests keep their env-gated+ * planet assertions and fall back to this fixture by default, so CI runs+ * the same assertions instead of skipping them.+ */+internal object PoiSyntheticArchive {++ data class Record(val name: String, val lat: Double, val lon: Double, val type: Int)++ /** The boundary every fixture record links to (relation 71525, "Paris"). */+ val PARIS_TAGGED: Long = (71_525L shl 2) or 3L+ private val FRANCE_TAGGED: Long = (2_202_162L shl 2) or 3L++ val RECORDS: List<Record> = listOf(+ Record("Golden Gate Bridge", 37.8199, -122.4783, 20),+ Record("Tartine Bakery", 37.7614, -122.4241, 0),+ Record("Golden Gate Park", 37.7694, -122.4862, 25),+ Record("Oakland", 37.8044, -122.2712, 51),+ Record("Cafe", 37.7749, -122.4194, 1),+ Record("Mall", 37.7750, -122.4194, 10),+ )++ const val BUILD_ID: Long = 0x0123_4567_89AB_CDEFL++ /** Write the fixture archive into a fresh temp dir and return the file. */+ fun write(dirName: String = "poisynth", blockCompressed: Boolean = false): File {+ val dir = Files.createTempDirectory(dirName).toFile()+ val f = File(dir, "test.mamaps")+ f.writeBytes(bytes(blockCompressed))+ return f+ }++ fun bytes(blockCompressed: Boolean = false): ByteArray {+ val payloads = listOf(+ Triple(PoiArchive.KIND_INDEX, indexBytes(), 0L),+ Triple(PoiArchive.KIND_NAMES, namesBytes(), 0L),+ Triple(PoiArchive.KIND_ATTRS, maybeCompress(attrsBytes(), blockCompressed), 0L),+ Triple(PoiArchive.KIND_SPATIAL, spatialBytes(), 0L),+ Triple(PoiArchive.KIND_WORDS, wordsBytes(), 0L),+ Triple(PoiArchive.KIND_REGION, maybeCompress(regionBytes(), blockCompressed), 0L),+ Triple(PoiArchive.KIND_ADMIN, adminBytes(), 0L),+ )+ return container(payloads)+ }++ private fun maybeCompress(raw: ByteArray, compress: Boolean): ByteArray =+ if (compress) zsecDeflate(raw, 5) else raw++ /** Name pool in record order. */+ fun namesBytes(): ByteArray {+ val out = java.io.ByteArrayOutputStream()+ for (r in RECORDS) out.write(r.name.toByteArray(Charsets.UTF_8) + byteArrayOf(0))+ return out.toByteArray()+ }++ private fun nameOffsets(): List<Int> {+ val out = ArrayList<Int>(RECORDS.size)+ var off = 0+ for (r in RECORDS) {+ out += off+ off += r.name.toByteArray(Charsets.UTF_8).size + 1+ }+ return out+ }++ private fun indexBytes(): ByteArray {+ val offs = nameOffsets()+ val buf = ByteBuffer.allocate(RECORDS.size * 14).order(ByteOrder.LITTLE_ENDIAN)+ RECORDS.forEachIndexed { i, r ->+ buf.putInt((r.lat * 1e7).toInt())+ buf.putInt((r.lon * 1e7).toInt())+ buf.putInt(offs[i])+ buf.putShort(r.type.toShort())+ }+ return buf.array()+ }++ /** Every record carries rating + review count + summary (plus phone/city). */+ private fun attrsBytes(): ByteArray {+ val bodies = RECORDS.mapIndexed { i, r ->+ val fields = java.io.ByteArrayOutputStream()+ fun field(key: Int, value: String) {+ val v = value.toByteArray(Charsets.UTF_8)+ fields.write(key)+ fields.write((v.size and 0xFF))+ fields.write((v.size shr 8 and 0xFF))+ fields.write(v)+ }+ field(KEY_RATING, "4.${5 + i % 5}")+ field(KEY_REVIEW_COUNT, "${120 + i * 37}")+ field(KEY_REVIEW_SUMMARY, "Loved by locals near ${r.name}")+ field(KEY_PHONE, "+1-555-010$i")+ field(KEY_CITY, "San Francisco")+ val body = fields.toByteArray()+ ByteBuffer.allocate(2 + body.size).order(ByteOrder.LITTLE_ENDIAN)+ .putShort(body.size.toShort()).put(body).array()+ }+ val blobStart = 12 + 4 * RECORDS.size+ var off = 0+ val buf = ByteBuffer.allocate(blobStart + bodies.sumOf { it.size }).order(ByteOrder.LITTLE_ENDIAN)+ buf.put("MAPA".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(RECORDS.size)+ for (b in bodies) {+ buf.putInt(off)+ off += b.size+ }+ for (b in bodies) buf.put(b)+ return buf.array()+ }++ /** One tagged boundary id per record. */+ private fun regionBytes(): ByteArray {+ val buf = ByteBuffer.allocate(12 + 8 * RECORDS.size).order(ByteOrder.LITTLE_ENDIAN)+ buf.put("PRG1".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(RECORDS.size)+ repeat(RECORDS.size) { buf.putLong(PARIS_TAGGED) }+ return buf.array()+ }++ /** Paris (level 8) under France (level 2), as in PoiArchiveTest. */+ private fun adminBytes(): ByteArray {+ val pool = "Paris\u0000France\u0000".toByteArray(Charsets.UTF_8)+ val buf = ByteBuffer.allocate(16 + 64 + pool.size).order(ByteOrder.LITTLE_ENDIAN)+ buf.put("PAD1".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(2).putInt(pool.size)+ buf.putLong(PARIS_TAGGED).putLong(FRANCE_TAGGED).putInt(0).putInt(-1).put(8.toByte()).put(ByteArray(7))+ buf.putLong(FRANCE_TAGGED).putLong(0L).putInt(6).putInt(-1).put(2.toByte()).put(ByteArray(7))+ buf.put(pool)+ return buf.array()+ }++ /** CSR grid: 0.1-degree cells over the fixture's bay-area extent. */+ private fun spatialBytes(): ByteArray {+ val lat0 = 37_6500_000+ val lon0 = -122_5500_000+ val cell = 1_000_000+ val cols = 10+ fun cellId(r: Record): Int {+ val row = ((r.lat * 1e7).toInt() - lat0) / cell+ val col = ((r.lon * 1e7).toInt() - lon0) / cell+ return row * cols + col+ }+ val byCell = RECORDS.indices.groupBy { cellId(RECORDS[it]) }.toSortedMap()+ val cellIds = byCell.keys.toIntArray()+ val offsets = IntArray(cellIds.size + 1)+ val ordinals = ArrayList<Int>()+ cellIds.forEachIndexed { ci, id ->+ offsets[ci] = ordinals.size+ ordinals += byCell.getValue(id).sorted()+ }+ offsets[cellIds.size] = ordinals.size+ val buf = ByteBuffer.allocate(32 + 4 * (cellIds.size + cellIds.size + 1 + ordinals.size))+ .order(ByteOrder.LITTLE_ENDIAN)+ buf.put("PSP1".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(RECORDS.size)+ buf.putInt(cellIds.size).putInt(lat0).putInt(lon0).putInt(cell).putInt(cols)+ cellIds.forEach { buf.putInt(it) }+ offsets.forEach { buf.putInt(it) }+ ordinals.forEach { buf.putInt(it) }+ return buf.array()+ }++ /** Word index: one entry per whitespace-separated word, sorted by word. */+ private fun wordsBytes(): ByteArray {+ data class Entry(val word: String, val ordinal: Int, val wordIdx: Int)+ val entries = ArrayList<Entry>()+ RECORDS.forEachIndexed { ord, r ->+ r.name.split(" ").forEachIndexed { wi, w -> entries += Entry(w.lowercase(), ord, wi) }+ }+ entries.sortWith(compareBy({ it.word }, { it.ordinal }, { it.wordIdx }))+ val buf = ByteBuffer.allocate(16 + 4 * entries.size + entries.size).order(ByteOrder.LITTLE_ENDIAN)+ buf.put("PNI1".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(RECORDS.size).putInt(entries.size)+ entries.forEach { buf.putInt(it.ordinal) }+ entries.forEach { buf.put(it.wordIdx.toByte()) }+ return buf.array()+ }++ /** Tile prefix + 8-aligned payloads in kind order + directory + MAMA8 footer. */+ private fun container(payloads: List<Triple<Int, ByteArray, Long>>): ByteArray {+ val out = java.io.ByteArrayOutputStream()+ out.write(ByteArray(4096))+ val entries = ArrayList<ByteArray>()+ for ((kind, bytes, extra) in payloads) {+ while (out.size() % 8 != 0) out.write(0)+ val offset = out.size().toLong()+ out.write(bytes)+ val e = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN)+ e.put(kind.toByte())+ e.put(byteArrayOf(0, 0, 0))+ e.putInt(0)+ e.putLong(offset)+ e.putLong(bytes.size.toLong())+ e.putLong(extra)+ entries.add(e.array())+ }+ while (out.size() % 8 != 0) out.write(0)+ val dirOffset = out.size().toLong()+ val dir = ByteBuffer.allocate(4 + entries.size * 32 + 7).order(ByteOrder.LITTLE_ENDIAN)+ dir.putInt(entries.size)+ for (e in entries) dir.put(e)+ while (dir.position() % 8 != 0) dir.put(0.toByte())+ out.write(dir.array(), 0, dir.position())+ val footer = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN)+ footer.put("MAMA8".toByteArray(Charsets.US_ASCII))+ footer.put(byteArrayOf(0, 0, 0))+ footer.putLong(dirOffset)+ footer.putLong(dir.position().toLong())+ footer.putLong(BUILD_ID)+ out.write(footer.array())+ val bytes = out.toByteArray()+ val head = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)+ head.put("MAMAPS".toByteArray(Charsets.US_ASCII))+ head.put(0.toByte())+ head.put(7.toByte())+ head.putShort(128.toShort())+ head.putShort(0.toShort())+ head.put(0.toByte())+ head.put(12.toByte())+ head.put(0.toByte())+ head.put(14.toByte())+ head.putLong(BUILD_ID)+ head.putLong(bytes.size.toLong())+ return bytes+ }+}