Commit 3a99d7a208

3a99d7a208361b885ef3552d349b340d26cc0ca1

parent: c48ca87415

Unsigned

cmc <hello@cleberg.net> · 2026-10-24 20:06 UTC

Cover the history store at the Pro+ cap, and measure it (!23)

Review Focus #2's gate, landed before W5 moves the substrate rather than after:
a store at its tier cap must not drop or duplicate rows across a save, a
repeated save or a backup import, and a restore must round-trip every field the
UI reads. 2000 rows is the Pro+ worst case under D1, not the 250 the store caps
at today.

No behaviour change in the app beyond C11 below.

## Coverage

7 tests, plus a populated `HistoryEntry` fixture they share — the existing
`HistoryEntryCodableTests` factory is deliberately minimal, which is no use for
asking whether a section survived:

- 2000 rows survive a save and load, with the same set of ids
- rows come back newest first, which every reader downstream assumes
- no row is duplicated across repeated saves
- every populated field survives a round trip, field by field
- a backup at the cap restores every row into a fresh store (`replace`)
- merging a backup of the same store does not double its rows
- validation accepts a store at the cap

5.4s of the suite's 6.8s. Worth it for the thing that can lose a user's data.

## A1, measured

One fully-populated entry per row, iOS 27.0:

| rows | blob | save | load |
|------|------|------|------|
| 50 (free under D1) | 162 KiB | 7 ms | 5 ms |
| 250 (today's cap) | 816 KiB | 27 ms | 25 ms |
| 2000 (Pro+ under D1) | 6,564 KiB | 214 ms | 209 ms |

Ten consecutive saves at 2000 rows: 2,098 ms, 210 ms each. Every save rewrites
the whole blob, so the cost does not amortize.

What that settles: today's 250-row cap is survivable at 27 ms, so A1 is not an
emergency at the current cap. The 2000-row Pro+ tier is a different matter —
`saveHistoryEntries` is called from the view model on the main actor after
every lookup and every monitoring run, so a Pro+ user with a full history pays
a 210 ms main-thread stall per write, and 6.4 MiB sits in one `UserDefaults`
key that is read into memory at launch.

So the retention tiers land *after* the substrate, not before. The plan's W5
entry is updated to that order.

## C11, found writing these tests

`historyKey(for:)` chose between an id key and a domain-plus-timestamp fallback
on `entry.id != UUID()` — a comparison against a freshly generated random UUID,
true for every entry that has ever existed. The fallback had never run.
`HistoryEntry.id` is non-optional with a `UUID()` default, so there is no entry
without one and nothing to distinguish. Keys on the id unconditionally now.

## Verification

Each tier as its own invocation, per E2: 216 tests, 0 failures on iOS 18.6
(iPhone 16) and iOS 27.0 (iPhone Air).

Layout: unified · split

DomainDataPortabilityService.swift +6 −4
@@ -1307,11 +1307,13 @@ enum DomainDataPortabilityService {
1307 return score 1307 return score
1308 } 1308 }
1309 1309
1310 /// `HistoryEntry.id` is non-optional with a `UUID()` default, so every
1311 /// entry has one and the id is the whole key. This used to branch on
1312 /// `entry.id != UUID()` — a comparison against a freshly generated random
1313 /// UUID, true for every entry — behind which the domain-plus-timestamp
1314 /// fallback had never run.
1310 private static func historyKey(for entry: HistoryEntry) -> String { 1315 private static func historyKey(for entry: HistoryEntry) -> String {
1311 if entry.id != UUID() { 1316 "id:\(entry.id.uuidString)"
1312 return "id:\(entry.id.uuidString)"
1313 }
1314 return "domain:\(normalizeDomain(entry.domain))|timestamp:\(entry.timestamp.timeIntervalSince1970)"
1315 } 1317 }
1316 1318
1317 private nonisolated static func normalizeDomain(_ value: String) -> String { 1319 private nonisolated static func normalizeDomain(_ value: String) -> String {
DomainDig.xcodeproj/project.pbxproj +4
@@ -33,6 +33,7 @@
33 A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */; }; 33 A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */; };
34 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */; }; 34 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */; };
35 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001101 /* LookupCacheTests.swift */; }; 35 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001101 /* LookupCacheTests.swift */; };
36 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001201 /* HistoryStoreTests.swift */; };
36 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; 37 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
37 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; 38 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
38 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; 39 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -113,6 +114,7 @@
113 A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MonitoringSchedulingTests.swift; sourceTree = "<group>"; }; 114 A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MonitoringSchedulingTests.swift; sourceTree = "<group>"; };
114 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainViewModelStoreTests.swift; sourceTree = "<group>"; }; 115 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainViewModelStoreTests.swift; sourceTree = "<group>"; };
115 A1B2C3D40000000000001101 /* LookupCacheTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LookupCacheTests.swift; sourceTree = "<group>"; }; 116 A1B2C3D40000000000001101 /* LookupCacheTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LookupCacheTests.swift; sourceTree = "<group>"; };
117 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryStoreTests.swift; sourceTree = "<group>"; };
116 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; 118 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
117 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; 119 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
118 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; 120 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -258,6 +260,7 @@
258 A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */, 260 A1B2C3D40000000000000901 /* MonitoringSchedulingTests.swift */,
259 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */, 261 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */,
260 A1B2C3D40000000000001101 /* LookupCacheTests.swift */, 262 A1B2C3D40000000000001101 /* LookupCacheTests.swift */,
263 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */,
261 A1B2C3D40000000000000301 /* AvailabilityTests.swift */, 264 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
262 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, 265 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
263 A1B2C3D40000000000000501 /* DomainNameTests.swift */, 266 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -528,6 +531,7 @@
528 A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */, 531 A1B2C3D40000000000000902 /* MonitoringSchedulingTests.swift in Sources */,
529 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */, 532 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */,
530 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */, 533 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */,
534 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */,
531 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, 535 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
532 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, 536 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
533 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, 537 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDigTests/Fixtures/SnapshotFixture.swift +76
@@ -173,6 +173,82 @@ enum SnapshotFixture {
173 ) 173 )
174 } 174 }
175 175
176 /// A `HistoryEntry` with every section populated, for the tests that care
177 /// about the persisted store rather than about one field. The store holds
178 /// up to 2000 of these at the Pro+ cap, so `index` varies the content: an
179 /// entry repeated verbatim would not measure a realistic encode.
180 static func historyEntry(index: Int = 0, domain: String? = nil) -> HistoryEntry {
181 let host = domain ?? "domain\(index).example"
182 return HistoryEntry(
183 identity: .init(
184 domain: host,
185 timestamp: referenceDate.addingTimeInterval(Double(index)),
186 trackedDomainID: UUID(),
187 note: "note for \(host)"
188 ),
189 inspection: .init(
190 dnsSections: [
191 dnsSection(type: .A, values: ["203.0.113.\(index % 256)", "198.51.100.\(index % 256)"]),
192 dnsSection(type: .MX, values: ["10 mail.\(host)"]),
193 dnsSection(type: .TXT, values: ["v=spf1 include:_spf.\(host) -all"])
194 ],
195 sslInfo: certificate(commonName: host, daysUntilExpiry: 30 + index % 300),
196 httpHeaders: [
197 HTTPHeader(name: "strict-transport-security", value: "max-age=31536000"),
198 HTTPHeader(name: "content-security-policy", value: "default-src 'self'"),
199 HTTPHeader(name: "server", value: "test/\(index)")
200 ],
201 reachabilityResults: [
202 PortReachability(port: 80, reachable: true, latencyMs: 12 + index % 50),
203 PortReachability(port: 443, reachable: true, latencyMs: 15 + index % 50)
204 ],
205 ipGeolocation: IPGeolocation(
206 ip: "203.0.113.\(index % 256)",
207 city: "Testville",
208 region: "Test Region",
209 countryName: "Testland",
210 org: "Test Org \(index)",
211 latitude: 45.0,
212 longitude: -93.0
213 ),
214 ptrRecord: "host\(index).\(host)",
215 redirectChain: [
216 RedirectHop(stepNumber: 1, statusCode: 301, url: "http://\(host)", isFinal: false),
217 RedirectHop(stepNumber: 2, statusCode: 200, url: "https://\(host)", isFinal: true)
218 ],
219 subdomains: (0..<5).map { DiscoveredSubdomain(hostname: "sub\($0).\(host)", source: "crt.sh") },
220 hstsPreloaded: index.isMultiple(of: 2)
221 ),
222 registration: .init(priorProviders: ["Provider \(index)", "Provider \(index + 1)"]),
223 intelligence: .init(
224 riskSignals: [
225 IntelligenceRiskSignal(
226 id: "signal-\(index)",
227 title: "Signal \(index)",
228 detail: "A detail string long enough to be representative of a real finding.",
229 severity: .medium,
230 firstObserved: referenceDate,
231 lastObserved: referenceDate.addingTimeInterval(Double(index))
232 )
233 ]
234 ),
235 provenance: .init(
236 dataSources: ["dns", "tls", "http", "crt.sh"],
237 validationIssues: [],
238 resolverDisplayName: "Test Resolver",
239 resolverURLString: defaultResolverURL,
240 totalLookupDurationMs: 1200 + index
241 ),
242 summary: .init(
243 primaryIP: "203.0.113.\(index % 256)",
244 finalRedirectURL: "https://\(host)",
245 tlsStatusSummary: "Valid",
246 snapshotIndex: index,
247 changeCount: index % 4
248 )
249 )
250 }
251
176 static func certificate( 252 static func certificate(
177 commonName: String = "example.com", 253 commonName: String = "example.com",
178 issuer: String = "Test CA", 254 issuer: String = "Test CA",
DomainDigTests/HistoryStoreTests.swift added +189
@@ -0,0 +1,189 @@
1import XCTest
2@testable import DomainDig
3
4/// Review Focus #2: a history store at its tier cap must not drop or duplicate
5/// rows across a save, an auto-prune or a backup import, and a restore must
6/// round-trip every field the UI reads. Pro+ at 2000 snapshots is the worst
7/// case, not the 250 the store caps at today.
8///
9/// These run against the store as it is. W5 moves the substrate underneath
10/// `DomainDataPortabilityService`'s API, and this is the gate that says the
11/// move lost nothing — so it comes before the switch, not after.
12final class HistoryStoreTests: XCTestCase {
13
14 /// The Pro+ retention tier D1 settled on, and the size every assertion here
15 /// is about.
16 private static let proPlusCap = 2000
17
18 private var suiteName = ""
19 private var scratch = UserDefaults.standard
20
21 override func setUpWithError() throws {
22 try super.setUpWithError()
23 suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
24 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
25 }
26
27 override func tearDown() {
28 UserDefaults.standard.removePersistentDomain(forName: suiteName)
29 super.tearDown()
30 }
31
32 private func entries(_ count: Int) -> [HistoryEntry] {
33 (0..<count).map { SnapshotFixture.historyEntry(index: $0) }
34 }
35
36 // MARK: Round trip at the cap
37
38 func testTwoThousandEntriesSurviveASaveAndLoad() {
39 let saved = entries(Self.proPlusCap)
40
41 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
42 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
43
44 XCTAssertEqual(loaded.count, Self.proPlusCap, "the store dropped or added rows")
45 XCTAssertEqual(Set(loaded.map(\.id)), Set(saved.map(\.id)), "the store changed which rows exist")
46 }
47
48 /// The store sorts on load, newest first. Every reader downstream — the
49 /// history list, the dashboard's recent activity, the diff view's
50 /// "previous snapshot" — takes that for granted.
51 func testTheStoreReturnsRowsNewestFirst() {
52 DomainDataPortabilityService.saveHistoryEntries(entries(Self.proPlusCap), defaults: scratch)
53
54 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
55
56 XCTAssertEqual(loaded.map(\.timestamp), loaded.map(\.timestamp).sorted(by: >))
57 XCTAssertEqual(loaded.first?.snapshotIndex, Self.proPlusCap - 1)
58 XCTAssertEqual(loaded.last?.snapshotIndex, 0)
59 }
60
61 func testNoRowIsDuplicatedAcrossRepeatedSaves() {
62 let saved = entries(Self.proPlusCap)
63
64 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
65 let once = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
66 DomainDataPortabilityService.saveHistoryEntries(once, defaults: scratch)
67 let twice = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
68
69 XCTAssertEqual(twice.count, Self.proPlusCap)
70 XCTAssertEqual(Set(twice.map(\.id)).count, Self.proPlusCap, "a row was duplicated")
71 XCTAssertEqual(twice.map(\.id), once.map(\.id), "a second save reordered the store")
72 }
73
74 /// Every field the UI reads, on an entry that has all of them set. A
75 /// substrate change that silently lost one section would still pass a
76 /// count assertion.
77 func testEveryPopulatedFieldSurvivesTheRoundTrip() throws {
78 let original = SnapshotFixture.historyEntry(index: 7)
79
80 DomainDataPortabilityService.saveHistoryEntries([original], defaults: scratch)
81 let restored = try XCTUnwrap(
82 DomainDataPortabilityService.loadHistoryEntries(defaults: scratch).first
83 )
84
85 XCTAssertEqual(restored.id, original.id)
86 XCTAssertEqual(restored.domain, original.domain)
87 XCTAssertEqual(restored.timestamp, original.timestamp)
88 XCTAssertEqual(restored.trackedDomainID, original.trackedDomainID)
89 XCTAssertEqual(restored.note, original.note)
90
91 XCTAssertEqual(restored.dnsSections.count, original.dnsSections.count)
92 XCTAssertEqual(restored.dnsSections.map(\.recordType), original.dnsSections.map(\.recordType))
93 XCTAssertEqual(
94 restored.dnsSections.flatMap { $0.records.map(\.value) },
95 original.dnsSections.flatMap { $0.records.map(\.value) }
96 )
97
98 XCTAssertEqual(restored.sslInfo?.commonName, original.sslInfo?.commonName)
99 XCTAssertEqual(restored.sslInfo?.issuer, original.sslInfo?.issuer)
100 XCTAssertEqual(restored.sslInfo?.daysUntilExpiry, original.sslInfo?.daysUntilExpiry)
101 XCTAssertEqual(restored.sslInfo?.subjectAltNames, original.sslInfo?.subjectAltNames)
102
103 XCTAssertEqual(restored.httpHeaders.map(\.name), original.httpHeaders.map(\.name))
104 XCTAssertEqual(restored.httpHeaders.map(\.value), original.httpHeaders.map(\.value))
105 XCTAssertEqual(restored.reachabilityResults.map(\.port), original.reachabilityResults.map(\.port))
106 XCTAssertEqual(restored.reachabilityResults.map(\.latencyMs), original.reachabilityResults.map(\.latencyMs))
107
108 XCTAssertEqual(restored.ipGeolocation?.ip, original.ipGeolocation?.ip)
109 XCTAssertEqual(restored.ipGeolocation?.countryName, original.ipGeolocation?.countryName)
110 XCTAssertEqual(restored.ipGeolocation?.org, original.ipGeolocation?.org)
111
112 XCTAssertEqual(restored.ptrRecord, original.ptrRecord)
113 XCTAssertEqual(restored.redirectChain.map(\.url), original.redirectChain.map(\.url))
114 XCTAssertEqual(restored.redirectChain.map(\.isFinal), original.redirectChain.map(\.isFinal))
115 XCTAssertEqual(restored.subdomains.map(\.hostname), original.subdomains.map(\.hostname))
116 XCTAssertEqual(restored.hstsPreloaded, original.hstsPreloaded)
117
118 XCTAssertEqual(restored.priorProviders, original.priorProviders)
119 XCTAssertEqual(restored.riskSignals.map(\.id), original.riskSignals.map(\.id))
120 XCTAssertEqual(restored.riskSignals.map(\.severity), original.riskSignals.map(\.severity))
121
122 XCTAssertEqual(restored.dataSources, original.dataSources)
123 XCTAssertEqual(restored.resolverDisplayName, original.resolverDisplayName)
124 XCTAssertEqual(restored.resolverURLString, original.resolverURLString)
125 XCTAssertEqual(restored.totalLookupDurationMs, original.totalLookupDurationMs)
126
127 XCTAssertEqual(restored.primaryIP, original.primaryIP)
128 XCTAssertEqual(restored.finalRedirectURL, original.finalRedirectURL)
129 XCTAssertEqual(restored.tlsStatusSummary, original.tlsStatusSummary)
130 XCTAssertEqual(restored.snapshotIndex, original.snapshotIndex)
131 XCTAssertEqual(restored.changeCount, original.changeCount)
132 }
133
134 // MARK: Backup and restore at the cap
135
136 func testABackupAtTheCapRestoresEveryRow() throws {
137 let saved = entries(Self.proPlusCap)
138 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
139
140 let backup = try DomainDataPortabilityService.backupData(defaults: scratch)
141
142 let restoreName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
143 defer { UserDefaults.standard.removePersistentDomain(forName: restoreName) }
144 let restoreStore = try XCTUnwrap(UserDefaults(suiteName: restoreName))
145
146 let preview = try DomainDataPortabilityService.prepareImport(
147 data: backup,
148 fileName: "backup.json",
149 mode: .replace,
150 defaults: restoreStore
151 )
152 _ = try DomainDataPortabilityService.applyImport(preview, mode: .replace, defaults: restoreStore)
153
154 let restored = DomainDataPortabilityService.loadHistoryEntries(defaults: restoreStore)
155 XCTAssertEqual(restored.count, Self.proPlusCap, "the backup round trip changed the row count")
156 XCTAssertEqual(Set(restored.map(\.id)), Set(saved.map(\.id)), "the backup round trip changed which rows exist")
157 }
158
159 /// A merge import of a backup of the same store must not double every row.
160 func testMergingABackupOfTheSameStoreDoesNotDuplicateRows() throws {
161 let saved = entries(500)
162 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
163
164 let backup = try DomainDataPortabilityService.backupData(defaults: scratch)
165 let preview = try DomainDataPortabilityService.prepareImport(
166 data: backup,
167 fileName: "backup.json",
168 mode: .merge,
169 defaults: scratch
170 )
171 _ = try DomainDataPortabilityService.applyImport(preview, mode: .merge, defaults: scratch)
172
173 let merged = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
174 XCTAssertEqual(merged.count, 500, "merging a backup of the same store duplicated rows")
175 XCTAssertEqual(Set(merged.map(\.id)).count, 500)
176 }
177
178 // MARK: Validation at the cap
179
180 func testValidationAcceptsAStoreAtTheCap() throws {
181 let saved = entries(Self.proPlusCap)
182 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
183
184 let backup = try DomainDataPortabilityService.backupData(defaults: scratch)
185 let report = try DomainDataPortabilityService.validateBackup(data: backup)
186
187 XCTAssertTrue(report.errors.isEmpty, "a store at the Pro+ cap failed validation: \(report.errors)")
188 }
189}