Commit aa4b71727c
aa4b71727c29f5f7116aba0dc2db4c279960721d
parent: 10eb70e1c4
Unsigned
cmc <hello@cleberg.net> · 2026-10-21 14:17 UTC
Sun snapshot: OVATION as a byte grid; Planets widget: one location read, sampling shared across a night (!81)
Engine report (perf/engine.md) findings 6 and 7.
## Changes
- `Ovation` encodes its cells as the feed's 360 × 181 grid, one byte per cell (base64 in the snapshot JSON), in the feed's order (longitude 0...359, then latitude −90...90), and decodes the non-zero cells back in that order. Snapshots saved with `cells` still decode. In-memory `cells` and the aurora map are unchanged.
- `PlanetsProvider` reads the location once per timeline (it made a `CLLocationManager` per entry) and calls the new `Tonight.visiblePlanets(at:from:)`. For each date it gives the night's end and the planets with a `best` time, brightest first, as `Tonight(at:from:)` does. The Sun's rise and set are still searched per date (Astronomy Engine's searches near polar day and night give different answers from neighbouring start times, and the entries must match); the 15-minute planet sampling is shared by dates whose nights end together (within 1 s) and start on the same 15-minute grid: dates before the same sunset, and dark dates whole quarter hours apart. `now`, `magnitude`, `rise` and `set` are per date as before.
## Measurements
Release benchmark package (perf/, pointed at this branch), M2 Pro, medians. Load (`uptime`, 12 cores): main 2.78 → 2.98, branch 2.40 → 3.65.
| | main | branch |
|---|---:|---:|
| Planets timeline, Chicago 13:00 start: location + 12 entries + rows | 16.9 ms | 4.3 ms |
| same, engine only (12 × `Tonight` / `visiblePlanets`) | 10.9 ms | 4.0 ms |
| same, engine only, 22:00 start | 7.8 ms | 3.4 ms |
| SunSnapshot, live NOAA data the app saved: size | 786 KB | 156 KB |
| decode | 24.7 ms (85,966 allocations, 21.8 MB) | 2.0 ms (7,684, 2.4 MB) |
| encode | 29.2 ms (106,336, 24.2 MB) | 2.3 ms (9,104, 2.2 MB) |
| `SunSnapshot.load` from file, peak footprint (baseline 2.2 MB) | 13.5 MB | 4.0 MB |
| load + `save`, peak footprint | 25.9 MB | 5.1 MB |
Of the 156 KB, 69 KB is the X-ray series (1,440 minutes, unchanged) and 87 KB the base64 grid.
Planets `getTimeline` in the widget extension, iPhone 18 Pro simulator, Release, fresh install and a Planets widget added from the gallery (Chicago fallback), 3 installs each, load 2.7–3.8:
| | main | branch |
|---|---:|---:|
| First timeline in the process | 26.2–31.3 ms | 8.2–10.0 ms |
| Later timelines | 22.8–23.3 ms | 5.1–6.3 ms |
Same output:
- `visiblePlanetsMatchTonightAtEachDate`: Chicago, Quito, Sydney and Tromsø, six dates (including 15 Jan and 14 May for Tromsø's polar transitions), four start hours, 12 hourly dates each; same bodies in the same order, equal `now`, `magnitude`, `rise`, `set` and `end`, `best` within 1 s.
- Widget rows (the provider's strings) for timelines starting every 259 minutes through 2026 at the same four places: 97,440 entries, 0 differ.
- Aurora map rendered from a live snapshot before and after a save in the new format: identical pixels. Round trip of feed-ordered data is `==`.
## Tests
- `swift test` (Packages/MoonriseKit): 199 passed (196 + `visiblePlanetsMatchTonightAtEachDate`, `ovationSavesAsGrid`, `ovationReadsCellsFromOlderSnapshots`).
- `npm test` (server): 55 passed.
- `xcodebuild test` (Moonrise, iPhone 18 Pro simulator): passed. Accessibility audit 63 issues: Sky 4, Settings 2, System 7, Sun 3, News & launches 20, Library 14, Library page: Saturn 13 (News & launches was 21 in !80; its content is live).
## Not verified
- A device or a Watch; timings are from the Mac and the simulator.
- Cells that are not on the 1° grid or not whole percentages: the feed has none, and such a cell would be dropped or rounded when saved.
Layout: unified · split
App/Widgets/MoonriseWidgets.swift
+14 −10
| @@ -149,26 +149,30 @@ struct PlanetsProvider: TimelineProvider { |
| 149 | } |
149 | } |
| 150 | |
150 | |
| 151 | func getSnapshot(in context: Context, completion: @escaping (PlanetsEntry) -> Void) { |
151 | func getSnapshot(in context: Context, completion: @escaping (PlanetsEntry) -> Void) { |
| 152 | completion(entry(at: .now)) |
152 | completion(entries(at: [.now])[0]) |
| 153 | } |
153 | } |
| 154 | |
154 | |
| 155 | func getTimeline(in context: Context, completion: @escaping (Timeline<PlanetsEntry>) -> Void) { |
155 | func getTimeline(in context: Context, completion: @escaping (Timeline<PlanetsEntry>) -> Void) { |
| 156 | completion(Timeline(entries: hourly(from: .now).map(entry), policy: .atEnd)) |
156 | completion(Timeline(entries: entries(at: hourly(from: .now)), policy: .atEnd)) |
| 157 | } |
157 | } |
| 158 | |
158 | |
| 159 | func entry(at date: Date) -> PlanetsEntry { |
159 | func entries(at dates: [Date]) -> [PlanetsEntry] { |
| 160 | let (observer, located) = widgetObserver() |
160 | let (observer, located) = widgetObserver() |
| 161 | engineLock.lock() |
161 | engineLock.lock() |
| 162 | defer { engineLock.unlock() } |
162 | defer { engineLock.unlock() } |
| 163 | guard let t = try? Tonight(at: date, from: observer) else { return PlanetsEntry(date: date, rows: [], located: located) } |
163 | guard let nights = try? Tonight.visiblePlanets(at: dates, from: observer) else { |
| |
164 | return dates.map { PlanetsEntry(date: $0, rows: [], located: located) } |
| |
165 | } |
| 164 | let time: (Date) -> String = { $0.formatted(date: .omitted, time: .shortened) } |
166 | let time: (Date) -> String = { $0.formatted(date: .omitted, time: .shortened) } |
| 165 | let rows = t.planets.filter { $0.best != nil }.map { p -> PlanetsEntry.Row in |
167 | return zip(dates, nights).map { date, night in |
| 166 | let name = p.body.rawValue.capitalized |
168 | let rows = night.planets.map { p -> PlanetsEntry.Row in |
| 167 | if p.now.altitude > 0 { return .init(name: name, detail: String(format: "up, %.0f°", p.now.altitude)) } |
169 | let name = p.body.rawValue.capitalized |
| 168 | if let rise = p.rise, rise < t.end { return .init(name: name, detail: "rises \(time(rise))") } |
170 | if p.now.altitude > 0 { return .init(name: name, detail: String(format: "up, %.0f°", p.now.altitude)) } |
| 169 | return .init(name: name, detail: "tonight") |
171 | if let rise = p.rise, rise < night.end { return .init(name: name, detail: "rises \(time(rise))") } |
| |
172 | return .init(name: name, detail: "tonight") |
| |
173 | } |
| |
174 | return PlanetsEntry(date: date, rows: rows, located: located) |
| 170 | } |
175 | } |
| 171 | return PlanetsEntry(date: date, rows: rows, located: located) |
| |
| 172 | } |
176 | } |
| 173 | } |
177 | } |
| 174 | |
178 | |
Packages/MoonriseKit/Sources/Feeds/Sun.swift
+32
| @@ -148,3 +148,35 @@ public struct Ovation: Sendable, Equatable, Codable { |
| 148 | try decode(await session.data(from: url).0) |
148 | try decode(await session.data(from: url).0) |
| 149 | } |
149 | } |
| 150 | } |
150 | } |
| |
151 | |
| |
152 | /// Saved as the feed's grid, one byte per cell in the feed's order (longitude 0...359, then latitude −90...90). |
| |
153 | /// Snapshots saved before the grid hold `cells`. |
| |
154 | extension Ovation { |
| |
155 | enum CodingKeys: String, CodingKey { |
| |
156 | case forecastTime, grid, cells |
| |
157 | } |
| |
158 | |
| |
159 | public init(from decoder: Decoder) throws { |
| |
160 | let c = try decoder.container(keyedBy: CodingKeys.self) |
| |
161 | forecastTime = try c.decode(Date.self, forKey: .forecastTime) |
| |
162 | if let grid = try c.decodeIfPresent(Data.self, forKey: .grid) { |
| |
163 | cells = grid.enumerated().compactMap { i, p in |
| |
164 | p > 0 ? Cell(lon: Double(i / 181), lat: Double(i % 181 - 90), probability: Double(p)) : nil |
| |
165 | } |
| |
166 | } else { |
| |
167 | cells = try c.decode([Cell].self, forKey: .cells) |
| |
168 | } |
| |
169 | } |
| |
170 | |
| |
171 | public func encode(to encoder: Encoder) throws { |
| |
172 | var grid = Data(count: 360 * 181) |
| |
173 | for cell in cells { |
| |
174 | let lon = Int(cell.lon), lat = Int(cell.lat) + 90 |
| |
175 | guard (0..<360).contains(lon), (0...180).contains(lat) else { continue } |
| |
176 | grid[lon * 181 + lat] = UInt8(clamping: Int(cell.probability.rounded())) |
| |
177 | } |
| |
178 | var c = encoder.container(keyedBy: CodingKeys.self) |
| |
179 | try c.encode(forecastTime, forKey: .forecastTime) |
| |
180 | try c.encode(grid, forKey: .grid) |
| |
181 | } |
| |
182 | } |
Packages/MoonriseKit/Sources/SkyEngine/Tonight.swift
+59
| @@ -79,4 +79,63 @@ public struct Tonight: Sendable { |
| 79 | public func moonAndDarkness(time: Date.FormatStyle = .init(date: .omitted, time: .shortened)) -> String { |
79 | public func moonAndDarkness(time: Date.FormatStyle = .init(date: .omitted, time: .shortened)) -> String { |
| 80 | SkyEngine.moonAndDarkness(night: DateInterval(start: start, end: end), dark: dark, moonUp: moonUp, moonIllumination: moonIllumination, time: time) |
80 | SkyEngine.moonAndDarkness(night: DateInterval(start: start, end: end), dark: dark, moonUp: moonUp, moonIllumination: moonIllumination, time: time) |
| 81 | } |
81 | } |
| |
82 | |
| |
83 | /// For each of `dates`, in order: the night's `end` and the planets with a `best` time, brightest first, as |
| |
84 | /// `Tonight(at:from:)` gives them. The 15-minute sampling is shared by dates whose nights end together and start on |
| |
85 | /// the same 15-minute grid: those before the same sunset, and dark dates whole quarter hours apart. |
| |
86 | public static func visiblePlanets(at dates: [Date], from observer: Observer) throws -> [(end: Date, planets: [PlanetTonight])] { |
| |
87 | var night: Night? |
| |
88 | return try dates.map { date in |
| |
89 | // As in `init(at:from:)`. |
| |
90 | let dark = try SkyEngine.horizontal(.sun, at: date, from: observer, refraction: true).altitude < -0.8 |
| |
91 | let start = dark ? date : SkyEngine.riseSet(.sun, after: date, from: observer).set ?? date |
| |
92 | let end = SkyEngine.riseSet(.sun, after: start, from: observer).rise ?? start.addingTimeInterval(12 * 3600) |
| |
93 | if night?.covers(start, end) != true { night = try Night(start: start, end: end, from: observer) } |
| |
94 | let n = night! |
| |
95 | let first = Int((start.timeIntervalSince(n.start) / 900).rounded()) |
| |
96 | var planets: [PlanetTonight] = [] |
| |
97 | for (body, altitudes) in n.altitudes { |
| |
98 | var best: (date: Date, position: Horizontal)? |
| |
99 | for i in first..<n.samples.count where altitudes[i].altitude > 10 && altitudes[i].altitude > best?.position.altitude ?? -90 { |
| |
100 | best = (n.samples[i], altitudes[i]) |
| |
101 | } |
| |
102 | guard best != nil else { continue } |
| |
103 | let rs = SkyEngine.riseSet(body, after: date, from: observer) |
| |
104 | planets.append(PlanetTonight( |
| |
105 | body: body, |
| |
106 | magnitude: try SkyEngine.illumination(body, at: date).magnitude, |
| |
107 | now: try SkyEngine.horizontal(body, at: date, from: observer, refraction: true), |
| |
108 | best: best, |
| |
109 | rise: rs.rise, |
| |
110 | set: rs.set |
| |
111 | )) |
| |
112 | } |
| |
113 | return (end, planets.sorted { $0.magnitude < $1.magnitude }) |
| |
114 | } |
| |
115 | } |
| |
116 | |
| |
117 | /// The planet samples of `Tonight(at:from:)` for a night. |
| |
118 | private struct Night { |
| |
119 | var start: Date |
| |
120 | var end: Date |
| |
121 | var samples: [Date] |
| |
122 | var altitudes: [(Body, [Horizontal])] |
| |
123 | |
| |
124 | init(start: Date, end: Date, from observer: Observer) throws { |
| |
125 | self.start = start |
| |
126 | self.end = end |
| |
127 | let samples = stride(from: start.timeIntervalSince1970, through: end.timeIntervalSince1970, by: 900).map(Date.init(timeIntervalSince1970:)) |
| |
128 | self.samples = samples |
| |
129 | altitudes = try [Body.mercury, .venus, .mars, .jupiter, .saturn].map { body in |
| |
130 | (body, try samples.map { try SkyEngine.horizontal(body, at: $0, from: observer, refraction: true) }) |
| |
131 | } |
| |
132 | } |
| |
133 | |
| |
134 | /// Whether the samples of a night from `start` to `end` are a run of these: the same end, and `start` on or |
| |
135 | /// after this start on its 15-minute grid. Rise and set searches from different dates agree to well under 1 s. |
| |
136 | func covers(_ start: Date, _ end: Date) -> Bool { |
| |
137 | let steps = start.timeIntervalSince(self.start) / 900 |
| |
138 | return abs(end.timeIntervalSince(self.end)) < 1 && steps > -0.5 && abs(steps - steps.rounded()) < 0.001 |
| |
139 | } |
| |
140 | } |
| 82 | } |
141 | } |
Packages/MoonriseKit/Tests/FeedsTests/SunTests.swift
+15
| @@ -58,3 +58,18 @@ import Testing |
| 58 | #expect(o.cells.last == Ovation.Cell(lon: 0, lat: 65, probability: 12)) |
58 | #expect(o.cells.last == Ovation.Cell(lon: 0, lat: 65, probability: 12)) |
| 59 | #expect(o.forecastTime == (try Date("2026-10-18T00:37:00Z", strategy: .iso8601))) |
59 | #expect(o.forecastTime == (try Date("2026-10-18T00:37:00Z", strategy: .iso8601))) |
| 60 | } |
60 | } |
| |
61 | |
| |
62 | @Test func ovationSavesAsGrid() throws { |
| |
63 | let rows = (0..<360).flatMap { lon in (-90...90).map { lat in "[\(lon),\(lat),\(abs(lat) >= 55 && abs(lat) <= 80 ? (lon + lat + 90) % 101 : 0)]" } } |
| |
64 | let feed = Data(#"{"Forecast Time": "2026-10-18T00:37:00Z", "coordinates": [\#(rows.joined(separator: ","))]}"#.utf8) |
| |
65 | let o = try Ovation.decode(feed) |
| |
66 | let data = try JSONEncoder().encode(o) |
| |
67 | #expect(data.count < 90_000) |
| |
68 | #expect(try JSONDecoder().decode(Ovation.self, from: data) == o) |
| |
69 | } |
| |
70 | |
| |
71 | @Test func ovationReadsCellsFromOlderSnapshots() throws { |
| |
72 | let data = Data(#"{"forecastTime": 782614800, "cells": [{"lon": 0, "lat": 65, "probability": 12}, {"lon": 359, "lat": -60, "probability": 3}]}"#.utf8) |
| |
73 | let o = try JSONDecoder().decode(Ovation.self, from: data) |
| |
74 | #expect(o.cells == [Ovation.Cell(lon: 0, lat: 65, probability: 12), Ovation.Cell(lon: 359, lat: -60, probability: 3)]) |
| |
75 | } |
Packages/MoonriseKit/Tests/SkyEngineTests/TonightTests.swift
+23
| @@ -22,3 +22,26 @@ import Testing |
| 22 | #expect(abs(sunset.timeIntervalSince(ut(23, 6))) < 120) |
22 | #expect(abs(sunset.timeIntervalSince(ut(23, 6))) < 120) |
| 23 | #expect(t.start == sunset) |
23 | #expect(t.start == sunset) |
| 24 | } |
24 | } |
| |
25 | |
| |
26 | @Test func visiblePlanetsMatchTonightAtEachDate() throws { |
| |
27 | let places = [chicago, Observer(latitude: -0.18, longitude: -78.47), Observer(latitude: -33.87, longitude: 151.21), Observer(latitude: 69.65, longitude: 18.96)] |
| |
28 | let days = try ["2026-01-15", "2026-03-20", "2026-05-14", "2026-06-21", "2026-10-17", "2026-12-21"].map { try Date($0 + "T00:00:00Z", strategy: .iso8601) } |
| |
29 | for observer in places { |
| |
30 | for day in days { |
| |
31 | for hour in [0.0, 6, 12, 18] { |
| |
32 | let dates = (0..<12).map { day.addingTimeInterval(hour * 3600 + 433.25 + Double($0) * 3600) } |
| |
33 | let got = try Tonight.visiblePlanets(at: dates, from: observer) |
| |
34 | for (date, g) in zip(dates, got) { |
| |
35 | let t = try Tonight(at: date, from: observer) |
| |
36 | let want = t.planets.filter { $0.best != nil } |
| |
37 | #expect(g.end == t.end) |
| |
38 | #expect(g.planets.map(\.body) == want.map(\.body), "\(observer) \(date)") |
| |
39 | for (a, b) in zip(g.planets, want) { |
| |
40 | #expect(a.magnitude == b.magnitude && a.now == b.now && a.rise == b.rise && a.set == b.set) |
| |
41 | #expect(abs(a.best!.date.timeIntervalSince(b.best!.date)) < 1) |
| |
42 | } |
| |
43 | } |
| |
44 | } |
| |
45 | } |
| |
46 | } |
| |
47 | } |