Eliminate repeated whole-store materialization when historical doses accumulate.
Old ownership validation materialized all records again for every historical dose, creating (history+1)×store-size work.
Each synchronous display/limit operation now builds one complete ID index and reuses existing ownership/link checks. Mutation checks remain fresh.
| Synthetic logs | Before median | After median | Materialized records |
|---|---|---|---|
| 10 | 9.99 ms | 1.23 ms | 121 → 11 |
| 100 | 224.84 ms | 6.39 ms | 10,201 → 101 |
| 500 | 4376.46 ms | 27.67 ms | 251,001 → 501 |
Measurements use optimized Release -O with testability/DEBUG hooks and isolated synthetic stores. They do not establish the unique physical-device cause.
Ready to push
Confirmed synthetic red reproduction. The optimized 500-log check improves from 4.38 seconds to 27.7 ms, approximately 158× faster. 50 focused domain declarations and 1 six-cycle UI scenario pass, with strict lint. Four source reviews found no blockers.
Opening a medicine checks its saved dose history. Previously the app repeatedly read the entire store for each log. It now reads the ownership information once for that operation.
The repeated work grew much faster than the number of logs. The new regression measures the work and confirms a large reduction.
The lookup is discarded after each read. Editing and care actions still check the current owner.
ProfileAccess.ReadScope groups the complete profile-owned graph by ID and delegates to the existing profile/link validator. AsNeededLimitService shares the index for a medicine and its events. ContentView batches visibility and excludes older/deleted rows before Today filtering.
The index is O(store-size) temporary work, reused across the operation. ID-filtered queries would still cause per-row I/O; a retained global cache would require safe invalidation. Neither is introduced.
The index retains every match across all eight entity types, so cross-type ID collisions still fail. Shared validation preserves unknown/archived profiles, lifecycle consistency, foreign/missing links and historical optional-link behavior. Writes continue through fresh owner/canonical/action checks. Every caller creates and consumes the scope synchronously; no suspension or retention across changes.
The unchanged parameterized benchmark covers 10/100/500 synthetic logs and three reads at each volume; row counts are deterministic and durations are medians. Tests compare read indexes with fresh validation for all eight types and pending/saved collisions, then exercise changed owner/archive/link states in separate operations. Existing care/limit/profile suites pass. Six native detail cycles with 500 historical logs and synthetic photos complete at stable automation timings.
The proven read-amplification defect is fixed. Live phone responsiveness, CloudKit observer lifetimes and remaining unmeasured display paths are not established by these tests. No deployment, reset, personal-data profiling or merge occurred.
Meddy/Meddy/Services/ProfileAccess.swift
Why it matters. Avoid repeated whole-store materialization without changing profile authorization rules.
What to look at. ReadScope and shared validateLinks lookup
Meddy/Meddy/Services/AsNeededLimitService.swift
Why it matters. Remove the dominant history-growth multiplication while keeping canonical event fetching and dose-limit engine output.
What to look at. check scope.owner and scope.visible
Meddy/Meddy/ContentView.swift
Why it matters. Avoid per-item global reads and skip irrelevant old history before Today visibility.
What to look at. medications and todayEvents
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| minor | Bug-fix report | Root-cause paragraph still said measurements pending after red proof. | Updated to distinguish confirmed synthetic defect and unverified physical cause, with full paired results. |
Source: local run at 2026-10-12T00:06:13.424832+00:00 · snapshot 85c50715e6eb4bcbe96e5e9c872416193fe0cd86
Baseline: none
Execution: passed · JUnit: 2 files · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 51 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 c4864852f243c5f1330f76dfe69b492c1ac936ec.
10 files: 6 code · 4 docs. Click to expand.
diff --git a/Meddy/Meddy/ContentView.swift b/Meddy/Meddy/ContentView.swiftindex 0036493..2ee2700 100644--- a/Meddy/Meddy/ContentView.swift+++ b/Meddy/Meddy/ContentView.swift@@ -30,14 +30,14 @@ struct ContentView: View { return Date() } private var medications: [Medication] {- allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+ ProfileAccess.visible(allMedications, for: selectedProfileID, context: context) } private var active: [Medication] { medications.filter(\.isActive) } private var todayEvents: [Administration] {- allEvents.filter {- !$0.isDeleted && ProfileAccess.visible($0, for: selectedProfileID, context: context)- && ScheduleCalendar.sameDay($0.timestamp, now, calendar: .current)+ let current = allEvents.filter {+ !$0.isDeleted && ScheduleCalendar.sameDay($0.timestamp, now, calendar: .current) }+ return ProfileAccess.visible(current, for: selectedProfileID, context: context) } private var scheduled: [(Medication, Date)] { active.filter { !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw) }.compactMap { medication in
diff --git a/Meddy/Meddy/Design/RedesignReferenceFixture.swift b/Meddy/Meddy/Design/RedesignReferenceFixture.swiftindex 88febc5..3a5059e 100644--- a/Meddy/Meddy/Design/RedesignReferenceFixture.swift+++ b/Meddy/Meddy/Design/RedesignReferenceFixture.swift@@ -65,6 +65,19 @@ .init(kind: .treatment, targetID: moisturise.id) ], purpose: purposes[4], confirmedMedicationIDs: [skinMedication.id])+ if let value = ProcessInfo.processInfo.environment["MEDDY_TEST_HISTORY_VOLUME"],+ let count = Int(value), (1...1000).contains(count) {+ // Synthetic history only; the outer guard requires an isolated test container.+ let now = Date()+ for index in 0..<count {+ let action = AdministrationAction(+ eventID: UUID(), medicationID: pain.id,+ timestamp: now.addingTimeInterval(-Double(index + 1) * 86400), source: .phone,+ dose: pain.defaultDose, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+ context.insert(Administration(action: action, medication: pain))+ }+ try context.save()+ } let alex = try ProfileService(context: context).create(displayName: "Alex") if ProcessInfo.processInfo.environment["MEDDY_TEST_RECOGNITION_PHOTOS"] == "1" { let bytes = try recognitionPhoto()
diff --git a/Meddy/Meddy/Services/AsNeededLimitService.swift b/Meddy/Meddy/Services/AsNeededLimitService.swiftindex 3145984..3c96e8f 100644--- a/Meddy/Meddy/Services/AsNeededLimitService.swift+++ b/Meddy/Meddy/Services/AsNeededLimitService.swift@@ -32,14 +32,15 @@ final class AsNeededLimitService { _ medication: Medication, proposedDose: RecordedDoseSnapshot? = nil, now: Date = Date() ) -> DoseLimitCheck { do {- let owner = try ProfileAccess.owner(medication, context: context)+ let scope = try ProfileAccess.ReadScope(context: context)+ let owner = try scope.owner(medication) let rules = try limits(medication) // Fetch canonical rows: relationship caches can retain pre-save tombstone values. let medicationID = medication.id let administrations = try context.fetch( FetchDescriptor<Administration>(predicate: #Predicate { $0.medicationID == medicationID })) let events = administrations.filter {- ProfileAccess.visible($0, for: owner, context: context)+ scope.visible($0, for: owner) }.map { DoseLimitAdministration( id: $0.id, medicationID: $0.medicationID, timestamp: $0.timestamp, dose: $0.recordedDose,
diff --git a/Meddy/Meddy/Services/ProfileAccess.swift b/Meddy/Meddy/Services/ProfileAccess.swiftindex d1c4465..3116dc7 100644--- a/Meddy/Meddy/Services/ProfileAccess.swift+++ b/Meddy/Meddy/Services/ProfileAccess.swift@@ -2,9 +2,17 @@ import Foundation import SwiftData @MainActor enum ProfileAccess {+ #if DEBUG || MEDDY_PERFORMANCE_TESTING+ // Synthetic work-count instrumentation; never receives record contents or identifiers.+ static var inspectedRows: ((Int) -> Void)?+ #endif static func profile(_ id: UUID, context: ModelContext, allowArchived: Bool = false) throws -> CareProfile? {- let rows = try context.fetch(FetchDescriptor<CareProfile>()).filter { $0.id == id }+ try profile(id, profiles: context.fetch(FetchDescriptor<CareProfile>()), allowArchived: allowArchived)+ }+ private static func profile(_ id: UUID, profiles: [CareProfile], allowArchived: Bool = false) throws+ -> CareProfile? {+ let rows = profiles.filter { $0.id == id } if id == ProfileIdentity.me && rows.isEmpty { return nil } guard let first = rows.first, first.lifecycleID != nil else { throw ProfileError.unknownOwner } guard@@ -24,10 +32,17 @@ import SwiftData private static func validateLinks(_ value: any ProfileOwned, owner: UUID, context: ModelContext) throws { let rows = try ProfileMigration.rows(context)- let matching = rows.filter { $0.id == value.id }- guard matching.count <= 1 else { throw ProfileError.conflictingOwnership }+ #if DEBUG || MEDDY_PERFORMANCE_TESTING+ inspectedRows?(rows.count)+ #endif+ try validateLinks(value, owner: owner, matching: { id in rows.filter { $0.id == id } })+ }+ private static func validateLinks(+ _ value: any ProfileOwned, owner: UUID, matching: (UUID) -> [any ProfileOwned]+ ) throws {+ guard matching(value.id).count <= 1 else { throw ProfileError.conflictingOwnership } func link(_ id: UUID) throws {- let matches = rows.filter { $0.id == id }+ let matches = matching(id) guard matches.count == 1, let row = matches.first, row.profileID == owner, row.ownershipVersion == ProfileIdentity.ownershipVersion else { throw ProfileError.conflictingOwnership }@@ -42,11 +57,11 @@ import SwiftData if let id = x.managedByRoutineID { try link(id) } case let x as Administration: try link(x.medicationID)- if let id = x.routineRunID, rows.contains(where: { $0.id == id }) { try link(id) }+ if let id = x.routineRunID, !matching(id).isEmpty { try link(id) } case let x as Treatment: if let purpose = x.purpose { try link(purpose.id) } case let x as TreatmentCompletion: try link(x.treatmentID)- if let id = x.routineRunID, rows.contains(where: { $0.id == id }) { try link(id) }+ if let id = x.routineRunID, !matching(id).isEmpty { try link(id) } case let x as Routine: if let purpose = x.purpose { try link(purpose.id) } for step in x.steps ?? [] {@@ -62,6 +77,34 @@ import SwiftData default: break } }+ // Use only within one synchronous read. Writes continue to revalidate against the context.+ // Never retain this index across navigation, mutations, suspension or remote-change delivery.+ @MainActor struct ReadScope {+ private let profiles: [CareProfile]+ private let rows: [UUID: [any ProfileOwned]]+ init(context: ModelContext) throws {+ profiles = try context.fetch(FetchDescriptor<CareProfile>())+ let values = try ProfileMigration.rows(context)+ #if DEBUG || MEDDY_PERFORMANCE_TESTING+ inspectedRows?(values.count)+ #endif+ rows = Dictionary(grouping: values, by: { $0.id })+ }+ func owner(_ value: any ProfileOwned) throws -> UUID {+ guard value.ownershipVersion == ProfileIdentity.ownershipVersion, let id = value.profileID+ else { throw ProfileError.unknownOwner }+ _ = try ProfileAccess.profile(id, profiles: profiles)+ try ProfileAccess.validateLinks(value, owner: id, matching: { rows[$0] ?? [] })+ return id+ }+ func visible(_ value: any ProfileOwned, for id: UUID) -> Bool {+ (try? owner(value)) == id+ }+ }+ static func visible<T: ProfileOwned>(_ values: [T], for id: UUID, context: ModelContext) -> [T] {+ guard !values.isEmpty, let scope = try? ReadScope(context: context) else { return [] }+ return values.filter { scope.visible($0, for: id) }+ } 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 }
diff --git a/Meddy/MeddyTests/MeddyProfileAccessPerformanceTests.swift b/Meddy/MeddyTests/MeddyProfileAccessPerformanceTests.swiftnew file mode 100644index 0000000..1bbe725--- /dev/null+++ b/Meddy/MeddyTests/MeddyProfileAccessPerformanceTests.swift@@ -0,0 +1,127 @@+import Foundation+import SwiftData+import Testing++@testable import Meddy++#if DEBUG || MEDDY_PERFORMANCE_TESTING+@MainActor+struct MeddyProfileAccessPerformanceTests {+ @Test func indexedReadMatchesFreshValidationForAllOwnedTypesAndRejectsDuplicateIDs() throws {+ let container = try AppEnvironment.makeContainer(isolated: true)+ let context = container.mainContext+ let purpose = Purpose(name: "Synthetic purpose")+ let medication = Medication(name: "Synthetic medicine")+ medication.purpose = purpose+ let action = AdministrationAction(+ eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+ dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+ let administration = Administration(action: action, medication: medication)+ let treatment = Treatment(name: "Synthetic care")+ treatment.purpose = purpose+ let completion = TreatmentCompletion(treatment: treatment, timestamp: Date(), source: .phone)+ let routine = Routine(name: "Synthetic routine", kind: .ordered)+ routine.purpose = purpose+ let step = RoutineStep(routine: routine, targetKind: .medication, targetID: medication.id, position: 0)+ let run = RoutineRun(routine: routine)+ context.insert(purpose)+ context.insert(medication)+ context.insert(administration)+ context.insert(treatment)+ context.insert(completion)+ context.insert(routine)+ context.insert(step)+ context.insert(run)+ try context.save()+ let values: [any ProfileOwned] = [purpose, medication, administration, treatment, completion, routine, step, run]+ for value in values {+ #expect(try ProfileAccess.ReadScope(context: context).owner(value) == ProfileAccess.owner(value, context: context))+ let collision = Medication(name: "Synthetic duplicate")+ collision.id = value.id+ context.insert(collision)+ // Pending and saved duplicates must both remain unavailable, including cross-type IDs.+ #expect(throws: ProfileError.self) { try ProfileAccess.ReadScope(context: context).owner(value) }+ try context.save()+ #expect(throws: ProfileError.self) { try ProfileAccess.owner(value, context: context) }+ #expect(throws: ProfileError.self) { try ProfileAccess.ReadScope(context: context).owner(value) }+ context.delete(collision)+ try context.save()+ #expect(try ProfileAccess.ReadScope(context: context).owner(value) == ProfileIdentity.me)+ }+ }++ @Test func separateReadOperationsObserveChangedOwnershipArchiveAndMissingLinks() throws {+ let container = try AppEnvironment.makeContainer(isolated: true)+ let context = container.mainContext+ let one = CareProfile(displayName: "Synthetic one")+ let two = CareProfile(displayName: "Synthetic two")+ let purpose = Purpose(name: "Synthetic purpose")+ purpose.profileID = two.id+ let medication = Medication(name: "Synthetic medicine")+ medication.profileID = one.id+ medication.purpose = purpose+ context.insert(one)+ context.insert(two)+ context.insert(purpose)+ context.insert(medication)+ try context.save()+ #expect(ProfileAccess.visible([medication], for: one.id, context: context).isEmpty)+ purpose.profileID = one.id+ try context.save()+ #expect(ProfileAccess.visible([medication], for: one.id, context: context).count == 1)+ medication.managedByRoutineID = UUID()+ try context.save()+ #expect(ProfileAccess.visible([medication], for: one.id, context: context).isEmpty)+ medication.managedByRoutineID = nil+ one.archivedAt = Date()+ try context.save()+ #expect(ProfileAccess.visible([medication], for: one.id, context: context).isEmpty)+ one.archivedAt = nil+ try context.save()+ #expect(ProfileAccess.visible([medication], for: one.id, context: context).count == 1)+ medication.ownershipVersion = nil+ try context.save()+ #expect(ProfileAccess.visible([medication], for: one.id, context: context).isEmpty)+ }++ @Test(arguments: [10, 100, 500])+ func historyGrowthDoesNotMultiplyOwnershipMaterialization(historyCount: Int) throws {+ let container = try AppEnvironment.makeContainer(isolated: true)+ let context = container.mainContext+ let medication = Medication(name: "Synthetic performance fixture")+ medication.defaultDoseAmount = 1+ medication.defaultDoseUnit = "measure"+ context.insert(medication)+ let now = Date(timeIntervalSince1970: 1_767_660_000)+ medication.asNeededDoseLimitsData = try JSONEncoder().encode(AsNeededDoseLimits(+ maximumAmount: 1000, windowSeconds: 86400, unit: "measure"))+ for index in 0..<historyCount {+ let action = AdministrationAction(+ eventID: UUID(), medicationID: medication.id,+ timestamp: now.addingTimeInterval(-Double(index + 1)), source: .phone,+ dose: .init(description: "", amount: 1, unit: "measure"),+ scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+ context.insert(Administration(action: action, medication: medication))+ }+ try context.save()+ var inspected = 0+ ProfileAccess.inspectedRows = { inspected += $0 }+ defer { ProfileAccess.inspectedRows = nil }+ let service = AsNeededLimitService(context: context)+ for visit in 0..<3 {+ inspected = 0+ let start = ProcessInfo.processInfo.systemUptime+ let result = service.check(medication, now: now)+ let elapsed = (ProcessInfo.processInfo.systemUptime - start) * 1000+ print("Synthetic ownership check history=\(historyCount) visit=\(visit) rows=\(inspected) milliseconds=\(elapsed)")+ #expect(result.knownAmount == Double(historyCount))+ #expect(result.state == .withinEnteredLimits && result.issues.isEmpty)+ // One check must not materialize the whole store again for every historical dose.+ // Bound inspected records linearly, without a machine-dependent timing threshold.+ #expect(inspected <= 4 * (historyCount + 1))+ #expect(!context.hasChanges)+ }+ }+}++#endif
diff --git a/Meddy/MeddyUITests/MeddyNavigationPerformanceUITests.swift b/Meddy/MeddyUITests/MeddyNavigationPerformanceUITests.swiftnew file mode 100644index 0000000..fdd9e44--- /dev/null+++ b/Meddy/MeddyUITests/MeddyNavigationPerformanceUITests.swift@@ -0,0 +1,36 @@+import XCTest++@MainActor+final class MeddyNavigationPerformanceUITests: XCTestCase {+ func testRepeatedDetailNavigationWithAccumulatedSyntheticHistory() {+ 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_RECOGNITION_PHOTOS"] = "1"+ app.launch()+ XCTAssertTrue(app.buttons["takeDueMedications"].waitForExistence(timeout: 15))+ app.tabBars.buttons["Medications"].tap()+ XCTAssertTrue(app.textFields["medicationSearch"].waitForExistence(timeout: 5))+ for visit in 0..<6 {+ let row = app.buttons.matching(NSPredicate(format: "label == %@", "Paracetamol")).firstMatch+ XCTAssertTrue(row.waitForExistence(timeout: 5))+ let start = ProcessInfo.processInfo.systemUptime+ row.tap()+ let bar = app.navigationBars["Paracetamol"]+ XCTAssertTrue(bar.waitForExistence(timeout: 5))+ XCTAssertTrue(app.descendants(matching: .any)["medicationRecognitionPhoto"].firstMatch.exists)+ print("Synthetic detail navigation visit=\(visit) milliseconds=\((ProcessInfo.processInfo.systemUptime - start) * 1000)")+ if visit == 0 || visit == 5 {+ let shot = XCTAttachment(screenshot: app.screenshot())+ shot.name = "synthetic-history-detail-\(visit)"+ shot.lifetime = .keepAlways+ add(shot)+ }+ bar.buttons["BackButton"].tap()+ XCTAssertTrue(app.textFields["medicationSearch"].waitForExistence(timeout: 5))+ }+ XCTAssertFalse(app.alerts.firstMatch.exists)+ }+}
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4249ccd..155b756 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+- 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. - Apply strict Swift lint cleanup and focused helpers while preserving care/state semantics; replace the deprecated Watch foreground-state API with WKApplication.
diff --git a/docs/meddy-design.md b/docs/meddy-design.mdindex d6fcca2..322fa60 100644--- a/docs/meddy-design.md+++ b/docs/meddy-design.md@@ -1711,3 +1711,8 @@ All medication modes support these fields, captured to the canonical medication/ Owner-tested feedback after PR #4 requests round recognition images. The shared `MedicationPhotoView` now fills a circular mask at each existing size, consistently covering thumbnails, detail/dose/editor previews and routine medication images. This is a display-only crop; names, accessibility labels, photo controls and original stored image data remain intact. Tapping the medication detail circle opens an accessible full-screen viewer of the full stored image, initially aspect-fit and uncropped. Pinch zoom and pan plus Zoom in/out/Reset controls support 1–4× inspection; Done is always available, including an unreadable-image fallback. Each presentation captures only that medication's current stored bytes/name, resets zoom on reopening and dismisses when the selected profile changes. The existing bounded import resolution remains authoritative; viewing does not retrieve the original Photos asset, rewrite bytes, edit/remove/export the photo or change care/accounting. The inline circle and other recognition surfaces retain their appearance.+++## Medication display read performance++A synchronous display/limit read may build one complete ownership index and reuse the existing profile and link checks across its rows. That index is local to the operation and must not survive suspension, navigation or model changes. Mutation/action validation continues to read the current context. Duplicate identifiers across entity types, unknown/archived owners and missing/foreign links remain unavailable; this optimization changes no dose-limit, history or care policy. Today excludes deleted/older-day rows before display validation.
diff --git a/docs/meddy-implementation-plan.md b/docs/meddy-implementation-plan.mdindex 3401429..a236266 100644--- a/docs/meddy-implementation-plan.md+++ b/docs/meddy-implementation-plan.md@@ -1,5 +1,9 @@ # Meddy — Implementation task plan +## Recurring medication detail slowness++Bug-fix investigation on merged c486485 reproduced growing main-actor ownership-read costs in an optimized synthetic test: 10/100/500 logs caused 121/10,201/251,001 materialized records per limit check, approximately 10 ms/225 ms/4.4 s. Short-lived read indexes share the existing duplicate/profile/link validation within a limit/display operation; writes retain fresh context authorization. Optimized green median at 500 logs is 27.7 ms/501 records versus 4.38 s/251,001 records before, approximately 158× faster. All 50 focused domain declarations and one six-cycle synthetic navigation scenario passed at 85c5071; strict lint passed 116 files/zero violations. Four source reviews clear; assigned simulators restored and lane released. UI automation times include XCTest overhead and are not phone tap-to-open measures; live observer/CloudKit paths and physical acceptance remain unverified. See specs/bugfixes/recurring-medication-detail-slowness/report.md for build-hook qualifications, raw evidence and physical-device limits. No live-store inspection, reset, deployment, cloud/account change or merge. Transit ticket for app Meddy pending unavailable tools; deduplicate the saved local draft before creation.+ ## Remove redundant detail edit shortcuts PR #9 scope update: photo Add/Change and medication Archive/Reactivate belong in the existing Edit screen. Remove those detail shortcuts, preserve the inline full-size viewer when a photo exists and a compact name-based header when absent. The existing editor retains photo Add/Replace/Remove and Archive/Reactivate. Repeats decrement/Undo is the explicit settings-mutation exception; dose logging, reminders, Undo Taken and historical care corrections remain. No model, persistence, care policy or account/signing changes. The photo journeys now assert shortcut absence with/without a photo and reach retained Add/Archive controls through Edit; the existing prescription journey verifies the repeats exception. Earlier PR #9 verification at d0025a4 covered Change-link removal only and is superseded for this expanded delta. Verification at clean `f7f1e13`: the initial targeted invocation passed all four photo journeys and timed out the progressing prescription journey at its 120-second allowance. A prescription-only retry on identical source passed in 185.5 seconds with a bounded 240-second allowance. Five disjoint cases have passing evidence across those runs; the original mixed timeout receipt is retained, not described as an all-green five-case invocation. Photo coverage includes both appearances, compact no-photo layout, retained Edit Add/Archive reachability, Save/Cancel/profile behavior, viewing zoom/dismiss/reopen and unreadable fallback. The prescription journey covers the repeats decrement/Undo exception. Reactivate retention is source-reviewed rather than exercised by active fixtures. Strict lint passed 114 files with zero violations; whitespace and four source review perspectives passed. Screenshots reviewed. Known synthetic fixture background-publication warning retained. Owned jobs drained, assigned phone/Watch simulators restored to Shutdown, and heavy lane explicitly released. Update the same pending Transit ticket for app Meddy when tracking becomes available, without creating a duplicate. No install or merge.
diff --git a/specs/bugfixes/recurring-medication-detail-slowness/report.md b/specs/bugfixes/recurring-medication-detail-slowness/report.mdnew file mode 100644index 0000000..5d84bd8--- /dev/null+++ b/specs/bugfixes/recurring-medication-detail-slowness/report.md@@ -0,0 +1,61 @@+# Bugfix Report: Recurring medication detail slowness++**Status:** Investigation; Fixed and verified on isolated synthetic stores; physical-phone acceptance remains unverified.++## Description of the Issue++The owner reports that opening a medicine takes a couple of seconds and worsens again over time. Installing optimized Release `c486485` briefly helped; recurrence does not establish a Debug-build cause. Expected: detail navigation remains responsive as retained history grows and after repeated viewing.++## Investigation Summary++- Inspected detail, ContentView queries, dose-limit service/engine, profile ownership validation, photo cache/import, root lifecycle, reminder task ordering and timer/observer ownership.+- `AsNeededLimitService.check` fetches historical rows for the medication and validates each through `ProfileAccess.visible` → `owner` → `validateLinks`.+- `validateLinks` calls `ProfileMigration.rows`, which fetches all eight profile-owned entity types for each row. With H history rows and S total records, a check inspects at least (H+1)×S records. ContentView also invokes ownership validation repeatedly when rendering lists/history.+- The optimized synthetic baseline measured approximately 10 ms at 10 logs, 225 ms at 100 and 4.4 seconds at 500, with 121/10,201/251,001 records materialized per check. All three repetitions at each size failed the linear-work regression while preserving output. This confirms a growth-dependent hot path, not the unique physical-device cause. No personal store or records inspected.+- Root services are guarded against repeated setup; task-owned status refreshes cancel on disappearance, reminder replacement drains its previous writer, round deadlines retain cancellable tokens. No observer leak established; CloudSyncMonitor has async observer tasks without teardown cancellation, a separate unmeasured lifecycle candidate. This patch does not speculate about it. Six repeated synthetic detail-navigation cycles completed at stable 2.04–2.13-second automation timings. XCTest tap/idle overhead is included; these are not phone tap-to-open timings.+- Photo thumbnails use a bounded NSCache but hash full stored bytes on lookup. This is separate bounded work; no photo change proposed without evidence.++## Discovered Root Cause++**Confirmed synthetic defect:** global record materialization inside per-row ownership validation, repeated on the main actor. Why detail can block: it checks limits/history synchronously; each history row validates ownership; validation fetches all store rows to find a few IDs; accumulated history makes each scan and the number of scans grow together. The red reproduction confirmed this path; physical-phone causation is not uniquely established. Preserve cross-entity duplicate-ID detection and link/profile rules in any fix; do not introduce a stale global authorization cache.++## Resolution for the Issue++A short-lived `ProfileAccess.ReadScope` builds one complete ID index for a synchronous read and reuses the existing profile/link validator. As-needed checks share that scope across the medication and its historical rows. ContentView batches visibility and excludes irrelevant old/deleted history before Today ownership checks. Mutation authorization continues to use fresh context reads; no cross-navigation, persistent or global ownership cache. The same duplicate-ID, missing/foreign-link, ownership-version and archived-profile rules are retained. This is a direct fix for deterministic redundant reads; no competing implementations or speculative lifecycle/photo changes are needed.++Alternatives: repeated ID-filtered database queries still perform per-row I/O and may scan unindexed columns; a long-lived cache risks stale ownership decisions. An operation-local complete index avoids both.++## Regression Test++`MeddyProfileAccessPerformanceTests.historyGrowthDoesNotMultiplyOwnershipMaterialization` uses retained isolated containers, synthetic 10/100/500-event histories and three consecutive reads. It checks unchanged dose-limit output, no persistence mutation and a deterministic linear bound on inspected row counts, and prints wall-clock durations. Debug-only instrumentation emits integer work counts only, no identifiers/data. The unfixed checkpoint `e821ee2` failed exactly the work bound at all three volumes and visits. First Release attempts could not compile the existing test target without testability and DEBUG-only hooks; those build-block receipts are retained separately and are not red reproductions. The measured run uses Release `-O`, invocation-only `ENABLE_TESTABILITY=YES` and DEBUG test hooks; it is representative optimized service code, not an exact shipping-device measurement.++## Verification++Parent granted the exclusive slot after Halo drained. Red reproduction confirmed. At clean `85c5071`, all 50 selected domain declarations and the one six-cycle UI scenario passed with no failures/skips. The unchanged performance declaration ran all 10/100/500-log parameter variants and three consecutive reads per volume. Ownership parity covers all eight owned entity types, pending/saved cross-type duplicates and fresh read visibility after ownership/archive/link changes. Existing dose-limit, migration, routing, definition and first-slice care suites passed. Strict lint passed 116 files with zero violations; whitespace and four source review perspectives passed. Screenshots at visits 0 and 5 show retained circular photo, name, care controls and layout. Owned groups drained and assigned simulators restored; heavy lane released. Simulator/synthetic timings must not be presented as physical phone timings. No deployment, merge, uninstall/reset, account/permission or cloud change.++## Related++Transit ticket for app/project Meddy pending: tools unavailable in this host. Deduplication-ready local draft retained outside the repository; search the exact project/title before creating when the service is available.+++## Measured Before/After++Same simulator, same fixture and unchanged benchmark declaration; median of three consecutive synchronous checks. Both app compilations confirm `-O` and whole-module optimization, with testability/DEBUG hooks enabled only in the invocation.++| Synthetic history | Before median | After median | Records materialized before → after |+|---|---:|---:|---:|+| 10 | 9.99 ms | 1.23 ms | 121 → 11 |+| 100 | 224.84 ms | 6.39 ms | 10,201 → 101 |+| 500 | 4376.46 ms | 27.67 ms | 251,001 → 501 |++At 500 logs, the measured check is approximately 158× faster. The index materializes the store once and is discarded after the synchronous read; there is no authorization cache surviving a change or navigation. This fixes the proven read-amplification defect without deleting or rewriting history.++## Evidence and Limits++- Baseline: `e821ee2`, native result 1 failed declaration, all nine parameter/visit work-bound assertions failed as intended; output and no-write assertions held.+- Green: `85c5071`, 50 domain declarations and one UI scenario passed. Parameter variants are counted once per declaration by native summary, not inflated as additional tests.+- Raw local receipts/metrics/screenshots: `/Users/arjen/Documents/Codex/2026-10-05/task/meddy-slowness-evidence/`; `performance-metrics.json` retains every sample. Build-block attempts are separate from the red failure.+- Reproduction: `gmake CONFIG=Release test-domain DOMAIN_TEST=MeddyTests/MeddyProfileAccessPerformanceTests TEST_FLAGS='-parallel-testing-enabled NO -maximum-concurrent-test-simulator-destinations 1 SWIFT_ACTIVE_COMPILATION_CONDITIONS=DEBUG ENABLE_TESTABILITY=YES'`.+- No physical device access error was encountered; the phone was not queried or profiled for this batch. No personal data was exported or opened. Live CloudKit/observer behavior and the owner's exact history volume are unmeasured; no unique-device-cause, universal responsiveness or absence-of-other-bottlenecks claim.+- CloudSyncMonitor observer teardown and remaining purpose/routine per-item read paths are source-level follow-up candidates only, not measured regressions addressed by this PR.+- No deployment or merge performed. Device acceptance should check repeated opening with the owner's existing data after an explicitly authorized in-place update.
50 native domain declarations and 1 UI scenario passed at clean 85c5071. Native parameter variants count once per declaration. Red failure and two Release-test build-block receipts are retained separately; final totals include green runs only. UI 2.04–2.13-second intervals include XCTest tap/idle overhead and are not phone tap-to-open times. Synthetic startup retains the known background-publication warning.
No observer leak is claimed or fixed speculatively. CloudSyncMonitor teardown and remaining purpose/routine per-item reads are follow-up candidates if device symptoms remain. Transit tools are unavailable; a project-qualified, deduplication-ready Meddy ticket draft is retained locally. No ID is invented.