T-2471 independent-review correction: restore an unfinished parent, move its completed child, then export again.
Ready to push
The reproduced historical-provenance backlink defect is corrected without weakening live canonical links or changing stored bytes. Four review lenses found no blocker. Complete source-qualified synthetic gates pass; live import/new-account acceptance remains unclaimed.
Meddy/Meddy/Services/Backups/BackupRecordsNested.swift
Why it matters. Historical progress cannot require a current backlink after a supported move.
What to look at. validateRun restoreOriginalExecutionData loop
Meddy/Meddy/Services/Backups/BackupRecordsFrozen.swift
Why it matters. A broad historical exemption would accept unrelated child links.
What to look at. validateProgress / validateCanonicalEvent
Meddy/MeddyTests/MeddyBackupRestoredHistoryTests.swift
Why it matters. The previous moved-history test lacked a prior restore, missing this valid composition.
What to look at. restoredParentRetainsHistoricalTimerProgressAfterConfirmedMove
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Restored parent / moved child | Immutable provenance reused required current timer backlinks and blocked later export. | Apply narrow audit-proven historical handling only to origin checkpoints. Actual synthetic red/green regression and full gates pass. |
Source: local run at 2026-10-20T02:11:58.548489+00:00 · snapshot 0fe5c2688cd80368662af72468645599924a4f97 (dirty working tree)
Baseline: none
Execution: passed · JUnit: 3 files · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 375 passed · 0 failed · 0 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
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 0fe5c2688cd80368662af72468645599924a4f97.
7 files: 3 code · 4 docs. Click to expand.
diff --git a/Meddy/Meddy/Services/Backups/BackupRecordsFrozen.swift b/Meddy/Meddy/Services/Backups/BackupRecordsFrozen.swiftindex 1d63dbd..f5cb864 100644--- a/Meddy/Meddy/Services/Backups/BackupRecordsFrozen.swift+++ b/Meddy/Meddy/Services/Backups/BackupRecordsFrozen.swift@@ -117,16 +117,18 @@ nonisolated extension BackupRecords { } func validateProgress(- _ progress: OrderedCheckpoint, frozen: FrozenRoutineDefinition?, run: BackupRoutineRun, lookup: BackupRecordLookup+ _ progress: OrderedCheckpoint, frozen: FrozenRoutineDefinition?, run: BackupRoutineRun, lookup: BackupRecordLookup,+ historical: Bool = false ) throws { try BackupValidationIssue.checking(run, code: "BK-PROGRESS-01", field: "saved progress events", reason: "A saved event, step or target disagrees with the captured session.") {- try validateProgressContents(progress, frozen: frozen, run: run, lookup: lookup)+ try validateProgressContents(progress, frozen: frozen, run: run, lookup: lookup, historical: historical) } } private func validateProgressContents(- _ progress: OrderedCheckpoint, frozen: FrozenRoutineDefinition?, run: BackupRoutineRun, lookup: BackupRecordLookup+ _ progress: OrderedCheckpoint, frozen: FrozenRoutineDefinition?, run: BackupRoutineRun, lookup: BackupRecordLookup,+ historical: Bool ) throws { guard Set(progress.steps.map(\.id)).count == progress.steps.count, Set(progress.steps.map(\.position)).count == progress.steps.count else {@@ -144,10 +146,10 @@ nonisolated extension BackupRecords { definition.kind == step.targetKind else { throw ArchiveError.inconsistentRecords } } if let eventID = step.canonicalEventID {- try validateCanonicalEvent(eventID, step: step, run: run, lookup: lookup)+ try validateCanonicalEvent(eventID, step: step, run: run, lookup: lookup, historical: historical) } for eventID in step.reviewedEventIDs {- try validateCanonicalEvent(eventID, step: step, run: run, lookup: lookup)+ try validateCanonicalEvent(eventID, step: step, run: run, lookup: lookup, historical: historical) } for audit in step.audit { if let eventID = audit.previousEventID {@@ -159,7 +161,8 @@ nonisolated extension BackupRecords { } private func validateCanonicalEvent(- _ eventID: UUID, step: StepProgress, run: BackupRoutineRun, lookup: BackupRecordLookup, required: Bool = true+ _ eventID: UUID, step: StepProgress, run: BackupRoutineRun, lookup: BackupRecordLookup, required: Bool = true,+ historical: Bool = false ) throws { switch step.targetKind { case .medication:@@ -180,9 +183,12 @@ nonisolated extension BackupRecords { guard child.routineID == step.targetID else { throw ArchiveError.inconsistentRecords } // Historical audit references retain the old relationship after an explicit move. if required {- guard child.parentRoutineRunID == run.id, child.parentRoutineStepID == step.id else {- throw ArchiveError.inconsistentRecords- }+ let currentLink = child.parentRoutineRunID == run.id && child.parentRoutineStepID == step.id+ // Immutable restore provenance can predate an explicit move. The current parent+ // must retain the exact child/step audit; live canonical/reviewed links stay strict.+ let provenMove = historical && lookup.historicalTimerWitnesses[eventID, default: []]+ .contains(.init(parentID: run.id, stepID: step.id))+ guard currentLink || provenMove else { throw ArchiveError.inconsistentRecords } } } else if required || (lookup.administrations[eventID] != nil) || (lookup.treatmentCompletions[eventID] != nil) {
diff --git a/Meddy/Meddy/Services/Backups/BackupRecordsNested.swift b/Meddy/Meddy/Services/Backups/BackupRecordsNested.swiftindex 4b02b6f..43f01d8 100644--- a/Meddy/Meddy/Services/Backups/BackupRecordsNested.swift+++ b/Meddy/Meddy/Services/Backups/BackupRecordsNested.swift@@ -80,7 +80,7 @@ nonisolated extension BackupRecords { if !origin.stepProgressData.isEmpty { let progress: OrderedCheckpoint = try nested( origin.stepProgressData, shape: .orderedCheckpoint, limits: limits)- try validateProgress(progress, frozen: frozen, run: row, lookup: lookup)+ try validateProgress(progress, frozen: frozen, run: row, lookup: lookup, historical: true) } if let timer = origin.timerCheckpointData { try validateTimer(timer, limits: limits) } }
diff --git a/Meddy/MeddyTests/MeddyBackupRestoredHistoryTests.swift b/Meddy/MeddyTests/MeddyBackupRestoredHistoryTests.swiftnew file mode 100644index 0000000..d94b065--- /dev/null+++ b/Meddy/MeddyTests/MeddyBackupRestoredHistoryTests.swift@@ -0,0 +1,98 @@+import Foundation+import SwiftData+import Testing+@testable import Meddy++@MainActor struct MeddyBackupRestoredHistoryTests {+ private struct Fixture {+ let store: ModelContainer+ let parentID: UUID+ let childID: UUID+ let origin: Data+ }++ @Test func restoredParentRetainsHistoricalTimerProgressAfterConfirmedMove() async throws {+ let fixture = try await restoredAndMoved()+ let payload = try PhoneBackupService.capture(context: fixture.store.mainContext, reminderState: .init())+ let parent = try #require(payload.records.routineRuns.first { $0.id == fixture.parentID })+ #expect(parent.restoreOriginalExecutionData == fixture.origin)+ #expect(try PhoneBackupCodec.decode(PhoneBackupCodec.encode(payload)) == payload)+ let copied = try BackupArchiveFixtures.container()+ try payload.records.insert(into: copied.mainContext)+ try copied.mainContext.save()+ #expect(try BackupRecords.capture(copied.mainContext) == payload.records)+ }++ @Test func restoredHistoricalLinksStillRequireMoveEvidenceAndStrictCurrentLinks() async throws {+ let fixture = try await restoredAndMoved()+ let payload = try PhoneBackupService.capture(context: fixture.store.mainContext, reminderState: .init())+ let index = try #require(payload.records.routineRuns.firstIndex { $0.id == fixture.parentID })+ var progress = try JSONDecoder().decode(OrderedCheckpoint.self, from: payload.records.routineRuns[index].stepProgressData)+ let step = try #require(progress.steps.firstIndex { $0.audit.contains { $0.previousEventID == fixture.childID } })+ var withoutProof = payload+ progress.steps[step].audit = []+ withoutProof.records.routineRuns[index].stepProgressData = try JSONEncoder().encode(progress)+ #expect(throws: (any Error).self) { try PhoneBackupCodec.encode(withoutProof) }+ var staleCurrent = payload+ progress = try JSONDecoder().decode(OrderedCheckpoint.self, from: payload.records.routineRuns[index].stepProgressData)+ progress.steps[step].canonicalEventID = fixture.childID+ staleCurrent.records.routineRuns[index].stepProgressData = try JSONEncoder().encode(progress)+ #expect(throws: (any Error).self) { try PhoneBackupCodec.encode(staleCurrent) }+ var wrongTarget = payload+ let child = try #require(wrongTarget.records.routineRuns.firstIndex { $0.id == fixture.childID })+ wrongTarget.records.routineRuns[child].routineID = UUID()+ #expect(throws: (any Error).self) { try PhoneBackupCodec.encode(wrongTarget) }+ }++ private func source() throws -> (PhoneBackupPayload, UUID, UUID) {+ let store = try AppEnvironment.makeContainer(isolated: true)+ let context = store.mainContext+ try ProfileMigration.bootstrap(context)+ let definitions = RoutineService(context: context)+ let timer = try definitions.createTimed(name: "Synthetic completed timer", rounds: 1, durationSeconds: 10)+ let later = try definitions.createTimed(name: "Synthetic pending timer", rounds: 1, durationSeconds: 5)+ let first = RoutineStepDraft(kind: .timedRoutine, targetID: timer.id)+ let second = RoutineStepDraft(kind: .timedRoutine, targetID: later.id)+ let group = try definitions.createOrdered(name: "Synthetic unfinished group", steps: [first, second])+ let sessions = RoutineSessionService(context: context)+ let parent = try sessions.start(group)+ let child = try sessions.beginTimedStep(parent, stepID: first.id)+ let clock: (Double) -> ClockSample = {+ .init(wall: Date(timeIntervalSince1970: $0), monotonic: $0, continuityID: "synthetic")+ }+ try sessions.changeTimer(child, actionID: UUID(), clock: clock(100), operation: .start)+ try sessions.changeTimer(child, actionID: UUID(), clock: clock(110), operation: .advance)+ #expect(child.wasCompleted)+ #expect(!parent.wasCompleted)+ return (try PhoneBackupService.capture(context: context, reminderState: .init()), parent.id, child.id)+ }++ private func restoredAndMoved() async throws -> Fixture {+ let (payload, parentID, childID) = try source()+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try BackupStorage.ensureDirectory(directory)+ defer { try? FileManager.default.removeItem(at: directory) }+ let schema = AppEnvironment.schema+ let store = try ModelContainer(for: schema, configurations: [+ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ ])+ let reminders = ReminderStateStore(directory: directory, legacyDefaults: nil)+ let importer = PhoneBackupImporter(container: store, directory: directory, reminderStore: reminders)+ let preview = try await importer.preparePreview(data: PhoneBackupCodec.encode(payload))+ try await importer.applyPrepared(preview)+ try ProfileMigration.bootstrap(store.mainContext)+ let context = store.mainContext+ let runs = try context.fetch(FetchDescriptor<RoutineRun>())+ let parent = try #require(runs.first { $0.id == parentID })+ let child = try #require(runs.first { $0.id == childID })+ let origin = try #require(parent.restoreOriginalExecutionData)+ let definitions = RoutineService(context: context)+ let step = RoutineStepDraft(kind: .timedRoutine, targetID: child.routineID)+ let group = try definitions.createOrdered(name: "Synthetic moved destination", steps: [step])+ let sessions = RoutineSessionService(context: context)+ let destination = try sessions.start(group)+ try sessions.link(child, to: destination, stepID: step.id, confirmedMove: true)+ #expect(parent.restoreOriginalExecutionData == origin)+ return Fixture(store: store, parentID: parentID, childID: childID, origin: origin)+ }+}
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex be2198a..d1b5d50 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ - Restore medication recognition photos throughout the redesigned iPhone care screens, bring the detail image and Add/Replace/Remove editor controls forward, and retain existing photo storage and Save/Cancel behavior. ### Fixed+- T2471: Preserve immutable restored execution provenance when a completed child timer is explicitly moved, while retaining strict current-link, owner and target validation. - T2471: Allow safe cancellation of an uncommitted restore with missing or damaged retained input; clean orphaned private stages at cold launch while preserving recovery evidence and durable reminder state. - T2471: Preserve legitimate nested timer revision pairs and moved-timer audit history in backups without rewriting saved values; identify each frozen identity rule with private diagnostics. - T2471: Preserve frozen historical step meaning when validating backups after routine edits, and explain rejected relationships with private diagnostic codes and safe copy details.
diff --git a/specs/portable-backup-restore/decision_log.md b/specs/portable-backup-restore/decision_log.mdindex adf0073..d16f25a 100644--- a/specs/portable-backup-restore/decision_log.md+++ b/specs/portable-backup-restore/decision_log.md@@ -184,3 +184,7 @@ Cancellation availability uses the same exact empty-baseline/no-commit proof as Cold launch, before previews or exports are exposed, removes only generated private input/export/stage files and scratch directories under the exclusive gate. A valid pending journal retains its named input even when its bytes are damaged. Unreadable, oversized, duplicate-key or unknown-key journals preserve all potential evidence. Cleanup skips top-level symlinks and never examines user-selected Files locations. Only disposable export files and scratch directories are excluded from device backup. Recovery inputs remain eligible alongside pending journals, bootstrap metadata and authoritative reminder receipts, preserving their existing durability relationship. The containing directory is not excluded. File protection and the archive/import schema remain unchanged. No automatic deletion or cancellation of a committed import is added.++## Restored execution provenance after a confirmed timer move (2026-10-20)++Immutable origin checkpoints describe historical execution, so their canonical child IDs can predate a supported confirmed move. Accept a stale backlink only in that origin scope and only when the current original parent's saved audit proves the exact child/parent/step association. Keep required child presence, typed target, owner and frozen-step checks; live canonical/reviewed links retain current backlinks. Preserve every original byte and value. This fulfils the existing historical-preservation contract without a schema change or automatic live repair.
diff --git a/specs/portable-backup-restore/implementation.md b/specs/portable-backup-restore/implementation.mdindex 8949ec7..219d7a1 100644--- a/specs/portable-backup-restore/implementation.md+++ b/specs/portable-backup-restore/implementation.md@@ -142,3 +142,13 @@ For an app developer: recovery-screen cancellation eligibility checks the journa For a persistence reviewer: duplicate/unknown journal keys are rejected before Foundation decoding. A valid journal's input is retained without requiring valid input bytes. Durable semantic reminders, bootstrap metadata, journal and recovery input remain device-backup eligible; only disposable exports/scratch are excluded. Cancellation cannot discard a committed receipt or bypass changed-baseline refusal. Synthetic focused tests and the required final gate results are recorded separately; live import/new-account acceptance remains unclaimed. Final review-fix gate: widget build, phone330/51suites, Watch14/2suites, fullUI29, strict lint/whitespace all pass with no failures/skips. Native receipts and the red/green reproduction are recorded in `specs/bugfixes/backup-recovery-cleanup/report.md`. Tested source/configuration hashes match the final tree.++## Restore, then move a completed child timer++For a new user: a supported move of a completed timer after restore no longer prevents the next backup. The saved original execution remains unchanged.++For an app developer: only immutable restore-origin checkpoints can use an old timer backlink, and only when the original parent's current audit retains the exact child/parent/step witness. Live links retain their current-backlink requirement.++For a persistence reviewer: the historical scope preserves required presence, type, target, owner and frozen-step checks, reuses the bounded witness index and never rewrites the provenance blob. The synthetic regression performs an actual import and confirmed service move before re-export/raw persistence; missing evidence and stale current links remain rejection cases. The full review and gate evidence is in `specs/bugfixes/restored-timer-provenance/report.md`.++Final provenance-fix gate: widgets/lint/whitespace, phone332/52suites, Watch14/2suites and fullUI29 pass with zero failures/skips. The final source/configuration hashes match the tested tree. Review evidence and retained failed fixture/reproduction logs are documented in the bugfix report.
diff --git a/specs/bugfixes/restored-timer-provenance/report.md b/specs/bugfixes/restored-timer-provenance/report.mdnew file mode 100644index 0000000..71146f1--- /dev/null+++ b/specs/bugfixes/restored-timer-provenance/report.md@@ -0,0 +1,21 @@+# Restored timer provenance after an explicit move++T-2471, PR14 independent native review, 2026-10-20.++## Reproduction++An unfinished ordered parent can contain a completed child timer and a pending later step. Import safely pauses the parent and preserves its original checkpoint as immutable provenance. A subsequent supported confirmed move of the completed child changes its current backlink and adds an audit to the original parent. The provenance checkpoint still retains the original canonical child ID. Applying current-backlink validation to that historical checkpoint rejects a later export with BK-PROGRESS-01.++The full native review at `0fe5c2688cd80368662af72468645599924a4f97` identified the composition. A synthetic actual import → confirmed service move → encode reproduction fails with BK-PROGRESS-01 in `test-domain.b71yR4`. Initial fixture attempts used an incomplete schema and prematurely deleted a temporary store; those failures are retained under `/tmp/cr-review-14/restored-history-red*.log` and are not evidence of the validator defect.++## Correction++Only immutable restore-origin progress opts into historical backlink handling. A stale child backlink is accepted only with an existing exact current-parent audit witness for that child ID, parent ID and step ID. Required child presence, record type, target, ownership and frozen-step checks remain strict. Live canonical/reviewed links retain the original current-backlink requirement. No origin bytes, care values, schema or stored relationships are rewritten.++Four read-only review lenses found no blocker or scope divergence; the implementation reuses the existing indexed witnesses without another scan or unbounded allocation. Synthetic tests verify exact origin-byte preservation through import/move/re-export/raw persistence and reject missing move evidence, stale current links and wrong targets. Focused tests and full phase-boundary gate receipts are recorded below when complete.++No live import/new-account acceptance, installation, account/entitlement change or PR15 action is performed. All test stores and care data are synthetic and isolated.++## Final verification++Focused corrected suite passes7 tests in2 suites (`test-domain.lkjS6b`), including both new regressions and the existing frozen-revision suite. The complete serial `make pre-push` exits0: widget build (`build-widgets.KOsqbX`), phone332/52suites (`test-domain.WmAAvD`), Watch14/2suites (`test-watch.MvE3FO`), fullUI29 (`test-ui-all.dKrmMh`), all zero failures/skips. Strict lint across191 Swift files and whitespace validation pass. Native summaries/JUnit conversions are under `/tmp/meddy-restored-history-review-inputs`; full log `/tmp/cr-review-14/restored-history-final-prepush.log`. Tracked-content comparison and197 source/configuration hashes found no test-run changes. No line-coverage claim is made.