commit 27ce8422d39fe3be1677bf307d0cc345c6bde185
parent 72efc444cd4376d3cb4b9d61c6b4a141d7d45650
Author: Michael Camilleri <[email protected]>
Date: Wed, 21 Oct 2026 10:35:47 +0900
Drop Reporter's original snapshots
Each imported report kept the original JSON alongside the
fields Reportage reads from it.
This commit discontinues that practice. Reports no longer have a legacy
field, the 'Reporter Original' row is gone from report details, and
exports no longer offer to include the snapshots. The project notes now
say the importer keeps everything Reportage models rather than
everything Reporter recorded.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
24 files changed, 221 insertions(+), 261 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -21,7 +21,7 @@ Use this file for orientation only; inspect the current filesystem and code befo Persistence is Core Data. CloudKit sync uses raw `CKSyncEngine` with a `Config` zone and a `Reports` zone in the private database. It does not use NSPersistentCloudKitContainer or SwiftData. The Watch fetches only the `Config` zone. -Reporter archives are imported from Reporter's JSON export. The importer must be lossless and idempotent: imported records keep their Reporter IDs, and each imported report keeps its original snapshot JSON in `legacy`. +Reporter archives are imported from Reporter's JSON export. The importer must be idempotent and keep everything Reportage models: imported records keep their Reporter IDs. Reporter-only fields are dropped; the user keeps the export file as the original. ## Personal Data
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -34,7 +34,7 @@ how the Reporter archive maps in.
activity rings, steps, heart rate and so on), and device state (ambient noise,
battery, connectivity). Photos taken aren't recorded.
- CloudKit sync between iPhone and Watch.
-- Lossless import of the full Reporter archive.
+- Import of the full Reporter archive, keeping everything Reportage models.
- On-demand JSON export with a documented, versioned format.
- Written narratives: each report reads as a short narrative built from its
answers, such as 'Not working. Reading at the library, with Sam. Feeling
@@ -94,8 +94,8 @@ The look is called Almanac: ink on paper, like a printed journal.
is a wordmark: italic, with its full stop in a brighter auburn (rust) than
the accent, since a mark that small has to stand out by colour alone. All
sizes are Dynamic Type styles.
-- **Tabs:** Timeline, Charts and Settings. The timeline keeps its serif 'Reportage' title, beside the quick
- log and new report buttons. A tapped prompt switches to the timeline to
+- **Tabs:** Timeline, Charts and Settings. The timeline keeps its serif
+ 'Reportage' title, beside the quick log and new report buttons. A tapped prompt switches to the timeline to
open its survey.
- **Home screen:** reports grouped under day headings, newest first. Each
shows its own local time (the period beneath on a 12-hour clock, so times
@@ -221,9 +221,7 @@ included: there is no fixed built-in set. Each question stores its own
on its ID. The default questions get their rules from `NarrativeRule.builtIn`
when they're seeded, and Reporter's built-in questions (`default-question-1` to
`-7`) get the rules of the defaults that ask the same things when they're
-imported, so imported answers read as narratives too. Stores made before rules
-were stored are filled in once from the same table; a rule the user clears is
-stored blank, so it isn't filled again.
+imported, so imported answers read as narratives too.
### Report
@@ -238,7 +236,6 @@ stored blank, so it isn't filled again.
| `promptedAt` | Fire time of the notification that prompted it, if any. Used to analyse response delay. |
| `completedAt` | When the survey was submitted. |
| `context` | Encoded `Context` value (below). |
-| `legacy` | For imported reports: the original Reporter snapshot JSON, compressed. This guarantees a lossless import without modelling every Reporter-specific field. |
| `modifiedAt` | Used for last-writer-wins on sync. |
### Response
@@ -404,8 +401,12 @@ entities. Every section is optional, and each section records a `source` where
more than one provider exists over time.
- `location`: coordinate, altitude, accuracies, speed, course, fix timestamp
- and placemark (name, thoroughfare, locality, administrative area, postal
- code, country and so on).
+ and placemark: the name, city and country, the region code, the city with
+ its region, the full and short addresses, and the language they're in, with
+ the address in other languages beside it (see [Location](#location)).
+ Imported reports have Reporter's placemark (thoroughfare, locality,
+ administrative area, postal code and so on) until **Update Addresses**
+ replaces it.
- `weather`: normalised to metric: condition, temperature, feels-like, dew
point, humidity, pressure, wind speed, gust and direction, visibility, UV,
cloud cover, precipitation. `source` is `wunderground`, `darkSky` or
@@ -500,18 +501,19 @@ bank'), so a place's `narrativeForm` wins over them. It replaces what follows
### Why not the on-device model
-Narratives used to be proofread by the on-device model (`SystemLanguageModel`)
-to add articles and fix casing. It was dropped:
+The on-device model (`SystemLanguageModel`) isn't used to write or proofread
+narratives:
- **Writing narratives from scratch** invents details (a kitchen table, a
date, a time of night), changes what notes mean, drops answers and assigns
people to the wrong activities.
-- **Proofreading** was safe only behind placeholders for names and non-ASCII
- words, and a check that every output kept every word. Even then the model
- left text unchanged about three times in ten ('at Home' kept its capital),
- so narratives needed retries, storage, versioning and a 'Writing narrative…'
- state while they were written. By then its only real job was places, which
- the rules above do reliably, at once and the same way every time.
+- **Proofreading** is safe only behind placeholders for names and non-ASCII
+ words, and a check that every output keeps every word. Even then the model
+ leaves text unchanged about three times in ten ('at Home' keeps its
+ capital), so narratives would need retries, storage, versioning and a
+ 'Writing narrative…' state while they're written. Its only real job would
+ be places, which the rules above do reliably, at once and the same way
+ every time.
## Prompt Scheduling
@@ -687,17 +689,16 @@ time a survey opens. Capture starts
when the survey opens, so the fix describes the moment of the report, and a
place answer records the fix as where it was given.
-Addresses come from MapKit as `MKMapItem`s; the placemark keeps Reporter's
-fields where they still exist, plus the language, the region code, the city
-with its region and the full and short addresses. Reverse geocoding uses
-MapKit's `MKReverseGeocodingRequest` (`CLGeocoder` is deprecated in iOS 26),
-using `preferredLocale`: once in the user's first language, and again in the
+Addresses come from MapKit as `MKMapItem`s: the placemark holds the name,
+city and country, the language, the region code, the city with its region
+and the full and short addresses. Reverse geocoding uses MapKit's
+`MKReverseGeocodingRequest` (`CLGeocoder` is deprecated in iOS 26), using
+`preferredLocale`: once in the user's first language, and again in the
place's local language when that differs (worked out from the first result's
country: `ja` for Japan, `zh-Hant` for Taiwan), so the placemark can be shown
-by the same rule as place names. Reporter's archive mixes Japanese and English
-placemarks depending on the device language at the time. Apple throttles
-geocoding, so two requests per report is fine but re-geocoding the archive
-would have to run slowly in the background.
+by the same rule as place names. Apple throttles geocoding: two requests per
+report is fine, and **Update Addresses** (see [Behaviour](#behaviour)) looks
+up older addresses again at the pace it allows.
### Weather
@@ -776,8 +777,8 @@ and `audio` and sync with the report.
allowed' look the same and the cache doesn't try to tell them apart.
Nothing is read until Health access has been asked for, so 'never asked'
is never confused with either. Settled entries aren't read again.
-- **Export.** Export can include the cache, since a file the user asked for
- isn't iCloud storage.
+- **Export.** Exports leave the cache out, since a new device rebuilds it
+ from Health.
### Ambient noise
@@ -802,9 +803,7 @@ Health grows.
### Device
-Battery from `UIDevice`, connectivity from `NWPathMonitor`. Photos taken
-between reports aren't recorded: the user doesn't want them logged. The
-`photos` field stays for metadata imported from Reporter.
+Battery from `UIDevice`, connectivity from `NWPathMonitor`.
## Sync
@@ -812,15 +811,15 @@ Private CloudKit database via `CKSyncEngine`, with two custom zones:
- `Config`: `Question` records and synced settings: the schedule, the waking
window, and which questions are asked when.
-- `Reports`: one `Report` record per report. Responses, context and the legacy
- blob are encoded into the record rather than stored as separate records. A
- report is the unit of editing, so coarse records keep record counts and
- operations low. At about 2–5 KB each, the imported archive is roughly 20,000
- records and under 100 MB. `Token` records live here too, one per token
+- `Reports`: one `Report` record per report. Responses and context are
+ encoded into the record rather than stored as separate records. A report
+ is the unit of editing, so coarse records keep record counts and
+ operations low. At about 2 KB each, the imported archive is roughly
+ 20,000 records and about 40 MB. `Token` records live here too, one per token
(about 1,200 in the archive). Keeping tokens separate means renaming 'Home'
changes one record instead of the thousands of reports that use it.
-Sensitive fields (responses, context, legacy, token text and places) go in
+Sensitive fields (responses, context, token text and places) go in
`encryptedValues`.
Conflicts are resolved last-writer-wins per record using `modifiedAt`. Editing
@@ -868,8 +867,8 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
These start on 2023-03-23, a week before Dark Sky's last record, so the
importer classifies records by their keys, not their dates.
- Normalise the first two eras. Treat the third as no weather. All of it stays
- verbatim in `legacy`. Some Weather Underground records have an empty
+ Normalise the first two eras. Treat the third as no weather. Some Weather
+ Underground records have an empty
condition but valid readings, and use `-999` for missing values.
4. **Numbers are mixed int and float** for the same field, and some numbers are
strings (`relativeHumidity: "50%"`, `numericResponse: "0"`). Decode leniently.
@@ -919,7 +918,7 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
token stays renamed; questions only gain new choice options.
- **Place answers record the report's location** as where they were given,
as new answers do. Reporter stored the place's own location with each
- answer; that becomes the place token's coordinate, and stays in `legacy`.
+ answer; that becomes the place token's coordinate.
- **Venues stay Foursquare's.** Imported venues keep their Foursquare IDs,
names and coordinates, and aren't matched to MapKit places: some have
closed, and a wrong match would be worse than none.
@@ -928,7 +927,7 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
device used, without the country code or city with its region that
MapKit gives. **Update Addresses** in Settings' Data section looks each
one up again as capture does, in the user's first language and the
- place's own, and replaces it; the original stays in `legacy`. Reports
+ place's own, and replaces it. Reports
within 25 m of each other share a lookup, since a fix is rarely better
than that: the archive's 20,552 located reports need about 1,700. It
waits out MapKit's throttling, keeps the screen on while it runs, and
@@ -936,9 +935,17 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
language), so stopping and starting again carries on. A spot MapKit has
no address for keeps the old one. It also covers new reports filed
before their address was found.
-- **`legacy` is byte-exact.** The importer slices each snapshot's bytes out of
- the export instead of re-serialising the decoded value, which would reorder
- keys and reformat numbers.
+- **The export file is the original.** Reportage keeps what it models and
+ drops the rest: imperial duplicates of metric readings, weather and
+ altitude fields it doesn't show, Reporter's own flags and sub-record IDs,
+ and timestamps as Reporter wrote them. The snapshot JSON itself isn't
+ kept: it would double the store's size for data nothing reads. The user
+ keeps the export file, and every snapshot can be matched to its report by
+ ID.
+- **Snapshots are decoded one at a time.** The importer slices each
+ snapshot's bytes out of the export and decodes them separately, so one
+ that can't be read is reported as a failure rather than failing the whole
+ import.
- Produces an import summary: counts by kind, question and year, plus zone
assignments and every report that needed a fallback.
- Verification: the importer test suite runs against the fixture. A debug-only
@@ -957,8 +964,7 @@ refer to them by ID. Dates inside a report are ISO 8601 with the report's own
offset, plus an explicit `timeZone` field; other dates are UTC. Records are
written one per line, in batches, so the archive is never held in memory as a
whole. The schema is documented in `Notes/ExportFormat.md` and covered by
-round-trip tests. Including the `legacy` snapshots is optional (off by
-default); when included, each is the original JSON text as a string.
+round-trip tests.
**Delete All Data**, also in the Data section, asks first, then deletes every
report, question and token and seeds the default questions again, leaving
@@ -1070,9 +1076,5 @@ the locale uses for weather. Sleep isn't charted.
- **Multi-select choice questions.** Reporter stores choice answers as arrays,
but every answer in the archive has a single value. The survey takes one
answer for now.
-- **Narrative rules for added questions.** The editor asks for what each kind
- needs (phrases for yes and no, a template for a choice, the nouns for a
- count, a lead-in for a note), and a blank rule shows the answer as prompt
- and answer.
- **Narratives in other languages.** Narratives are English only.
- **App lock.** Should there be an optional Face ID lock? The data is personal.
diff --git a/Notes/ExportFormat.md b/Notes/ExportFormat.md
@@ -93,7 +93,6 @@ refer to tokens by ID, so a token's `text` is the name of every answer using it.
| `completedAt` | date? | When the survey was submitted. |
| `context` | object | See [Context](#context). `{}` when nothing was captured. |
| `responses` | [object] | In survey order. See below. |
-| `legacy` | string? | Imported reports only, and only if the export was made with legacy data included (off by default): the original Reporter snapshot JSON, byte for byte, as a string. |
| `modifiedAt` | date | |
### Response
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -46,7 +46,6 @@
6B71941AAD84B87358A969A0 /* LogPassiveReportIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90F9BD4EA70DCB46924CF9B8 /* LogPassiveReportIntent.swift */; };
6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */ = {isa = PBXBuildFile; fileRef = A00E589A8387E7A1E348503C /* InlineCasing.swift */; };
6E6EAFD0C182B2482F6B6FBD /* HealthFill.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5CC1EB95C82F2D9B0982650 /* HealthFill.swift */; };
- 6F06CC539C4D17B343A9321C /* LegacyBlob.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */; };
7488B9EE97D419E2B6B9FCEA /* PromptNotification.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C326FBA3249ED86912FBF5 /* PromptNotification.swift */; };
7676E79864C7C26CB9EA4B10 /* PromptSchedule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86474CD2E8EC300CD6B37BB2 /* PromptSchedule.swift */; };
7A6543B7C48EC93D468EBBD8 /* PlacePhrase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 577EC17EF58F65207B7EA15D /* PlacePhrase.swift */; };
@@ -164,7 +163,6 @@
24A77AE6DE479403D1D4C9CF /* QuestionPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionPage.swift; sourceTree = "<group>"; };
28AD66BC8ED4AEABF6640108 /* ReportStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportStore.swift; sourceTree = "<group>"; };
2F8F059CE98371610A663BE7 /* SleepSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SleepSummary.swift; sourceTree = "<group>"; };
- 30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LegacyBlob.swift; sourceTree = "<group>"; };
36C7E4E96538BB14AD6956CA /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
383FF2C73A8FBAA2AB13D653 /* ReportageApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageApp.swift; sourceTree = "<group>"; };
3A4B10FFBEDE5D6E23B1B2B4 /* AnswerSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnswerSummaryTests.swift; sourceTree = "<group>"; };
@@ -538,7 +536,6 @@
children = (
5BE7248E73E2859EFF232170 /* EntityMapping.swift */,
E1F55B30D0B5E711A28CD0B1 /* HealthCache.swift */,
- 30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */,
61C0B5BB02ECDBE84F5F73FA /* PersistenceController.swift */,
28AD66BC8ED4AEABF6640108 /* ReportStore.swift */,
74FF461F6E8A0241C18357B2 /* Vocabulary.swift */,
@@ -785,7 +782,6 @@
6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */,
275A9497C40065F5C77AE473 /* InstantReportLogger.swift in Sources */,
3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */,
- 6F06CC539C4D17B343A9321C /* LegacyBlob.swift in Sources */,
BDEB83CDBA9E0B4DB7712491 /* LogPassiveReportIntent.swift in Sources */,
9DFFA4F1FE8F9201855D5884 /* NarrativeBuilder.swift in Sources */,
BD1AA0F75635BF9C68DFA12A /* NarrativeRule.swift in Sources */,
diff --git a/Reportage/Services/Export/ReportageExport.swift b/Reportage/Services/Export/ReportageExport.swift
@@ -38,7 +38,6 @@ struct ReportageExport: Decodable, Sendable {
enum ReportageExportError: Error, Equatable {
case unknownFormat(String)
case unsupportedVersion(Int)
- case legacyNotUTF8(UUID)
case unknownSurvey(String)
}
@@ -197,17 +196,14 @@ struct ExportedReport: Codable, Hashable, Sendable {
var completedAt: Date?
var context: Context
var responses: [Response]
- /// The original Reporter snapshot JSON, byte for byte, as a string. Only
- /// present when the export includes legacy data.
- var legacy: String?
var modifiedAt: Date
private enum CodingKeys: String, CodingKey {
case id, date, timeZone, kind, trigger, state, promptedAt, completedAt
- case context, responses, legacy, modifiedAt
+ case context, responses, modifiedAt
}
- init(_ report: Report, includingLegacy: Bool) throws {
+ init(_ report: Report) {
id = report.id
date = report.date
timeZone = report.timeZone
@@ -218,12 +214,6 @@ struct ExportedReport: Codable, Hashable, Sendable {
completedAt = report.completedAt
context = report.context
responses = report.responses
- if includingLegacy, let blob = report.legacy {
- guard let text = String(data: try LegacyBlob.decompress(blob), encoding: .utf8) else {
- throw ReportageExportError.legacyNotUTF8(report.id)
- }
- legacy = text
- }
modifiedAt = report.modifiedAt
}
@@ -239,7 +229,6 @@ struct ExportedReport: Codable, Hashable, Sendable {
completedAt: completedAt,
context: context,
responses: responses,
- legacy: try legacy.map { try LegacyBlob.compress(Data($0.utf8)) },
modifiedAt: modifiedAt
)
}
@@ -260,7 +249,6 @@ struct ExportedReport: Codable, Hashable, Sendable {
try container.encodeIfPresent(completedAt, forKey: .completedAt)
try container.encode(context, forKey: .context)
try container.encode(responses, forKey: .responses)
- try container.encodeIfPresent(legacy, forKey: .legacy)
try container.encode(modifiedAt, forKey: .modifiedAt)
}
}
diff --git a/Reportage/Services/Export/ReportageExporter.swift b/Reportage/Services/Export/ReportageExporter.swift
@@ -1,12 +1,6 @@
import CoreData
import Foundation
-struct ReportageExportOptions: Sendable {
- /// Include each imported report's original Reporter snapshot. Off by
- /// default: the snapshots are large and only matter for imported reports.
- var includeLegacy = false
-}
-
struct ReportageExportSummary: Equatable, Sendable {
var questions = 0
var tokens = 0
@@ -25,7 +19,6 @@ struct ReportageExporter: Sendable {
@concurrent
func export(
to url: URL,
- options: ReportageExportOptions = ReportageExportOptions(),
now: Date = Date()
) async throws -> ReportageExportSummary {
let context = persistence.newBackgroundContext()
@@ -36,7 +29,7 @@ struct ReportageExporter: Sendable {
do {
let handle = try FileHandle(forWritingTo: url)
defer { try? handle.close() }
- return try Self.write(to: handle, from: context, options: options, now: now)
+ return try Self.write(to: handle, from: context, now: now)
} catch {
try? FileManager.default.removeItem(at: url)
throw error
@@ -47,7 +40,6 @@ struct ReportageExporter: Sendable {
private static func write(
to handle: FileHandle,
from context: NSManagedObjectContext,
- options: ReportageExportOptions,
now: Date
) throws -> ReportageExportSummary {
let encoder = ExportDates.encoder
@@ -113,7 +105,7 @@ struct ReportageExporter: Sendable {
let batch = try context.fetch(reportRequest)
for entity in batch {
let report = try entity.report()
- try writeRecord(ExportedReport(report, includingLegacy: options.includeLegacy))
+ try writeRecord(ExportedReport(report))
summary.reports += 1
}
context.reset()
diff --git a/Reportage/Services/Places/AddressFill.swift b/Reportage/Services/Places/AddressFill.swift
@@ -191,8 +191,8 @@ extension ReportStore {
/// Gives the reports `placemarks` as their address: the first in the
/// user's first language, and the rest in other languages. The address
- /// they had is replaced; for an imported report, Reporter's stays in
- /// `legacy`.
+ /// they had is replaced; for an imported report, Reporter's is still in
+ /// the Reporter export.
func setPlacemarks(_ placemarks: [Placemark], for ids: [UUID], now: Date = Date()) async throws {
guard let first = placemarks.first else { return }
let context = persistence.newBackgroundContext()
diff --git a/Reportage/Services/ReporterImport/JSONSlicer.swift b/Reportage/Services/ReporterImport/JSONSlicer.swift
@@ -2,10 +2,8 @@ import Foundation /// Finds the byte ranges of JSON values without decoding them. /// -/// The Reporter importer keeps each snapshot's original bytes in -/// `Report.legacy`. Re-serialising a decoded snapshot would reorder keys and -/// reformat numbers, so the importer slices the source bytes instead and -/// decodes each slice separately. +/// The Reporter importer decodes each snapshot separately, so one that can't +/// be read is reported as a failure rather than failing the whole export. /// /// The slicer assumes well-formed JSON. It checks structure only as far as it /// needs to find value boundaries; each slice is validated when it's decoded.
diff --git a/Reportage/Services/ReporterImport/ReporterArchive.swift b/Reportage/Services/ReporterImport/ReporterArchive.swift
@@ -1,8 +1,8 @@
import Foundation
/// A parsed Reporter JSON export: two top-level arrays, `questions` and
-/// `snapshots`. Each snapshot keeps its original bytes alongside the decoded
-/// fields.
+/// `snapshots`. Each snapshot is decoded on its own, so one that can't be
+/// read is reported rather than failing the whole export.
struct ReporterArchive: Sendable {
enum Error: Swift.Error, Equatable {
case noJSONObject
@@ -10,8 +10,6 @@ struct ReporterArchive: Sendable {
}
struct Snapshot: Sendable {
- /// The snapshot's bytes exactly as they appear in the export.
- var raw: Data
/// `nil` when the snapshot couldn't be decoded.
var fields: ReporterSnapshot?
var decodingError: String?
@@ -39,12 +37,10 @@ struct ReporterArchive: Sendable {
[ReporterQuestion].self, from: data[try range(of: "questions")])
snapshots = try JSONSlicer.arrayElements(in: data, range: try range(of: "snapshots")).map {
range in
- let raw = Data(data[range])
do {
- return Snapshot(
- raw: raw, fields: try decoder.decode(ReporterSnapshot.self, from: raw))
+ return Snapshot(fields: try decoder.decode(ReporterSnapshot.self, from: data[range]))
} catch {
- return Snapshot(raw: raw, fields: nil, decodingError: String(describing: error))
+ return Snapshot(fields: nil, decodingError: String(describing: error))
}
}
}
@@ -53,7 +49,7 @@ struct ReporterArchive: Sendable {
// MARK: - Export records
// Field names follow the export. Only the fields Reportage normalises are
-// declared; everything else survives in `Report.legacy`. Numbers are decoded
+// declared; everything else is left in the export. Numbers are decoded
// leniently because the export mixes ints, floats and numeric strings for the
// same field.
diff --git a/Reportage/Services/ReporterImport/ReporterImportPlan.swift b/Reportage/Services/ReporterImport/ReporterImportPlan.swift
@@ -50,7 +50,7 @@ struct ReporterImportSummary: Hashable, Sendable {
/// the questions in the report.
case kindInferred(impetus: Int?)
/// A response carried answers in more than one field. The one matching
- /// the question's kind was kept; all of them remain in `legacy`.
+ /// the question's kind was kept, and the others were dropped.
case extraAnswerIgnored(questionID: String)
/// A response's prompt matched no question in the export. It was
/// attached to an archived question synthesised from the prompt.
@@ -223,14 +223,6 @@ private struct Builder {
fail(index, reportID, "Unparseable date")
return
}
- let legacy: Data
- do {
- legacy = try LegacyBlob.compress(snapshot.raw)
- } catch {
- fail(index, reportID, "Compression failed: \(error)")
- return
- }
-
var responses: [Response] = []
var questionIDs: Set<String> = []
for reporterResponse in fields.responses ?? [] {
@@ -272,7 +264,6 @@ private struct Builder {
state: .complete,
context: Self.context(of: fields),
responses: responses,
- legacy: legacy,
modifiedAt: date
)
pending.append(
diff --git a/Reportage/Services/ReporterImport/ReporterImportVerifier.swift b/Reportage/Services/ReporterImport/ReporterImportVerifier.swift
@@ -45,9 +45,6 @@
if report.date != ReporterDates.parse(fields.date) {
mismatch("date differs")
}
- if try report.legacy.map(LegacyBlob.decompress) != snapshot.raw {
- mismatch("legacy bytes differ")
- }
if TimeZone(identifier: report.timeZone) == nil {
mismatch("invalid time zone")
}
diff --git a/Reportage/Views/Report/ReportDetails.swift b/Reportage/Views/Report/ReportDetails.swift
@@ -253,7 +253,6 @@ struct ReportDetails: Equatable {
private static func record(_ report: Report, _ f: Formatter) -> Section {
let rows = [
row("Last Changed", f.dateTime(report.modifiedAt)),
- row("Reporter Original", report.legacy == nil ? nil : String(localized: "Kept", comment: "The original Reporter data is stored")),
row("ID", report.id.uuidString),
]
return Section(kind: .record, title: String(localized: "Record"), rows: rows.compactMap { $0 })
diff --git a/Reportage/Views/Settings/DataSection.swift b/Reportage/Views/Settings/DataSection.swift
@@ -165,7 +165,7 @@ struct DataSection: View {
let url = URL.temporaryDirectory.appending(path: "Reportage \(date).json")
do {
let summary = try await ReportageExporter(persistence: store.persistence)
- .export(to: url, options: ReportageExportOptions())
+ .export(to: url)
logger.info("Exported \(summary.reports) reports, \(summary.questions) questions, \(summary.tokens) tokens")
exported = ExportFile(url: url)
} catch {
diff --git a/Shared/Models/Report.swift b/Shared/Models/Report.swift
@@ -18,9 +18,6 @@ struct Report: Hashable, Sendable {
var completedAt: Date?
var context = Context()
var responses: [Response] = []
- /// For imported reports: the original Reporter snapshot JSON, compressed
- /// with `LegacyBlob`.
- var legacy: Data?
var modifiedAt: Date
}
diff --git a/Shared/Persistence/EntityMapping.swift b/Shared/Persistence/EntityMapping.swift
@@ -104,7 +104,6 @@ extension ReportEntity {
promptedAt = report.promptedAt
completedAt = report.completedAt
self.context = try ModelCoding.encode(report.context)
- legacy = report.legacy
modifiedAt = report.modifiedAt
for case let existing as ResponseEntity in responses ?? [] {
@@ -157,7 +156,6 @@ extension ReportEntity {
context: try self.context.map { try ModelCoding.decode(Context.self, from: $0) }
?? Context(),
responses: try responseEntities.map { try $0.response() },
- legacy: legacy,
modifiedAt: modifiedAt
)
}
diff --git a/Shared/Persistence/LegacyBlob.swift b/Shared/Persistence/LegacyBlob.swift
@@ -1,13 +0,0 @@
-import Foundation
-
-/// Compression for `Report.legacy`, which holds the original Reporter snapshot
-/// JSON byte for byte.
-enum LegacyBlob {
- static func compress(_ data: Data) throws -> Data {
- try (data as NSData).compressed(using: .zlib) as Data
- }
-
- static func decompress(_ data: Data) throws -> Data {
- try (data as NSData).decompressed(using: .zlib) as Data
- }
-}
diff --git a/Shared/Persistence/PersistenceController.swift b/Shared/Persistence/PersistenceController.swift
@@ -29,6 +29,11 @@ final class PersistenceController: @unchecked Sendable {
for description in container.persistentStoreDescriptions {
description.shouldMigrateStoreAutomatically = true
description.shouldInferMappingModelAutomatically = true
+ // A migration that drops data frees space SQLite keeps for reuse
+ // rather than returning, so the file is rebuilt after one.
+ if Self.needsMigration(description) {
+ description.setOption(true as NSNumber, forKey: NSSQLiteManualVacuumOption)
+ }
}
container.loadPersistentStores { _, error in
@@ -41,6 +46,17 @@ final class PersistenceController: @unchecked Sendable {
container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
}
+ /// Whether the SQLite store at `description` exists and was made with an
+ /// earlier model.
+ private static func needsMigration(_ description: NSPersistentStoreDescription) -> Bool {
+ guard description.type == NSSQLiteStoreType, let url = description.url,
+ FileManager.default.fileExists(atPath: url.path),
+ let metadata = try? NSPersistentStoreCoordinator.metadataForPersistentStore(
+ type: .sqlite, at: url)
+ else { return false }
+ return !sharedModel.isConfiguration(withName: description.configuration, compatibleWithStoreMetadata: metadata)
+ }
+
func newBackgroundContext() -> NSManagedObjectContext {
let context = container.newBackgroundContext()
context.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
diff --git a/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents b/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents
@@ -24,7 +24,6 @@
<attribute name="date" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="id" attributeType="UUID" usesScalarValueType="NO"/>
<attribute name="kind" attributeType="String"/>
- <attribute name="legacy" optional="YES" attributeType="Binary"/>
<attribute name="modifiedAt" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="promptedAt" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="state" attributeType="String"/>
diff --git a/Tests/Support/TestHelpers.swift b/Tests/Support/TestHelpers.swift
@@ -34,8 +34,7 @@ enum Fixtures {
}
/// The fixture with its last `count` snapshots removed, as an older export
- /// would be. The remaining bytes are untouched, so legacy blobs still
- /// match the full fixture's.
+ /// would be. The remaining bytes are untouched.
static func reporterExport(droppingLast count: Int) throws -> Data {
let data = try reporterExport()
let start = try #require(data.firstIndex(of: UInt8(ascii: "{")))
diff --git a/Tests/Unit/RealExportVerificationTests.swift b/Tests/Unit/RealExportVerificationTests.swift
@@ -133,58 +133,41 @@ struct RealExportVerificationTests {
let exporter = ReportageExporter(persistence: persistence)
let directory = FileManager.default.temporaryDirectory
let clock = ContinuousClock()
- var lines: [String] = []
-
- for includeLegacy in [false, true] {
- let file = directory.appendingPathComponent("reportage-real-\(UUID().uuidString).json")
- defer { try? FileManager.default.removeItem(at: file) }
-
- let start = clock.now
- let summary = try await exporter.export(
- to: file, options: ReportageExportOptions(includeLegacy: includeLegacy))
- let exportDuration = clock.now - start
- let data = try Data(contentsOf: file)
-
- let readStart = clock.now
- let export = try ReportageExport.decode(data)
- let readDuration = clock.now - readStart
-
- // Counted rather than compared with #expect, which would print
- // the records themselves on a failure.
- let questionsMatch = Set(try export.questions.map { try $0.question() }) == questions
- let tokensMatch = Set(export.tokens.map { $0.token() }) == tokens
- var reportMismatches = 0
- var legacyMismatches = 0
- for (exported, stored) in zip(export.reports, reports) {
- var decoded = try exported.report()
- decoded.legacy = nil
- var expected = stored
- expected.legacy = nil
- if decoded != expected { reportMismatches += 1 }
-
- let original = try stored.legacy.map { try LegacyBlob.decompress($0) }
- let written = exported.legacy.map { Data($0.utf8) }
- if written != (includeLegacy ? original : nil) { legacyMismatches += 1 }
- }
- let countsMatch = export.reports.count == reports.count
-
- lines.append(
- """
- legacy \(includeLegacy ? "included" : "omitted"):
- size: \(ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: .file)), export time: \(exportDuration), read time: \(readDuration)
- questions: \(summary.questions), tokens: \(summary.tokens), reports: \(summary.reports)
- questions match: \(questionsMatch), tokens match: \(tokensMatch), report counts match: \(countsMatch)
- report mismatches: \(reportMismatches), legacy mismatches: \(legacyMismatches)
- """
- )
+ let file = directory.appendingPathComponent("reportage-real-\(UUID().uuidString).json")
+ defer { try? FileManager.default.removeItem(at: file) }
- #expect(questionsMatch)
- #expect(tokensMatch)
- #expect(countsMatch)
- #expect(reportMismatches == 0)
- #expect(legacyMismatches == 0)
+ let start = clock.now
+ let summary = try await exporter.export(to: file)
+ let exportDuration = clock.now - start
+ let data = try Data(contentsOf: file)
+
+ let readStart = clock.now
+ let export = try ReportageExport.decode(data)
+ let readDuration = clock.now - readStart
+
+ // Counted rather than compared with #expect, which would print
+ // the records themselves on a failure.
+ let questionsMatch = Set(try export.questions.map { try $0.question() }) == questions
+ let tokensMatch = Set(export.tokens.map { $0.token() }) == tokens
+ var reportMismatches = 0
+ for (exported, stored) in zip(export.reports, reports) where try exported.report() != stored {
+ reportMismatches += 1
}
+ let countsMatch = export.reports.count == reports.count
+
+ print(
+ """
+ REAL ARCHIVE EXPORT SUMMARY
+ size: \(ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: .file)), export time: \(exportDuration), read time: \(readDuration)
+ questions: \(summary.questions), tokens: \(summary.tokens), reports: \(summary.reports)
+ questions match: \(questionsMatch), tokens match: \(tokensMatch), report counts match: \(countsMatch)
+ report mismatches: \(reportMismatches)
+ """
+ )
- print("REAL ARCHIVE EXPORT SUMMARY\n" + lines.joined(separator: "\n"))
+ #expect(questionsMatch)
+ #expect(tokensMatch)
+ #expect(countsMatch)
+ #expect(reportMismatches == 0)
}
}
diff --git a/Tests/Unit/ReportageExportTests.swift b/Tests/Unit/ReportageExportTests.swift
@@ -12,13 +12,12 @@ struct ReportageExportTests {
private var exporter: ReportageExporter { ReportageExporter(persistence: persistence) }
private func exportData(
- options: ReportageExportOptions = ReportageExportOptions(),
now: Date = Date(timeIntervalSince1970: 0)
) async throws -> (summary: ReportageExportSummary, data: Data) {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("reportage-export-\(UUID().uuidString).json")
defer { try? FileManager.default.removeItem(at: url) }
- let summary = try await exporter.export(to: url, options: options, now: now)
+ let summary = try await exporter.export(to: url, now: now)
return (summary, try Data(contentsOf: url))
}
@@ -78,8 +77,7 @@ struct ReportageExportTests {
try await importFixture()
let (summary, data) = try await exportData()
let export = try ReportageExport.decode(data)
- var expected = try await stored()
- for index in expected.reports.indices { expected.reports[index].legacy = nil }
+ let expected = try await stored()
#expect(summary == ReportageExportSummary(questions: 9, tokens: 11, reports: 14))
#expect(export.format == "reportage")
@@ -125,22 +123,6 @@ struct ReportageExportTests {
#expect(text.contains(#"{"prompt":"Skipped?","questionID":"Q2"}"#))
}
- @Test("Legacy snapshots are left out unless asked for, and are byte-exact")
- func legacy() async throws {
- try await importFixture()
- let without = try ReportageExport.decode(try await exportData().data)
- #expect(without.reports.allSatisfy { $0.legacy == nil })
-
- let with = try ReportageExport.decode(
- try await exportData(options: ReportageExportOptions(includeLegacy: true)).data)
- let reports = try await stored().reports
- #expect(with.reports.count == reports.count)
- for (exported, report) in zip(with.reports, reports) {
- let original = try LegacyBlob.decompress(try #require(report.legacy))
- #expect(Data(try #require(exported.legacy).utf8) == original)
- }
- }
-
@Test("Question surveys are written as names")
func askOn() throws {
let question = Question(
diff --git a/Tests/Unit/ReporterArchiveTests.swift b/Tests/Unit/ReporterArchiveTests.swift
@@ -17,19 +17,6 @@ struct ReporterArchiveTests {
#expect(archive.snapshots.allSatisfy { $0.fields != nil })
}
- @Test("Each snapshot keeps its exact source bytes")
- func rawBytes() throws {
- let data = try Fixtures.reporterExport()
- let archive = try ReporterArchive(data: data)
- let text = String(decoding: data, as: UTF8.self)
-
- for snapshot in archive.snapshots {
- let raw = String(decoding: snapshot.raw, as: UTF8.self)
- #expect(raw.hasPrefix("{") && raw.hasSuffix("}"))
- #expect(text.contains(raw))
- }
- }
-
@Test("Data without an object is rejected")
func noObject() {
#expect(throws: ReporterArchive.Error.noJSONObject) {
diff --git a/Tests/Unit/ReporterImportPlanTests.swift b/Tests/Unit/ReporterImportPlanTests.swift
@@ -47,18 +47,6 @@ struct ReporterImportPlanTests {
#expect(first.modifiedAt == first.date)
}
- @Test("Legacy holds the snapshot's original bytes")
- func legacy() throws {
- let archive = try Fixtures.reporterArchive()
- for snapshot in archive.snapshots {
- let fields = try #require(snapshot.fields)
- let id = try #require(UUID(uuidString: fields.uniqueIdentifier))
- let report = try #require(plan.reports.first { $0.id == id })
- let legacy = try #require(report.legacy)
- #expect(try LegacyBlob.decompress(legacy) == snapshot.raw)
- }
- }
-
// MARK: Time zones
@Test(
diff --git a/Tests/Unit/SchemaMigrationTests.swift b/Tests/Unit/SchemaMigrationTests.swift
@@ -1,5 +1,6 @@
import CoreData
import Foundation
+import SQLite3
import Testing
@testable import Reportage
@@ -15,25 +16,34 @@ struct SchemaMigrationTests {
PersistenceController(inMemory: true).container.managedObjectModel
}
- /// The model as it was while reports had narrative attributes, before
- /// the Health cache. Its entities use plain managed objects, so it
- /// doesn't claim the app's entity classes.
- private static func narrativeModel() -> NSManagedObjectModel {
+ private static func attribute(
+ _ name: String, _ type: NSAttributeDescription.AttributeType, optional: Bool
+ ) -> NSAttributeDescription {
+ let attribute = NSAttributeDescription()
+ attribute.name = name
+ attribute.type = type
+ attribute.isOptional = optional
+ return attribute
+ }
+
+ /// The model as it was while imported reports kept their Reporter
+ /// originals. Its entities use plain managed objects, so it doesn't
+ /// claim the app's entity classes.
+ private static func legacyModel() -> NSManagedObjectModel {
let copy = model.copy() as! NSManagedObjectModel
- copy.entities.removeAll { $0.name == "HealthEntity" }
- copy.entitiesByName["ReportEntity"]?.properties.removeAll { $0.name == "health" }
for entity in copy.entities {
entity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)
}
- func attribute(_ name: String, _ type: NSAttributeDescription.AttributeType, optional: Bool)
- -> NSAttributeDescription
- {
- let attribute = NSAttributeDescription()
- attribute.name = name
- attribute.type = type
- attribute.isOptional = optional
- return attribute
- }
+ copy.entitiesByName["ReportEntity"]?.properties += [attribute("legacy", .binaryData, optional: true)]
+ return copy
+ }
+
+ /// The model as it was while reports had narrative attributes, before
+ /// the Health cache.
+ private static func narrativeModel() -> NSManagedObjectModel {
+ let copy = legacyModel()
+ copy.entities.removeAll { $0.name == "HealthEntity" }
+ copy.entitiesByName["ReportEntity"]?.properties.removeAll { $0.name == "health" }
let version = attribute("narrativeVersion", .integer16, optional: false)
version.defaultValue = 0
copy.entitiesByName["ReportEntity"]?.properties += [
@@ -44,27 +54,87 @@ struct SchemaMigrationTests {
return copy
}
- /// Makes a store with the narrative model holding one report. Everything
- /// that opened it is released on return, so migration can replace it.
- private static func makeNarrativeStore(at url: URL, reportID: UUID) throws {
- let coordinator = NSPersistentStoreCoordinator(managedObjectModel: narrativeModel())
+ /// Makes a store with `model` holding a report for each of `values`.
+ /// Everything that opened it is released on return, so migration can
+ /// replace it.
+ private static func makeStore(
+ at url: URL, model: NSManagedObjectModel, reports values: [[String: any Sendable]]
+ ) throws {
+ let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
let store = try coordinator.addPersistentStore(type: .sqlite, at: url)
let context = NSManagedObjectContext(.privateQueue)
context.persistentStoreCoordinator = coordinator
try context.performAndWait {
let entity = try #require(coordinator.managedObjectModel.entitiesByName["ReportEntity"])
- let report = NSManagedObject(entity: entity, insertInto: context)
- report.setValuesForKeys([
- "id": reportID, "date": Date(), "modifiedAt": Date(), "kind": "manual",
- "state": "complete", "timeZone": "Asia/Tokyo", "trigger": "app",
- "narrative": "Reading at the library.", "narrativeDraft": "Reading at Library.",
- ])
+ for values in values {
+ let report = NSManagedObject(entity: entity, insertInto: context)
+ report.setValuesForKeys(
+ [
+ "id": UUID(), "date": Date(), "modifiedAt": Date(), "kind": "manual",
+ "state": "complete", "timeZone": "Asia/Tokyo", "trigger": "app",
+ ].merging(values) { $1 })
+ }
try context.save()
context.reset()
}
try coordinator.remove(store)
}
+ /// Opens the store at `url` with the app's model, migrating it, and
+ /// returns its reports' IDs, closing it again so its file is complete.
+ private static func openMigrating(_ url: URL) throws -> [UUID?] {
+ let persistence = PersistenceController(storeURL: url)
+ let ids = try persistence.viewContext.fetch(ReportEntity.fetchRequest()).map(\.id)
+ let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(type: .sqlite, at: url)
+ #expect(model.isConfiguration(withName: nil, compatibleWithStoreMetadata: metadata))
+ let coordinator = persistence.container.persistentStoreCoordinator
+ for store in coordinator.persistentStores {
+ try coordinator.remove(store)
+ }
+ return ids
+ }
+
+ /// How many pages the database at `url` has, counting those still in
+ /// its write-ahead log, which the file's size doesn't.
+ private static func pageCount(_ url: URL) throws -> Int {
+ var database: OpaquePointer?
+ defer { sqlite3_close(database) }
+ try #require(sqlite3_open_v2(url.path, &database, SQLITE_OPEN_READONLY, nil) == SQLITE_OK)
+ var statement: OpaquePointer?
+ defer { sqlite3_finalize(statement) }
+ try #require(sqlite3_prepare_v2(database, "PRAGMA page_count", -1, &statement, nil) == SQLITE_OK)
+ try #require(sqlite3_step(statement) == SQLITE_ROW)
+ return Int(sqlite3_column_int64(statement, 0))
+ }
+
+ private static func temporaryStoreURL() throws -> URL {
+ let directory = URL.temporaryDirectory.appending(path: UUID().uuidString)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ return directory.appending(path: "Store.sqlite")
+ }
+
+ @Test("The rebuilt legacy model matches the one stores were made with")
+ func legacyModelHash() {
+ // ReportEntity's version hash in builds with Reporter originals.
+ let hash = Data(base64Encoded: "RJN+/VCeLQPP68SRtVSZQBkDTecnABs7F4UQ6Xp0fBA=")
+ #expect(Self.legacyModel().entityVersionHashesByName["ReportEntity"] == hash)
+ }
+
+ @Test("A store with Reporter originals opens with its reports, and is rebuilt smaller")
+ func removedLegacy() throws {
+ let storeURL = try Self.temporaryStoreURL()
+ defer { try? FileManager.default.removeItem(at: storeURL.deletingLastPathComponent()) }
+ let ids = (0..<200).map { _ in UUID() }
+ try Self.makeStore(
+ at: storeURL, model: Self.legacyModel(),
+ reports: ids.map { ["id": $0, "legacy": Data((0..<3000).map { _ in UInt8.random(in: 0...255) })] })
+ let before = try Self.pageCount(storeURL)
+
+ #expect(Set(try Self.openMigrating(storeURL)) == Set(ids))
+ // 200 originals of 3 KB took at least 600 KB, about 150 pages.
+ #expect(try Self.pageCount(storeURL) < before - 120)
+ }
+
@Test("The rebuilt narrative model matches the one stores were made with")
func narrativeModelHash() {
// ReportEntity's version hash in builds with the narrative attributes.
@@ -74,17 +144,13 @@ struct SchemaMigrationTests {
@Test("A store made with the narrative attributes opens with its reports")
func removedAttributes() throws {
- let directory = URL.temporaryDirectory.appending(path: UUID().uuidString)
- try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
- defer { try? FileManager.default.removeItem(at: directory) }
- let storeURL = directory.appending(path: "Store.sqlite")
+ let storeURL = try Self.temporaryStoreURL()
+ defer { try? FileManager.default.removeItem(at: storeURL.deletingLastPathComponent()) }
let id = UUID()
- try Self.makeNarrativeStore(at: storeURL, reportID: id)
+ try Self.makeStore(
+ at: storeURL, model: Self.narrativeModel(),
+ reports: [["id": id, "narrative": "Reading at the library.", "narrativeDraft": "Reading at Library."]])
- let persistence = PersistenceController(storeURL: storeURL)
- let reports = try persistence.viewContext.fetch(ReportEntity.fetchRequest())
- #expect(reports.map(\.id) == [id])
- let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(type: .sqlite, at: storeURL)
- #expect(Self.model.isConfiguration(withName: nil, compatibleWithStoreMetadata: metadata))
+ #expect(try Self.openMigrating(storeURL) == [id])
}
}