halo-family commits 2 files 4 domain functions 211 passed

Pre-push review: Halo backup payload correction

PR #1 follow-up: a successful backup now fits the same platform’s aggregate restoration budget.

At a glance

  • Export rejects cumulative binary payload excess before writing the next file.
  • Preview rejects excess before reading the next payload; restore retains its atomic-save guard.
  • Platform limits remain 128 MB on iOS and 512 MB on macOS.

Verdict

Ready to push

The major review defect is fixed. Two real-path boundary regressions and all 211 domain functions pass; strict lint and clean committed-project iOS/macOS builds pass. Four independent reviews found no material issue. Native UI and live CloudKit acceptance retain their previous scope.

Review findings

1 raised · 1 fixed · 0 skipped

Jump to findings →

Tests

Pass rate: 100% (211 of 211)

New tests: 2

Diff coverage: 100% (79 of 79 added lines)

Jump to tests →

Three-level explanation

What changed: creating a backup checks the same total attachment limit as opening and restoring it. Previously a backup could succeed and then be too large to restore.

Why it matters: success now respects the same platform’s memory budget. A budget is a maximum total amount of attachment data.

Implementation: the repository captures one immutable, capped budget before background export or detached preview work. Both paths use the same checked cumulative addition. The internal constructor permits a stricter budget for small real-path regression fixtures.

Trade-off: existing platform caps remain unchanged. Larger macOS backups may still require macOS for restoration.

Edge cases: subtraction-based guards prevent overflow and include exactly-at-limit payloads. Export rejects before the next payload write and retains deferred temporary-folder cleanup. Preview accounts for declared member size before reading, and ZIP checksums/graph validation remain intact. Atomic restore still rejects excess before entering the import state.

Completeness: the aggregate export defect is implemented and verified. No schema, native UI, account or live CloudKit change is included. Arbitrary same-platform families can still exceed the supported cap and receive an explicit size error.

Important changes — detailed

Export enforces restoration budget

Halo Family/Halo Family/Persistence/BackupRepository.swift

Why it matters. A returned archive should respect the platform’s existing aggregate restore limit.

What to look at. BackupRepository.export and addPayloadBytes

Takeaway. Count cumulative size before output success.
Rationale. Retain existing atomic restore memory bounds and reject unsupported export size.

Preview rejects before payload allocation

Halo Family/Halo Family/Persistence/BackupRepository.swift

Why it matters. Unsupported payload totals should fail before the next member is loaded.

What to look at. validatePayloads

Takeaway. Use archive metadata for an early bounded-size check, then retain content validation.
Rationale. Reuse the same overflow-safe addition rule.

Boundary regressions use actual repositories

Tests/HaloPersistenceTests/FamilyBackupTests.swift

Why it matters. Prove multi-asset round-trip identity/data and absence of writes after rejection.

What to look at. aggregatePayloadAtBudgetRoundTripsWithStableAssets; aggregatePayloadOverBudgetRejectsExportPreviewAndRestoreWithoutChanges

Takeaway. Tighten the real policy for small fixtures rather than duplicate its implementation.
Rationale. Exercise limits without allocating hundreds of megabytes.

Key decisions

Retain per-platform limits

Keep the existing 128 MB iOS and 512 MB macOS caps. A caller may lower its budget but cannot increase the platform limit. This fixes export consistency without expanding the supported restore range or changing cross-platform policy.

Review findings

SeverityAreaFindingResolution
majorBackupRepository.exportSuccessful export could exceed the same platform’s preview/restore aggregate limit.Shared capped budget now applies before export writes and preview reads. Boundary and full domain gates pass.

Tests

Source: local run at 2026-10-09T11:46:20.723422+00:00 · snapshot 2d90b2de163c3dcf7dd125c9f4348dc43f22b581 (dirty working tree)

Baseline: none

Execution: passed · JUnit: 1 file · Coverage: 1 file · Baseline: absent

Coverage scope: as the project configures it

Totals: 211 passed · 0 failed · 0 skipped · 0 errored · 0 flaky

New and removed tests

Derived by declaration name, from the diff (no baseline run).

Diff coverage

FileAdded linesCoveredDiff coverage
CHANGELOG.md8—no coverage data
Halo Family/Halo Family/Persistence/BackupRepository.swift2619100%
Tests/HaloPersistenceTests/FamilyBackupTests.swift6260100%
docs/halo_family_design_pack/10-initial-implementation-results.md42—no coverage data

Aggregate diff coverage: 100% (79 of 79 measurable added lines).

Overall coverage

Head 93.5% (9351 of 9996 lines)

2 of 4 changed files matched coverage data.

Blast radius

Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 2d90b2de163c3dcf7dd125c9f4348dc43f22b581.

