Modern Apps git

← Modern-Apps.git

maps: read planet5 block-compressed POI attrs and region (#planet5)

Commit
c0312440cf39b946436a28eb8a2547787f92d028
Author
Vayun Mathur <[email protected]>
When
2026-11-14 04:08 UTC (22 days ago)
Parents
9a6e14e
planet5 stores the POI attribute sidecar (kind 10, 1.19 GB) and the
boundary-link sidecar (kind 15, 0.25 GB) as DEFLATE block sections
(tilecodec ZSEC codec 1): 340 MB and 7 MB. Both are read per record
-- a place sheet's attributes, a search row's or pin's boundary id --
never scanned, so a block cache serves them; the hot search and
spatial sections (index, names, words, grid) stay raw.

- PoiBytes: the random-access view the attrs/region readers now take
  instead of a MappedByteBuffer: get/getShort/getInt/getLong/bytes at
  raw byte offsets, little-endian, so every offset and bounds check in
  the readers is unchanged. PoiBytes.of(buf) opens a section that
  starts with the ZSEC magic as a PoiBlockSection and reads anything
  else in place (MappedPoiBytes) -- planet4 and side files unchanged.
- PoiBlockSection: validates the header, codec and the whole offset
  table on open (a malformed table reads as "section absent", like
  every other POI validation failure); inflates a 64 KiB block with a
  per-thread java.util.zip.Inflater(nowrap) on first touch into a
  64-block (4 MiB) LRU; reads straddling a block edge are stitched;
  out-of-range reads throw IndexOutOfBoundsException, which the
  existing bufferFailure paths already treat as corrupt data.
  Thread-safe.
- attrsFromBuffer / regionFromBuffer return PoiBytes; decodeAttrRecord
  and stringAt read through it; Mapped.attrs / Mapped.region are
  PoiBytes.

Tests: PoiBlockSectionTest (random reads at 4 block sizes against the
raw bytes, straddles, bulk copies, truncated/foreign/inconsistent
tables refused, bounds, one inflate per block); PoiArchiveTest adds an
archive with block attrs + region (5-byte blocks) answering phone,
region and "Paris, France" exactly like the raw one; and
PoiPlanetParityTest (env-gated, two real archives) compares every
search hit, nearest/viewport hit, boundary link, City/State/Country
line and attribute record between a raw-POI and a block-POI planet
and prints cold/warm timings per query path.

Diff

maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.ktindex e418e16017..a41fda068c 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt@@ -201,10 +201,10 @@ object PoiArchive {         indexBuf: MappedByteBuffer,         namesBuf: MappedByteBuffer,         count: Int,-        attrs: Pair<MappedByteBuffer, Int>?,+        attrs: Pair<PoiBytes, Int>?,         grid: PoiIndex.Grid?,         words: Pair<MappedByteBuffer, Int>?,-        region: MappedByteBuffer?,+        region: PoiBytes?,         admin: AdminTable?,     ): PoiIndex.Mapped {         return PoiIndex.Mapped(
maps/src/main/java/com/vayunmathur/maps/util/PoiBlockSection.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiBlockSection.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiBlockSection.ktnew file mode 100644index 0000000000..f2bad673c1--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiBlockSection.kt@@ -0,0 +1,224 @@+package com.vayunmathur.maps.util++import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.util.zip.DataFormatException+import java.util.zip.Inflater++/**+ * Random-access bytes of one POI sidecar: the mapped section itself (planet4, and every+ * section planet5 leaves raw) or a planet5 block-compressed section ([PoiBlockSection]).+ * Positions are byte offsets into the section's *raw* layout, so the readers keep their+ * offsets and bounds checks unchanged; little-endian like every POI file.+ */+internal interface PoiBytes {+    /** The raw section length in bytes. */+    val size: Int++    fun get(pos: Int): Byte++    fun getShort(pos: Int): Short++    fun getInt(pos: Int): Int++    fun getLong(pos: Int): Long++    /** `len` bytes at `pos`, copied out. */+    fun bytes(pos: Int, len: Int): ByteArray++    companion object {+        /**+         * [buf] as [PoiBytes]: a block-compressed section (it starts with the `ZSEC` magic)+         * is opened through [PoiBlockSection], anything else is read in place. Null for a+         * block section whose table does not validate (the caller treats it as absent).+         */+        fun of(buf: ByteBuffer): PoiBytes? {+            buf.order(ByteOrder.LITTLE_ENDIAN)+            return if (PoiBlockSection.isBlockSection(buf)) PoiBlockSection.open(buf) else MappedPoiBytes(buf)+        }+    }+}++/** An uncompressed section, read straight out of its mapping. */+internal class MappedPoiBytes(private val buf: ByteBuffer) : PoiBytes {+    init {+        buf.order(ByteOrder.LITTLE_ENDIAN)+    }++    override val size: Int get() = buf.capacity()++    override fun get(pos: Int): Byte = buf.get(pos)++    override fun getShort(pos: Int): Short = buf.getShort(pos)++    override fun getInt(pos: Int): Int = buf.getInt(pos)++    override fun getLong(pos: Int): Long = buf.getLong(pos)++    override fun bytes(pos: Int, len: Int): ByteArray {+        val out = ByteArray(len)+        // Absolute bulk read through a duplicate: the shared buffer's position never moves.+        val dup = buf.duplicate()+        dup.position(pos)+        dup.get(out, 0, len)+        return out+    }+}++/**+ * A planet5 block-compressed POI section (the attrs and region sidecars; the layout is+ * tilecodec `zsec.rs`, DEFLATE codec):+ *+ * ```+ * [magic "ZSEC"][block_size u32][raw_len u64][block_count u32][codec u32 = 1]+ * [offsets u64 x (block_count + 1)]   from the section start; the last is its end+ * [raw DEFLATE block]...+ * ```+ *+ * Each 64 KiB block of the raw file is an independent raw-DEFLATE stream, inflated with+ * `java.util.zip.Inflater` (`nowrap`) on first touch and kept in a small LRU, so a lookup+ * costs at most one block inflate (~0.1-0.3 ms on a phone) and repeated or neighbouring+ * lookups none. Nothing is ever inflated whole. Thread-safe: queries run on any thread.+ */+internal class PoiBlockSection private constructor(+    private val buf: ByteBuffer,+    override val size: Int,+    private val blockSize: Int,+    private val blockCount: Int,+) : PoiBytes {+    private val cache = object : LinkedHashMap<Int, ByteArray>(CACHE_BLOCKS * 2, LOAD_FACTOR, true) {+        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Int, ByteArray>?): Boolean =+            this.size > CACHE_BLOCKS+    }++    /** Blocks inflated so far (tests and the real-archive timing read it). */+    @Volatile+    internal var inflated: Int = 0+        private set++    private fun offset(i: Int): Long = buf.getLong(HEADER_BYTES + OFFSET_BYTES * i)++    private fun block(b: Int): ByteArray {+        if (b !in 0 until blockCount) throw IndexOutOfBoundsException("POI block $b of $blockCount")+        synchronized(cache) { cache[b]?.let { return it } }+        val start = offset(b)+        val end = offset(b + 1)+        val want = minOf(blockSize.toLong(), size.toLong() - b.toLong() * blockSize).toInt()+        val input = ByteArray((end - start).toInt())+        val dup = buf.duplicate()+        dup.position(start.toInt())+        dup.get(input)+        val out = ByteArray(want)+        val inflater = INFLATER.get()!!+        inflater.reset()+        inflater.setInput(input)+        var n = 0+        try {+            while (n < want) {+                val got = inflater.inflate(out, n, want - n)+                if (got == 0 && (inflater.finished() || inflater.needsInput() || inflater.needsDictionary())) break+                n += got+            }+        } catch (e: DataFormatException) {+            throw IllegalArgumentException("POI block $b will not inflate", e)+        }+        require(n == want) { "POI block $b inflated to $n of $want bytes" }+        inflated+++        synchronized(cache) { cache[b] = out }+        return out+    }++    override fun get(pos: Int): Byte {+        checkRange(pos, 1)+        return block(pos / blockSize)[pos % blockSize]+    }++    override fun getShort(pos: Int): Short = (littleEndian(pos, 2)).toInt().toShort()++    override fun getInt(pos: Int): Int = littleEndian(pos, 4).toInt()++    override fun getLong(pos: Int): Long = littleEndian(pos, 8)++    override fun bytes(pos: Int, len: Int): ByteArray {+        checkRange(pos, len)+        val out = ByteArray(len)+        var done = 0+        while (done < len) {+            val p = pos + done+            val blk = block(p / blockSize)+            val off = p % blockSize+            val n = minOf(len - done, blk.size - off)+            System.arraycopy(blk, off, out, done, n)+            done += n+        }+        return out+    }++    /** `width` bytes at `pos` as a little-endian integer; one block unless it straddles two. */+    private fun littleEndian(pos: Int, width: Int): Long {+        checkRange(pos, width)+        val off = pos % blockSize+        val blk = block(pos / blockSize)+        val src: ByteArray+        val at: Int+        if (off + width <= blk.size) {+            src = blk+            at = off+        } else {+            src = bytes(pos, width)+            at = 0+        }+        var v = 0L+        for (i in width - 1 downTo 0) v = (v shl BYTE_BITS) or (src[at + i].toLong() and BYTE_MASK)+        return v+    }++    private fun checkRange(pos: Int, len: Int) {+        if (pos < 0 || len < 0 || pos > size - len) {+            throw IndexOutOfBoundsException("POI block section read $pos+$len of $size")+        }+    }++    internal companion object {+        private val MAGIC = byteArrayOf('Z'.code.toByte(), 'S'.code.toByte(), 'E'.code.toByte(), 'C'.code.toByte())+        const val HEADER_BYTES = 24+        const val OFFSET_BYTES = 8+        const val CODEC_DEFLATE = 1+        private const val BLOCK_SIZE_OFF = 4+        private const val RAW_LEN_OFF = 8+        private const val BLOCK_COUNT_OFF = 16+        private const val CODEC_OFF = 20+        /** 64 blocks x 64 KiB = 4 MiB per section, at most. */+        const val CACHE_BLOCKS = 64+        private const val LOAD_FACTOR = 0.75f+        private const val BYTE_BITS = 8+        private const val BYTE_MASK = 0xFFL+        private const val MAX_BLOCK = 1 shl 20++        private val INFLATER = ThreadLocal.withInitial { Inflater(true) }++        fun isBlockSection(buf: ByteBuffer): Boolean =+            buf.capacity() >= HEADER_BYTES && MAGIC.indices.all { buf.get(it) == MAGIC[it] }++        /** The section, or null when its header or offset table does not validate. */+        fun open(buf: ByteBuffer): PoiBlockSection? {+            buf.order(ByteOrder.LITTLE_ENDIAN)+            if (!isBlockSection(buf) || buf.getInt(CODEC_OFF) != CODEC_DEFLATE) return null+            val blockSize = buf.getInt(BLOCK_SIZE_OFF)+            val rawLen = buf.getLong(RAW_LEN_OFF)+            val blockCount = buf.getInt(BLOCK_COUNT_OFF)+            if (blockSize !in 1..MAX_BLOCK || rawLen !in 0..Int.MAX_VALUE.toLong() || blockCount < 0) return null+            if (blockCount.toLong() != (rawLen + blockSize - 1) / blockSize) return null+            val tableEnd = HEADER_BYTES.toLong() + OFFSET_BYTES.toLong() * (blockCount + 1)+            if (tableEnd > buf.capacity()) return null+            var prev = tableEnd+            for (i in 0..blockCount) {+                val o = buf.getLong(HEADER_BYTES + OFFSET_BYTES * i)+                if (o < prev || o > buf.capacity()) return null+                prev = o+            }+            if (prev != buf.capacity().toLong()) return null+            return PoiBlockSection(buf, rawLen.toInt(), blockSize, blockCount)+        }+    }+}
maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.ktindex 335c7e4912..eb2119681e 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -185,8 +185,8 @@ object PoiIndex {         val names: MappedByteBuffer,         val namesLen: Int,         val count: Int,-        /** The attribute sidecar, or null when it is absent or does not match. */-        val attrs: MappedByteBuffer?,+        /** The attribute sidecar (raw or planet5 block-compressed), or null when absent or mismatched. */+        val attrs: PoiBytes?,         /** Byte offset of the attribute blob, i.e. just past the offset array. */         val attrsBlobStart: Int,         /** The CSR spatial grid, or null when absent or mismatched. */@@ -199,8 +199,8 @@ object PoiIndex {         /** The word index, or null when absent or mismatched. */         internal val nameIdx: MappedByteBuffer? = null,         internal val entryCount: Int = 0,-        /** The region sidecar, or null when absent or mismatched. */-        internal val region: MappedByteBuffer? = null,+        /** The region sidecar (raw or planet5 block-compressed), or null when absent or mismatched. */+        internal val region: PoiBytes? = null,         /** The boundary hierarchy (`poi_admin.bin`, archive kind 16), or null when absent. */         internal val admin: AdminTable? = null,     ) {@@ -466,15 +466,22 @@ object PoiIndex {         }     } -    /** Buffer core of the attrs sidecar, reused by the single-archive path. */-    internal fun attrsFromBuffer(buf: MappedByteBuffer, count: Int): Pair<MappedByteBuffer, Int>? {-        buf.order(ByteOrder.LITTLE_ENDIAN)-        return runCatching { readAttrs(buf, count) }-            .getOrElse { bufferFailure(it, ATTRS_FILE) }+    /**+     * Buffer core of the attrs sidecar, reused by the single-archive path. A planet5 archive+     * stores it block-compressed ([PoiBlockSection]); [PoiBytes.of] reads either form.+     */+    internal fun attrsFromBuffer(buf: MappedByteBuffer, count: Int): Pair<PoiBytes, Int>? {+        return runCatching {+            val bytes = PoiBytes.of(buf) ?: run {+                Log.status(TAG, "$ATTRS_FILE block table is malformed; ignoring it")+                return null+            }+            readAttrs(bytes, count)+        }.getOrElse { bufferFailure(it, ATTRS_FILE) }     } -    private fun readAttrs(buf: MappedByteBuffer, count: Int): Pair<MappedByteBuffer, Int>? {-        if (buf.capacity() < ATTRS_HEADER_BYTES) {+    private fun readAttrs(buf: PoiBytes, count: Int): Pair<PoiBytes, Int>? {+        if (buf.size < ATTRS_HEADER_BYTES) {             Log.status(TAG, "$ATTRS_FILE is truncated")             return null         }@@ -497,7 +504,7 @@ object PoiIndex {             return null         }         val blobStart = ATTRS_HEADER_BYTES + ATTR_OFFSET_BYTES * attrCount-        if (blobStart > buf.capacity()) {+        if (blobStart > buf.size) {             Log.status(TAG, "$ATTRS_FILE offset array runs past the file")             return null         }@@ -703,7 +710,7 @@ object PoiIndex {     /** (bodyStart, bodyEnd) of the [ordinal]th record's attribute blob, or null. */     private fun attrBodyAt(         m: Mapped,-        buf: MappedByteBuffer,+        buf: PoiBytes,         ordinal: Int,     ): Pair<Int, Int>? {         if (ordinal < 0 || ordinal >= m.count) return null@@ -712,12 +719,12 @@ object PoiIndex {         // Bounded before the add, not after: `attrsBlobStart + off` can wrap negative         // for a large positive off, and a negative index passes an `at + 2 > capacity`         // test on its way to an IndexOutOfBoundsException.-        val blobLen = buf.capacity() - m.attrsBlobStart+        val blobLen = buf.size - m.attrsBlobStart         if (off > blobLen - ATTR_BODY_HEADER_LEN) return null         val at = m.attrsBlobStart + off         val bodyLen = buf.getShort(at).toInt() and U16_MASK         val body = at + ATTR_BODY_HEADER_LEN-        if (bodyLen > buf.capacity() - body) return null+        if (bodyLen > buf.size - body) return null         return body to body + bodyLen     } 
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAttrs.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAttrs.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAttrs.ktindex 0b94b8694d..8074cf4fa2 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAttrs.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAttrs.kt@@ -1,6 +1,5 @@ package com.vayunmathur.maps.util -import java.nio.MappedByteBuffer  /**  * The attribute-decode half of [PoiIndex]: reading `poi_attrs.bin` records.@@ -43,7 +42,7 @@ private const val ATTR_HEADER_LEN = 3  * length-prefixed: a device on an older build must still read the keys it does  * understand out of a newer file.  */-internal fun decodeAttrRecord(buf: MappedByteBuffer, from: Int, to: Int): PoiIndex.PoiAttributes? {+internal fun decodeAttrRecord(buf: PoiBytes, from: Int, to: Int): PoiIndex.PoiAttributes? {     val fields = AttrFields()     var i = from     while (i + ATTR_HEADER_LEN <= to) {@@ -110,12 +109,8 @@ private class AttrFields {     } } -private fun stringAt(buf: MappedByteBuffer, off: Int, len: Int): String? {+private fun stringAt(buf: PoiBytes, off: Int, len: Int): String? {     if (len <= 0) return null-    val bytes = ByteArray(len)-    // Absolute reads via a duplicate, so the shared buffer's position is untouched.-    val dup = buf.duplicate()-    dup.position(off)-    dup.get(bytes, 0, len)-    return String(bytes, Charsets.UTF_8)+    // An absolute copy ([PoiBytes.bytes]): a shared mapping's position never moves.+    return String(buf.bytes(off, len), Charsets.UTF_8) }
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.ktindex d628f66180..57396a0a1d 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexRegion.kt@@ -1,7 +1,6 @@ package com.vayunmathur.maps.util  import com.vayunmathur.library.log.Log-import java.nio.ByteOrder import java.nio.MappedByteBuffer  /**@@ -35,15 +34,22 @@ internal const val REGION_NONE = 0L internal fun PoiIndex.Mapped.regionId(i: Int): Long =     region?.getLong(REGION_HEADER_BYTES + i * REGION_ID_BYTES) ?: REGION_NONE -/** Buffer core of the region sidecar, reused by the single-archive path. */-internal fun regionFromBuffer(buf: MappedByteBuffer, count: Int): MappedByteBuffer? {-    buf.order(ByteOrder.LITTLE_ENDIAN)-    return runCatching { readRegion(buf, count) }-        .getOrElse { PoiIndex.bufferFailure(it, REGION_FILE) }+/**+ * Buffer core of the region sidecar, reused by the single-archive path. A planet5 archive+ * stores it block-compressed ([PoiBlockSection]: 0.25 GB -> 7 MB); [PoiBytes.of] reads either.+ */+internal fun regionFromBuffer(buf: MappedByteBuffer, count: Int): PoiBytes? {+    return runCatching {+        val bytes = PoiBytes.of(buf) ?: run {+            Log.status(TAG, "$REGION_FILE block table is malformed; ignoring it")+            return null+        }+        readRegion(bytes, count)+    }.getOrElse { PoiIndex.bufferFailure(it, REGION_FILE) } } -private fun readRegion(buf: MappedByteBuffer, count: Int): MappedByteBuffer? {-    if (buf.capacity() < REGION_HEADER_BYTES) return null+private fun readRegion(buf: PoiBytes, count: Int): PoiBytes? {+    if (buf.size < REGION_HEADER_BYTES) return null     for (i in REGION_MAGIC.indices) {         if (buf.get(i) != REGION_MAGIC[i]) {             Log.status(TAG, "$REGION_FILE has the wrong magic; ignoring it")@@ -59,7 +65,7 @@ private fun readRegion(buf: MappedByteBuffer, count: Int): MappedByteBuffer? {         Log.status(TAG, "$REGION_FILE covers $records record(s), index has $count; ignoring it")         return null     }-    if (REGION_HEADER_BYTES + REGION_ID_BYTES.toLong() * records > buf.capacity().toLong()) {+    if (REGION_HEADER_BYTES + REGION_ID_BYTES.toLong() * records > buf.size.toLong()) {         Log.status(TAG, "$REGION_FILE is truncated; ignoring it")         return null     }
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.ktindex cb533070f3..46fa0c02d6 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt@@ -56,7 +56,7 @@ internal object PoiIndexSideFiles {      *      * @return the mapped buffer and the byte offset of the blob, or null.      */-    private fun openAttrs(file: File, count: Int): Pair<MappedByteBuffer, Int>? {+    private fun openAttrs(file: File, count: Int): Pair<PoiBytes, Int>? {         if (!file.isFile) {             Log.debug(TAG, "POI attribute sidecar absent")             return null@@ -89,7 +89,7 @@ internal object PoiIndexSideFiles {      * others: the sidecar joins purely by ordinal, so a region file from a      * different build would hand every place someone else's boundary.      */-    private fun openRegion(file: File, count: Int): MappedByteBuffer? {+    private fun openRegion(file: File, count: Int): PoiBytes? {         if (!file.isFile) return null         return regionFromBuffer(PoiIndex.mapReadOnly(file), count)     }
maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.ktindex 6e61a442e4..ea32685b7f 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt@@ -170,6 +170,47 @@ class PoiArchiveTest {         assertEquals("Paris, France", PoiIndex.localityAt(1, english = false))     } +    /**+     * planet5: the attrs (kind 10) and region (kind 15) sidecars block-compressed (DEFLATE ZSEC,+     * tiny blocks so records straddle block edges) read exactly like their raw planet4 forms.+     */+    @Test+    fun `block compressed attrs and region read like raw ones`() {+        val paris = (71_525L shl 2) or 3L+        val france = (2_202_162L shl 2) or 3L+        val region = ByteBuffer.allocate(12 + 16).order(ByteOrder.LITTLE_ENDIAN)+        region.put("PRG1".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(2).putLong(paris).putLong(paris)+        val pool = "Paris\u0000France\u0000".toByteArray(Charsets.UTF_8)+        val admin = ByteBuffer.allocate(16 + 64 + pool.size).order(ByteOrder.LITTLE_ENDIAN)+        admin.put("PAD1".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(2).putInt(pool.size)+        admin.putLong(paris).putLong(france).putInt(0).putInt(-1).put(8.toByte()).put(ByteArray(7))+        admin.putLong(france).putLong(0L).putInt(6).putInt(-1).put(2.toByte()).put(ByteArray(7))+        admin.put(pool)+        val phone = "+1-555-CAFE".toByteArray(Charsets.UTF_8)+        val body = 3 + phone.size+        val attrs = ByteBuffer.allocate(12 + 8 + 2 + body).order(ByteOrder.LITTLE_ENDIAN)+        attrs.put("MAPA".toByteArray(Charsets.US_ASCII)).put(1.toByte()).put(ByteArray(3)).putInt(2)+        attrs.putInt(0).putInt(-1) // record 0 has a body at blob offset 0, record 1 none+        attrs.putShort(body.toShort()).put(KEY_PHONE.toByte()).putShort(phone.size.toShort()).put(phone)+        val f = writeArchive(+            listOf(+                indexPayload(),+                Triple(PoiArchive.KIND_NAMES, namesBytes(), 0L),+                Triple(PoiArchive.KIND_ATTRS, zsecDeflate(attrs.array(), 5), 0L),+                Triple(PoiArchive.KIND_REGION, zsecDeflate(region.array(), 5), 0L),+                Triple(PoiArchive.KIND_ADMIN, admin.array(), 0L),+            ),+        )+        assertTrue(PoiIndex.reloadArchive(f), "archive did not map")+        val m = kotlin.test.assertNotNull(PoiIndex.mappedForQuery())+        assertTrue(m.attrs is PoiBlockSection, "attrs should open as a block section")+        assertTrue(m.region is PoiBlockSection, "region should open as a block section")+        assertEquals(paris, m.regionId(1))+        assertEquals("Paris, France", PoiIndex.localityAt(0, english = true))+        assertEquals("+1-555-CAFE", PoiIndex.attributesAt(0)?.phone)+        assertEquals(null, PoiIndex.attributesAt(1))+    }+     @Test     fun `bad magic is refused`() {         val bytes = archive(
maps/src/test/java/com/vayunmathur/maps/util/PoiBlockSectionTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiBlockSectionTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiBlockSectionTest.ktnew file mode 100644index 0000000000..ae68ea12eb--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiBlockSectionTest.kt@@ -0,0 +1,105 @@+package com.vayunmathur.maps.util++import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.util.zip.Deflater+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * A DEFLATE-codec ZSEC section of [raw], built the way tilecodec `write_zsec_deflate` builds+ * it (raw DEFLATE per block, absolute u64 offsets, codec 1), for the planet5 POI reader tests.+ */+internal fun zsecDeflate(raw: ByteArray, blockSize: Int, codec: Int = PoiBlockSection.CODEC_DEFLATE): ByteArray {+    val blocks = (0 until raw.size step blockSize).map { start ->+        val d = Deflater(Deflater.BEST_COMPRESSION, true)+        d.setInput(raw, start, minOf(blockSize, raw.size - start))+        d.finish()+        val out = java.io.ByteArrayOutputStream()+        val buf = ByteArray(4096)+        while (!d.finished()) out.write(buf, 0, d.deflate(buf))+        d.end()+        out.toByteArray()+    }+    val tableEnd = PoiBlockSection.HEADER_BYTES + PoiBlockSection.OFFSET_BYTES * (blocks.size + 1)+    val total = tableEnd + blocks.sumOf { it.size }+    val b = ByteBuffer.allocate(total).order(ByteOrder.LITTLE_ENDIAN)+    b.put("ZSEC".toByteArray(Charsets.US_ASCII)).putInt(blockSize).putLong(raw.size.toLong())+    b.putInt(blocks.size).putInt(codec)+    var at = tableEnd.toLong()+    for (blk in blocks) {+        b.putLong(at)+        at += blk.size+    }+    b.putLong(at)+    for (blk in blocks) b.put(blk)+    return b.array()+}++class PoiBlockSectionTest {+    private val raw = ByteArray(10_000) { i -> ((i * 31) % 251 xor (i shr 7)).toByte() }+    private val plain = ByteBuffer.wrap(raw).order(ByteOrder.LITTLE_ENDIAN)++    private fun section(blockSize: Int): PoiBytes =+        assertNotNull(PoiBytes.of(ByteBuffer.wrap(zsecDeflate(raw, blockSize))), "block section refused")++    @Test+    fun `every read matches the raw bytes, across block edges`() {+        for (bs in listOf(7, 64, 1000, 65_536)) {+            val s = section(bs)+            assertTrue(s is PoiBlockSection)+            assertEquals(raw.size, s.size)+            val rnd = Random(bs)+            repeat(2_000) {+                val p = rnd.nextInt(raw.size - 8)+                assertEquals(plain.get(p), s.get(p), "get $p bs $bs")+                assertEquals(plain.getShort(p), s.getShort(p), "getShort $p bs $bs")+                assertEquals(plain.getInt(p), s.getInt(p), "getInt $p bs $bs")+                assertEquals(plain.getLong(p), s.getLong(p), "getLong $p bs $bs")+            }+            assertContentEquals(raw.copyOfRange(990, 2_345), s.bytes(990, 1_355))+            assertContentEquals(raw, s.bytes(0, raw.size))+        }+    }++    @Test+    fun `an uncompressed section reads in place`() {+        val s = assertNotNull(PoiBytes.of(ByteBuffer.wrap(raw)))+        assertTrue(s is MappedPoiBytes)+        assertEquals(plain.getLong(123), s.getLong(123))+    }++    @Test+    fun `a malformed or foreign block section is refused`() {+        val good = zsecDeflate(raw, 64)+        // Truncated: the last offset no longer names the end.+        assertNull(PoiBytes.of(ByteBuffer.wrap(good.copyOf(good.size - 1))))+        // A zstd-codec section (transit's) is not for this reader.+        assertNull(PoiBytes.of(ByteBuffer.wrap(zsecDeflate(raw, 64, codec = 0))))+        // Block count disagrees with raw_len / block_size.+        val bad = good.copyOf()+        ByteBuffer.wrap(bad).order(ByteOrder.LITTLE_ENDIAN).putInt(16, 3)+        assertNull(PoiBytes.of(ByteBuffer.wrap(bad)))+    }++    @Test+    fun `reads outside the section throw instead of wrapping`() {+        val s = section(64)+        assertTrue(runCatching { s.getLong(raw.size - 4) }.exceptionOrNull() is IndexOutOfBoundsException)+        assertTrue(runCatching { s.get(-1) }.exceptionOrNull() is IndexOutOfBoundsException)+    }++    @Test+    fun `repeated reads inflate each block once`() {+        val s = section(1000) as PoiBlockSection+        repeat(50) { s.getInt(1_500) }+        assertEquals(1, s.inflated)+        s.getInt(998) // straddles blocks 0 and 1+        assertEquals(2, s.inflated)+    }+}
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.ktnew file mode 100644index 0000000000..72712c113c--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiPlanetParityTest.kt@@ -0,0 +1,151 @@+package com.vayunmathur.maps.util++import java.io.File+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.+ *+ * Skipped unless both are named (the inputs are 60-80 GB files):+ *+ * ```+ * 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+    }++    /** Everything a user sees from the POI index for the fixed query set, plus timings. */+    private data class Answers(val lines: List<String>, val timings: Map<String, Pair<Double, Double>>)++    private fun nanosPer(n: Int, block: () -> Unit): Double {+        val t = System.nanoTime()+        block()+        return (System.nanoTime() - t) / 1_000.0 / n+    }++    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 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)}"++        // Name search, City/State/Country line and attributes of each hit.+        fun searchPass(): Unit = QUERIES.forEach { (q, lat, lon) ->+            PoiIndex.searchByName(q, lat, lon, limit = 10).forEach { lines.add("search $q: ${row(it)}") }+        }+        val searchCold = nanosPer(QUERIES.size) { searchPass() }+        val keep = lines.size+        val searchWarm = nanosPer(QUERIES.size) { searchPass() }+        while (lines.size > keep) lines.removeAt(lines.size - 1)+        timings["search (us/query)"] = searchCold to searchWarm++        // Spatial: nearest + viewport in each city (each record carries its regionId).+        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 }}")+        }+        val spatialCold = nanosPer(CITIES.size) { spatialPass() }+        val keep2 = lines.size+        val spatialWarm = nanosPer(CITIES.size) { spatialPass() }+        while (lines.size > keep2) lines.removeAt(lines.size - 1)+        timings["nearest+viewport (us/city)"] = spatialCold to spatialWarm++        // 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) }+        fun attrPass(): Unit = ords.forEach { o -> lines.add("attrs $o: ${PoiIndex.attributesAt(o)}") }+        val attrCold = nanosPer(ords.size) { attrPass() }+        val keep3 = lines.size+        val attrWarm = nanosPer(ords.size) { attrPass() }+        while (lines.size > keep3) lines.removeAt(lines.size - 1)+        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) }+        fun regionPass(): Unit = ords2.forEach { o ->+            lines.add("region $o: ${m.regionId(o)} ${PoiIndex.localityAt(o, english = true)}")+        }+        val regCold = nanosPer(ords2.size) { regionPass() }+        val keep4 = lines.size+        val regWarm = nanosPer(ords2.size) { regionPass() }+        while (lines.size > keep4) lines.removeAt(lines.size - 1)+        timings["regionId+locality random (us/call)"] = regCold to regWarm+        return Answers(lines, timings)+    }++    @Test+    fun `block compressed POI sections answer exactly like raw ones`() {+        val baseline = file(BASELINE_ENV)+        val candidate = file(CANDIDATE_ENV)+        val a = answers(baseline)+        val b = answers(candidate)+        println("POI parity: ${a.lines.size} answer lines")+        for (k in a.timings.keys) {+            val (ac, aw) = a.timings.getValue(k)+            val (bc, bw) = b.timings.getValue(k)+            println(+                "TIMING %-36s baseline cold %9.1f warm %9.1f | candidate cold %9.1f warm %9.1f".format(k, ac, aw, bc, bw),+            )+        }+        a.lines.filter { it.startsWith("search ") }.distinctBy { it.substringBefore(":") }.forEach { println(it) }+        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")+    }++    private companion object {+        const val BASELINE_ENV = "MAMAPS_BASELINE_ARCHIVE"+        const val CANDIDATE_ENV = "MAMAPS_REAL_ARCHIVE"+        const val SEED = 5+        const val ATTR_PROBES = 2_000+        const val REGION_PROBES = 2_000+        val CITIES = listOf(+            Triple("SF", 37.7749, -122.4194),+            Triple("NYC", 40.7580, -73.9855),+            Triple("London", 51.5074, -0.1278),+            Triple("Tokyo", 35.6812, 139.7671),+            Triple("Sydney", -33.8688, 151.2093),+            Triple("Paris", 48.8566, 2.3522),+        )+        val QUERIES = listOf(+            Triple("Golden Gate Bridge", 37.7749, -122.4194),+            Triple("Space Needle", 47.6062, -122.3321),+            Triple("Empire State Building", 40.7580, -73.9855),+            Triple("Tartine Bakery", 37.7614, -122.4241),+            Triple("British Museum", 51.5194, -0.1270),+            Triple("Tour Eiffel", 48.8584, 2.2945),+            Triple("Brandenburger Tor", 52.5163, 13.3777),+            Triple("Sydney Opera House", -33.8568, 151.2153),+            Triple("Tokyo Station", 35.6812, 139.7671),+            Triple("Starbucks", 47.6062, -122.3321),+            Triple("pharmacy", 40.7580, -73.9855),+            Triple("Oakland", 37.80, -122.27),+        )+    }+}