Modern Apps git

← Modern-Apps.git

weather: read everything from R2 static files

Commit
97458310c89a7a52f3e01973560e619ad2fdfbbf
Author
Vayun Mathur <[email protected]>
When
2026-11-25 23:52 UTC (10 days ago)
Parents
60bf26a
The app now composes all weather reads from the static R2 packs (wx/v1/latest.json manifest + run.wxp land tiles + hist/<day>.wxp + geo.wxp): WxStatic samples current conditions, hourly/daily bundles, timezone/elevation, and map metadata/sampling client-side at the requested coordinate, and WeatherApi's origin paths are removed (the now-unused origin DTOs are deleted). One flagged exception: a coordinate with no land tile (open ocean, or history days not yet in the packs) falls back to the origin bundle, documented in WeatherApi and weather/AGENTS.md, because the generator emits land tiles only and all-ocean tiles would multiply the pack for coordinates the place catalogue never returns. Location search stays on the bundled GeoNames asset (already static/offline from first launch) and reverse geocoding stays on the OS Geocoder; neither was an origin read. The Rust map renderer remains in tree but off the read path.

Verified: :weather:testDevUnitTest 226 tests, 0 failures (including new WxStatic fixture-pack tests); :weather:lint has only 3 pre-existing RouteScreenshotCoverage errors on untouched Route.kt, zero findings in changed files.

Diff

