Meddy native tests 69 passed source 011be8c strict lint 118 files / 0 violations

Pre-push review: Meddy T-2450 taken feedback

Remove measured repeated ownership reads before saved dose feedback. Isolated synthetic evidence; no phone deployment or merge.

At a glance

  • At 500 synthetic doses, save with untimed-history observer improves from roughly700ms to52ms.

  • Routine display validation improves from5.17s to13.7ms. XCTest routine feedback improves from67.07s to7.05s including automation overhead.

  • Care saves, canonical action/replay validation, tombstone Undo and notification writer order remain unchanged.

Verdict

Ready for draft PR

Four read-only source perspectives have no blocking code findings. Native affected checks pass (68 domain + 1 UI), strict lint and whitespace checks pass. Synthetic service and UI evidence is qualified; physical acceptance and full-suite results are not claimed.

Review findings

2 raised · 1 fixed · 1 skipped

Jump to findings →

Tests

Pass rate: 100% (69 of 69)

New tests: 5

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

The app reread the same history for every displayed dose and checked untimed sessions for timers. Read filters now validate together, and untimed histories skip deadline discovery. A taken result still waits for its saved dose.

Views reuse ProfileAccess.visible arrays; snapshots and reminder planning use a validated batch with one synchronous ReadScope per filter. Pending timer cleanup runs before discovery. No cache spans writes, navigation or actor suspension.

Existing indexed validation retains cross-type UUID collision, linked-owner/version and archive checks. All mutation authorization remains fresh. Snapshot per-run reads and timed/dependant lifecycle paths retain pre-existing scale costs; the entire system is not claimed linear. Optimized test code uses DEBUG/testability hooks required by existing fixtures.

Important changes — detailed

Skip untimed foreground deadline discovery

Meddy/Meddy/Services/PhoneRoundAlertService.swift

Why it matters. The synchronous save observer spent roughly700ms on histories without timer checkpoints.

What to look at. setActive and refresh

Takeaway. Reject impossible deadline candidates before expensive validation, while preserving pending cleanup.
Rationale. No checkpoint means no timer to discover; existing pending entries and actual timer actions still validate.

Batch routine and Today display validation

Meddy/Meddy/Features/RoutineRunView.swift

Why it matters. Per-event global reads occupied UI recomputation after saved routine doses.

What to look at. visible display arrays and existing-log picker

Takeaway. Use the existing operation-local read index for arrays.
Rationale. The shared validator preserves strict ownership without a long-lived cache.

Batch initial snapshot and reminder filters

Meddy/Meddy/Services/ProfileAccess.swift

Why it matters. History event filtering multiplied whole-store materialization.

What to look at. validated

Takeaway. Keep read scopes entirely inside synchronous filters.
Rationale. Returned models remain ordinary context-owned rows; subsequent service actions still validate freshly.

Preserve measured regression and synthetic UI evidence

Meddy/MeddyTests/MeddyTakenLatencyTests.swift

Why it matters. Work-count bounds avoid brittle wall-time gates; exact event counts, links and replay protect accounting.

What to look at. MeddyTakenLatencyTests and MeddyTakenLatencyUITests

Takeaway. Separate save/observer/render/snapshot timings from automated visible-state latency.
Rationale. Synthetic Release-optimized evidence cannot establish physical-device frame timings.

Key decisions

No optimistic UI or transaction reordering

Remove demonstrated read amplification while showing committed care state and preserving existing rollback/notification semantics.

Targeted local verification

The task authorizes isolated affected suites and one UI journey. Full phone/Watch/UI gates and device/live-cloud acceptance were not run or claimed.

Review findings

SeverityAreaFindingResolution
minorEvidence scopeNotification plan is timed but has no direct work-bound assertion.Report explicitly describes this stage as diagnostic; existing reminder/followup/snooze tests verify semantics.
minorConstant-factor optimizationSnapshot/reminder initial filters construct several independent scopes.Optional consolidation deferred: current scopes have explicit synchronous lifetimes and remove measured per-history multiplication.

Tests

Source: local run at 2026-10-13T08:07:59.557901+00:00 · snapshot 011be8c1f0256fd18654909c93aa94750283b477

Baseline: none

Execution: passed · JUnit: 2 files · Coverage: none · Baseline: absent

Coverage scope: as the project configures it

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

New and removed tests

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

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 82ff4d97e20f4e76d59f628a00c5b4d45b86f5ba.

addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

14 files: 11 code · 3 docs. Click to expand.

Code (11)

