maps: offline POI search works on the planet archive (#planet4)
- Commit
96f24bafc82a0499fcddcbe870252e352df63d45- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-11 21:10 UTC (24 days ago)
- Parents
bee3b2c
Offline POI search/attributes never loaded from a planet archive, and once
loaded, name search failed at planet scale.
- PoiArchive mapped the whole file with one MappedByteBuffer, which Java
caps at 2 GiB. On the ~80 GB planet the mapping was silently truncated,
file_len never matched, and the archive path always gave up (the POI
sections sit past byte 73 GB). It now reads the header, footer and
section directory with positional reads and maps each POI section on
its own (largest: attrs, 1.19 GB in planet4); mappings outlive the
channel, so PoiIndex.Mapped.archive (the whole-file pin) is gone. All
container checks are kept (magic, build id, alignment, bounds,
overlap), plus "every payload precedes the directory".
- Name search: each token's word-index walk stopped after 2000 entries in
word order, i.e. an arbitrary Morton slice of a 30.9 M-record index, so
"Golden Gate Bridge" from SF returned a Lego model in Carlsbad and
"British Museum"/"Tartine Bakery" nothing. Now (PoiIndexWordSearch.kt):
measure every token's prefix range (two binary searches), walk the
rarest one whole (<= 200k entries) and verify the other tokens against
each candidate's own name; when every token is too common ("cafe"),
keep the capped walks and add a local pass that scans the spatial grid
in growing rings (2/10/40/150 km, 40k-record budget) around the search
centre, which also answers mid-word substrings ("izza") like the scan
path. Candidates are pre-ranked on index coordinates and only the best
5000 names decoded. Within a rank an exact whole-name match wins when it
is a place label (type 51, new in planet4: "Oakland" the city among
hundreds of "Oakland ..." shops) or local (<~55 km).
- PoiCategories.TYPE_PLACE = 51 named; detekt magic numbers in
PoiSearch/PoiIndexWords given names; PoiIndexSmartTest fixture split.
Real-archive test (PoiArchiveRealFileTest, MAMAPS_REAL_ARCHIVE gated, run
in the toolchain container against world.mamaps): all six POI sections
map (30,898,961 records; 3.97 M grid cells; 69.6 M word entries; region
links on 99.99% of sampled records); nearest/viewport answer in SF, NYC,
London, Tokyo; landmarks resolve locally; Oakland/Brooklyn/Camden Town
resolve to type-51 labels with tagged relation boundary links; 16,651 of
200,642 sampled records decode rating + review count (15,827 with a
summary); Katz's Delicatessen 4.6 / 58,703 / summary, Tartine Bakery
4.5 / 6,368 / summary.
Verified: :maps:testDevUnitTest green (incl. the real-archive suite),
./check maps (detekt + lint) green.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 e94057cacb..ec68a4295c 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt@@ -2,8 +2,11 @@ package com.vayunmathur.maps.util import com.vayunmathur.library.log.Log import java.io.File+import java.io.RandomAccessFile+import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.MappedByteBuffer+import java.nio.channels.FileChannel /** * Load the POI side files out of a single-archive `.mamaps` file.@@ -11,16 +14,23 @@ import java.nio.MappedByteBuffer * The archive carries the same six payloads as the side files (`poi_index`, * `poi_names`, and the optional `poi_attrs` / `poi_spatial` / `poi_name_index` * / `poi_region` sections, kinds 8-12 and 15) after the tile data, each 8-byte aligned and named by- * the section directory + `MAMA8` footer. This maps the one file once and- * slices views of it, then runs the same validators the multi-file path runs+ * the section directory + `MAMA8` footer. This reads the container (tile+ * header, footer, directory) with positional reads, maps each POI section on+ * its own, then runs the same validators the multi-file path runs * ([PoiIndex.attrsFromBuffer] and siblings) — only the mapping step differs, * so the checks cannot drift apart. *+ * Per-section mappings, not one whole-file mapping: a `MappedByteBuffer` is+ * capped at 2 GiB, and the planet archive is ~80 GB with its POI sections at+ * byte offsets past 70 GB. A whole-file mapping silently truncated at 2 GiB,+ * so the declared `file_len` never matched and the offline POI index never+ * loaded from a planet archive. Each POI section is far below the cap+ * (planet4: attrs 1.19 GB, the largest), and a mapping stays valid after its+ * channel closes, so each section buffer pins itself.+ * * Every access the queries make is absolute (`getInt`, `get`, duplicate +- * position for bulk), so a slice reads exactly as the whole file it came- * from: all payload offsets are section-relative either way. The single- * whole-file mapping is held in [PoiIndex.Mapped.archive], which keeps every- * slice alive; without it a slice could outlive its mapping.+ * position for bulk), so a section reads exactly as its side file would: all+ * payload offsets are section-relative either way. */ object PoiArchive { private const val TAG = "PoiArchive"@@ -83,8 +93,11 @@ object PoiArchive { */ internal fun openArchive(file: File): PoiIndex.Mapped? { if (!file.isFile) return null- return runCatching { buildMapped(PoiIndex.mapReadOnly(file), overrideDir(file)) }- .getOrElse { archiveFailure(it) }+ return runCatching {+ RandomAccessFile(file, "r").use { raf ->+ raf.channel.use { ch -> buildMapped(ch, overrideDir(file)) }+ }+ }.getOrElse { archiveFailure(it) } } /**@@ -115,8 +128,7 @@ object PoiArchive { } } - private fun buildMapped(whole: MappedByteBuffer, overrides: File?): PoiIndex.Mapped? {- whole.order(ByteOrder.LITTLE_ENDIAN)+ private fun buildMapped(whole: FileChannel, overrides: File?): PoiIndex.Mapped? { val sections = parseSections(whole) ?: return null // Overrides validate through the same validators as base slices; a // failed override degrades to the base slice, never to corrupt bytes.@@ -163,7 +175,7 @@ object PoiArchive { } private fun mappedFromSections(- whole: MappedByteBuffer,+ whole: FileChannel, sections: Map<Int, Section>, indexBuf: MappedByteBuffer, namesBuf: MappedByteBuffer,@@ -178,6 +190,20 @@ object PoiArchive { ?.let { PoiIndex.nameIndexFromBuffer(it, count) } val region = overrideOrBase(overrides, KIND_REGION, sections, whole) ?.let { regionFromBuffer(it, count) }+ return mappedOf(indexBuf, namesBuf, count, attrs, grid, words, region)+ }++ /** The [PoiIndex.Mapped] for already-validated section buffers (absent ones degrade). */+ @Suppress("LongParameterList")+ private fun mappedOf(+ indexBuf: MappedByteBuffer,+ namesBuf: MappedByteBuffer,+ count: Int,+ attrs: Pair<MappedByteBuffer, Int>?,+ grid: PoiIndex.Grid?,+ words: Pair<MappedByteBuffer, Int>?,+ region: MappedByteBuffer?,+ ): PoiIndex.Mapped { return PoiIndex.Mapped( index = indexBuf, names = namesBuf,@@ -194,19 +220,18 @@ object PoiArchive { nameIdx = words?.first, entryCount = words?.second ?: 0, region = region,- archive = whole, ).also { Log.debug( TAG, "Loaded $count POI records from archive, " +- "grid=${grid?.cellCount ?: 0} cells, words=${words?.second ?: 0}",+ "grid=${it.cellCount} cells, words=${it.entryCount}", ) } } - private fun slice(whole: MappedByteBuffer, sections: Map<Int, Section>, kind: Int): MappedByteBuffer? {+ private fun slice(whole: FileChannel, sections: Map<Int, Section>, kind: Int): MappedByteBuffer? { val s = sections[kind] ?: return null- return sliceRaw(whole, s)+ return mapSection(whole, s) } /**@@ -219,7 +244,7 @@ object PoiArchive { overrides: File?, kind: Int, sections: Map<Int, Section>,- whole: MappedByteBuffer,+ whole: FileChannel, ): MappedByteBuffer? { if (overrides != null) { validatedOverride(overrides, kind)?.let { return it }@@ -228,19 +253,29 @@ object PoiArchive { } /**- * A little-endian view of `[offset, offset + len)`.+ * A little-endian mapping of `[offset, offset + len)`. *- * Absolute gets on the view are section-relative, matching what the- * validators expect; the view shares the mapping, so no bytes are copied.+ * Absolute gets on it are section-relative, matching what the validators+ * expect. A section past the 2 GiB per-mapping cap is refused (degrades+ * as absent); its absolute offset may be anywhere in the file. */- private fun sliceRaw(whole: MappedByteBuffer, s: Section): MappedByteBuffer {- require(s.offset <= Int.MAX_VALUE && s.len <= Int.MAX_VALUE) { "section past the 2GB mapping cap" }- val dup = whole.duplicate()- dup.position(s.offset.toInt())- dup.limit((s.offset + s.len).toInt())- // slice() shares the mapping: no bytes are copied, and the parent is- // pinned by Mapped.archive.- return (dup.slice() as MappedByteBuffer).also { it.order(ByteOrder.LITTLE_ENDIAN) }+ private fun mapSection(whole: FileChannel, s: Section): MappedByteBuffer {+ require(s.len <= Int.MAX_VALUE) { "section of ${s.len} bytes is past the 2 GiB mapping cap" }+ return whole.map(FileChannel.MapMode.READ_ONLY, s.offset, s.len)+ .also { it.order(ByteOrder.LITTLE_ENDIAN) }+ }++ /** [len] bytes at absolute [offset], little-endian, or null on a short read. */+ private fun readAt(ch: FileChannel, offset: Long, len: Int): ByteBuffer? {+ val buf = ByteBuffer.allocate(len).order(ByteOrder.LITTLE_ENDIAN)+ var at = offset+ while (buf.hasRemaining()) {+ val n = ch.read(buf, at)+ if (n <= 0) return null+ at += n+ }+ buf.flip()+ return buf } /**@@ -248,39 +283,51 @@ object PoiArchive { * * Mirrors `tilecodec`'s `ArchiveView::parse` container checks — footer * magic, directory fit, build-id equality, per-entry bounds/alignment and- * overlap — so a corrupt container is refused here rather than sliced+ * overlap — so a corrupt container is refused here rather than mapped * into. Per-kind magic/version/count agreement stays in the existing- * validators, which see the same bytes either way.+ * validators, which see the same bytes either way. Unknown kinds are kept+ * in the map (a newer writer's section) and simply never asked for. */- private fun parseSections(whole: MappedByteBuffer): Map<Int, Section>? {- whole.order(ByteOrder.LITTLE_ENDIAN)- if (!hasContainer(whole)) return null- val footerAt = whole.capacity() - FOOTER_LEN- val footer = readFooter(whole, footerAt) ?: return null- val dirRange = dirRange(whole, footer) ?: return null- val out = readEntries(whole, dirRange) ?: return null- if (sectionsOverlap(out.values.toList())) return null- return out+ private fun parseSections(ch: FileChannel): Map<Int, Section>? {+ val size = ch.size()+ if (!hasContainer(ch, size)) return null+ val footer = readFooter(ch, size - FOOTER_LEN) ?: return null+ val out = readDirectory(ch, footer) ?: return null+ return out.takeUnless { sectionsOverlap(it.values.toList()) }+ }++ /** The directory's entries, or null when its count or padded length is off. */+ private fun readDirectory(ch: FileChannel, footer: Footer): Map<Int, Section>? {+ val dir = readAt(ch, footer.dirOffset, footer.dirLen.toInt()) ?: return null+ val count = dir.getInt(0)+ val aligned = (DIR_HEADER_LEN + count.coerceIn(0, MAX_SECTIONS) * ENTRY_LEN + ALIGN_MASK) /+ ALIGN_BYTES * ALIGN_BYTES+ if (count !in 0..MAX_SECTIONS || footer.dirLen != aligned.toLong()) return null+ return readEntries(dir, count, footer.dirOffset) } /** Header + footer magic present, and the declared length agrees. */- private fun hasContainer(whole: MappedByteBuffer): Boolean {- if (whole.capacity() < MIN_CONTAINER_BYTES) return false- val buildId = whole.getLong(HEADER_BUILD_ID_OFF)- val fileLen = whole.getLong(HEADER_FILE_LEN_OFF)- if (fileLen != whole.capacity().toLong()) {- Log.status(TAG, "archive declares $fileLen bytes but is ${whole.capacity()}")+ private fun hasContainer(ch: FileChannel, size: Long): Boolean {+ if (size < MIN_CONTAINER_BYTES) return false+ val head = readAt(ch, 0, HEADER_FILE_LEN_OFF + Long.SIZE_BYTES) ?: return false+ val footer = readAt(ch, size - FOOTER_LEN, FOOTER_LEN) ?: return false+ return declaresLength(head, size) && footerMatches(head, footer)+ }++ /** Whether the tile header's `file_len` is the file's real length. */+ private fun declaresLength(head: ByteBuffer, size: Long): Boolean {+ val fileLen = head.getLong(HEADER_FILE_LEN_OFF)+ if (fileLen != size) Log.status(TAG, "archive declares $fileLen bytes but is $size")+ return fileLen == size+ }++ /** Whether the footer carries the `MAMA8` magic and the header's build id. */+ private fun footerMatches(head: ByteBuffer, footer: ByteBuffer): Boolean {+ if (FOOTER_MAGIC.indices.any { footer.get(it) != FOOTER_MAGIC[it] }) {+ Log.debug(TAG, "not a single archive (bad MAMA8 magic)") return false }- val footerAt = whole.capacity() - FOOTER_LEN- for (i in FOOTER_MAGIC.indices) {- if (whole.get(footerAt + i) != FOOTER_MAGIC[i]) {- Log.debug(TAG, "not a single archive (bad MAMA8 magic)")- return false- }- }- val footerBuild = whole.getLong(footerAt + FOOTER_BUILD_OFF)- if (footerBuild != buildId) {+ if (footer.getLong(FOOTER_BUILD_OFF) != head.getLong(HEADER_BUILD_ID_OFF)) { Log.status(TAG, "archive footer build disagrees with its header") return false }@@ -289,44 +336,37 @@ object PoiArchive { private data class Footer(val dirOffset: Long, val dirLen: Long) - private fun readFooter(whole: MappedByteBuffer, footerAt: Int): Footer? {- val dirOffset = whole.getLong(footerAt + FOOTER_DIR_OFF)- val dirLen = whole.getLong(footerAt + FOOTER_LEN_OFF)+ private fun readFooter(ch: FileChannel, footerAt: Long): Footer? {+ val footer = readAt(ch, footerAt, FOOTER_LEN) ?: return null+ val dirOffset = footer.getLong(FOOTER_DIR_OFF)+ val dirLen = footer.getLong(FOOTER_LEN_OFF) if (dirOffset < 0 || dirLen < DIR_HEADER_LEN || dirOffset + dirLen > footerAt) return null- if (dirOffset > Int.MAX_VALUE || dirOffset + dirLen > Int.MAX_VALUE) return null+ // The directory itself is tiny (count is capped), wherever it sits in the file.+ if (dirLen > DIR_HEADER_LEN + MAX_SECTIONS * ENTRY_LEN + ALIGN_BYTES) return null return Footer(dirOffset, dirLen) } - private fun dirRange(whole: MappedByteBuffer, footer: Footer): IntRange? {- val count = whole.getInt(footer.dirOffset.toInt())- if (count < 0 || count > MAX_SECTIONS) return null- val want = DIR_HEADER_LEN + count * ENTRY_LEN- val aligned = (want + ALIGN_MASK) / ALIGN_BYTES * ALIGN_BYTES- if (footer.dirLen != aligned.toLong()) return null- val at = footer.dirOffset.toInt() + DIR_HEADER_LEN- return at until at + count * ENTRY_LEN- }-- private fun readEntries(whole: MappedByteBuffer, range: IntRange): Map<Int, Section>? {+ private fun readEntries(dir: ByteBuffer, count: Int, dirOffset: Long): Map<Int, Section>? { val out = LinkedHashMap<Int, Section>() var prevKind = -1- var at = range.first- while (at < range.last) {- val kind = whole.get(at).toInt() and BYTE_MASK- if (whole.get(at + ENTRY_PAD_1) != 0.toByte() ||- whole.get(at + ENTRY_PAD_2) != 0.toByte() ||- whole.get(at + ENTRY_PAD_3) != 0.toByte()+ for (n in 0 until count) {+ val at = DIR_HEADER_LEN + n * ENTRY_LEN+ val kind = dir.get(at).toInt() and BYTE_MASK+ if (dir.get(at + ENTRY_PAD_1) != 0.toByte() ||+ dir.get(at + ENTRY_PAD_2) != 0.toByte() ||+ dir.get(at + ENTRY_PAD_3) != 0.toByte() ) { return null }- if (whole.getInt(at + ENTRY_RESERVED_OFF) != 0) return null- if (kind <= prevKind) return null+ if (dir.getInt(at + ENTRY_RESERVED_OFF) != 0) return null+ if (kind == 0 || kind <= prevKind) return null prevKind = kind- val offset = whole.getLong(at + ENTRY_OFFSET_OFF)- val len = whole.getLong(at + ENTRY_LEN_OFF)- if (len <= 0 || offset % ALIGN != 0L) return null+ val offset = dir.getLong(at + ENTRY_OFFSET_OFF)+ val len = dir.getLong(at + ENTRY_LEN_OFF)+ if (len <= 0 || offset < 0 || offset % ALIGN != 0L) return null+ // Every payload sits before the directory; checked without overflow.+ if (offset > dirOffset || len > dirOffset - offset) return null out[kind] = Section(offset, len)- at += ENTRY_LEN } return out }
maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.ktindex 435b03ab6c..8ddbf7ff17 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt@@ -193,6 +193,9 @@ object PoiCategories { else -> null } + /** Place labels (cities, towns, villages…), searchable since planet4 (`osm_ingest` `TYPE_PLACE`). */+ internal const val TYPE_PLACE = 51+ private const val TYPE_RESTAURANT = 0 private const val TYPE_CAFE = 1 private const val TYPE_FAST_FOOD = 2
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 118570571a..66bfb774bc 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -31,7 +31,7 @@ import java.nio.channels.FileChannel * Both are laid out in `scripts/maps/osm_ingest/src/poi_side.rs`. * * It exposes a name search and a spatial nearest lookup, so a POI query can resolve- * locally without a Google call. Everything is a harmless no-op until the index and+ * locally, with no network call. Everything is a harmless no-op until the index and * the name pool are present (they ship from the same host as the graph); queries then * return empty lists. The three side files are each separately optional, and each is * refused rather than trusted when its record count disagrees with the index — they@@ -211,9 +211,6 @@ object PoiIndex { internal val entryCount: Int = 0, /** The region sidecar, or null when absent or mismatched. */ internal val region: MappedByteBuffer? = null,- /** The whole archive mapping, when loaded from one file: pins every slice above. */- @Suppress("unused")- val archive: MappedByteBuffer? = null, ) { internal fun latE7(i: Int): Int = index.getInt(i * RECORD_BYTES) internal fun lonE7(i: Int): Int = index.getInt(i * RECORD_BYTES + LON_FIELD_OFF)
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.ktnew file mode 100644index 0000000000..3a4d650bd9--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt@@ -0,0 +1,233 @@+package com.vayunmathur.maps.util++/**+ * Planet-scale halves of the indexed name search ([searchByWordIndex]).+ *+ * The word index was designed against state-sized archives, where walking the first+ * [PoiIndex.CANDIDATE_CAP] entries of a word's prefix range saw every match. A planet+ * (planet4: 30.9 M records, 69.6 M word entries) breaks that: a range is sorted by word and+ * then by ordinal, ordinals are Morton-sorted, so a capped walk sees one arbitrary corner of+ * the world. Two fixes, both bounded:+ *+ * * [rarestTokenMatches] — measure every token's range (two binary searches each), walk the+ * smallest one whole, and check the other tokens against each candidate's own name.+ * * [localWordMatches] — scan the spatial grid around the search centre in growing rings,+ * under a visit budget, so a common word ("cafe") still finds what is near the user. It+ * reads each name anyway, so it also answers mid-word substrings ("izza" → "Pizza") the+ * way the scan path does, which a sorted word index cannot.+ */++/** Rank of a name that starts with the whole phrase (tokens on its first words, in order). */+private const val RANK_PHRASE = 0++/** Rank of a name where every token starts some word. */+private const val RANK_WORDS = 1++/** No match. */+private const val RANK_NONE = -1++private const val BYTE_MASK = 0xFF++/** Rings the local pass grows through, in metres from the search centre. */+private val LOCAL_RADII_M = doubleArrayOf(2_000.0, 10_000.0, 40_000.0, 150_000.0)++/** Records the local pass checks at most, across all rings. */+private const val LOCAL_VISIT_BUDGET = 40_000++private const val METERS_PER_DEGREE_LAT = 111_320.0+private const val MIN_COS_LAT = 1e-6+private const val E7_PER_DEGREE = 1e7++/** Entries `[first, last]` whose word starts with [key]; empty when none. */+internal fun PoiIndex.Mapped.prefixRange(key: ByteArray): IntRange {+ if (nameIdx == null || entryCount == 0) return IntRange.EMPTY+ val lo = lowerBoundWord(key)+ val hi = nextPrefix(key)?.let { lowerBoundWord(it) } ?: entryCount+ return lo until hi+}++/**+ * The smallest key strictly greater than every key starting with [key] (its last+ * non-0xFF byte incremented, the rest dropped), or null when no such key exists.+ */+private fun nextPrefix(key: ByteArray): ByteArray? {+ var i = key.size - 1+ while (i >= 0 && (key[i].toInt() and BYTE_MASK) == BYTE_MASK) i--+ if (i < 0) return null+ return key.copyOf(i + 1).also { it[i] = (it[i] + 1).toByte() }+}++/**+ * Ordinal → rank for every record whose name matches all [keys], found by walking the+ * rarest key's whole prefix range; null when even that range is longer than [walkCap]+ * (the caller then falls back to capped walks plus the local pass).+ */+internal fun PoiIndex.Mapped.rarestTokenMatches(keys: List<ByteArray>, walkCap: Int): Map<Int, Int>? {+ if (keys.isEmpty() || nameIdx == null) return null+ val ranges = keys.map { prefixRange(it) }+ val rarest = ranges.minBy { it.last - it.first + 1 }+ val size = rarest.last - rarest.first + 1+ if (size <= 0) return emptyMap()+ if (size > walkCap) return null+ val out = HashMap<Int, Int>()+ for (i in rarest) {+ val ordinal = entryOrdinal(i)+ if (ordinal < 0 || ordinal >= count || ordinal in out) continue+ val rank = nameTokenRank(ordinal, keys)+ if (rank != RANK_NONE) out[ordinal] = rank+ }+ return out+}++/**+ * The pre-planet exact pass: per-token walks capped at [cap] entries, intersected on the+ * ordinal, each survivor re-ranked from its own name. Only used when every token is too+ * common to walk whole.+ */+internal fun cappedExactMatches(m: PoiIndex.Mapped, keys: List<ByteArray>, cap: Int): Map<Int, Int> {+ var ordinals: Set<Int>? = null+ for (key in keys) {+ val hits = m.wordPrefixMatches(key, cap).mapTo(HashSet()) { it[0] }+ ordinals = ordinals?.intersect(hits) ?: hits+ }+ val out = HashMap<Int, Int>()+ for (o in ordinals.orEmpty()) {+ val rank = m.nameTokenRank(o, keys)+ if (rank != RANK_NONE) out[o] = rank+ }+ return out+}++/**+ * Ordinal → rank for records near ([lat],[lon]) whose name matches all [keys]: rings of+ * [LOCAL_RADII_M] through the spatial index, nearest ring first, stopping once [want]+ * matches are in hand or [LOCAL_VISIT_BUDGET] records were checked.+ */+internal fun PoiIndex.Mapped.localWordMatches(+ keys: List<ByteArray>,+ lat: Double,+ lon: Double,+ want: Int,+): Map<Int, Int> {+ if (keys.isEmpty() || count == 0) return emptyMap()+ val out = HashMap<Int, Int>()+ val seen = HashSet<Int>()+ var visited = 0+ val cosLat = Math.cos(Math.toRadians(lat)).coerceAtLeast(MIN_COS_LAT)+ for (radius in LOCAL_RADII_M) {+ val dLat = radius / METERS_PER_DEGREE_LAT+ val dLon = radius / (METERS_PER_DEGREE_LAT * cosLat)+ forEachInBbox(+ ((lat - dLat) * E7_PER_DEGREE).toInt(),+ ((lat + dLat) * E7_PER_DEGREE).toInt(),+ ((lon - dLon) * E7_PER_DEGREE).toInt(),+ ((lon + dLon) * E7_PER_DEGREE).toInt(),+ ) { ordinal, _, _ ->+ if (seen.add(ordinal)) {+ visited+++ var rank = nameTokenRank(ordinal, keys)+ if (rank == RANK_NONE && nameContainsAll(ordinal, keys)) rank = RANK_WORDS+ if (rank != RANK_NONE) out[ordinal] = rank+ }+ visited < LOCAL_VISIT_BUDGET+ }+ if (out.size >= want || visited >= LOCAL_VISIT_BUDGET) break+ }+ return out+}++/**+ * How record [ordinal]'s name matches [keys]: [RANK_PHRASE] when word `t` starts with key+ * `t` for every token, [RANK_WORDS] when every key starts some word, else [RANK_NONE].+ * Same word split and ASCII case fold as the index itself (`poi_side.rs`).+ */+internal fun PoiIndex.Mapped.nameTokenRank(ordinal: Int, keys: List<ByteArray>): Int {+ val off = nameOff(ordinal)+ val matched = BooleanArray(keys.size)+ var phrase = true+ var w = 0+ while (true) {+ val range = wordRange(off, w) ?: break+ for (t in keys.indices) {+ val hit = wordStartsWith(range, keys[t])+ if (hit) matched[t] = true+ if (w == t && !hit) phrase = false+ }+ w+++ }+ if (w < keys.size) phrase = false+ return when {+ matched.any { !it } -> RANK_NONE+ phrase -> RANK_PHRASE+ else -> RANK_WORDS+ }+}++/** Whether every key occurs somewhere in record [ordinal]'s name (ASCII case-folded bytes). */+private fun PoiIndex.Mapped.nameContainsAll(ordinal: Int, keys: List<ByteArray>): Boolean {+ val off = nameOff(ordinal)+ if (off < 0 || off >= namesLen) return false+ var end = off+ while (end < namesLen && names.get(end).toInt() != 0) end+++ val folded = ByteArray(end - off) { asciiLowerW(names.get(off + it)).toByte() }+ return keys.all { key -> indexOf(folded, key) >= 0 }+}++/** First index of [needle] in [hay], or -1. Names are short; a naive scan is enough. */+private fun indexOf(hay: ByteArray, needle: ByteArray): Int {+ if (needle.isEmpty()) return 0+ outer@ for (i in 0..hay.size - needle.size) {+ for (j in needle.indices) if (hay[i + j] != needle[j]) continue@outer+ return i+ }+ return -1+}++/** Candidates whose names are decoded and boost-ranked; the rest lose on (rank, distance). */+private const val DECODE_SHORTLIST = 5_000++/**+ * Fuzzy pass: ordinal → rank 2 for names where every token matches exactly or within one+ * edit, minus the exact [ordinals]. Runs even when the exact pass hit — a typo'd name+ * ("Piza Kitchen" for "pizza") should surface below the exact hits, not vanish. Tokens under+ * [MIN_TYPO_TOKEN_LEN] chars are all typo-noise and contribute their exact matches only.+ */+internal fun fuzzyMatches(+ m: PoiIndex.Mapped,+ tokens: List<String>,+ exact: List<Map<Int, Int>>,+ ordinals: Set<Int>,+ candidateCap: Int,+): Map<Int, Int> {+ var fuzzyOrdinals: Set<Int>? = null+ for (t in tokens.indices) {+ val set = HashSet(exact[t].keys)+ set.addAll(ordinals)+ if (tokens[t].length >= MIN_TYPO_TOKEN_LEN) {+ set.addAll(m.fuzzyWordMatches(tokens[t], candidateCap).keys)+ }+ fuzzyOrdinals = fuzzyOrdinals?.intersect(set) ?: set+ }+ return fuzzyOrdinals.orEmpty().filter { it !in ordinals }.associateWith { 2 }+}++/**+ * At most [DECODE_SHORTLIST] of [candidates] (ordinal, rank), best (rank, distance) first.+ * A whole-range walk can hand back tens of thousands of matches; decoding every name (for+ * the record and the boost) would dominate the search, so the cut uses only the index's+ * coordinates.+ */+internal fun PoiIndex.Mapped.shortlist(+ candidates: List<Pair<Int, Int>>,+ lat: Double,+ lon: Double,+): List<Pair<Int, Int>> {+ if (candidates.size <= DECODE_SHORTLIST) return candidates+ return candidates.sortedWith(+ compareBy<Pair<Int, Int>> { it.second }.thenBy { (o, _) -> distanceSqTo(o, lat, lon) },+ ).take(DECODE_SHORTLIST)+}++/** Squared degree distance from record [ordinal] to ([lat],[lon]), straight from the index. */+private fun PoiIndex.Mapped.distanceSqTo(ordinal: Int, lat: Double, lon: Double): Double =+ PoiIndex.distanceSq(lat, lon, latE7(ordinal) * PoiIndex.E7_TO_DEGREES, lonE7(ordinal) * PoiIndex.E7_TO_DEGREES)
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.ktindex 06bde71d73..fc87cfbfda 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt@@ -42,10 +42,10 @@ internal fun poiQueryKey(query: String): ByteArray { return ByteArray(raw.size) { asciiLowerW(raw[it]).toByte() } } -private fun PoiIndex.Mapped.entryOrdinal(i: Int): Int =+internal fun PoiIndex.Mapped.entryOrdinal(i: Int): Int = nameIdx!!.getInt(PoiIndex.NAME_INDEX_HEADER_BYTES + INT_SLOT_BYTES * i) -private fun PoiIndex.Mapped.entryWordIdx(i: Int): Int {+internal fun PoiIndex.Mapped.entryWordIdx(i: Int): Int { val off = PoiIndex.NAME_INDEX_HEADER_BYTES + INT_SLOT_BYTES * entryCount + i return nameIdx!!.get(off).toInt() and WORD_BYTE_MASK }@@ -54,7 +54,7 @@ private fun PoiIndex.Mapped.entryWordIdx(i: Int): Int { * Byte range of the [wordIdx]th whitespace-separated word of the name at [off], or * null when the name has fewer words. Must match `word_at` in `poi_side.rs`. */-private fun PoiIndex.Mapped.wordRange(off: Int, wordIdx: Int): IntRange? {+internal fun PoiIndex.Mapped.wordRange(off: Int, wordIdx: Int): IntRange? { if (off < 0 || off >= namesLen) return null var i = off var idx = 0@@ -100,7 +100,7 @@ private fun PoiIndex.Mapped.compareWord(range: IntRange, key: ByteArray): Int { return len - key.size } -private fun PoiIndex.Mapped.wordStartsWith(range: IntRange, key: ByteArray): Boolean {+internal fun PoiIndex.Mapped.wordStartsWith(range: IntRange, key: ByteArray): Boolean { if (range.last - range.first + 1 < key.size) return false for (k in key.indices) { if (asciiLowerW(names.get(range.first + k)) != (key[k].toInt() and WORD_BYTE_MASK)) return false@@ -109,7 +109,7 @@ private fun PoiIndex.Mapped.wordStartsWith(range: IntRange, key: ByteArray): Boo } /** First entry whose word is >= [key], or [entryCount]. */-private fun PoiIndex.Mapped.lowerBoundWord(key: ByteArray): Int {+internal fun PoiIndex.Mapped.lowerBoundWord(key: ByteArray): Int { var lo = 0 var hi = entryCount while (lo < hi) {@@ -271,7 +271,7 @@ private fun rankName(name: String?, q: String, tokens: List<String>): Int? { val lower = name.lowercase() if (lower.startsWith(q)) return 0 if (tokens.all { lower.contains(it) }) return 1- if (tokens.size > 1 || (tokens.size == 1 && tokens[0].length >= 3)) {+ if (tokens.size > 1 || (tokens.size == 1 && tokens[0].length >= MIN_TYPO_TOKEN_LEN)) { val words = splitTokens(lower) if (tokens.all { token -> tokenMatchesWord(token, lower, words) }) return 2 }@@ -283,7 +283,7 @@ private fun tokenMatchesWord(token: String, lowerName: String, words: List<Strin if (lowerName.contains(token)) return true // Tokens under 3 chars are all typo-noise ("al" is one edit from "ax", // "at", "an", ...); they only match exactly.- if (token.length < 3) return false+ if (token.length < MIN_TYPO_TOKEN_LEN) return false return words.any { editDistanceLE1(token, it) } } @@ -354,56 +354,59 @@ internal fun searchByWordIndex( if (tokens.isEmpty()) return emptyList() val keys = tokens.map { poiQueryKey(it) } - // Exact pass: per-token prefix matches, intersected on the ordinal.+ // Exact pass, planet-safe: walk the RAREST token's whole prefix range and verify the+ // other tokens against each candidate's own name ([rarestTokenMatches]). The old+ // per-token walks stopped at [candidateCap] entries in word order, which at planet scale+ // (30.9 M records, 69.6 M word entries in planet4) is an arbitrary Morton slice of the+ // world: "golden" alone has tens of thousands of entries, so "Golden Gate Bridge" from+ // SF intersected to a Lego model in Carlsbad and "British Museum" to nothing. When even+ // the rarest token is too common to walk whole ("cafe"), fall back to the capped walks;+ // the local pass below then supplies the nearby hits.+ val exactRanks: Map<Int, Int> = m.rarestTokenMatches(keys, FULL_WALK_CAP)+ ?: cappedExactMatches(m, keys, candidateCap) val exact = keys.map { key ->- m.wordPrefixMatches(key, candidateCap).associate { it[0] to it[1] }- }- var ordinals: Set<Int> = exact[0].keys- for (t in 1 until exact.size) ordinals = ordinals.intersect(exact[t].keys)-- // Rank 0 needs the tokens on the name's first words in order.- fun isPhrasePrefix(o: Int): Boolean {- for (t in exact.indices) {- if (exact[t][o] != t) return false- }- return true- }-- // Fuzzy pass: every token must match exactly or within one edit. Runs even- // when the exact pass hit — a typo'd name ("Piza Kitchen" for "pizza")- // should surface below the exact hits, not vanish. Tokens under 3 chars- // are all typo-noise and contribute their exact matches only.- val fuzzy = HashMap<Int, Int>()- val fuzzyPerToken = keys.mapIndexed { t, _ ->- if (tokens[t].length >= 3) {- val set = HashSet(exact[t].keys)- set.addAll(m.fuzzyWordMatches(tokens[t], candidateCap).keys)- set+ if (keys.size == 1) {+ emptyMap() } else {- exact[t].keys+ m.wordPrefixMatches(key, FUZZY_EXACT_SEED_CAP).associate { it[0] to it[1] } } }- var fuzzyOrdinals: Set<Int>? = null- for (set in fuzzyPerToken) {- fuzzyOrdinals = if (fuzzyOrdinals == null) set else fuzzyOrdinals.intersect(set)- }- for (o in (fuzzyOrdinals ?: emptySet())) {- if (o !in ordinals) fuzzy[o] = 2- }-- val out = ArrayList<WordRanked>(minOf(candidateCap, ordinals.size + fuzzy.size))- for (o in ordinals) {- out.add(wordRanked(m, o, if (isPhrasePrefix(o)) 0 else 1, nearLat, nearLon, boost))- }- for ((o, rank) in fuzzy) {+ val local = m.localWordMatches(keys, nearLat, nearLon, limit)+ val ordinals: Set<Int> = exactRanks.keys + local.keys+ fun isPhrasePrefix(o: Int): Boolean = (exactRanks[o] ?: local[o]) == 0++ val fuzzy = fuzzyMatches(m, tokens, exact, ordinals, candidateCap)+ val shortlist = m.shortlist(+ ordinals.map { it to if (isPhrasePrefix(it)) 0 else 1 } + fuzzy.toList(),+ nearLat,+ nearLon,+ )+ val out = ArrayList<WordRanked>(shortlist.size)+ for ((o, rank) in shortlist) { out.add(wordRanked(m, o, rank, nearLat, nearLon, boost)) }+ // Within a rank, a name that IS the query comes first when it is a place label (type 51:+ // "Oakland" the city, among hundreds of "Oakland …" businesses nearer the centre — a city+ // is searched for from anywhere) or is local (a same-named bar on another continent must+ // not beat the "Tokyo Station Cafe" next to the user); then the user's signal; then+ // distance.+ val whole = query.trim()+ fun exactTier(r: WordRanked): Boolean =+ r.record.name.equals(whole, ignoreCase = true) &&+ (r.record.type == PoiCategories.TYPE_PLACE || r.distSq <= EXACT_LOCAL_DEG_SQ) out.sortWith(- compareBy<WordRanked> { it.rank }.thenByDescending { it.boost }.thenBy { it.distSq },+ compareBy<WordRanked> { it.rank }+ .thenBy { !exactTier(it) }+ .thenByDescending { it.boost }+ .thenBy { it.distSq }, ) return out.take(limit).map { it.record } } +/** "Local" for the exact-name tier: ~0.5° (≈55 km) from the centre, squared. */+private const val EXACT_LOCAL_DEG_SQ = 0.25++ private fun wordRanked( m: PoiIndex.Mapped, ordinal: Int,@@ -437,7 +440,7 @@ private fun wordRanked( * deliberately misses (documented: first-letter typos need a different * index). Tokens under 3 chars are all typo-noise and skip the pass. */-private fun PoiIndex.Mapped.fuzzyWordMatches(+internal fun PoiIndex.Mapped.fuzzyWordMatches( token: String, candidateCap: Int, ): Map<Int, Int> {@@ -450,7 +453,7 @@ private fun PoiIndex.Mapped.fuzzyWordMatches( } // A mid-word substitution ("pizxa" for "pizza") shares no full deletion // with the true word, but does share a two-shorter prefix.- if (tokenLower.length >= 5) {+ if (tokenLower.length >= SUBSTITUTION_MIN_LEN) { variants.add(tokenLower.dropLast(2)) } val out = HashMap<Int, Int>()@@ -477,6 +480,22 @@ private fun PoiIndex.Mapped.wordWithinOneEdit(ordinal: Int, wordIdx: Int, token: return editDistanceLE1(token, String(word)) } +/**+ * Entries the exact pass will walk for the rarest query token before it falls back to the+ * capped walks: a planet's rare words ("tartine", "golden") are well under this, its common+ * ones ("cafe", "street") well over.+ */+private const val FULL_WALK_CAP = 200_000++/** Per-token exact seed for the fuzzy intersection (its exact half), kept small. */+private const val FUZZY_EXACT_SEED_CAP = 2_000++/** Shortest token the typo passes consider (shorter ones are all typo-noise). */+internal const val MIN_TYPO_TOKEN_LEN = 3++/** Shortest token whose mid-word substitution is looked up via a two-shorter prefix. */+private const val SUBSTITUTION_MIN_LEN = 5+ /** Per-variant walk cap and total fuzzy-candidate cap for one token. */ private const val FUZZY_PER_VARIANT_CAP = 50 private const val FUZZY_CANDIDATE_CAP = 500
maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.ktindex ee80d82e8c..7d31e34674 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.kt@@ -44,7 +44,7 @@ object PoiSearch { /** Singular form of a token for category matching ("restaurants" -> "restaurant"). */ fun singular(token: String): String =- if (token.length > 3 && token.endsWith('s')) token.dropLast(1) else token+ if (token.length > MIN_PLURAL_LEN && token.endsWith('s')) token.dropLast(1) else token /** * Tier at which the normalised [name] matches the normalised query@@ -82,8 +82,8 @@ object PoiSearch { /** Typo budget for a token: none for short tokens, growing with length. */ fun maxEditDistance(token: String): Int = when {- token.length < 4 -> 0- token.length < 8 -> 1+ token.length < ONE_TYPO_MIN_LEN -> 0+ token.length < TWO_TYPO_MIN_LEN -> 1 else -> 2 } @@ -118,7 +118,16 @@ object PoiSearch { val match = COORD_QUERY.matchEntire(query) ?: return null val lat = match.groupValues[1].toDoubleOrNull() ?: return null val lon = match.groupValues[2].toDoubleOrNull() ?: return null- if (lat !in -90.0..90.0 || lon !in -180.0..180.0) return null+ if (lat !in -MAX_LAT..MAX_LAT || lon !in -MAX_LON..MAX_LON) return null return lat to lon }++ /** Tokens longer than this lose a trailing "s" for category matching. */+ private const val MIN_PLURAL_LEN = 3+ /** Shortest token allowed one typo, and the shortest allowed two. */+ private const val ONE_TYPO_MIN_LEN = 4+ private const val TWO_TYPO_MIN_LEN = 8+ /** Valid WGS84 latitude / longitude magnitudes for a typed coordinate. */+ private const val MAX_LAT = 90.0+ private const val MAX_LON = 180.0 }
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.ktnew file mode 100644index 0000000000..73f013db75--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveRealFileTest.kt@@ -0,0 +1,200 @@+package com.vayunmathur.maps.util++import java.io.File+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:+ *+ * ```+ * 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 fun load(): PoiIndex.Mapped {+ val file = archive()+ assertTrue(PoiIndex.reloadArchive(file), "the app could not map POI sections from $file")+ return assertNotNull(PoiIndex.mappedForQuery())+ }++ @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")+ 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")+ }++ @Test+ fun `nearest and viewport queries answer in four cities`() {+ load()+ for ((city, lat, lon) in CITIES) {+ 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")+ }+ }++ @Test+ fun `name search finds landmarks and the new type-51 place labels`() {+ load()+ 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'")+ val d = PoiIndex.distanceSq(hits[0].lat, hits[0].lon, lat, lon)+ 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 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")+ assertNotNull(place, "'$query' has no type-51 place label among ${hits.map { it.name to it.type }}")+ assertEquals("Place", PoiCategories.label(place.type))+ assertTrue(place.regionId != 0L, "'$query' place label carries no boundary link")+ // 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}")+ }+ }++ @Test+ fun `attributes decode incl rating review count and summary`() {+ val m = load()+ var withAttrs = 0+ var rated = 0+ var counted = 0+ var summarised = 0+ var example: PoiIndex.PoiAttributes? = null+ // Stride across the whole index: cheap, and covers every region of the file.+ val stride = (m.count / ATTR_SAMPLES).coerceAtLeast(1)+ var i = 0+ while (i < m.count) {+ val a = PoiIndex.attributesAt(i)+ if (a != null) {+ withAttrs+++ if (a.rating != null) {+ rated+++ assertTrue(a.rating in 1.0..5.0)+ }+ if (a.reviewCount != null) counted+++ if (a.reviewSummary != null) {+ summarised+++ if (example == null) example = a+ }+ }+ i += stride+ }+ println("attrs sampled=${m.count / stride} with=$withAttrs rating=$rated count=$counted summary=$summarised")+ println("example with summary: $example")+ assertTrue(withAttrs > 0, "no attributes decoded")+ 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")+ }++ @Test+ fun `well known places show archive rating count and summary`() {+ load()+ var rated = 0+ var summarised = 0+ 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(+ "review '$query' -> ${hit?.name} rating=${attrs?.rating} count=${attrs?.reviewCount} " ++ "summary=${attrs?.reviewSummary?.take(SUMMARY_PREVIEW)}",+ )+ if (attrs?.rating != null) rated+++ if (attrs?.rating != null && attrs.reviewCount != null && attrs.reviewSummary != null) summarised+++ }+ // 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(summarised >= 1, "no famous place carries rating + count + summary")+ }++ @Test+ fun `boundary links cover most records`() {+ val m = load()+ var linked = 0+ val stride = (m.count / ATTR_SAMPLES).coerceAtLeast(1)+ var sampled = 0+ var i = 0+ while (i < m.count) {+ if (m.regionId(i) != 0L) linked+++ sampled+++ i += stride+ }+ println("region links $linked/$sampled sampled")+ assertTrue(linked * 2 > sampled, "fewer than half the sampled POIs link to a boundary")+ }++ private companion object {+ const val ENV = "MAMAPS_REAL_ARCHIVE"+ const val MIN_PLANET_RECORDS = 10_000_000+ const val TYPE_PLACE = 51+ const val SPACE_MASK = 3L+ const val ATTR_SAMPLES = 200_000+ /** ~0.5 degrees squared: "in the same metro". */+ const val NEAR_DEG_SQ = 0.25++ 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),+ )+ val LANDMARKS = listOf(+ Triple("Golden Gate Bridge", 37.7749, -122.4194),+ Triple("Empire State Building", 40.7580, -73.9855),+ Triple("British Museum", 51.5074, -0.1278),+ Triple("Tokyo Station", 35.6812, 139.7671),+ )+ const val SUMMARY_PREVIEW = 80+ val FAMOUS = listOf(+ Triple("Tartine Bakery", 37.7614, -122.4241),+ Triple("Golden Gate Park", 37.7694, -122.4862),+ Triple("Katz's Delicatessen", 40.7223, -73.9874),+ Triple("Central Park", 40.7829, -73.9654),+ Triple("British Museum", 51.5194, -0.1270),+ Triple("Borough Market", 51.5055, -0.0910),+ Triple("Senso-ji", 35.7148, 139.7967),+ Triple("Tokyo Tower", 35.6586, 139.7454),+ )+ val PLACES = listOf(+ Triple("Oakland", 37.80, -122.27),+ Triple("Brooklyn", 40.65, -73.95),+ Triple("Camden Town", 51.539, -0.1426),+ )+ }+}
maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.ktindex 1af249bd1b..eb9ccad75a 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt@@ -51,6 +51,14 @@ class PoiIndexSmartTest { spatialFromE7(b.latE7, b.lonE7), ) }+ val nameOff = writeNames(dir, sorted)+ writeIndex(dir, sorted, nameOff)+ writeWordIndex(dir, sorted)+ writeGrid(dir, sorted)+ assertTrue(PoiIndex.reload(dir), "fixture did not map")+ }++ private fun writeNames(dir: File, sorted: List<Poi>): Map<String, Int> { val nameOff = LinkedHashMap<String, Int>() val namesOut = java.io.ByteArrayOutputStream() for (p in sorted) {@@ -62,6 +70,10 @@ class PoiIndexSmartTest { } File(dir, PoiIndex.NAMES_FILE).writeBytes(namesOut.toByteArray()) + return nameOff+ }++ private fun writeIndex(dir: File, sorted: List<Poi>, nameOff: Map<String, Int>) { val index = ByteBuffer.allocate(sorted.size * 14).order(ByteOrder.LITTLE_ENDIAN) for (p in sorted) { index.putInt(p.latE7)@@ -70,7 +82,9 @@ class PoiIndexSmartTest { index.putShort(p.type.toShort()) } File(dir, PoiIndex.INDEX_FILE).writeBytes(index.array())+ } + private fun writeWordIndex(dir: File, sorted: List<Poi>) { val entries = ArrayList<Pair<Int, Int>>() sorted.forEachIndexed { ordinal, p -> words(p.name).indices.take(255).forEach { wordIdx -> entries.add(ordinal to wordIdx) }@@ -90,7 +104,9 @@ class PoiIndexSmartTest { entries.forEach { nameIndex.putInt(it.first) } entries.forEach { nameIndex.put(it.second.toByte()) } File(dir, PoiIndex.NAME_INDEX_FILE).writeBytes(nameIndex.array())+ } + private fun writeGrid(dir: File, sorted: List<Poi>) { val lat0 = sorted.minOfOrNull { it.latE7 } ?: 0 val lon0 = sorted.minOfOrNull { it.lonE7 } ?: 0 val cols = if (sorted.isEmpty()) 0 else axis(sorted.maxOf { it.lonE7 }, lon0) + 1@@ -121,8 +137,6 @@ class PoiIndexSmartTest { cellOff.forEach { grid.putInt(it) } pairs.forEach { grid.putInt(it.second) } File(dir, PoiIndex.SPATIAL_FILE).writeBytes(grid.array())-- assertTrue(PoiIndex.reload(dir), "fixture did not map") } @Test
maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.ktindex 4f069605c0..fac4c14321 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt@@ -500,6 +500,28 @@ class PoiIndexTest { assertFalse(b?.isEmpty ?: true, "a summary alone is a record") } + @Test+ fun `the place sheet model takes rating count and summary from archive attrs`() {+ // The only review source the app has: poi_attrs keys 10/11/12 -> osmPlace ->+ // GenericPlace, which PlaceSheetHeader (rating/count) and PlaceSheet+ // (ReviewSummaryRow) render. No Google call is involved.+ val recs = load(listOf(Poi(377_749_000, -1_224_194_000, 1, "Diner")), attrs = emptyMap())+ load(+ recs,+ attrs = mapOf(0 to "+1-555-DINER"),+ attrFields = mapOf(+ 0 to listOf(KEY_RATING to "4.3", KEY_REVIEW_COUNT to "1234", KEY_REVIEW_SUMMARY to "Huge portions."),+ ),+ )+ val place = kotlinx.coroutines.runBlocking {+ com.vayunmathur.maps.data.osmPlace("Diner", com.vayunmathur.library.map.GeoPoint(-122.4194, 37.7749))+ }+ assertEquals(4.3, place.rating)+ assertEquals(1234, place.reviewCount)+ assertEquals("Huge portions.", place.reviewSummary)+ assertEquals("+1-555-DINER", place.phone)+ }+ @Test fun `attributesNear returns null when nothing nearby carries attributes`() { load(