weather/AGENTS.md
diff --git a/weather/AGENTS.md b/weather/AGENTS.mdindex 6d19b796a7..109aa1b58e 100644--- a/weather/AGENTS.md+++ b/weather/AGENTS.md@@ -16,11 +16,11 @@ _Install: ./install weather (dev by default)._ - Saved locations + device location (reverse-geocoded) with Room-cached forecasts refreshed by `WeatherRefreshWorker` - Metric blocks + graphs per location; Open-Meteo vector map tiles via the Rust core (`domain/map/OmTilesNative`) - Two Glance widgets (standard + blob); `GetWeather`/`GetWeatherByName` assistant intents-**Architecture / data-flow:** `ui/` home/map/locations → `platform/WeatherViewModel` (+ `WeatherUiContract`) → `data/WeatherRepository` over Room + `network/WeatherApi` DTOs; `domain/` holds pure unit/metric/WMO formatting + map metadata; widgets read the same repository snapshot.+**Architecture / data-flow:** `ui/` home/map/locations → `platform/WeatherViewModel` (+ `WeatherUiContract`) → `data/WeatherRepository` over Room + `network/WeatherApi`; all weather reads come from the static R2 packs (`network/WxStatic`: `run.wxp`/`hist/<day>.wxp`/`geo.wxp` + `latest.json` manifest on `static.maproj.org/wx/v1/`), computed on device by `domain/wx/`; the map samples the same run tiles (no `.om`/`data_spatial` read); place search is the on-device `places.db.br` catalogue; `domain/` holds pure unit/metric/WMO formatting + map metadata; widgets read the same repository snapshot. **Entry points + reading order:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/HomePage.kt` → `platform/WeatherViewModel.kt` → `data/WeatherRepository.kt` → `network/WeatherApi.kt`. **Gotchas:** - Unit system follows the device locale (`platform/SystemUnits`) — format in `domain/`, never in `ui/`-- Map tiles are native-rendered Open-Meteo domains; tile bugs live in Rust or `domain/map/`, not the Compose layer+- Map shading is sampled on device from the R2 run tiles in `network/WxStatic`; the Rust `.om` bridge (`domain/map/OmTilesNative`) is not on the read path - Widgets must render from cache alone — never network on the widget path  ## Key files@@ -47,11 +47,13 @@ _Install: ./install weather (dev by default)._ - com/vayunmathur/weather/domain/map/OmMapMetadata.kt - com/vayunmathur/weather/domain/map/OmColorize.kt - com/vayunmathur/weather/domain/map/OmTilesNative.kt — Rust tile bridge-### network/ — Open-Meteo DTOs + API-- com/vayunmathur/weather/network/WeatherApi.kt+### network/ — static R2 reads + DTOs+- com/vayunmathur/weather/network/WeatherApi.kt — one entry point: bundles/temperatures/time zone via `WxStatic`, place search via the on-device catalogue; the only origin read left is the flagged `WxStatic.NotCovered` (no land tile, e.g. open ocean) bundle fallback to `api.maproj.org/wx/v1`, which stays up for older clients+- com/vayunmathur/weather/network/WxStatic.kt — R2 pack reader (Range + disk cache, run `next_check` staleness), manifest (`latest.json` `generated_at`), geo-block time zone, search-row temperatures, and map metadata/region sampling from the run tiles (nearest 0.125° cell; the old `.om` path bilinearly interpolated the same grid) - com/vayunmathur/weather/network/OpenMeteoDto.kt - com/vayunmathur/weather/network/GeocodingDto.kt - com/vayunmathur/weather/network/AirQualityDto.kt+- com/vayunmathur/weather/network/WxBundleDto.kt / WxBundleMapper.kt — bundle format + mapping to the DTOs above ### platform/ — ViewModel, location, summaries - com/vayunmathur/weather/platform/WeatherViewModel.kt - com/vayunmathur/weather/platform/WeatherUiContract.kt
weather/src/main/java/com/vayunmathur/weather/MainActivity.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt b/weather/src/main/java/com/vayunmathur/weather/MainActivity.ktindex 88b8786c13..3595ea61b9 100644--- a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt+++ b/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt@@ -23,10 +23,10 @@ class MainActivity : MaActivity() {      override fun onCreateBeforeContent() {         com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)-        // FIRST_PARTY covers api.maproj.org (self-hosted weather bundle-        // fallback and tiles proxy) and static.maproj.org (static weather-        // tiles, R2 custom domain on the same Cloudflare roots); place-        // search is a committed on-device asset.+        // FIRST_PARTY covers static.maproj.org (static weather packs on+        // R2, the app's only weather origin) and, for the flagged+        // no-land-tile fallback only, api.maproj.org; place search is a+        // committed on-device asset.         NetworkClient.init(this, TrustBundle.FIRST_PARTY)         // Static weather tiles (static.maproj.org), cached under cacheDir.         WxStatic.init(this)
weather/src/main/java/com/vayunmathur/weather/domain/map/OmColorize.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/domain/map/OmColorize.kt b/weather/src/main/java/com/vayunmathur/weather/domain/map/OmColorize.ktindex 0ad6ef2a26..24f07d8645 100644--- a/weather/src/main/java/com/vayunmathur/weather/domain/map/OmColorize.kt+++ b/weather/src/main/java/com/vayunmathur/weather/domain/map/OmColorize.kt@@ -7,8 +7,8 @@ import androidx.core.graphics.createBitmap import com.vayunmathur.weather.domain.ColorStop  /**- * Colorize a row-major [values] grid (`w × h`, from- * [OmTilesNative.decodeRegion]) into an opaque [ImageBitmap] using [ramp].+ * Colorize a row-major [values] grid (`w × h`, sampled from the R2 run+ * tiles by `WxStatic.regionValues`) into an opaque [ImageBitmap] using [ramp].  * `NaN` values become fully transparent so gaps in coverage show the basemap.  * The overall overlay translucency is applied by the `RasterLayer`, so pixels  * here are fully opaque.
weather/src/main/java/com/vayunmathur/weather/domain/map/OmDomains.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/domain/map/OmDomains.kt b/weather/src/main/java/com/vayunmathur/weather/domain/map/OmDomains.ktindex 85a5d0206d..c9ab0a655c 100644--- a/weather/src/main/java/com/vayunmathur/weather/domain/map/OmDomains.kt+++ b/weather/src/main/java/com/vayunmathur/weather/domain/map/OmDomains.kt@@ -7,7 +7,7 @@ package com.vayunmathur.weather.domain.map  * stored `[ny, nx]`.  */ data class OmDomain(-    /** Model id used in the `data_spatial/<model>/…` bucket paths. */+    /** Model id of the ICON grid the R2 run tiles are built on. */     val model: String,     val nx: Int,     val ny: Int,@@ -18,7 +18,7 @@ data class OmDomain( )  /**- * v1 model: DWD ICON global, a regular 0.125° lat/lon grid covering the whole+ * DWD ICON global, a regular 0.125° lat/lon grid covering the whole  * globe. Chosen because it exposes the direct variables we shade (temperature,  * humidity, precipitation, gusts, pressure, cloud cover) plus the u/v wind  * components we derive wind speed from. Projected/Gaussian grids and
weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.kt b/weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.ktindex 782048d31c..07f9a3a7c9 100644--- a/weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.kt+++ b/weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.kt@@ -1,18 +1,17 @@ package com.vayunmathur.weather.domain.map -import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.weather.domain.WeatherMetric import com.vayunmathur.weather.domain.bundleHourlyVar import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json  /**- * Metadata for a spatial model, from- * `https://api.maproj.org/data_spatial/<model>/latest.json` (P1 tiles- * passthrough; upstream is the model-data S3 bucket).+ * Metadata for the shaded map, derived on device from the static R2 run+ * tiles ([com.vayunmathur.weather.network.WxStatic.mapMetadata]): the+ * model run, the forecast hours its tiles hold, and the variables it can+ * shade. No origin `data_spatial` read remains.  *- * - [referenceTime] is the model run (drives the `.om` folder path).+ * - [referenceTime] is the model run.  * - [validTimes] are the hourly forecast steps (drive the time slider).  * - [variables] is the availability list for this run (drives which measures  *   we can shade).@@ -31,52 +30,9 @@ data class OmMapMetadata(     } } -/** The `.om` variable name backing [WeatherMetric]; identical to the JSON API name. */+/** The grid variable name backing [WeatherMetric]; identical to the bundle hourly name. */ val WeatherMetric.omVariable: String     get() = bundleHourlyVar  private const val WIND_U = "wind_u_component_10m" private const val WIND_V = "wind_v_component_10m"--/** Self-hosted tiles origin: axum Range proxy on `api.maproj.org` (P1). */-private const val SPATIAL_BASE = "https://api.maproj.org/data_spatial"--private val metadataJson = Json { ignoreUnknownKeys = true }--/**- * Fetch the latest-run metadata for [domain]. The `variable` query param is- * only a hint — the response lists every variable in the run — so we pass a- * stable one. Returns `null` on network/parse failure.- *- * The bucket serves `latest.json` as `application/octet-stream`, so content-type- * based deserialization won't fire; we fetch the raw body and parse it ourselves.- */-suspend fun fetchOmMapMetadata(domain: OmDomain): OmMapMetadata? {-    val url = "$SPATIAL_BASE/${domain.model}/latest.json?variable=temperature_2m"-    return runCatching {-        val response = NetworkClient.performRequest(url)-        if (!response.isSuccess) return null-        metadataJson.decodeFromString<OmMapMetadata>(response.body)-    }.getOrNull()-}--/**- * Build the `.om` file URL for [domain] at model run [referenceTime] and step- * [validTime].- *- * `reference_time` `2026-07-01T18:00:00Z` → folder `2026/07/01/1800Z`;- * `valid_time` `2026-07-01T18:00Z` → filename `2026-07-01T1800.om`.- */-fun omFileUrl(domain: OmDomain, referenceTime: String, validTime: String): String? {-    // reference_time comes from the server's latest.json; a short or-    // reformatted value must not crash the map with substring OOB.-    if (referenceTime.length < 16) return null-    val year = referenceTime.substring(0, 4)-    val month = referenceTime.substring(5, 7)-    val day = referenceTime.substring(8, 10)-    val hour = referenceTime.substring(11, 13)-    val minute = referenceTime.substring(14, 16)-    val folder = "$year/$month/$day/$hour${minute}Z"-    val file = validTime.replace(":", "").removeSuffix("Z")-    return "$SPATIAL_BASE/${domain.model}/$folder/$file.om"-}
weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.ktindex 5c98bb24cf..7bb6e89e3e 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt@@ -5,7 +5,7 @@ import kotlinx.serialization.Serializable  /**  * Subset of the forecast response we actually use, mapped from the- * self-hosted `wx/v1/bundle`.+ * static `wx/v1` bundle computed on device from the R2 packs.  *  * We always request: current weather + hourly arrays + daily arrays in metric  * units. Unit conversion for the UI happens at display time so swapping@@ -25,10 +25,8 @@ data class ForecastResponse( )  /**- * Minimal bundle envelope used only to resolve the IANA- * time zone (and its current abbreviation) for a coordinate.- * Requested with `fields=tz`, which returns the envelope with no weather- * data at all.+ * Time zone (and its current abbreviation) for a coordinate, resolved+ * from the R2 geo block by `WxStatic.timezoneAt`.  */ @Serializable data class RegionTimezone(@@ -37,22 +35,6 @@ data class RegionTimezone(     @SerialName("utc_offset_seconds") val utcOffsetSeconds: Int = 0, ) -/**- * Minimal bundle response used to show the current- * temperature next to a city-search result. Requests only the `current`- * section so the per-result lookups stay cheap.- */-@Serializable-data class CurrentTemperatureResponse(-    val current: CurrentTemperature? = null,-)--/** Immutable value describing current temperature. */-@Serializable-data class CurrentTemperature(-    @SerialName("temperature_2m") val temperature: Double,-)- /** Immutable value describing minutely15. */ @Serializable data class Minutely15(
weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.ktindex b156acc32f..01fe24230a 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt@@ -5,22 +5,33 @@ import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.weather.data.GeoDatabase  /**- * Thin wrapper over the shared [NetworkClient] for the self-hosted `wx/v1`- * bundle API on `api.maproj.org`. One `bundle()` call carries everything- * the weather screen needs; the mapper normalizes it into the existing- * DTOs so nothing downstream of `network/` changes. Place search is fully- * on-device ([GeoDatabase]) — no geocoding host remains.+ * The weather app's one network entry point. Every read is served from+ * the static packs on Cloudflare R2 (`static.maproj.org/wx/v1/`, written+ * by the server's `wx export` — see [WxStatic]) or, for place search,+ * from the on-device catalogue ([GeoDatabase]). The origin bundle API+ * (`api.maproj.org/wx/v1`) stays up for released/older clients, but this+ * app no longer reads it for any normal read.  *- * Everything is requested in metric units; the UI converts at display time so- * toggling °C/°F doesn't trigger another HTTP call.+ * FLAGGED EXCEPTION (the one read that is not fully moved): a point with+ * no land tile — open ocean, or a tile whose history days are not yet in+ * the packs — throws [WxStatic.NotCovered] from the static path. The+ * generator emits land tiles only; emitting every ocean tile would+ * multiply the run pack several-fold for coordinates the place catalogue+ * never returns. For that case only, [bundle] falls back to the origin+ * bundle so a user standing on a ferry still gets weather instead of an+ * error. Every other read (current, batch temperatures, time zone, map)+ * is R2/on-device only and simply degrades (absent row / null) there.+ *+ * Everything is in metric units; the UI converts at display time so+ * toggling °C/°F doesn't trigger another fetch.  */ object WeatherApi {      private const val BUNDLE_BASE = "https://api.maproj.org/wx/v1"     private const val TAG = "WeatherApi" -    // Test seam: point the bundle API at an unroutable address so the-    // failure-path tests are hermetic on boxes that have internet.+    // Test seam for the flagged NotCovered fallback only: point it at an+    // unroutable address so failure-path tests stay hermetic.     @androidx.annotation.VisibleForTesting     internal var bundleBaseOverride: String? = null @@ -28,30 +39,19 @@ object WeatherApi {      /**      * Fetch the full bundle (current + hourly + daily + 15-min + AQ) for a-     * single coordinate. Single HTTP call. Throws on network / parse failure-     * — callers wrap in try/catch and fall back to cache.+     * single coordinate from R2. Throws on network / parse failure —+     * callers wrap in try/catch and fall back to cache. See the class doc+     * for the flagged [WxStatic.NotCovered] origin fallback.      */-    suspend fun bundle(latitude: Double, longitude: Double, fields: String = "all"): WxBundle {-        // Full bundles come from the static R2 tiles first (computed on-        // device, identical to the server's); any failure there — ocean-        // point, no network to R2, a format change — falls back to the API.-        // Tests that point the API somewhere (bundleBaseOverride) skip it.-        if (fields == "all" && bundleBaseOverride == null && WxStatic.enabled) {-            try {-                return WxStatic.bundle(latitude, longitude)-            } catch (e: kotlinx.coroutines.CancellationException) {-                throw e-            } catch (@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Exception) {-                Log.status(TAG, "static weather unavailable (${e.javaClass.simpleName}: ${e.message}); using the API")-            }-        }-        val url = buildString {-            append(bundleBase).append("/bundle")-            append("?lat=").append(latitude)-            append("&lon=").append(longitude)-            append("&fields=").append(fields)+    suspend fun bundle(latitude: Double, longitude: Double): WxBundle {+        try {+            return WxStatic.bundle(latitude, longitude)+        } catch (e: WxStatic.NotCovered) {+            if (bundleBaseOverride != null) throw e+            Log.status(TAG, "static weather does not cover ($latitude,$longitude): ${e.message}; using the flagged origin fallback")+            val url = "$bundleBase/bundle?lat=$latitude&lon=$longitude&fields=all"+            return NetworkClient.getJson(url)         }-        return NetworkClient.getJson(url)     }      /**@@ -69,8 +69,11 @@ object WeatherApi {      * `get_weather_by_name` intent.      *      * Fully on-device: the places catalogue (`places.db.br`) is a committed-     * asset unpacked by [GeoDatabase], so search works on a clean checkout-     * with no network. Empty when the catalogue is absent or nothing matches.+     * asset unpacked by [GeoDatabase], so search works with no network and+     * no R2 download on first run. It is deliberately not an R2 gazetteer:+     * the catalogue is already static, ships with the APK, and works+     * offline from first launch; moving it to R2 would add a first-run+     * download and an offline gap for no origin-read benefit.      */     suspend fun geocode(query: String, limit: Int = 5): GeocodingResponse {         if (query.isBlank()) return GeocodingResponse(emptyList())@@ -81,44 +84,39 @@ object WeatherApi {     }      /**-     * Fetch just the current temperature (°C) for a coordinate. Used by the-     * city-search list to show the current temp next to each result.-     * Requests only the `current` bundle section (~200-byte body).+     * Fetch just the current temperature (°C) for a coordinate, sampled+     * from its R2 tile bundle. Used by the city-search list to show the+     * current temp next to each result. Null when the point cannot be+     * served statically.      */     suspend fun currentTemperature(latitude: Double, longitude: Double): Double? {-        return bundle(latitude, longitude, "current").current?.temp+        return runCatching { WxStatic.currentTemperature(latitude, longitude) }.getOrNull()     }      /**-     * Batch current temperatures for search results: one round trip for all-     * rows instead of N parallel [currentTemperature] calls. Returns-     * temp-per-coordinate in request order; a failed point is absent (callers-     * keep the per-row spinner → blank, same as today's `getOrNull`).+     * Batch current temperatures for search results, sampled per point+     * from the R2 tiles (cached, so rows sharing a tile cost one fetch).+     * Returns temp-per-coordinate in request order; a failed point is+     * absent (callers keep the per-row spinner → blank).      */     suspend fun currentTemperatures(points: List<Pair<Double, Double>>): Map<Pair<Double, Double>, Double> {-        if (points.isEmpty()) return emptyMap()-        val url = buildString {-            append(bundleBase).append("/current?points=")-            append(points.take(20).joinToString("|") { (lat, lon) -> "$lat,$lon" })-        }-        val batch: WxCurrentBatch = NetworkClient.getJson(url)-        return batch.points.associate { p -> (p.lat to p.lon) to p.temp }+        return WxStatic.currentTemperatures(points)     }      /**-     * Resolve the IANA time zone for a coordinate. Requests only the envelope-     * (no weather data at all). Used by the map to label the zoomed-in-     * region's local time. Throws on failure.+     * Resolve the IANA time zone for a coordinate from its R2 geo block+     * (offset/abbreviation resolved on device). Used by the map to label+     * the zoomed-in region's local time. Throws on failure.      */     suspend fun timezoneAt(latitude: Double, longitude: Double): RegionTimezone {-        return bundle(latitude, longitude, "tz").toRegionTimezone()+        return WxStatic.timezoneAt(latitude, longitude)     }      /**-     * Air quality + pollen for a coordinate. Best-effort: the service has gaps-     * outside Europe/North America, so callers should treat the whole response-     * as optional. Missing `aq` section maps to [AirQualityResponse](null),-     * exactly like today's nullable DTO.+     * Air quality + pollen for a coordinate, from the same static bundle.+     * Best-effort: the service has gaps outside Europe/North America, so+     * callers should treat the whole response as optional. Missing `aq`+     * section maps to [AirQualityResponse](null).      */     suspend fun airQuality(latitude: Double, longitude: Double): AirQualityResponse {         return bundle(latitude, longitude).toAirQuality() ?: AirQualityResponse(null)
weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.ktindex 5db1a9b9a4..48e528c1ca 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.kt@@ -117,20 +117,3 @@ data class WxAq(     val ragweed: Double? = null,     val mugwort: Double? = null, )--/** P4 batch response: current-hour temp/code/is_day per requested point. */-@Serializable-data class WxCurrentBatch(-    val v: Int = 1,-    val points: List<WxCurrentPoint> = emptyList(),-)--/** Immutable value describing wx current point. */-@Serializable-data class WxCurrentPoint(-    val lat: Double,-    val lon: Double,-    val temp: Double,-    val code: Int,-    val day: Int,-)
weather/src/main/java/com/vayunmathur/weather/network/WxStatic.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WxStatic.kt b/weather/src/main/java/com/vayunmathur/weather/network/WxStatic.ktindex a3c096b50e..5f2551ac47 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/WxStatic.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/WxStatic.kt@@ -2,10 +2,15 @@ package com.vayunmathur.weather.network  import android.content.Context import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.weather.domain.map.OmMapMetadata import com.vayunmathur.weather.domain.wx.WxCompute+import com.vayunmathur.weather.domain.wx.WxDerive import com.vayunmathur.weather.domain.wx.WxGrid import com.vayunmathur.weather.domain.wx.WxPack import com.vayunmathur.weather.domain.wx.WxTiles+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock@@ -25,11 +30,19 @@ import java.io.File  * tile (If-Match the entry's ETag, so a run replaced in between is caught)  * plus one per new finished day (`hist/<day>.wxp`). The location's geo block  * (elevation + time zone) is fetched once ever. Everything is cached on- * disk. Any failure throws and [WeatherApi.bundle] falls back to the server- * API, so the rollout is safe.+ * disk. Any failure throws; callers fall back to their Room cache. The one+ * exception is [NotCovered] (a point with no land tile, e.g. open ocean),+ * where [WeatherApi] keeps a flagged origin fallback — see its doc.  */ object WxStatic {     private const val BASE = "https://static.maproj.org/wx/v1/"++    /** Bundle-vocabulary variables the map can shade from the run tiles. */+    val MAP_VARIABLES = listOf(+        "temperature_2m", "apparent_temperature", "relative_humidity_2m", "dew_point_2m", "precipitation",+        "wind_speed_10m", "wind_u_component_10m", "wind_v_component_10m", "wind_gusts_10m", "pressure_msl",+        "visibility", "cloud_cover", "uv_index",+    )     private const val RUN_KEY = "run.wxp"     private const val GEO_KEY = "geo.wxp"     private const val HTTP_PARTIAL = 206@@ -261,6 +274,237 @@ object WxStatic {             WxCompute.computeBundle(lat, lon, nowEpoch, t.iconRunIso, s)         } +    // --- Manifest (latest.json) -------------------------------------------++    /** `latest.json` manifest written last by each generator run. */+    @Serializable+    data class Manifest(+        val v: Int = 1,+        val run: String = "",+        val gen: Long = 0,+        @SerialName("generated_at") val generatedAt: Long = 0,+        @SerialName("next_check") val nextCheck: Long = 0,+        @SerialName("icon_run") val iconRun: String = "",+        @SerialName("valid_times") val validTimes: List<String> = emptyList(),+        val variables: List<String> = emptyList(),+    )++    private val manifestJson = Json { ignoreUnknownKeys = true }++    /** Test seam: full (non-ranged) GET of `latest.json` as text. */+    @androidx.annotation.VisibleForTesting+    internal var manifestFetcher: suspend (String) -> String = { url ->+        val r = NetworkClient.performRequest(url)+        if (!r.isSuccess) throw java.io.IOException("wx manifest: HTTP ${r.status}")+        r.body+    }++    @Volatile private var manifestCache: Manifest? = null++    /**+     * The current run's manifest, cached until its `next_check`. Advisory:+     * the bundle path works without it (per-tile entries carry the same+     * `gen`/`next_check`); this is how callers learn the run's+     * `generated_at` and valid hours without decoding a tile.+     */+    suspend fun manifest(nowEpoch: Long = System.currentTimeMillis() / MS_PER_S): Manifest {+        manifestCache?.let { if (nowEpoch < it.nextCheck) return it }+        val m = manifestJson.decodeFromString<Manifest>(manifestFetcher(base + "latest.json"))+        manifestCache = m+        return m+    }++    /** When the served run was generated (epoch seconds), or 0 if unknown. */+    suspend fun generatedAtEpoch(): Long = runCatching { manifest().generatedAt }.getOrDefault(0L)++    // --- Point reads derived from the packs --------------------------------++    /**+     * Time zone of a point from its `geo.wxp` block alone (zone name), with+     * the offset/abbreviation resolved on device for [nowEpoch]. Works for+     * ocean points too: the geo grid carries `Etc/GMT±N` zones. Throws+     * [NotCovered] off the geo grid.+     */+    suspend fun timezoneAt(lat: Double, lon: Double, nowEpoch: Long = System.currentTimeMillis() / MS_PER_S): RegionTimezone =+        withContext(Dispatchers.IO) {+            if (!enabled) throw NotCovered("disabled")+            val k = WxGrid.geoOf(lat, lon) ?: throw NotCovered("off the DEM grid")+            val g = lock.withLock { geo(k) }+            val name = g.zone(k.px, k.py) ?: throw NotCovered("no zone")+            val tz = java.util.TimeZone.getTimeZone(name)+            // getTimeZone falls back to GMT for unknown ids; only trust an+            // exact id match (or UTC), else report the name with 0 offset.+            val known = tz.id == name || name == "UTC"+            val at = java.util.Date(nowEpoch * MS_PER_S)+            RegionTimezone(+                timezone = name,+                abbreviation = if (known) tz.getDisplayName(tz.inDaylightTime(at), java.util.TimeZone.SHORT, java.util.Locale.US) else name,+                utcOffsetSeconds = if (known) tz.getOffset(nowEpoch * MS_PER_S) / 1000 else 0,+            )+        }++    /** Current temperature (°C) of one point from its static bundle. */+    suspend fun currentTemperature(lat: Double, lon: Double, nowEpoch: Long = System.currentTimeMillis() / MS_PER_S): Double? =+        bundle(lat, lon, nowEpoch).current?.temp++    /**+     * Current temperatures for up to 20 points (search-result rows). Each+     * point is sampled from its tile — tiles are disk/memory cached, so+     * points sharing a tile cost one fetch. A point that cannot be served+     * is absent from the result, as with the old batch endpoint.+     */+    suspend fun currentTemperatures(+        points: List<Pair<Double, Double>>,+        nowEpoch: Long = System.currentTimeMillis() / MS_PER_S,+    ): Map<Pair<Double, Double>, Double> {+        if (points.isEmpty()) return emptyMap()+        val out = LinkedHashMap<Pair<Double, Double>, Double>()+        for (p in points.take(20)) {+            val t = runCatching { currentTemperature(p.first, p.second, nowEpoch) }.getOrNull()+            if (t != null) out[p] = t+        }+        return out+    }++    // --- Map reads (tiles instead of the `.om` spatial proxy) --------------++    private suspend fun tileAt(ty: Int, tx: Int, now: Long): WxTiles.Tile {+        var en = entry(ty, tx, now)+        if (en.e.gen == 0L || en.e.tile.isEmpty) throw NotCovered("no tile $ty/$tx")+        return try {+            runTile(en, ty, tx)+        } catch (_: RunChanged) {+            en = entry(ty, tx, now, force = true)+            runTile(en, ty, tx)+        }+    }++    private fun isoHour(epochHour: Long): String {+        val d = java.time.Instant.ofEpochSecond(epochHour * 3600).atOffset(java.time.ZoneOffset.UTC)+        return String.format(java.util.Locale.US, "%04d-%02d-%02dT%02d:00Z", d.year, d.monthValue, d.dayOfMonth, d.hour)+    }++    private fun parseHourIso(s: String): Long? = runCatching {+        val norm = when {+            s.endsWith("Z") && s.count { it == ':' } == 1 -> s.dropLast(1) + ":00Z"+            else -> s+        }+        java.time.Instant.parse(norm).epochSecond / 3600+    }.getOrNull()++    /**+     * Map metadata for the run serving (lat, lon): run time, the ICON hours+     * its tiles hold, and the shadeable variables. Null when the point has+     * no tile. Replaces `data_spatial/<model>/latest.json` on the origin.+     */+    suspend fun mapMetadata(lat: Double, lon: Double, nowEpoch: Long = System.currentTimeMillis() / MS_PER_S): OmMapMetadata? =+        withContext(Dispatchers.IO) {+            if (!enabled) return@withContext null+            val (ty, tx) = WxGrid.tileOf(lat, lon, WxPack.NY, WxPack.NX, WxPack.CELLS)+            val tile = runCatching { lock.withLock { tileAt(ty, tx, nowEpoch) } }.getOrNull() ?: return@withContext null+            val icon = tile.section(WxTiles.MODEL_ICON) ?: return@withContext null+            val temp = icon.variable("temperature_2m") ?: return@withContext null+            OmMapMetadata(+                referenceTime = tile.iconRunIso,+                validTimes = (0 until temp.nt).map { isoHour(temp.h0 + it) },+                variables = MAP_VARIABLES,+            )+        }++    /**+     * Values of [variable] (bundle vocabulary, e.g. `temperature_2m`,+     * `apparent_temperature`, `wind_speed_10m`, `uv_index`) over a bbox at+     * [validTime], sampled nearest-cell from the run tiles into an+     * [outW]×[outH] row-major raster (row 0 = north, Mercator rows as the+     * old `.om` resampler). NaN where no tile/variable covers a pixel.+     *+     * Precision: the old path bilinearly interpolated the same 0.125°+     * ICON grid from `.om` files; this reads the identical grid from the+     * R2 tiles but takes the nearest cell (no interpolation, no DEM lapse+     * correction — the `.om` path had neither lapse either), so edges are+     * up to half a cell (~7 km) blockier. Derived series (feels/dew/+     * visibility/wind speed) use the same [WxDerive] formulas as the bundle.+     */+    @Suppress("LongParameterList", "CyclomaticComplexMethod")+    suspend fun regionValues(+        variable: String, validTime: String,+        west: Double, south: Double, east: Double, north: Double,+        outW: Int, outH: Int,+        nowEpoch: Long = System.currentTimeMillis() / MS_PER_S,+    ): FloatArray? = withContext(Dispatchers.IO) {+        if (!enabled || outW <= 0 || outH <= 0) return@withContext null+        val epochH = parseHourIso(validTime) ?: return@withContext null+        val byTile = HashMap<Pair<Int, Int>, WxTiles.Tile?>()+        suspend fun tileFor(lat: Double, lon: Double): WxTiles.Tile? {+            val tt = WxGrid.tileOf(lat, lon, WxPack.NY, WxPack.NX, WxPack.CELLS)+            if (!byTile.containsKey(tt)) {+                byTile[tt] = runCatching { lock.withLock { tileAt(tt.first, tt.second, nowEpoch) } }.getOrNull()+            }+            return byTile[tt]+        }+        val merc = { latDeg: Double -> StrictMath.log(StrictMath.tan(Math.PI / 4 + Math.toRadians(latDeg) / 2)) }+        val invMerc = { y: Double -> Math.toDegrees(2 * StrictMath.atan(StrictMath.exp(y)) - Math.PI / 2) }+        val yN = merc(north)+        val yS = merc(south)+        val out = FloatArray(outW * outH) { Float.NaN }+        for (r in 0 until outH) {+            val lat = invMerc(yN + (r + 0.5) / outH * (yS - yN))+            for (c in 0 until outW) {+                val lon = west + (c + 0.5) * (east - west) / outW+                val tile = tileFor(lat, lon) ?: continue+                out[r * outW + c] = sampleVariable(tile, variable, lat, lon, epochH)+            }+        }+        out+    }++    private fun sampleVariable(tile: WxTiles.Tile, variable: String, lat: Double, lon: Double, epochH: Long): Float {+        val icon = tile.section(WxTiles.MODEL_ICON) ?: return Float.NaN+        val (j, i) = WxGrid.cellIndex(WxGrid.ICON, lat, lon, icon.ny, icon.nx)+        val cell = icon.cell(j, i) ?: return Float.NaN+        fun raw(section: WxTiles.Section, name: String, cj: Int, ci: Int): Double {+            val b = section.variable(name) ?: return Double.NaN+            val cc = section.cell(cj, ci) ?: return Double.NaN+            val k = epochH - b.h0+            if (k < 0 || k >= b.nt) return Double.NaN+            val v = b.values[cc * b.nt + k.toInt()].toDouble()+            return if (v.isFinite()) WxDerive.applyUnitSeries(name, floatArrayOf(v.toFloat()))[0].toDouble() else v+        }+        fun iv(name: String): Double = raw(icon, name, j, i)+        val temp = iv("temperature_2m")+        val rh = iv("relative_humidity_2m")+        return when (variable) {+            "temperature_2m" -> temp.toFloat()+            "relative_humidity_2m" -> rh.toFloat()+            "pressure_msl" -> iv("pressure_msl").toFloat()+            "cloud_cover" -> iv("cloud_cover").toFloat()+            "precipitation" -> iv("precipitation").toFloat()+            "wind_gusts_10m" -> iv("wind_gusts_10m").toFloat()+            "wind_speed_10m" -> {+                val u = iv("wind_u_component_10m") / 3.6+                val v = iv("wind_v_component_10m") / 3.6+                (WxDerive.windSpdDir(u, v)?.first ?: Double.NaN).toFloat()+            }+            "apparent_temperature" -> {+                val u = iv("wind_u_component_10m") / 3.6+                val v = iv("wind_v_component_10m") / 3.6+                val ms = if (u.isFinite() && v.isFinite()) StrictMath.hypot(u, v) else Double.NaN+                (WxDerive.apparentTemperature(temp, rh, ms) ?: Double.NaN).toFloat()+            }+            "dew_point_2m" -> (WxDerive.dewPoint(temp, rh) ?: Double.NaN).toFloat()+            "visibility" -> (WxDerive.visibility(iv("precipitation"), rh) ?: Double.NaN).toFloat()+            "uv_index" -> {+                val inEurope = WxGrid.europeContains(lat, lon)+                val sec = tile.section(if (inEurope) WxTiles.MODEL_CAMS_EUROPE else WxTiles.MODEL_CAMS_GLOBAL)+                    ?: return Float.NaN+                val def = if (inEurope) WxGrid.CAMS_EUROPE else WxGrid.CAMS_GLOBAL+                val (cj, ci) = WxGrid.cellIndex(def, lat, lon, sec.ny, sec.nx)+                raw(sec, "uv_index", cj, ci).toFloat()+            }+            else -> Float.NaN+        }+    }+     @androidx.annotation.VisibleForTesting     internal fun resetForTest() {         entries.clear()@@ -268,6 +512,7 @@ object WxStatic {         hists.clear()         geos.clear()         geoHeader = null+        manifestCache = null         dir = null     } }
weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.ktindex bd9c74de93..946962f4ed 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.kt@@ -50,11 +50,11 @@ import com.vayunmathur.library.util.ConnectivityMonitor import com.vayunmathur.library.map.GeoPoint  /**- * Full-screen map that shades an area by a chosen weather [metric], decoded- * natively from the self-hosted binary `.om` spatial files (keyless,- * model-native resolution) via the Rust/JNI [OmTilesNative] bridge. The decoded field is- * colorized to a bitmap and drawn as a translucent [RasterLayer] over a muted- * raster basemap. Panning/zooming re-decodes only the visible region; the+ * Full-screen map that shades an area by a chosen weather [metric], sampled+ * on device from the static R2 run tiles (same 0.125° ICON grid the bundle+ * uses; nearest cell, no `.om` files and no origin read). The sampled field is+ * colorized to a bitmap and drawn as a translucent overlay over a muted+ * basemap. Panning/zooming re-samples only the visible region; the  * measure and time step can be changed on the fly. Pre-set from the graph sheet  * to a location + time + measure.  */@@ -78,7 +78,7 @@ fun WeatherMapPage(         CameraPosition(target = GeoPoint(longitude, latitude), zoom = 7.0),     ) -    WeatherMapMetadataEffect(state, isoTime)+    WeatherMapMetadataEffect(state, isoTime, latitude, longitude)     WeatherMapCameraEffects(state, camera)     WeatherMapDecodeEffect(state) 
weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapState.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapState.kt b/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapState.ktindex 0b4a1fde08..e9cb7ff556 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapState.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapState.kt@@ -2,13 +2,10 @@ package com.vayunmathur.weather.ui  import com.vayunmathur.library.log.Log import com.vayunmathur.library.map.GeoBounds-import com.vayunmathur.weather.domain.map.DwdIconGlobal import com.vayunmathur.weather.domain.map.OmMapMetadata-import com.vayunmathur.weather.domain.map.OmTilesNative import com.vayunmathur.weather.domain.map.colorizeToBitmap-import com.vayunmathur.weather.domain.map.fetchOmMapMetadata-import com.vayunmathur.weather.domain.map.omFileUrl import com.vayunmathur.weather.domain.map.omVariable+import com.vayunmathur.weather.network.WxStatic import com.vayunmathur.weather.domain.WeatherMetric import com.vayunmathur.weather.domain.colorRamp import com.vayunmathur.weather.domain.mapMetrics@@ -61,8 +58,6 @@ internal data class DecodeRequest( internal class WeatherMapState(     metric: String, ) {-    val domain = DwdIconGlobal-     var selectedMetric by mutableStateOf(         runCatching { WeatherMetric.valueOf(metric) }             .getOrDefault(WeatherMetric.Temperature)@@ -95,16 +90,16 @@ internal fun rememberWeatherMapState(metric: String): WeatherMapState {     return remember { WeatherMapState(metric) } } -/** Loads model metadata once, then seeds the time index near the requested time. */+/** Loads run metadata (from the R2 tile serving the page's location) once, then seeds the time index near the requested time. */ @Composable-internal fun WeatherMapMetadataEffect(state: WeatherMapState, isoTime: String?) {-    LaunchedEffect(state.domain) {-        val meta = fetchOmMapMetadata(state.domain)+internal fun WeatherMapMetadataEffect(state: WeatherMapState, isoTime: String?, latitude: Double, longitude: Double) {+    LaunchedEffect(latitude, longitude) {+        val meta = WxStatic.mapMetadata(latitude, longitude)         state.metadata = meta         Log.status(             "OmMap",-            if (meta == null) "metadata NULL (fetch failed)"-            else "metadata ok ref=${meta.referenceTime} times=${meta.validTimes.size} vars=${meta.variables.size} native=${OmTilesNative.isAvailable}",+            if (meta == null) "metadata NULL (no static tile for the page location)"+            else "metadata ok ref=${meta.referenceTime} times=${meta.validTimes.size} vars=${meta.variables.size}",         )         if (meta != null) {             if (meta.validTimes.isNotEmpty() && !state.userScrubbed) {@@ -176,11 +171,8 @@ internal fun WeatherMapDecodeEffect(state: WeatherMapState) {                 val bbox = req.bbox ?: return@collectLatest                 val meta = req.meta ?: return@collectLatest                 val validTime = meta.validTimes.getOrNull(req.timeIndex) ?: return@collectLatest-                if (!meta.supports(req.metric) || !OmTilesNative.isAvailable) {-                    Log.status(-                        "OmMap",-                        "skip decode: supports=${meta.supports(req.metric)} native=${OmTilesNative.isAvailable} metric=${req.metric}",-                    )+                if (!meta.supports(req.metric)) {+                    Log.status("OmMap", "skip decode: metric ${req.metric} not in the static run")                     state.overlay = null                     return@collectLatest                 }@@ -191,25 +183,21 @@ internal fun WeatherMapDecodeEffect(state: WeatherMapState) {                     state.loading = true                     val decoded = withContext(Dispatchers.IO) {                         val (w, h) = rasterSize(bbox)-                        val url = omFileUrl(state.domain, meta.referenceTime, validTime) ?: return@withContext null                         val t0 = System.currentTimeMillis()-                        // Range-fetching decodeRegion(url); ranges are fetched natively in Rust.-                        // (HttpURLConnection 64KB blocks, LRU) instead of full-file-                        // performRequestBytes (~148 MB) which caused OOM crash.-                        val values = OmTilesNative.decodeRegion(-                            url,-                            variable,-                            state.domain.nx, state.domain.ny, state.domain.lonMin, state.domain.latMin, state.domain.dx, state.domain.dy,+                        // Sampled from the R2 run tiles (nearest ICON cell;+                        // see WxStatic.regionValues for the precision note).+                        val values = WxStatic.regionValues(+                            variable, validTime,                             bbox.west, bbox.south, bbox.east, bbox.north,                             w, h,                         )                         if (values == null) {-                            Log.status("OmMap", "decodeRegion null for $variable $validTime")+                            Log.status("OmMap", "regionValues null for $variable $validTime")                             return@withContext null                         }                         Log.status(                             "OmMap",-                            "decoded $variable $validTime ${w}x$h in ${System.currentTimeMillis() - t0}ms",+                            "sampled $variable $validTime ${w}x$h in ${System.currentTimeMillis() - t0}ms",                         )                         DecodedRegion(values, w, h, bbox)                     }
weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.ktindex 4148a55e87..39d55bbc7a 100644--- a/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/data/GeoAndWorkerTest.kt@@ -65,9 +65,10 @@ class GeoAndWorkerTest {      @JUnitTest(timeout = 60_000)     fun apiBundleFailsWithoutNetwork() = runTest {-        // Hermetic: point the API at a dead loopback port so the failure-        // happens on internet-connected boxes too (CI reached the real-        // api.maproj.org and the "expected failure" never came).+        // Hermetic: disable the static path (NotCovered) and point the+        // flagged fallback at a dead loopback port, so the failure happens+        // on internet-connected boxes too.+        com.vayunmathur.weather.network.WxStatic.enabled = false         com.vayunmathur.weather.network.WeatherApi.bundleBaseOverride = "https://127.0.0.1:9/wx/v1"         try {             try {@@ -76,12 +77,11 @@ class GeoAndWorkerTest {             } catch (e: Exception) {                 assertTrue(e.message != null || e is RuntimeException)             }-            val failure = kotlin.test.assertFailsWith<Exception> {-                WeatherApi.currentTemperatures(listOf(52.0 to 13.0))-            }-            assertNotNull(failure)+            // Batch temperatures degrade to an empty map, never a throw.+            assertTrue(WeatherApi.currentTemperatures(listOf(52.0 to 13.0)).isEmpty())         } finally {             com.vayunmathur.weather.network.WeatherApi.bundleBaseOverride = null+            com.vayunmathur.weather.network.WxStatic.enabled = true         }     } }
weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.ktindex 3e35474409..cac3808c66 100644--- a/weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/network/NetworkDtoTest.kt@@ -2,7 +2,6 @@ package com.vayunmathur.weather.network  import com.vayunmathur.weather.domain.map.OmMapMetadata import com.vayunmathur.weather.domain.WeatherMetric-import com.vayunmathur.weather.domain.map.omFileUrl import com.vayunmathur.weather.domain.map.DwdIconGlobal import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.Json@@ -84,22 +83,10 @@ class NetworkDtoTest {         assertEquals(2879, DwdIconGlobal.nx)     } -    @Test fun omFileUrl() {-        assertEquals(-            "https://api.maproj.org/data_spatial/dwd_icon/2026/07/01/1800Z/2026-07-01T1800.om",-            omFileUrl(DwdIconGlobal, "2026-07-01T18:00:00Z", "2026-07-01T18:00Z"),-        )-    }-     @Test fun geocodeBlankIsEmpty() = runTest {         assertTrue(WeatherApi.geocode("").results.isEmpty())         assertTrue(WeatherApi.geocode("   ").results.isEmpty())         assertTrue(WeatherApi.currentTemperatures(emptyList()).isEmpty())     } -    @Test fun currentTempResponseDefaults() {-        val c = json.decodeFromString<CurrentTemperatureResponse>("""{"current":{"temperature_2m":21.5}}""")-        assertEquals(21.5, c.current!!.temperature)-        assertNull(json.decodeFromString<CurrentTemperatureResponse>("{}").current)-    } }
weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.ktindex e72141145e..4dd34ef865 100644--- a/weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/network/WeatherApiBehaviourTest.kt@@ -21,11 +21,15 @@ class WeatherApiBehaviourTest {      @BeforeTest fun setUp() {         GeoDatabase.init(ctx)+        // Hermetic failure path: static path disabled (NotCovered) and the+        // flagged fallback pointed at a dead loopback port.+        WxStatic.enabled = false         WeatherApi.bundleBaseOverride = "https://127.0.0.1:9/wx/v1"     }      @AfterTest fun tearDown() {         WeatherApi.bundleBaseOverride = null+        WxStatic.enabled = true     }      @Test fun geocodeBlankShortCircuits() = runTest {@@ -44,12 +48,13 @@ class WeatherApiBehaviourTest {         assertEquals(emptyMap(), WeatherApi.currentTemperatures(emptyList()))     } -    @Test fun bundleDerivedCallsFailAgainstDeadServer() = runTest {+    @Test fun bundleDerivedCallsFailWithoutStaticCoverage() = runTest {         assertFailsWith<Exception> { WeatherApi.forecast(52.0, 13.0) }         assertFailsWith<Exception> { WeatherApi.airQuality(52.0, 13.0) }         assertFailsWith<Exception> { WeatherApi.timezoneAt(52.0, 13.0) }-        assertFailsWith<Exception> { WeatherApi.currentTemperature(52.0, 13.0) }-        assertFailsWith<Exception> { WeatherApi.currentTemperatures(listOf(52.0 to 13.0)) }+        // Per-point reads degrade to absent/null instead of throwing.+        assertEquals(null, WeatherApi.currentTemperature(52.0, 13.0))+        assertEquals(emptyMap(), WeatherApi.currentTemperatures(listOf(52.0 to 13.0)))     }      @Test fun dtoDefaultsAndJsonRoundTrip() {
weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.ktindex 661ec6c90e..eb15a9ba8a 100644--- a/weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/network/WxDtoWireTest.kt@@ -6,26 +6,10 @@ import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertTrue -/** Wire-format round trips for the bundle/batch DTOs: serial names, defaults, nullability. */+/** Wire-format round trips for the bundle DTOs: serial names, defaults, nullability. */ class WxDtoWireTest {     private val json = Json { ignoreUnknownKeys = true } -    @Test-    fun currentBatchDecodesPointsAndDefaultsVersion() {-        val batch = json.decodeFromString<WxCurrentBatch>(-            """{"points":[{"lat":51.5,"lon":-0.12,"temp":9.5,"code":3,"day":1},{"lat":40.7,"lon":-74.0,"temp":21.25,"code":0,"day":0}]}""",-        )-        assertEquals(1, batch.v)-        assertEquals(2, batch.points.size)-        assertEquals(WxCurrentPoint(51.5, -0.12, 9.5, 3, 1), batch.points[0])-        assertEquals(0, batch.points[1].day)-        assertEquals("""{"v":2}""", json.encodeToString(WxCurrentBatch.serializer(), WxCurrentBatch(v = 2))) // default empty points omitted-        assertEquals(WxCurrentBatch(), json.decodeFromString<WxCurrentBatch>("""{}"""))-        // copy/component semantics carry the point values, not defaults-        val moved = batch.points[1].copy(temp = -3.0, code = 61)-        assertEquals(-3.0, moved.temp); assertEquals(61, moved.code); assertEquals(40.7, moved.lat)-    }-     @Test     fun min15AndCurrentSerialNames() {         val min15 = json.decodeFromString<WxMin15>("""{"start":1700000000,"precip":[0.0,0.2,1.4]}""")@@ -40,15 +24,11 @@ class WxDtoWireTest {     }      @Test-    fun regionTimezoneAndCurrentTemperatureDefaults() {+    fun regionTimezoneDefaults() {         val tz = json.decodeFromString<RegionTimezone>("""{"timezone":"Europe/London","timezone_abbreviation":"GMT","utc_offset_seconds":0}""")         assertEquals("Europe/London", tz.timezone); assertEquals("GMT", tz.abbreviation); assertEquals(0, tz.utcOffsetSeconds)         val empty = json.decodeFromString<RegionTimezone>("""{}""")         assertNull(empty.timezone); assertNull(empty.abbreviation)-        val temp = json.decodeFromString<CurrentTemperatureResponse>("""{"current":{"temperature_2m":18.25}}""")-        assertEquals(18.25, temp.current!!.temperature)-        assertNull(json.decodeFromString<CurrentTemperatureResponse>("""{}""").current)-        assertTrue(json.encodeToString(CurrentTemperature.serializer(), CurrentTemperature(7.5)).contains("\"temperature_2m\":7.5"))     }      @Test
weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.ktindex 55a17e4df4..a98b63f54d 100644--- a/weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.kt@@ -22,8 +22,8 @@ import java.util.zip.GZIPInputStream  * tile + the finished days + the geo block (header, entry, block); the same  * run later costs nothing until `next_check`, then one entry GET; a new run  * costs entry + tile; a run replaced between the two GETs is caught by- * If-Match; an ocean tile is a clean [WxStatic.NotCovered] (→ API fallback)- * and is not re-checked for 6 h.+ * If-Match; an ocean tile is a clean [WxStatic.NotCovered] (the flagged+ * no-land-tile case) and is not re-checked for 6 h.  */ class WxStaticTest {     private val json = Json { ignoreUnknownKeys = true }@@ -124,6 +124,40 @@ class WxStaticTest {         assertEquals("entry, tile (412), entry, tile", 4, requests.count { it.startsWith("run.wxp@") })     } +    @Test+    fun `timezone current and map reads come from the packs`() = runBlocking {+        val b = WxStatic.bundle(lat, lon, now)+        val tz = WxStatic.timezoneAt(lat, lon, now)+        assertEquals(b.tz, tz.timezone)+        assertEquals(b.utcOffset, tz.utcOffsetSeconds)+        assertEquals(b.current!!.temp, WxStatic.currentTemperature(lat, lon, now)!!, 0.0)+        assertEquals(+            mapOf((lat to lon) to b.current!!.temp),+            WxStatic.currentTemperatures(listOf(lat to lon), now),+        )+        val meta = WxStatic.mapMetadata(lat, lon, now)!!+        assertEquals(b.run, meta.referenceTime)+        assertTrue(meta.validTimes.size > 24)+        assertTrue(meta.supports(com.vayunmathur.weather.domain.WeatherMetric.Temperature))+        val values = WxStatic.regionValues(+            "temperature_2m", meta.validTimes[meta.validTimes.size / 2],+            lon - 0.5, lat - 0.5, lon + 0.5, lat + 0.5, 8, 8, now,+        )!!+        assertTrue("some finite samples", values.any { it.isFinite() })+        assertTrue("some gaps stay NaN-transparent or finite, never invented", values.all { it.isNaN() || it.isFinite() })+    }++    @Test+    fun `manifest decodes generated_at and valid times`() = runBlocking {+        WxStatic.manifestFetcher = {+            """{"v":1,"run":"r1","gen":1794600000,"generated_at":1794600000,"next_check":1794607421,"icon_run":"2026-11-13T12:00:00Z","valid_times":["2026-11-13T12:00Z"],"variables":["temperature_2m"]}"""+        }+        val m = WxStatic.manifest(now)+        assertEquals(1794600000L, m.generatedAt)+        assertEquals(listOf("2026-11-13T12:00Z"), m.validTimes)+        assertEquals(1794600000L, WxStatic.generatedAtEpoch())+    }+     @Test     fun `an ocean tile is NotCovered and not re-checked for hours`() = runBlocking {         repeat(2) {
weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.ktindex 1736115f95..668c0d8fa2 100644--- a/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt@@ -157,7 +157,7 @@ class PagesTest {     @Test fun mapMetadataEffectHandlesFetchFailure() {         rule.setContent {             val state = rememberWeatherMapState("Humidity")-            WeatherMapMetadataEffect(state, "2026-07-01T18:00Z")+            WeatherMapMetadataEffect(state, "2026-07-01T18:00Z", 52.52, 13.40)             assertEquals(WeatherMetric.Humidity, state.selectedMetric)         }         rule.waitForIdle()