Dependents none found Changed Dependencies none found …amily/Halo Family/Persistence Tests/HaloPersistenceTests Halo Family/Halo Family/Persistence/BackupRepository.swift…stence/BackupRepository.swift Tests/HaloPersistenceTests/FamilyBackupTests.swift…Tests/FamilyBackupTests.swift
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

4 files: 2 code · 2 docs. Click to expand.

Code (2)

Halo Family/Halo Family/Persistence/BackupRepository.swift Modified +26 / -8
diff --git a/Halo Family/Halo Family/Persistence/BackupRepository.swift b/Halo Family/Halo Family/Persistence/BackupRepository.swiftindex ff5ed39..9105371 100644--- a/Halo Family/Halo Family/Persistence/BackupRepository.swift	+++ b/Halo Family/Halo Family/Persistence/BackupRepository.swift	@@ -16,16 +16,27 @@ nonisolated struct BackupPreview: Sendable { @MainActor final class BackupRepository {     #if os(iOS)-    nonisolated private static let payloadLimit: UInt64 = 128_000_000+    nonisolated private static let maximumPayloadBytes: UInt64 = 128_000_000     #else-    nonisolated private static let payloadLimit: UInt64 = 512_000_000+    nonisolated private static let maximumPayloadBytes: UInt64 = 512_000_000     #endif     private let stack: PersistenceStack-    init(stack: PersistenceStack) { self.stack = stack }+    private let payloadLimit: UInt64++    convenience init(stack: PersistenceStack) {+        self.init(stack: stack, payloadLimit: Self.maximumPayloadBytes)+    }++    // Callers may tighten the memory budget, but cannot raise the platform's restoration limit.+    init(stack: PersistenceStack, payloadLimit: UInt64) {+        self.stack = stack+        self.payloadLimit = min(payloadLimit, Self.maximumPayloadBytes)+    }      func export(familyID: NSManagedObjectID, readable: Bool = true) async throws -> URL {         try stack.access.check()         let access = stack.access+        let payloadLimit = payloadLimit         guard stack.role == .host else { throw GraphError.readOnly }         let context = stack.container.newBackgroundContext()         let cancellation = BackupCancellation()@@ -44,6 +55,7 @@ final class BackupRepository {             defer { if !delivered { try? FileManager.default.removeItem(at: folder) } }             var files: [BackupFile] = []             var records: [PortableRecord] = []+            var payloadBytes: UInt64 = 0             for entity in model.entities.sorted(by: { ($0.name ?? "") < ($1.name ?? "") }) {                 guard let name = entity.name else { continue }                 let request = NSFetchRequest<NSManagedObject>(entityName: name)@@ -56,6 +68,7 @@ final class BackupRepository {                     try cancellation.check()                     guard let id = object.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity }                     let record = try PortableGraph.record(object) { key, data in+                        payloadBytes = try Self.addPayloadBytes(UInt64(data.count), to: payloadBytes, limit: payloadLimit)                         let path = "payloads/\(id.uuidString)/\(key).bin"                         let url = folder.appendingPathComponent(path)                         try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)@@ -103,6 +116,7 @@ final class BackupRepository {      func preview(_ archive: URL) async throws -> BackupPreview {         let container = stack.container+        let payloadLimit = payloadLimit         let task = Task.detached {             let model = container.managedObjectModel             let fingerprint = try Self.fingerprint(archive)@@ -112,8 +126,7 @@ final class BackupRepository {             let data = try BackupArchive.read(manifest, from: archive, limit: 32_000_000)             let backup = try PortableGraph.decode(FamilyBackup.self, data: data)             try BackupValidation.validate(backup, model: model)-            let bytes = try Self.validatePayloads(backup, archive: archive, members: indexed)-            guard bytes <= Self.payloadLimit else { throw BackupError.tooLarge }+            let bytes = try Self.validatePayloads(backup, archive: archive, members: indexed, limit: payloadLimit)             _ = try BackupHistory(backup: backup, model: model) { path in                 try Self.payload(path, archive: archive, members: indexed)             }@@ -135,7 +148,7 @@ final class BackupRepository {         guard stack.role == .host else { throw GraphError.readOnly }         guard !stack.importingBackup else { throw BackupError.importing }         // A single atomic context save avoids exposing a partially imported family. Bound its payload memory.-        guard preview.payloadBytes <= Self.payloadLimit else { throw BackupError.tooLarge }+        guard preview.payloadBytes <= payloadLimit else { throw BackupError.tooLarge }         stack.importingBackup = true         defer { stack.importingBackup = false }         let container = stack.container@@ -243,8 +256,13 @@ final class BackupRepository {         return try BackupArchive.read(member, from: archive, limit: 32_000_000)     } +    nonisolated private static func addPayloadBytes(_ size: UInt64, to total: UInt64, limit: UInt64) throws -> UInt64 {+        guard total <= limit, size <= limit - total else { throw BackupError.tooLarge }+        return total + size+    }+     nonisolated private static func validatePayloads(_ backup: FamilyBackup, archive: URL,-                                                     members: [String: ArchiveMember]) throws -> UInt64 {+                                                     members: [String: ArchiveMember], limit: UInt64) throws -> UInt64 {         var expected: Set<String> = ["family.json"]         if members["Family.md"] != nil {             expected.insert("Family.md")@@ -256,9 +274,9 @@ final class BackupRepository {                 guard case .binary(let path) = value else { continue }                 guard path == "payloads/\(record.id.uuidString)/\(key).bin", expected.insert(path).inserted,                       let member = members[path] else { throw BackupError.invalidArchive }+                bytes = try addPayloadBytes(UInt64(member.size), to: bytes, limit: limit)                 let data = try payload(path, archive: archive, members: members)                 try BackupValidation.payload(data, key: key, record: record)-                bytes += UInt64(member.size)             }         }         guard expected == Set(members.keys) else { throw BackupError.invalidArchive }
Tests/HaloPersistenceTests/FamilyBackupTests.swift Modified +62 / -0
diff --git a/Tests/HaloPersistenceTests/FamilyBackupTests.swift b/Tests/HaloPersistenceTests/FamilyBackupTests.swiftindex b9f1fb0..6a57def 100644--- a/Tests/HaloPersistenceTests/FamilyBackupTests.swift+++ b/Tests/HaloPersistenceTests/FamilyBackupTests.swift@@ -46,6 +46,68 @@ struct FamilyBackupTests {         }     } +    @Test func aggregatePayloadAtBudgetRoundTripsWithStableAssets() async throws {+        try await withStore { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic boundary")+            let assets = AssetRepository(stack: stack)+            let first = try await assets.save(data: Data([1, 2, 3, 4]), familyID: family)+            let second = try await assets.save(data: Data([5, 6, 7, 8]), familyID: family)+            let identifiers = try [first, second].map {+                try #require(try graph.readable($0, entity: "Asset").value(forKey: "id") as? UUID)+            }+            let service = BackupRepository(stack: stack, payloadLimit: 8)+            let archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            #expect(preview.payloadBytes == 8)+            let targetDirectory = directory.appendingPathComponent("Restore")+            let target = try PersistenceStack(directory: targetDirectory)+            _ = try await BackupRepository(stack: target, payloadLimit: 8).restore(preview, asNewCopy: false)+            let reopened = try PersistenceStack(directory: targetDirectory)+            let request = NSFetchRequest<NSManagedObject>(entityName: "Asset")+            let imported = try reopened.container.viewContext.fetch(request)+            #expect(Set(imported.compactMap { $0.value(forKey: "id") as? UUID }) == Set(identifiers))+            let restoredAssets = AssetRepository(stack: reopened)+            for object in imported {+                let id = try #require(object.value(forKey: "id") as? UUID)+                let index = try #require(identifiers.firstIndex(of: id))+                let expected = index == 0 ? Data([1, 2, 3, 4]) : Data([5, 6, 7, 8])+                #expect(try await restoredAssets.data(for: object.objectID) == expected)+            }+        }+    }++    @Test func aggregatePayloadOverBudgetRejectsExportPreviewAndRestoreWithoutChanges() async throws {+        try await withStore { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic excess")+            let assets = AssetRepository(stack: stack)+            let first = try await assets.save(data: Data([1, 2, 3, 4]), familyID: family)+            let second = try await assets.save(data: Data([5, 6, 7, 8, 9]), familyID: family)+            let limited = BackupRepository(stack: stack, payloadLimit: 8)+            await #expect { try await limited.export(familyID: family) } throws: {+                if case BackupError.tooLarge = $0 { true } else { false }+            }+            #expect(try await assets.data(for: first) == Data([1, 2, 3, 4]))+            #expect(try await assets.data(for: second) == Data([5, 6, 7, 8, 9]))+            #expect(try graph.families().count == 1)+            let service = BackupRepository(stack: stack, payloadLimit: 9)+            let archive = try await service.export(familyID: family, readable: false)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            await #expect { try await limited.preview(archive) } throws: {+                if case BackupError.tooLarge = $0 { true } else { false }+            }+            let preview = try await service.preview(archive)+            #expect(preview.payloadBytes == 9)+            let target = try PersistenceStack(directory: directory.appendingPathComponent("Restore"))+            await #expect { try await BackupRepository(stack: target, payloadLimit: 8).restore(preview, asNewCopy: false) } throws: {+                if case BackupError.tooLarge = $0 { true } else { false }+            }+            #expect(try FamilyRepository(stack: target).families().isEmpty)+            #expect(try target.container.viewContext.count(for: NSFetchRequest<NSManagedObject>(entityName: "Asset")) == 0)+            #expect(!target.importingBackup)+        }+    }+     @Test func existingIdentityStopsRestoreWithoutPartialRowsOrOverwrite() async throws {         try await withStore { stack, graph, _ in             let family = try graph.createFamily(name: "Synthetic family")

Docs (2)

CHANGELOG.md Modified +8 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6d15d6e..c7ba23d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,10 @@  ## [Unreleased] +Backup payload correction `b21c53d` passes the full synthetic domain suite, strict+lint and fresh platform builds from the committed project/plist configuration.+Exact counts and development compilation evidence belong to the evidence document.+ Own-child Context role source `cec2976` passes focused domain, native, strict lint and fresh platform gates. The clarified rule uses same-family ChildProfile identity; legacy entries remain available for explicit review/removal. Exact counts and@@ -28,6 +32,10 @@ acceptance. Historical gate entries below describe their own snapshots.  ### Fixed +- Bound backup export by the same aggregate binary-payload budget as preview and+  restore, rejecting excess before returning an archive. Retain the existing iOS+  and macOS memory limits and check incoming payload sizes before loading them.+ - Exclude this family's own children from the Context teacher/role picker and   reject their role creation, repeated submissions and edits using ChildProfile   identity. Keep legacy entries visible for review and explicit removal without
docs/halo_family_design_pack/10-initial-implementation-results.md Modified +42 / -0
diff --git a/docs/halo_family_design_pack/10-initial-implementation-results.md b/docs/halo_family_design_pack/10-initial-implementation-results.mdindex 9898fbf..6051add 100644--- a/docs/halo_family_design_pack/10-initial-implementation-results.md+++ b/docs/halo_family_design_pack/10-initial-implementation-results.md@@ -1,5 +1,47 @@ # Implementation evidence +## PR #1 backup payload review correction — 2026-10-09 UTC++The requested PR Pilot review of `2d90b2d` found that export could return a backup+whose aggregate binary payload exceeded the same platform's preview/restore limit.+Source **`b21c53d`** applies one budget to all three operations: 128,000,000 bytes on iOS+and 512,000,000 bytes on macOS. Export rejects excess before writing the next payload+and its existing failure cleanup removes temporary output. Preview checks declared+payload sizes before loading them. Restore retains its atomic-save limit and import+guard. A caller can tighten the budget but cannot raise the platform limit.++Two synthetic regressions use small budgets to exercise the actual repository paths:+multiple assets exactly at the limit retain identities/data after restore and reopen;+an aggregate one byte over the limit fails export, preview and restore without changing+the source or creating target rows. The platform limits are deliberately unchanged;+a macOS archive exceeding the iOS budget still requires macOS for restoration.+No data-model, CloudKit, account, signing, reset or native UI change is introduced.++Final coordinated validation:++- New boundary selection: **2/2 functions**, 0.158 seconds; runner exit 0 in 6.274+  seconds. The first attempt stops at compilation before any test runs because nested+  Swift Testing `#require` calls recursively expand. Separate assertions correct the+  test; the failed attempt remains in the raw development log.+- Full synthetic domain suite: **211/211 functions in 24 suites**, 10.320 seconds;+  runner exit 0 in 20.520 seconds. JUnit records no failures, errors or skips; LCOV+  covers the package code. No runner startup/teardown stall occurs.+- Strict lint: **0 violations/121 files**. Fresh sequential iOS Simulator/macOS Debug+  builds both pass; runner exit 0 in 58.619 seconds. The unchanged HistoryProcessor+  optional-interpolation warning remains; no new platform warning appears.+- Four independent reuse, quality, efficiency and spec/documentation reviews find+  no material issue. All **162 tracked input hashes** remain identical through the+  final gates; runners change no source and create no untracked repository files.++Artifacts are retained in `/tmp/halo-prpilot-20261009-pmdk3i2s`: focused/full JUnit,+package LCOV, raw logs, pre/post-run hashes, dirty-file backups and the pre-push review.+The original checkout's two user project/plist edits and committed icon remain unchanged.+These gates use an isolated checkout of the committed project/plist source, so they+establish that configuration independently of earlier dirty-project gates. No native+UI suite is repeated for this domain-only correction. Earlier native/live acceptance+qualifications below retain their original snapshots. The build/test lane is drained+and released before the remaining PR Pilot comment/rebase/publication work.+ ## Own children excluded from Context roles — 2026-10-09 UTC  The user clarified that their own children must be excluded from the teacher/adult-style

Things to double-check

Existing acceptance limits

Native UI was not repeated for this persistence-only change. Local synthetic gates do not establish live account/share/CloudKit or production extension acceptance.