Meddy/Meddy/Design/RedesignReferenceFixture.swift Modified +17 / -0
diff --git a/Meddy/Meddy/Design/RedesignReferenceFixture.swift b/Meddy/Meddy/Design/RedesignReferenceFixture.swiftindex 3a5059e..7698ca8 100644--- a/Meddy/Meddy/Design/RedesignReferenceFixture.swift+++ b/Meddy/Meddy/Design/RedesignReferenceFixture.swift@@ -79,6 +79,23 @@         try context.save()       }       let alex = try ProfileService(context: context).create(displayName: "Alex")+      if let value = ProcessInfo.processInfo.environment["MEDDY_TEST_ROUTINE_HISTORY"],+        let count = Int(value), (1...100).contains(count),+        let routine = try context.fetch(FetchDescriptor<Routine>()).first(where: { $0.kindRaw == "ordered" }) {+        let service = RoutineSessionService(context: context)+        let template = try service.start(routine)+        try service.end(template, actionID: UUID())+        for _ in 1..<count {+          let run = RoutineRun(routine: routine)+          run.definitionSnapshotData = template.definitionSnapshotData+          run.stepProgressData = template.stepProgressData+          run.processedActionIDsData = template.processedActionIDsData+          run.statusRaw = template.statusRaw+          run.endedAt = template.endedAt+          context.insert(run)+        }+        try context.save()+      }       if ProcessInfo.processInfo.environment["MEDDY_TEST_RECOGNITION_PHOTOS"] == "1" {         let bytes = try recognitionPhoto()         let service = MedicationPhotoService(context: context)
Meddy/Meddy/Features/RoutineRunView.swift Modified +7 / -21
diff --git a/Meddy/Meddy/Features/RoutineRunView.swift b/Meddy/Meddy/Features/RoutineRunView.swiftindex b81e6e6..9d12851 100644--- a/Meddy/Meddy/Features/RoutineRunView.swift+++ b/Meddy/Meddy/Features/RoutineRunView.swift@@ -7,27 +7,19 @@ struct RoutineRunView: View {   @Environment(\.modelContext) private var context   @Query private var allMedications: [Medication]   private var medications: [Medication] {-    allMedications.filter {-      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)-    }+    ProfileAccess.visible(allMedications, for: run.profileID ?? ProfileIdentity.me, context: context)   }   @Query private var allAdministrations: [Administration]   private var administrations: [Administration] {-    allAdministrations.filter {-      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)-    }+    ProfileAccess.visible(allAdministrations, for: run.profileID ?? ProfileIdentity.me, context: context)   }   @Query private var allCompletions: [TreatmentCompletion]   private var completions: [TreatmentCompletion] {-    allCompletions.filter {-      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)-    }+    ProfileAccess.visible(allCompletions, for: run.profileID ?? ProfileIdentity.me, context: context)   }   @Query private var allRuns: [RoutineRun]   private var runs: [RoutineRun] {-    allRuns.filter {-      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)-    }+    ProfileAccess.visible(allRuns, for: run.profileID ?? ProfileIdentity.me, context: context)   }   let run: RoutineRun   @State private var error: String?@@ -574,22 +566,16 @@ struct ExistingLogPicker: View {   @Query(sort: \Administration.timestamp, order: .reverse) private var allAdministrations:     [Administration]   private var administrations: [Administration] {-    allAdministrations.filter {-      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)-    }+    ProfileAccess.visible(allAdministrations, for: run.profileID ?? ProfileIdentity.me, context: context)   }   @Query(sort: \TreatmentCompletion.timestamp, order: .reverse) private var allCompletions:     [TreatmentCompletion]   private var completions: [TreatmentCompletion] {-    allCompletions.filter {-      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)-    }+    ProfileAccess.visible(allCompletions, for: run.profileID ?? ProfileIdentity.me, context: context)   }   @Query(sort: \RoutineRun.completedAt, order: .reverse) private var allRuns: [RoutineRun]   private var runs: [RoutineRun] {-    allRuns.filter {-      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)-    }+    ProfileAccess.visible(allRuns, for: run.profileID ?? ProfileIdentity.me, context: context)   }   let run: RoutineRun   let step: FrozenRoutineStep
Meddy/Meddy/Features/RoutinesView.swift Modified +5 / -5
diff --git a/Meddy/Meddy/Features/RoutinesView.swift b/Meddy/Meddy/Features/RoutinesView.swiftindex 3b07168..78db0ee 100644--- a/Meddy/Meddy/Features/RoutinesView.swift+++ b/Meddy/Meddy/Features/RoutinesView.swift@@ -26,15 +26,15 @@ struct RoutinesView: View {   @Environment(\.modelContext) private var context   @Query(sort: \Routine.name) private var allRoutines: [Routine]   private var routines: [Routine] {-    allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allRoutines, for: selectedProfileID, context: context)   }   @Query(sort: \Treatment.name) private var allTreatments: [Treatment]   private var treatments: [Treatment] {-    allTreatments.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allTreatments, for: selectedProfileID, context: context)   }   @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]   private var runs: [RoutineRun] {-    allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allRuns, for: selectedProfileID, context: context)   }   @State private var archived = false   @State private var creation: CareCreation?@@ -192,7 +192,7 @@ struct RoutineDetailView: View {   }   @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]   private var runs: [RoutineRun] {-    allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allRuns, for: selectedProfileID, context: context)   }   let routine: Routine   let onStart: (Routine, RoutineOccurrence?) -> Void@@ -321,7 +321,7 @@ struct TreatmentDetailView: View {   @Query(sort: \TreatmentCompletion.timestamp, order: .reverse) private var allCompletions:     [TreatmentCompletion]   private var completions: [TreatmentCompletion] {-    allCompletions.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allCompletions, for: selectedProfileID, context: context)   }   let treatment: Treatment   @State private var editing = false
Meddy/Meddy/Features/TodayRoutineSections.swift Modified +4 / -4
diff --git a/Meddy/Meddy/Features/TodayRoutineSections.swift b/Meddy/Meddy/Features/TodayRoutineSections.swiftindex aabb3ac..e7fe0bc 100644--- a/Meddy/Meddy/Features/TodayRoutineSections.swift+++ b/Meddy/Meddy/Features/TodayRoutineSections.swift@@ -14,11 +14,11 @@ struct TodayRoutineSections: View {   @Environment(PhoneNavigation.self) private var navigation   @Query(sort: \Routine.name) private var allRoutines: [Routine]   private var routines: [Routine] {-    allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allRoutines, for: selectedProfileID, context: context)   }   @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]   private var runs: [RoutineRun] {-    allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allRuns, for: selectedProfileID, context: context)   }   private var cards: [(Routine, RoutineOccurrence)] {     let represented = runs.map {@@ -159,11 +159,11 @@ struct CurrentMedicationsView: View {   @Environment(\.modelContext) private var context   @Query(sort: \Medication.name) private var allMedications: [Medication]   private var medications: [Medication] {-    allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allMedications, for: selectedProfileID, context: context)   }   @Query(sort: \Routine.name) private var allRoutines: [Routine]   private var routines: [Routine] {-    allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+    ProfileAccess.visible(allRoutines, for: selectedProfileID, context: context)   }   private var groups: [String: [Medication]] {     Dictionary(grouping: medications.filter(\.isActive)) { $0.purpose?.name ?? "Ungrouped" }
Meddy/Meddy/Services/PhoneCompanionService.swift Modified +6 / -18
diff --git a/Meddy/Meddy/Services/PhoneCompanionService.swift b/Meddy/Meddy/Services/PhoneCompanionService.swiftindex f156dcd..1b3c565 100644--- a/Meddy/Meddy/Services/PhoneCompanionService.swift+++ b/Meddy/Meddy/Services/PhoneCompanionService.swift@@ -140,24 +140,12 @@ final class PhoneCompanionService {   func snapshot() throws -> CompanionSnapshot {     let service = RoutineSessionService(context: context)     let schedules = ScheduleService(context: context)-    let medications = try context.fetch(FetchDescriptor<Medication>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }-    let routines = try context.fetch(FetchDescriptor<Routine>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }-    let runs = try context.fetch(FetchDescriptor<RoutineRun>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }-    let events = try context.fetch(FetchDescriptor<Administration>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }-    let treatments = try context.fetch(FetchDescriptor<Treatment>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }-    let completions = try context.fetch(FetchDescriptor<TreatmentCompletion>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }+    let medications = ProfileAccess.validated(try context.fetch(FetchDescriptor<Medication>()), context: context)+    let routines = ProfileAccess.validated(try context.fetch(FetchDescriptor<Routine>()), context: context)+    let runs = ProfileAccess.validated(try context.fetch(FetchDescriptor<RoutineRun>()), context: context)+    let events = ProfileAccess.validated(try context.fetch(FetchDescriptor<Administration>()), context: context)+    let treatments = ProfileAccess.validated(try context.fetch(FetchDescriptor<Treatment>()), context: context)+    let completions = ProfileAccess.validated(try context.fetch(FetchDescriptor<TreatmentCompletion>()), context: context)     let represented = runs.map {       ScheduledRunSnapshot(         id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID,
Meddy/Meddy/Services/PhoneRoundAlertService.swift Modified +5 / -2
diff --git a/Meddy/Meddy/Services/PhoneRoundAlertService.swift b/Meddy/Meddy/Services/PhoneRoundAlertService.swiftindex 2e5864b..d80b6c9 100644--- a/Meddy/Meddy/Services/PhoneRoundAlertService.swift+++ b/Meddy/Meddy/Services/PhoneRoundAlertService.swift@@ -84,7 +84,8 @@ final class PhoneRoundAlertService {     // No catch-up buzz on returning from background: the OS notification was responsible     // for that deadline. Reconcile the saved boundary without duplicating that alert.     do {-      for run in try context.fetch(FetchDescriptor<RoutineRun>()) where owns(run) {+      for run in try context.fetch(FetchDescriptor<RoutineRun>())+      where run.timerCheckpointData != nil && owns(run) {         let service = RoutineSessionService(context: context)         guard let timer = try? service.timer(run), timer.phase == .running else { continue }         if timer.deadline.map({ $0 <= clock().wall }) == true@@ -123,7 +124,9 @@ final class PhoneRoundAlertService {           pending.removeValue(forKey: id)         }       }-      for run in runs where owns(run) {+      // Untimed history cannot have a deadline. Pending entries above still reconcile+      // removal/corruption before discovery, and actual timer actions revalidate ownership.+      for run in runs where run.timerCheckpointData != nil && owns(run) {         guard let timer = try? service.timer(run), timer.phase == .running,           let deadline = timer.deadline         else { continue }
Meddy/Meddy/Services/ProfileAccess.swift Modified +4 / -0
diff --git a/Meddy/Meddy/Services/ProfileAccess.swift b/Meddy/Meddy/Services/ProfileAccess.swiftindex 3116dc7..63d21e3 100644--- a/Meddy/Meddy/Services/ProfileAccess.swift+++ b/Meddy/Meddy/Services/ProfileAccess.swift@@ -105,6 +105,10 @@ import SwiftData     guard !values.isEmpty, let scope = try? ReadScope(context: context) else { return [] }     return values.filter { scope.visible($0, for: id) }   }+  static func validated<T: ProfileOwned>(_ values: [T], context: ModelContext) -> [T] {+    guard !values.isEmpty, let scope = try? ReadScope(context: context) else { return [] }+    return values.filter { (try? scope.owner($0)) != nil }+  }   static func canonical<T: ProfileOwned>(_ type: T.Type, id: UUID, context: ModelContext) throws     -> T {     let rows = try context.fetch(FetchDescriptor<T>()).filter { $0.id == id }
Meddy/Meddy/Services/ReminderService.swift Modified +3 / -9
diff --git a/Meddy/Meddy/Services/ReminderService.swift b/Meddy/Meddy/Services/ReminderService.swiftindex 7ca05e4..1cca725 100644--- a/Meddy/Meddy/Services/ReminderService.swift+++ b/Meddy/Meddy/Services/ReminderService.swift@@ -248,15 +248,9 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate {   func plan(now: Date, includeElapsedWake: Bool = false) throws -> [PlannedReminder] {     let planner = NotificationPlanner()     let schedules = ScheduleService(context: context)-    let medications = try context.fetch(FetchDescriptor<Medication>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }-    let routines = try context.fetch(FetchDescriptor<Routine>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }-    let runs = try context.fetch(FetchDescriptor<RoutineRun>()).filter {-      (try? ProfileAccess.owner($0, context: context)) != nil-    }+    let medications = ProfileAccess.validated(try context.fetch(FetchDescriptor<Medication>()), context: context)+    let routines = ProfileAccess.validated(try context.fetch(FetchDescriptor<Routine>()), context: context)+    let runs = ProfileAccess.validated(try context.fetch(FetchDescriptor<RoutineRun>()), context: context)     var result: [PlannedReminder] = []     followupReceipts.advance(now: now)     wakeReceipts.advance(now: now)
Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift Modified +18 / -0
diff --git a/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift b/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swiftindex 9067e5c..b914708 100644--- a/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift+++ b/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift@@ -167,6 +167,24 @@ struct MeddyPhoneRoundAlertTests {     old.action()     #expect(old.cancelled && buzzes == 0)   }+  @Test func removedTimerCheckpointStillCancelsPreviouslyScheduledDeadline() throws {+    let (store, run, service) = try fixture()+    defer { MutationEffects.remove(store.mainContext) }+    let scheduler = SyntheticDeadlineScheduler()+    let sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic")+    var buzzes = 0+    let alerts = PhoneRoundAlertService(+      context: store.mainContext, scheduler: scheduler, clock: { sample },+      feedback: { buzzes += 1 }, keepAwake: { _ in })+    alerts.setActive(true)+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)+    let old = try #require(scheduler.entries.last)+    run.timerCheckpointData = nil+    try store.mainContext.save()+    alerts.refresh()+    old.action()+    #expect(old.cancelled && buzzes == 0 && scheduler.entries.count == 1)+  } }  @MainActor
Meddy/MeddyTests/MeddyTakenLatencyTests.swift Added +128 / -0
diff --git a/Meddy/MeddyTests/MeddyTakenLatencyTests.swift b/Meddy/MeddyTests/MeddyTakenLatencyTests.swiftnew file mode 100644index 0000000..9c276e1--- /dev/null+++ b/Meddy/MeddyTests/MeddyTakenLatencyTests.swift@@ -0,0 +1,128 @@+import Foundation+import SwiftData+import Testing++@testable import Meddy++#if DEBUG || MEDDY_PERFORMANCE_TESTING+@MainActor+struct MeddyTakenLatencyTests {+  private func fixture(history: Int, runs: Int) throws -> (ModelContainer, Medication, RoutineRun) {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let context = store.mainContext+    let medication = Medication(name: "Synthetic dose latency")+    context.insert(medication)+    let managed = Medication(name: "Synthetic routine dose latency")+    context.insert(managed)+    let routine = try RoutineService(context: context).createOrdered(+      name: "Synthetic dose routine", steps: [.init(kind: .medication, targetID: managed.id)],+      confirmedMedicationIDs: [managed.id])+    let active = try RoutineSessionService(context: context).start(routine)+    var ended = try RoutineSessionService(context: context).progress(active)+    ended.phase = .endedIncomplete+    for _ in 0..<runs {+      let run = RoutineRun(routine: routine)+      run.definitionSnapshotData = active.definitionSnapshotData+      run.stepProgressData = try JSONEncoder().encode(ended)+      run.processedActionIDsData = active.processedActionIDsData+      run.statusRaw = SessionPhase.endedIncomplete.rawValue+      run.endedAt = Date()+      context.insert(run)+    }+    for index in 0..<history {+      let action = AdministrationAction(+        eventID: UUID(), medicationID: medication.id,+        timestamp: Date().addingTimeInterval(-Double(index + 1) * 86400), source: .phone,+        dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+      context.insert(Administration(action: action, medication: medication))+    }+    try context.save()+    return (store, medication, active)+  }++  @Test(arguments: [100, 500])+  func takenWriteAndUntimedObserverDoNotMultiplyHistory(history: Int) throws {+    let (store, medication, _) = try fixture(history: history, runs: 25)+    let context = store.mainContext+    defer { MutationEffects.remove(context) }+    let alerts = PhoneRoundAlertService(context: context, feedback: {}, keepAwake: { _ in })+    alerts.setActive(true)+    var inspected = 0+    ProfileAccess.inspectedRows = { inspected += $0 }+    defer { ProfileAccess.inspectedRows = nil }+    for visit in 0..<3 {+      inspected = 0+      var observerRows = 0+      let refreshStart = ProcessInfo.processInfo.systemUptime+      alerts.refresh()+      let refreshMilliseconds = (ProcessInfo.processInfo.systemUptime - refreshStart) * 1000+      observerRows = inspected+      inspected = 0+      let start = ProcessInfo.processInfo.systemUptime+      let events = try TodayMedicationAction.take([medication], at: Date(), context: context)+      let elapsed = (ProcessInfo.processInfo.systemUptime - start) * 1000+      print("Synthetic dose history=\(history) visit=\(visit) writeWithObserverMS=\(elapsed) writeRows=\(inspected) observerMS=\(refreshMilliseconds) observerRows=\(observerRows)")+      #expect(events.count == 1 && !events[0].isDeleted)+      #expect(try context.fetchCount(FetchDescriptor<Administration>()) == history + visit + 1)+      // Untimed histories have no deadlines to reconcile. Their count must not multiply+      // whole-store ownership reads before a saved dose can return to its screen.+      #expect(observerRows <= 4 * (history + 32))+      #expect(inspected <= 40 * (history + 32))+    }+  }++  @Test func routineRecordAndRenderingStagesWithAccumulatedHistory() throws {+    let (store, _, run) = try fixture(history: 500, runs: 25)+    let context = store.mainContext+    let service = RoutineSessionService(context: context)+    let step = try #require(service.definition(run).steps.first)+    let medication = try ProfileAccess.canonical(Medication.self, id: step.targetID, context: context)+    let action = AdministrationAction(+      eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+      dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+    var inspected = 0+    ProfileAccess.inspectedRows = { inspected += $0 }+    defer { ProfileAccess.inspectedRows = nil }+    let start = ProcessInfo.processInfo.systemUptime+    let event = try service.recordMedication(action, in: run, stepID: step.id)+    print("Synthetic routine writeMS=\((ProcessInfo.processInfo.systemUptime - start) * 1000) rows=\(inspected)")+    #expect(event.routineRunID == run.id && event.routineStepID == step.id)+    // Repeating a captured tap must retain exactly one dose and one step completion.+    #expect(try service.recordMedication(action, in: run, stepID: step.id).id == event.id)+    #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 501)+    inspected = 0+    let reminderStart = ProcessInfo.processInfo.systemUptime+    let plans = try ReminderService(context: context, registerDelegate: false).plan(now: Date())+    print("Synthetic reminder planMS=\((ProcessInfo.processInfo.systemUptime - reminderStart) * 1000) rows=\(inspected)")+    #expect(plans.isEmpty)+    inspected = 0+    let rows = try context.fetch(FetchDescriptor<Administration>())+    let renderStart = ProcessInfo.processInfo.systemUptime+    let visible = rows.filter { ProfileAccess.visible($0, for: ProfileIdentity.me, context: context) }+    print("Synthetic routine legacyRenderMS=\((ProcessInfo.processInfo.systemUptime - renderStart) * 1000) rows=\(inspected)")+    #expect(visible.count == 501)+    inspected = 0+    let indexedStart = ProcessInfo.processInfo.systemUptime+    let indexed = ProfileAccess.visible(rows, for: ProfileIdentity.me, context: context)+    print("Synthetic routine indexedRenderMS=\((ProcessInfo.processInfo.systemUptime - indexedStart) * 1000) rows=\(inspected)")+    #expect(indexed.map(\.id) == visible.map(\.id))+    #expect(inspected <= 532)+  }++  @Test func companionSnapshotDoesNotRevalidateWholeStoreForEveryHistoricalEvent() throws {+    let (store, _, _) = try fixture(history: 500, runs: 25)+    let context = store.mainContext+    let companion = PhoneCompanionService(context: context)+    var inspected = 0+    ProfileAccess.inspectedRows = { inspected += $0 }+    defer { ProfileAccess.inspectedRows = nil }+    let start = ProcessInfo.processInfo.systemUptime+    let snapshot = try companion.snapshot()+    print("Synthetic conditional Watch snapshotMS=\((ProcessInfo.processInfo.systemUptime - start) * 1000) rows=\(inspected)")+    #expect(snapshot.appliedEventIDs.count == 500 && snapshot.runs.count == 26)+    #expect(snapshot.eventOwners?.count == 500)+    #expect(inspected <= 120 * 532)+    #expect(!context.hasChanges)+  }+}+#endif
Meddy/MeddyUITests/MeddyTakenLatencyUITests.swift Added +43 / -0
diff --git a/Meddy/MeddyUITests/MeddyTakenLatencyUITests.swift b/Meddy/MeddyUITests/MeddyTakenLatencyUITests.swiftnew file mode 100644index 0000000..3555957--- /dev/null+++ b/Meddy/MeddyUITests/MeddyTakenLatencyUITests.swift@@ -0,0 +1,43 @@+import XCTest++@MainActor+final class MeddyTakenLatencyUITests: XCTestCase {+  func testSavedTakenFeedbackAndRoutineProgressWithSyntheticHistory() {+    continueAfterFailure = false+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launchEnvironment["MEDDY_TEST_REDESIGN_REFERENCE"] = "1"+    app.launchEnvironment["MEDDY_TEST_HISTORY_VOLUME"] = "500"+    app.launchEnvironment["MEDDY_TEST_ROUTINE_HISTORY"] = "25"+    app.launch()+    let take = app.buttons["takeDueMedications"]+    XCTAssertTrue(take.waitForExistence(timeout: 30))+    let start = ProcessInfo.processInfo.systemUptime+    take.tap()+    let undo = app.buttons["Undo Taken"]+    XCTAssertTrue(undo.waitForExistence(timeout: 20))+    print("Synthetic UI Today tap-to-accessible-feedbackMS=\((ProcessInfo.processInfo.systemUptime - start) * 1000)")+    undo.tap()+    XCTAssertTrue(take.waitForExistence(timeout: 20))+    app.tabBars.buttons["Routines"].tap()+    let routine = app.buttons.matching(identifier: "Evening skin care").firstMatch+    XCTAssertTrue(routine.waitForExistence(timeout: 20))+    routine.tap()+    app.buttons["Start"].firstMatch.tap()+    XCTAssertTrue(app.buttons["Done"].waitForExistence(timeout: 20))+    app.buttons["Done"].tap()+    let routineTake = app.buttons["Taken / Applied"]+    XCTAssertTrue(routineTake.waitForExistence(timeout: 20))+    let routineStart = ProcessInfo.processInfo.systemUptime+    routineTake.tap()+    let progress = app.descendants(matching: .any).matching(+      NSPredicate(format: "label == %@", "2 of 3 steps completed")).firstMatch+    XCTAssertTrue(progress.waitForExistence(timeout: 30))+    print("Synthetic UI routine tap-to-accessible-feedbackMS=\((ProcessInfo.processInfo.systemUptime - routineStart) * 1000)")+    XCTAssertFalse(app.alerts.firstMatch.exists)+    let shot = XCTAttachment(screenshot: app.screenshot())+    shot.name = "synthetic-dose-saved-routine-progress"+    shot.lifetime = .keepAlways+    add(shot)+  }+}

Docs (3)

CHANGELOG.md Modified +1 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 155b756..8d630f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,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+- T2450: Batch ownership validation in Today/routine display and snapshot/reminder read filters, and skip untimed history during foreground deadline discovery, reducing saved Taken feedback work while preserving care transactions, Undo and notification ordering. - Reuse an operation-local ownership index for medication limit checks and display filtering, avoiding repeated whole-store reads as history grows while retaining profile/link validation and fresh mutation authorization. - Restore the scheduled medication detail’s Remind me later action through the existing reminder service, without recording a dose. - T2425: Open the saved child timer immediately after Start timer in an ordered routine, preserving its paused/resume state on return.
specs/bugfixes/taken-feedback-latency/implementation.md Added +21 / -0
diff --git a/specs/bugfixes/taken-feedback-latency/implementation.md b/specs/bugfixes/taken-feedback-latency/implementation.mdnew file mode 100644index 0000000..755af14--- /dev/null+++ b/specs/bugfixes/taken-feedback-latency/implementation.md@@ -0,0 +1,21 @@+# Taken feedback implementation review++## Beginner++A taken dose must be saved before the app says it happened. The app was repeatedly rereading the same history while deciding which records it could show. It also checked untimed sessions for timer deadlines. This change reads ownership once per display filter and avoids timer work where no timer exists. It does not display a speculative dose or change the recorded care.++## Intermediate++Today/routine consumers now use the existing `ProfileAccess.visible` batch helper. The new all-owner `validated` helper uses the same `ReadScope` for snapshot and reminder filtering. Each helper builds and discards its index synchronously. Foreground timer discovery checks checkpoint presence first; existing pending entries still reconcile removal, handoff and invalidation before discovery. The care transaction and asynchronous reminder writer remain unchanged.++The measured 500-dose fixture reduces save-with-observer from roughly700ms to roughly52ms and routine filtering from5.17s to13.7ms. End-to-end XCTest feedback improves too, but includes automation overhead and is not physical frame timing.++## Expert++The indexed validator retains cross-type UUID collisions, required link/owner/version checks, archive rejection and the same fail-closed filtering behavior. Scopes do not escape into mutation services, actor suspension, navigation caches or remote-delivery handling. Canonical writes, replay validation, tombstone Undo, lifecycle fencing and notification cancellation/drain ordering remain fresh. Pending deadline cleanup precedes the nil-checkpoint discovery optimization, and a stale callback cannot manufacture feedback after checkpoint removal.++The snapshot still has per-run fresh definition/progress validation and therefore does not become globally linear. Timed and dependant lifecycle paths retain existing scale costs. Combining initial filter scopes would reduce a constant but is unnecessary to remove the demonstrated historical-event multiplication.++## Completeness assessment++Implemented and locally verified: the measured repeated read work, saved dose accounting/replay, timer cancellation safety and synthetic Taken/Undo/routine UI journey. Four source perspectives are clear and native affected checks pass. Physical-device acceptance, actual Watch installation/delivery and live CloudKit performance are unmeasured; no deployment or merge is part of this change.
specs/bugfixes/taken-feedback-latency/report.md Added +99 / -0
diff --git a/specs/bugfixes/taken-feedback-latency/report.md b/specs/bugfixes/taken-feedback-latency/report.mdnew file mode 100644index 0000000..5c49ea6--- /dev/null+++ b/specs/bugfixes/taken-feedback-latency/report.md@@ -0,0 +1,99 @@+# Bugfix Report: Taken feedback latency++**Date:** 2026-10-13+**Status:** Fixed in branch — isolated simulator verified; physical acceptance pending+**Ticket:** T-2450++## Description of the Issue++The owner reports roughly one second without visible feedback after marking medication taken, worse inside routines. Yesterday’s medication opening/read fix helped other interactions and remains in current main and installed optimized Release `82ff4d97e20f4e76d59f628a00c5b4d45b86f5ba`.++Reproduction uses only isolated synthetic stores: 100/500 historical doses, 25 untimed retained runs, one standalone medication and a separate routine-managed medication. No live health records, phone installation, reset, account changes or audio are used.++## Investigation Summary++Inspected `TodayMedicationAction`, `MedicationService`, `EditorTransaction`, `RoutineSessionService`, `MutationEffects`, `RoutineRunView`, `PhoneRoundAlertService`, `PhoneCompanionService` and notification reconciliation. The care transaction saves before invoking synchronous observers; the screen receives its result only after those observers return. No optimistic UI is present.++Release-optimized (`-O`, whole-module optimization) simulator tests require DEBUG/testability hooks because existing tests reference DEBUG-only dependencies. These measurements characterize the optimized synthetic service path, not shipping physical-device latency. The prior `ReadScope` fix remains present. The original fixture run failed on missing routine ownership confirmation; it is retained separately and is not performance evidence.++| Stage, 500 doses / 25 untimed histories | Baseline elapsed | Ownership rows materialized |+| --- | --- | --- |+| Today save, foreground observer enabled, three samples | 687.6 / 701.8 / 709.2 ms | 29,732 / 29,788 / 29,844 |+| Foreground observer refresh, three samples | 631.6 / 627.9 / 1,066.2 ms | 27,560 / 27,612 / 27,664 |+| Routine dose write, no observers | 94.0 ms | 3,712 |+| Routine administration display filter | 5,168.4 ms | 266,031 |+| Notification plan, no external notification calls | 531.6 ms | 18,585 |+| Conditional Watch snapshot | 6,133.4 ms | 314,290 |++At 100 doses the observer costs 193.9–209.5 ms, and save including that observer costs 212.0–250.8 ms. The deterministic work bounds fail with 13 issues in three native test declarations (the dose test runs 100/500 variants). Dose counts and replay checks pass.++## Discovered Root Cause++**Defect type:** repeated whole-store validation in synchronous read loops.++1. Why does a dose remain visually unchanged? The main actor is occupied before action return and while rebuilding its saved-state display.+2. Why is the save action occupied? Its foreground timer observer validates every retained run, including untimed runs with no timer.+3. Why do routines add more work? Their display filters validate every historical administration separately when showing saved completion links.+4. Why does each validation grow with history? `ProfileAccess.owner` intentionally validates against all eight owned entity types, including cross-type duplicate IDs.+5. Why did yesterday’s fix not resolve this? It batched selected medication read consumers, while these independent consumers retain per-row validation.++Watch publication adds the same mechanism when a Watch app is installed. This conditional contributor is demonstrated by direct snapshot generation, not established for the owner’s device. Notification asynchronous writer ordering and SwiftData rollback guidance were recalled; neither is shown to be the cause, and those contracts must remain intact.++## Resolution for the Issue++Implemented bounded change: reuse the existing synchronous operation-local read index for Today/routine display, snapshot and notification-plan filtering; omit untimed rows from foreground timer discovery before expensive owner/timer validation. Preserve fresh canonical/mutation authorization, pending timer cancellation, exactly-once feedback, captured action identity, dose accounting and rollback.++No long-lived ownership cache, optimistic care result, transaction reordering, entitlement or schema change is proposed. The root cause is now clear and the implementation is a localized reuse of the existing validation path rather than competing architectural strategies.++## Regression Test++`Meddy/MeddyTests/MeddyTakenLatencyTests.swift` measures each stage. Red work bounds cover saves/untimed observers and historical-event snapshot filtering; notification-plan timing is diagnostic, with semantics verified by the affected reminder/followup/snooze suites. The display check compares batched output against fresh validation and bounds its work. It also verifies exactly one dose per tap, idempotent routine replay, intact routine/step links, complete snapshot event ownership and no read-only dirtying.++`Meddy/MeddyUITests/MeddyTakenLatencyUITests.swift` exercises Today Taken/Undo and routine progress with accumulated synthetic history. Its tap-to-accessible feedback duration includes automation overhead and is not a physical frame-rendering measurement. UI baseline passed: Today tap-to-accessible Undo 7,962.2 ms, routine tap-to-accessible saved progress 67,070.2 ms. The routine has two treatment steps around its medication; 25 retained sessions have canonical ended-incomplete checkpoints. These full-path automated measurements include XCTest quiescence/automation overhead and do not prove physical-device timing.++## Affected Files++- `ProfileAccess.swift`: new all-owner batch filtering through the existing ReadScope validator.+- `PhoneRoundAlertService.swift`: skip nil timer checkpoints before deadline discovery, preserving pending cancellation and fresh timer action validation.+- `RoutineRunView.swift`, `RoutinesView.swift`, `TodayRoutineSections.swift`: reuse existing batch display validation, including saved-log picker/history paths.+- `PhoneCompanionService.swift`, `ReminderService.swift`: batch initial valid-row filtering, without retaining an index across later writes or suspensions.+- `MeddyTakenLatencyTests.swift`, `MeddyPhoneRoundAlertTests.swift`: work-count/timing and removed-checkpoint callback coverage.+- `MeddyTakenLatencyUITests.swift`, `RedesignReferenceFixture.swift`: identical Taken/Undo plus routine progress journey; fixture is restricted to DEBUG plus `MEDDY_TESTING`.++Mutation services, schema, encoded payloads, signing and entitlements are unchanged.++## Verification++| Stage, same synthetic fixture | Before | After |+| --- | --- | --- |+| Today save with foreground observer, 500 doses, three samples | 687.6 / 701.8 / 709.2 ms | 53.7 / 51.4 / 52.3 ms |+| Untimed observer refresh, 500 doses | 627.9–1,066.2 ms; 27,560–27,664 rows | 0.78–1.11 ms; zero ownership rows |+| Routine write without observers | 94.0 ms; 3,712 rows | 86.0 ms; 3,712 rows |+| Routine display filter | 5,168.4 ms; 266,031 rows | 13.7 ms; 531 rows |+| Notification plan | 531.6 ms; 18,585 rows | 178.4 ms; 4,779 rows |+| Conditional Watch snapshot | 6,133.4 ms; 314,290 rows | 739.5 ms; 36,040 rows |+| UI Today tap-to-accessible Undo, automation included | 7,962.2 ms | 3,035.0 ms |+| UI routine tap-to-accessible 2-of-3 progress, automation included | 67,070.2 ms | 7,048.8 ms |++The same green run also measures the unchanged legacy filter at 5,247.0 ms before comparing its exact IDs/order with the indexed result. Raw timing samples are descriptive; deterministic work bounds are the regression gates. These are not on-phone frame-latency guarantees or a claim of subsecond physical feedback.++- Native red inventory: 3 tests, 1 passed / 2 failed, 13 recorded issues. Initial fixture-only failure and prototype run retained separately.+- Native green inventory: **68 tests / 11 suites, all passed**. Includes prior read-scope performance, profile isolation/routing, Today Taken/Undo and whole-batch rollback, routine session/idempotence, companion ownership/ledgers, timer completion/handoff/pause/end/removed-checkpoint cancellation, reminder, followup and snooze ordering.+- Native UI inventory: **1 affected UI test passed** before and after; saved screenshot inspected, showing two completed steps and the next treatment ready. No alerts appeared.+- Strict lint: 118 files / zero violations; whitespace check passed.+- Four independent source review perspectives found no blocking code issue. The spec review requested a notification-plan work-bound assertion or narrower evidence wording; the report now explicitly marks that stage diagnostic. Other suggestions to combine initial indexes were deferred as unnecessary constant-factor optimization.+- Full phone/Watch/UI suites were not run: this task authorizes isolated targeted checks. No physical installation, launch, sound, CloudKit/live data or account operation occurred.++### Practical limits++Snapshot generation still performs fresh per-run definition/progress reads, so the entire snapshot is not globally linear in run count. Timed histories still require individual ownership/timer checks; dependant timer planning still has lifecycle checks. These are existing scale limits, not eliminated by this measured historical-event fix. Read indexes are temporary within individual filters. Physical owner acceptance remains pending.++Evidence: `/Users/arjen/Documents/Codex/2026-10-05/task/meddy-taken-latency-evidence/` (`red.json`, `red.log`, `ui-baseline.json`, `ui-baseline.log`). Native result bundles are retained under the isolated worktree’s ignored `build/results`.++## Prevention++Batch validation within a synchronous read. Never retain an ownership index across writes, suspension, navigation or remote change delivery. Continue to authorize every care mutation against the current context. Prefer deterministic work-count regressions to machine-dependent wall-time gates.++## Related++Previous read fix: [PR #10](https://github.com/ArjenSchwarz/meddy/pull/10), T-2440. No merge or deployment is part of this bugfix.

Things to double-check

Remaining limits

Snapshot run definition/progress, timed histories and dependant lifecycle checks retain existing scale costs. Physical owner acceptance remains pending.