maps: overlay scheduling plus rebase and section overrides
- Commit
fbc87f7031281787fa2587d1847c71e3a8de3c48- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 00:50 UTC (1 month ago)
- Parents
58845a5
Diff
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex acd1fe9625..ea1ca50547 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -33,6 +33,7 @@ import com.vayunmathur.maps.ui.settings.MapSettingsPage import com.vayunmathur.maps.data.MapPreferences import com.vayunmathur.maps.data.ThemeMode import com.vayunmathur.maps.util.MapTileCache+import com.vayunmathur.maps.util.MapOverlayWorker import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.NavigationService import com.vayunmathur.maps.util.NavigationSessionManager@@ -76,6 +77,9 @@ class MainActivity : MaActivity() { // FIRST_PARTY: data.maproj.org tiles + amenities + api.maproj.org -> ISRG+GTS NetworkClient.init(this, TrustBundle.FIRST_PARTY) intentLauncher = IntentLauncher(this)+ // Daily overlay check chain (UNMETERED): KEEP leaves an existing chain+ // alone; the toggle gates inside syncAutoUpdateSchedule.+ syncOverlaySchedule() // Reclaim the ~44 MB bundled basemap copied into filesDir by older // builds; the basemap now streams live and is cached on demand. File(filesDir, "world_z0-6.pmtiles").delete()@@ -84,6 +88,14 @@ class MainActivity : MaActivity() { handleIntent(intent) } + /** Enqueue the daily overlay check when the auto-update toggle is on. */+ private fun syncOverlaySchedule() {+ val ds = DataStoreUtils.getInstance(this)+ if (ds.getBoolean(MapPreferences.KEY_MAP_AUTO_UPDATE, MapPreferences.DEFAULT_MAP_AUTO_UPDATE)) {+ MapOverlayWorker.scheduleAuto(this)+ }+ }+ @Composable override fun AppTheme(content: @Composable () -> Unit) { val ds = DataStoreUtils.getInstance(this)
maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.ktindex 31416111f4..887a1821b7 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt@@ -186,4 +186,22 @@ object MapOverlay { dir.mkdirs() File(dir, MANIFEST_FILE).writeText(text) }++ /**+ * Crash recovery for the rebase two-rename swap (`current` <- `.next`+ * via `.prev`). States:+ * - `.prev` + current: swap completed before cleanup → drop `.prev`.+ * - `.prev`, no current: crashed between renames → restore `.prev`.+ * - `.next` alone: crashed before any rename → leave for resume.+ */+ fun recoverRebaseCrash(root: File, baseName: String) {+ val current = File(root, baseName)+ val prev = File(root, "$baseName.prev")+ if (!prev.exists()) return+ if (current.exists()) {+ prev.delete()+ } else {+ prev.renameTo(current)+ }+ } }
maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.ktindex 98c84b71e7..5c8283e09e 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt@@ -4,18 +4,21 @@ import android.content.Context import androidx.work.BackoffPolicy import androidx.work.Constraints import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ExistingWorkPolicy import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import androidx.work.workDataOf import com.vayunmathur.library.downloadservice.ModelDownloadItem import com.vayunmathur.library.downloadservice.downloadModels import com.vayunmathur.library.log.Log+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.util.DataStoreUtils import java.io.File-import java.net.URL import java.util.concurrent.TimeUnit /**@@ -40,8 +43,12 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) : override suspend fun doWork(): Result { val manifestUrl = inputData.getString(KEY_MANIFEST_URL) ?: MapOverlay.MANIFEST_URL+ // WorkManager can cold-start the process without MainActivity's TLS+ // init; without it the pinned manifest fetch below has no trust store.+ NetworkClient.init(applicationContext, TrustBundle.FIRST_PARTY) val ds = DataStoreUtils.getInstance(applicationContext) val root = applicationContext.getExternalFilesDir(null) ?: return Result.failure()+ recoverRebaseCrash(root) // No base, no overlay: the startup gate owns the full download. if (!File(root, MapTileCache.BASEMAP_ARCHIVE_FILE).exists()) { Log.status(TAG, "no base archive; skipping overlay check")@@ -60,8 +67,15 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) : Log.status(TAG, "overlay seq ${manifest.overlaySeq} already applied") return Result.success() }- // Base mismatch refuses: an overlay for another build must never apply.+ // Base mismatch: either a foreign overlay (refuse) or a server+ // rebase (refresh the base once, then drop the old stack). An empty+ // segment list with a newer seq is the rebase signal. if (!baseMatches(root, manifest)) {+ if (manifest.segments.isEmpty() &&+ (pinned == null || manifest.overlaySeq > pinned.overlaySeq)+ ) {+ return refreshBase(root, ds, manifest, text)+ } Log.status(TAG, "overlay seq ${manifest.overlaySeq} is for another base; skipping") return Result.success() }@@ -102,6 +116,13 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) : return Result.success() } + private fun recoverRebaseCrash(root: File) {+ val before = File(root, MapTileCache.BASEMAP_ARCHIVE_FILE).exists()+ MapOverlay.recoverRebaseCrash(root, MapTileCache.BASEMAP_ARCHIVE_FILE)+ val after = File(root, MapTileCache.BASEMAP_ARCHIVE_FILE).exists()+ if (before != after) Log.status(TAG, "rebase crash recovery restored the base")+ }+ /** * Whether the local base is the build [manifest] was made for. The base * header's `build_id` lives at bytes 16..24 (little-endian u64); the@@ -123,6 +144,60 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) : return true } + /**+ * Server rebase: the manifest pins a NEW base with an empty overlay.+ * Download the base once (the documented quarterly exception to no-2x:+ * old + `.next` coexist transiently), swap it in, and drop the old+ * overlay stack + segments. Readers mmap by path and reopen per surface,+ * so the rename-then-reload is the same atomicity as the initial+ * download; a crash mid-download resumes via `.part`, a crash+ * mid-swap keeps the old base (rename is atomic).+ */+ private suspend fun refreshBase(+ root: File,+ ds: DataStoreUtils,+ manifest: MapOverlay.Manifest,+ text: String,+ ): Result {+ Log.status(TAG, "rebase to seq ${manifest.overlaySeq}: refreshing base")+ ds.setLong(KEY_PENDING_BYTES, manifest.baseLen)+ val item = ModelDownloadItem(+ url = manifest.baseUrl,+ fileName = "${MapTileCache.BASEMAP_ARCHIVE_FILE}.next",+ description = "Map data consolidation",+ sha256 = null,+ )+ if (!downloadModels(applicationContext, ds, listOf(item))) return Result.retry()+ val next = File(root, "${MapTileCache.BASEMAP_ARCHIVE_FILE}.next")+ if (!next.isFile || (manifest.baseLen > 0 && next.length() != manifest.baseLen)) {+ Log.status(TAG, "rebased base failed verification")+ return Result.retry()+ }+ if (readBaseBuildId(next) != manifest.baseBuildId) {+ Log.status(TAG, "rebased base build mismatch; refusing swap")+ next.delete()+ return Result.success()+ }+ val current = File(root, MapTileCache.BASEMAP_ARCHIVE_FILE)+ val backup = File(root, "${MapTileCache.BASEMAP_ARCHIVE_FILE}.prev")+ if (backup.exists()) backup.delete()+ // Two renames, crash-safe either way: a leftover `.prev` with no+ // `.next` work means the swap completed (drop it); a leftover+ // `.next` means it did not (resume it next run).+ if (!current.renameTo(backup)) return Result.retry()+ if (!next.renameTo(current)) {+ backup.renameTo(current)+ return Result.retry()+ }+ backup.delete()+ File(root, MapOverlay.OVERLAY_ROOT).deleteRecursively()+ MapOverlay.pin(root, text)+ ds.setLong(KEY_APPLIED_SEQ, manifest.overlaySeq)+ ds.setLong(KEY_PENDING_BYTES, 0L)+ Log.status(TAG, "rebase seq ${manifest.overlaySeq} complete")+ return Result.success()+ }+ companion object { private const val TAG = "MapOverlay" private const val KEY_MANIFEST_URL = "manifest_url"@@ -144,6 +219,35 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) : fun checkManual(context: Context) = enqueue(context, MapOverlay.MANIFEST_URL, requireUnmetered = false) + /**+ * Daily auto-check chain (UNMETERED + battery-not-low). KEEP leaves an+ * already-scheduled chain alone. The worker self-skips when applied+ * (one small manifest GET), so the periodic slot costs nothing idle.+ * Call on app start when the auto-update toggle is on; [cancelAuto]+ * when it is off.+ */+ fun scheduleAuto(context: Context) {+ val request = PeriodicWorkRequestBuilder<MapOverlayWorker>(24, TimeUnit.HOURS)+ .setConstraints(+ Constraints.Builder()+ .setRequiredNetworkType(NetworkType.UNMETERED)+ .setRequiresBatteryNotLow(true)+ .build(),+ )+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_SECONDS, TimeUnit.SECONDS)+ .build()+ WorkManager.getInstance(context).enqueueUniquePeriodicWork(+ UNIQUE_PERIODIC,+ ExistingPeriodicWorkPolicy.KEEP,+ request,+ )+ }++ /** Drop the periodic chain (auto-update toggled off). */+ fun cancelAuto(context: Context) {+ WorkManager.getInstance(context).cancelUniqueWork(UNIQUE_PERIODIC)+ }+ private fun enqueue(context: Context, manifestUrl: String, requireUnmetered: Boolean) { val request = OneTimeWorkRequestBuilder<MapOverlayWorker>() .setInputData(workDataOf(KEY_MANIFEST_URL to manifestUrl))@@ -165,28 +269,23 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) : private const val UNIQUE_AUTO = "map_overlay_auto" private const val UNIQUE_MANUAL = "map_overlay_manual"+ private const val UNIQUE_PERIODIC = "map_overlay_periodic" /** Attempt count guard lives in doWork's caller: WorkManager retries. */ fun maxAttempts(): Int = MAX_RUN_ATTEMPTS } } -/** GET [url] as text, or null on any failure (caller retries). */+/**+ * GET [url] as text over the pinned FIRST_PARTY bundle, or null on any+ * failure (caller retries). Pinned, not plain HTTPS: the manifest names+ * segment URLs + SHA-256, so a MITM-swapped manifest must not verify —+ * and with pinning it cannot even be served.+ */ private suspend fun fetchText(url: String): String? = runCatching {- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {- (URL(url).openConnection() as java.net.HttpURLConnection).run {- connectTimeout = 30_000- readTimeout = 30_000- requestMethod = "GET"- try {- connect()- if (responseCode != java.net.HttpURLConnection.HTTP_OK) return@run null- inputStream.bufferedReader().use { it.readText() }- } finally {- disconnect()- }- }- }+ val (status, body) = NetworkClient.performRequestBytes(url)+ if (status != 200) return null+ body.toString(Charsets.UTF_8) }.getOrNull() /** The base archive's header `build_id` (bytes 16..24 LE), or null. */
maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.ktindex ff5d7b4045..145fad2e9a 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt@@ -89,7 +89,20 @@ class MapSettingsViewModel(application: Application) : AndroidViewModel(applicat ) fun setMapAutoUpdate(enabled: Boolean) =- launch { ds.setBoolean(MapPreferences.KEY_MAP_AUTO_UPDATE, enabled) }+ launch {+ ds.setBoolean(MapPreferences.KEY_MAP_AUTO_UPDATE, enabled)+ val context = getApplication<Application>().applicationContext+ if (enabled) MapOverlayWorker.scheduleAuto(context)+ else MapOverlayWorker.cancelAuto(context)+ }++ /** Ensure the periodic chain matches the persisted toggle (call on start). */+ fun syncAutoUpdateSchedule() {+ val context = getApplication<Application>().applicationContext+ if (ds.getBoolean(MapPreferences.KEY_MAP_AUTO_UPDATE, MapPreferences.DEFAULT_MAP_AUTO_UPDATE)) {+ MapOverlayWorker.scheduleAuto(context)+ }+ } // --- Layers sheet ------------------------------------------------------
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 77f94bae0a..2bb91522fa 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt@@ -73,13 +73,30 @@ object PoiArchive { * index section. Optional sections absent from the directory degrade * exactly as absent files do: no attributes, Morton fallback, scan * fallback.+ *+ * Section overrides (incremental updates): when the applied overlay pins+ * chunked sidecar sections, `<root>/overlays/sections/<kind>.section`+ * files replace the base slices for those kinds. Validators run+ * unchanged — an override that fails validation degrades exactly as an+ * absent section does, never as corrupt base bytes. */ internal fun openArchive(file: File): PoiIndex.Mapped? { if (!file.isFile) return null- return runCatching { buildMapped(PoiIndex.mapReadOnly(file)) }+ return runCatching { buildMapped(PoiIndex.mapReadOnly(file), overrideDir(file)) } .getOrElse { archiveFailure(it) } } + /**+ * The section-override dir for [baseFile] (`overlays/sections/` beside+ * it), or null when no applied overlay pins sections. Files are named+ * `<kind>.section` (e.g. `13.section` for transit).+ */+ private fun overrideDir(baseFile: File): File? {+ val root = baseFile.parentFile ?: return null+ val dir = File(File(root, MapOverlay.OVERLAY_ROOT), "sections")+ return dir.takeIf { it.isDirectory }+ }+ /** Log a mapping failure and yield null (the archive path degrades to side files). */ private fun archiveFailure(cause: Throwable): PoiIndex.Mapped? { // Only the failures a corrupt/truncated file can actually produce reach@@ -97,14 +114,32 @@ object PoiArchive { } } - private fun buildMapped(whole: MappedByteBuffer): PoiIndex.Mapped? {+ private fun buildMapped(whole: MappedByteBuffer, overrides: File?): PoiIndex.Mapped? { whole.order(ByteOrder.LITTLE_ENDIAN) val sections = parseSections(whole) ?: return null- val indexBuf = slice(whole, sections, KIND_INDEX) ?: run {+ // Overrides validate through the same validators as base slices; a+ // failed override degrades to the base slice, never to corrupt bytes.+ // Index + names override as a pair (ordinal join): one without the+ // other falls back to the base pair, never a mixed vintage.+ val overrideIndex = overrides?.let { validatedOverride(it, KIND_INDEX) }+ val overrideNames = overrides?.let { validatedOverride(it, KIND_NAMES) }+ val paired = (overrideIndex == null) == (overrideNames == null)+ if (!paired) {+ Log.status(TAG, "half-paired POI override; using base index+names")+ }+ val indexBuf = if (paired) {+ overrideIndex ?: slice(whole, sections, KIND_INDEX)+ } else {+ slice(whole, sections, KIND_INDEX)+ } ?: run { Log.status(TAG, "archive carries no POI index section") return null }- val namesBuf = slice(whole, sections, KIND_NAMES) ?: run {+ val namesBuf = if (paired) {+ overrideNames ?: slice(whole, sections, KIND_NAMES)+ } else {+ slice(whole, sections, KIND_NAMES)+ } ?: run { Log.status(TAG, "archive carries a POI index but no POI names") return null }@@ -112,7 +147,26 @@ object PoiArchive { Log.status(TAG, "archive POI index or names section is empty") return null }- return mappedFromSections(whole, sections, indexBuf, namesBuf)+ return mappedFromSections(whole, sections, indexBuf, namesBuf, overrides)+ }++ /**+ * The override file for [kind] as a validated buffer, or null when absent+ * or invalid (caller falls back to base). The returned duplicate shares+ * the file mapping and pins it exactly like a base slice: once stored in+ * [PoiIndex.Mapped] fields it lives as long as they do, so no separate+ * holder is needed.+ */+ private fun validatedOverride(dir: File, kind: Int): MappedByteBuffer? {+ val file = File(dir, "$kind.section")+ if (!file.isFile || file.length() == 0L || file.length() > Int.MAX_VALUE) return null+ return runCatching {+ val mapped = PoiIndex.mapReadOnly(file)+ // Minimal shape check now; the per-kind validators in+ // mappedFromSections run the full agreement (magic/count).+ if (mapped.capacity() == 0) return null+ (mapped.duplicate() as MappedByteBuffer).also { it.order(ByteOrder.LITTLE_ENDIAN) }+ }.getOrNull() } private fun mappedFromSections(@@ -120,11 +174,15 @@ object PoiArchive { sections: Map<Int, Section>, indexBuf: MappedByteBuffer, namesBuf: MappedByteBuffer,+ overrides: File?, ): PoiIndex.Mapped { val count = indexBuf.capacity() / INDEX_RECORD_BYTES- val attrs = sections[KIND_ATTRS]?.let { PoiIndex.attrsFromBuffer(sliceRaw(whole, it), count) }- val grid = sections[KIND_SPATIAL]?.let { PoiIndex.spatialFromBuffer(sliceRaw(whole, it), count) }- val words = sections[KIND_WORDS]?.let { PoiIndex.nameIndexFromBuffer(sliceRaw(whole, it), count) }+ val attrs = overrideOrBase(overrides, KIND_ATTRS, sections, whole)+ ?.let { PoiIndex.attrsFromBuffer(it, count) }+ val grid = overrideOrBase(overrides, KIND_SPATIAL, sections, whole)+ ?.let { PoiIndex.spatialFromBuffer(it, count) }+ val words = overrideOrBase(overrides, KIND_WORDS, sections, whole)+ ?.let { PoiIndex.nameIndexFromBuffer(it, count) } return PoiIndex.Mapped( index = indexBuf, names = namesBuf,@@ -155,6 +213,24 @@ object PoiArchive { return sliceRaw(whole, s) } + /**+ * The override buffer for [kind], or the base slice when no valid+ * override exists. Override validators are the same functions the base+ * path runs ([PoiIndex.attrsFromBuffer] and siblings) — only the mapping+ * step differs, so the checks cannot drift apart.+ */+ private fun overrideOrBase(+ overrides: File?,+ kind: Int,+ sections: Map<Int, Section>,+ whole: MappedByteBuffer,+ ): MappedByteBuffer? {+ if (overrides != null) {+ validatedOverride(overrides, kind)?.let { return it }+ }+ return slice(whole, sections, kind)+ }+ /** * A little-endian view of `[offset, offset + len)`. *
maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.ktindex 9cbdb551e1..8a2e790ee8 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt@@ -117,4 +117,23 @@ class MapOverlayTest { assertEquals(0x1234L, MapOverlay.parseBuildId("0x0000000000001234")) assertEquals(0L, MapOverlay.parseBuildId("garbage")) }++ @Test+ fun rebase_recovery_drops_completed_backup() {+ val dir = root()+ File(dir, "base.mamaps").writeBytes(ByteArray(4))+ File(dir, "base.mamaps.prev").writeBytes(ByteArray(4))+ MapOverlay.recoverRebaseCrash(dir, "base.mamaps")+ assertTrue(File(dir, "base.mamaps").isFile)+ assertFalse(File(dir, "base.mamaps.prev").exists())+ }++ @Test+ fun rebase_recovery_restores_interrupted_swap() {+ val dir = root()+ File(dir, "base.mamaps.prev").writeBytes(ByteArray(4))+ MapOverlay.recoverRebaseCrash(dir, "base.mamaps")+ assertTrue(File(dir, "base.mamaps").isFile)+ assertFalse(File(dir, "base.mamaps.prev").exists())+ } }
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 64067af8fe..ff2afc2062 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt@@ -172,4 +172,61 @@ class PoiArchiveTest { f.writeBytes(bytes) assertFalse(PoiIndex.reloadArchive(f), "build id mismatch must refuse") }++ /**+ * A paired index+names override replaces the base pair: the queries+ * answer from the override's records, validated by the same validators.+ */+ @Test+ fun `paired override replaces the base pair`() {+ val f = writeArchive(+ listOf(+ indexPayload(),+ Triple(PoiArchive.KIND_NAMES, namesBytes(), 0L),+ ),+ )+ // Override dir beside the archive: overlays/sections/<kind>.section.+ val sections = File(File(f.parentFile, "overlays"), "sections")+ sections.mkdirs()+ // One-record override: Diner@0.+ val index = ByteBuffer.allocate(14).order(ByteOrder.LITTLE_ENDIAN)+ index.putInt(377_749_050)+ index.putInt(-1_224_194_000)+ index.putInt(0)+ index.putShort(2.toShort())+ File(sections, "${PoiArchive.KIND_INDEX}.section").writeBytes(index.array())+ File(sections, "${PoiArchive.KIND_NAMES}.section")+ .writeBytes("Diner\u0000".toByteArray(Charsets.UTF_8))+ assertTrue(PoiIndex.reloadArchive(f), "paired override must map")+ assertEquals(1, PoiIndex.recordCount)+ val hits = PoiIndex.nearest(37.7749050, -122.4194000)+ assertEquals(1, hits.size)+ assertEquals("Diner", hits[0].name)+ }++ /**+ * A half-paired override (index without names) falls back to the base+ * pair: mixed vintages must never join.+ */+ @Test+ fun `half paired override falls back to base`() {+ val f = writeArchive(+ listOf(+ indexPayload(),+ Triple(PoiArchive.KIND_NAMES, namesBytes(), 0L),+ ),+ )+ val sections = File(File(f.parentFile, "overlays"), "sections")+ sections.mkdirs()+ val index = ByteBuffer.allocate(14).order(ByteOrder.LITTLE_ENDIAN)+ index.putInt(377_749_050)+ index.putInt(-1_224_194_000)+ index.putInt(0)+ index.putShort(2.toShort())+ File(sections, "${PoiArchive.KIND_INDEX}.section").writeBytes(index.array())+ assertTrue(PoiIndex.reloadArchive(f), "half pair must still map (from base)")+ assertEquals(2, PoiIndex.recordCount)+ val hits = PoiIndex.nearest(37.7749050, -122.4194000)+ assertEquals("Cafe", hits[0].name)+ } }
scripts/maps/upload_planet.py
diff --git a/scripts/maps/upload_planet.py b/scripts/maps/upload_planet.pyindex 8d118fa11d..2865cd1ce4 100644--- a/scripts/maps/upload_planet.py+++ b/scripts/maps/upload_planet.py@@ -49,9 +49,12 @@ MIN_CLIENT_COMPAT = 1 def main() -> int: if len(sys.argv) >= 2 and sys.argv[1] == "--manifest": return publish_manifest(sys.argv[2:])+ if len(sys.argv) >= 2 and sys.argv[1] == "--rebase":+ return publish_rebase(sys.argv[2:]) if len(sys.argv) != 2: print(f"usage: {os.path.basename(sys.argv[0])} <local-file>", flush=True) print(f" or: {os.path.basename(sys.argv[0])} --manifest <overlay-dir> --overlay-seq N --base-build-id HEX [--base-len N]", flush=True)+ print(f" or: {os.path.basename(sys.argv[0])} --rebase --overlay-seq N --base-build-id HEX --base-len N", flush=True) return 2 missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY") if not os.environ.get(v)]@@ -210,5 +213,59 @@ def sha256_file(path: str) -> str: return h.hexdigest() +def publish_rebase(argv: list) -> int:+ """Publish a consolidation: a fresh full base becomes the world, and the+ overlay stack resets to empty.++ Run quarterly, or when the stacked overlays exceed ~20% of the base or+ the sequence depth passes 3. The new base uploads exactly like a normal+ planet publish (same KEY, new bytes, new build_id); the manifest then+ pins it with zero segments, so clients do one background full download+ and drop their old segments. No client-side rewrite pass exists by+ design (the no-2x guarantee stays trivially true).++ Args: --overlay-seq N --base-build-id HEX --base-len N+ (N continues the sequence; segments/tombstones/sections are empty.)+ """+ import argparse+ ap = argparse.ArgumentParser()+ ap.add_argument("--overlay-seq", type=int, required=True)+ ap.add_argument("--base-build-id", required=True)+ ap.add_argument("--base-len", type=int, required=True)+ args = ap.parse_args(argv)+ missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY")+ if not os.environ.get(v)]+ if missing:+ print(f"missing env: {', '.join(missing)} (see module docstring)", flush=True)+ return 2+ s3 = boto3.client(+ "s3",+ endpoint_url=os.environ["R2_ENDPOINT"],+ aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"],+ aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"],+ region_name="auto",+ )+ manifest = {+ "version": MANIFEST_VERSION,+ "base": {+ "url": f"{CDN}/{KEY}",+ "build_id": args.base_build_id,+ "len": args.base_len,+ },+ "overlay_seq": args.overlay_seq,+ "overlay_build_id": "0x0",+ "segments": [],+ "sections": [],+ "tombstones": [],+ "min_client": MIN_CLIENT_COMPAT,+ }+ body = json.dumps(manifest, indent=1).encode()+ s3.put_object(Bucket=BUCKET, Key=MANIFEST_KEY, Body=body,+ ContentType="application/json")+ print(f"wrote s3://{BUCKET}/{MANIFEST_KEY} rebase seq={args.overlay_seq} "+ f"(empty overlay; clients refresh the base once)", flush=True)+ return 0++ if __name__ == "__main__": sys.exit(main())