Bläddra i källkod

Adapt the state models to the new pattern

Marvin Polscheit 1 månad sedan
förälder
incheckning
3612b655e6
21 ändrade filer med 93 tillägg och 38 borttagningar
  1. 0 1
      Trio/Sources/Modules/Adjustments/AdjustmentsStateModel.swift
  2. 3 2
      Trio/Sources/Modules/DynamicSettings/DynamicSettingsStateModel.swift
  3. 3 0
      Trio/Sources/Modules/Home/HomeStateModel+Setup/BatterySetup.swift
  4. 6 0
      Trio/Sources/Modules/Home/HomeStateModel+Setup/CarbSetup.swift
  5. 7 6
      Trio/Sources/Modules/Home/HomeStateModel+Setup/ChartAxisSetup.swift
  6. 3 0
      Trio/Sources/Modules/Home/HomeStateModel+Setup/CurrentTDDSetup.swift
  7. 5 2
      Trio/Sources/Modules/Home/HomeStateModel+Setup/DeterminationSetup.swift
  8. 3 0
      Trio/Sources/Modules/Home/HomeStateModel+Setup/ForecastSetup.swift
  9. 4 1
      Trio/Sources/Modules/Home/HomeStateModel+Setup/GlucoseSetup.swift
  10. 6 0
      Trio/Sources/Modules/Home/HomeStateModel+Setup/OverrideSetup.swift
  11. 6 0
      Trio/Sources/Modules/Home/HomeStateModel+Setup/PumpHistorySetup.swift
  12. 6 0
      Trio/Sources/Modules/Home/HomeStateModel+Setup/TempTargetSetup.swift
  13. 0 10
      Trio/Sources/Modules/Home/HomeStateModel.swift
  14. 0 2
      Trio/Sources/Modules/ISFEditor/ISFEditorStateModel.swift
  15. 0 2
      Trio/Sources/Modules/NightscoutConfig/NightscoutConfigStateModel.swift
  16. 6 0
      Trio/Sources/Modules/Stat/StatStateModel+Setup/BolusStatsSetup.swift
  17. 10 1
      Trio/Sources/Modules/Stat/StatStateModel+Setup/LoopChartSetup.swift
  18. 6 0
      Trio/Sources/Modules/Stat/StatStateModel+Setup/MealStatsSetup.swift
  19. 10 4
      Trio/Sources/Modules/Stat/StatStateModel+Setup/TDDSetup.swift
  20. 3 5
      Trio/Sources/Modules/Stat/StatStateModel.swift
  21. 6 2
      Trio/Sources/Modules/Treatments/TreatmentsStateModel.swift

+ 0 - 1
Trio/Sources/Modules/Adjustments/AdjustmentsStateModel.swift

@@ -67,7 +67,6 @@ extension Adjustments {
         var didSaveSettings: Bool = false
 
         // Core Data
-        let coredataContext = CoreDataStack.shared.newTaskContext()
         let viewContext = CoreDataStack.shared.persistentContainer.viewContext
 
         // Help Sheet

+ 3 - 2
Trio/Sources/Modules/DynamicSettings/DynamicSettingsStateModel.swift

@@ -39,8 +39,6 @@ extension DynamicSettings {
 
         var units: GlucoseUnits = .mgdL
 
-        let context = CoreDataStack.shared.newTaskContext()
-
         override func subscribe() {
             units = settingsManager.settings.units
 
@@ -102,6 +100,9 @@ extension DynamicSettings {
         /// - Returns: `true` if sufficient TDD data is available, otherwise `false`.
         /// - Throws: An error if the Core Data count operation fails.
         private func hasSufficientTDD() throws -> Bool {
+            let context = CoreDataStack.shared.newTaskContext()
+            context.name = "DynamicSettingsStateModel.hasSufficientTDD"
+
             var result = false
 
             context.performAndWait {

+ 3 - 0
Trio/Sources/Modules/Home/HomeStateModel+Setup/BatterySetup.swift

@@ -19,6 +19,9 @@ extension Home.StateModel {
     }
 
     private func fetchBattery() async throws -> [NSManagedObjectID] {
+        let batteryFetchContext = CoreDataStack.shared.newTaskContext()
+        batteryFetchContext.name = "HomeStateModel.fetchBattery"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: OpenAPS_Battery.self,
             onContext: batteryFetchContext,

+ 6 - 0
Trio/Sources/Modules/Home/HomeStateModel+Setup/CarbSetup.swift

@@ -16,6 +16,9 @@ extension Home.StateModel {
     }
 
     private func fetchCarbs() async throws -> [NSManagedObjectID] {
+        let carbsFetchContext = CoreDataStack.shared.newTaskContext()
+        carbsFetchContext.name = "HomeStateModel.fetchCarbs"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: CarbEntryStored.self,
             onContext: carbsFetchContext,
@@ -52,6 +55,9 @@ extension Home.StateModel {
     }
 
     private func fetchFPUs() async throws -> [NSManagedObjectID] {
+        let fpuFetchContext = CoreDataStack.shared.newTaskContext()
+        fpuFetchContext.name = "HomeStateModel.fetchFPUs"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: CarbEntryStored.self,
             onContext: fpuFetchContext,

+ 7 - 6
Trio/Sources/Modules/Home/HomeStateModel+Setup/ChartAxisSetup.swift

@@ -1,13 +1,14 @@
+import CoreData
 import Foundation
 
 extension Home.StateModel {
-    func yAxisChartData(glucoseValues: [GlucoseStored]) {
+    func yAxisChartData(glucoseValues: [GlucoseStored], on context: NSManagedObjectContext) {
         // Capture the forecast values from `preprocessedData` on the main thread
         Task { @MainActor in
             let forecastValues = self.preprocessedData.map { Decimal($0.forecastValue.value) }
 
             // Perform the glucose processing on the background context
-            glucoseFetchContext.perform {
+            context.perform {
                 let glucoseMapped = glucoseValues.map { Decimal($0.glucose) }
 
                 // Calculate min and max values for glucose and forecast
@@ -53,8 +54,8 @@ extension Home.StateModel {
         maxYAxisValue = maxValue
     }
 
-    func yAxisChartDataCobChart(determinations: [[String: Any]]) {
-        determinationFetchContext.perform {
+    func yAxisChartDataCobChart(determinations: [[String: Any]], on context: NSManagedObjectContext) {
+        context.perform {
             // Map the COB values from the dictionary results
             let cobMapped = determinations.compactMap { entry in
                 // First cast to Int16, then convert to Decimal
@@ -84,8 +85,8 @@ extension Home.StateModel {
         maxValueCobChart = maxValue
     }
 
-    func yAxisChartDataIobChart(determinations: [[String: Any]]) {
-        determinationFetchContext.perform {
+    func yAxisChartDataIobChart(determinations: [[String: Any]], on context: NSManagedObjectContext) {
+        context.perform {
             // Map the IOB values from the fetched dictionaries
             let iobMapped = determinations.compactMap { ($0["iob"] as? NSDecimalNumber)?.decimalValue }
             let minIob = iobMapped.min()

+ 3 - 0
Trio/Sources/Modules/Home/HomeStateModel+Setup/CurrentTDDSetup.swift

@@ -32,6 +32,9 @@ extension Home.StateModel {
     }
 
     private func fetchTDDIDs() async throws -> [NSManagedObjectID] {
+        let tddFetchContext = CoreDataStack.shared.newTaskContext()
+        tddFetchContext.name = "HomeStateModel.fetchTDDIDs"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: TDDStored.self,
             onContext: tddFetchContext,

+ 5 - 2
Trio/Sources/Modules/Home/HomeStateModel+Setup/DeterminationSetup.swift

@@ -40,6 +40,9 @@ extension Home.StateModel {
 
     // Custom fetch to more efficiently filter only for cob and iob
     private func fetchCobAndIob() async throws -> [NSManagedObjectID] {
+        let determinationFetchContext = CoreDataStack.shared.newTaskContext()
+        determinationFetchContext.name = "HomeStateModel.fetchCobAndIob"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: OrefDetermination.self,
             onContext: determinationFetchContext,
@@ -56,8 +59,8 @@ extension Home.StateModel {
             }
 
             // Update Chart Scales
-            self.yAxisChartDataCobChart(determinations: fetchedResults)
-            self.yAxisChartDataIobChart(determinations: fetchedResults)
+            self.yAxisChartDataCobChart(determinations: fetchedResults, on: determinationFetchContext)
+            self.yAxisChartDataIobChart(determinations: fetchedResults, on: determinationFetchContext)
             return fetchedResults.compactMap { $0["objectID"] as? NSManagedObjectID }
         }
     }

+ 3 - 0
Trio/Sources/Modules/Home/HomeStateModel+Setup/ForecastSetup.swift

@@ -15,6 +15,9 @@ extension Home.StateModel {
                 return []
             }
 
+            let taskContext = CoreDataStack.shared.newTaskContext()
+            taskContext.name = "HomeStateModel.preprocessForecastData"
+
             // Fetch complete forecast hierarchy with prefetched values
             return try await determinationStorage.fetchForecastHierarchy(
                 for: determination.objectID,

+ 4 - 1
Trio/Sources/Modules/Home/HomeStateModel+Setup/GlucoseSetup.swift

@@ -19,6 +19,9 @@ extension Home.StateModel {
     }
 
     private func fetchGlucose() async throws -> [NSManagedObjectID] {
+        let glucoseFetchContext = CoreDataStack.shared.newTaskContext()
+        glucoseFetchContext.name = "HomeStateModel.fetchGlucose"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: GlucoseStored.self,
             onContext: glucoseFetchContext,
@@ -35,7 +38,7 @@ extension Home.StateModel {
 
             // Update Main Chart Y Axis Values
             // Perform everything on "context" to be thread safe
-            self.yAxisChartData(glucoseValues: fetchedResults)
+            self.yAxisChartData(glucoseValues: fetchedResults, on: glucoseFetchContext)
 
             return fetchedResults.map(\.objectID)
         }

+ 6 - 0
Trio/Sources/Modules/Home/HomeStateModel+Setup/OverrideSetup.swift

@@ -19,6 +19,9 @@ extension Home.StateModel {
     }
 
     private func fetchOverrides() async throws -> [NSManagedObjectID] {
+        let overrideFetchContext = CoreDataStack.shared.newTaskContext()
+        overrideFetchContext.name = "HomeStateModel.fetchOverrides"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: OverrideStored.self,
             onContext: overrideFetchContext,
@@ -56,6 +59,9 @@ extension Home.StateModel {
     }
 
     private func fetchOverrideRunStored() async throws -> [NSManagedObjectID] {
+        let overrideFetchContext = CoreDataStack.shared.newTaskContext()
+        overrideFetchContext.name = "HomeStateModel.fetchOverrideRunStored"
+
         let predicate = NSPredicate(format: "startDate >= %@", Date.oneDayAgo as NSDate)
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: OverrideRunStored.self,

+ 6 - 0
Trio/Sources/Modules/Home/HomeStateModel+Setup/PumpHistorySetup.swift

@@ -19,6 +19,9 @@ extension Home.StateModel {
     }
 
     private func fetchInsulin() async throws -> [NSManagedObjectID] {
+        let pumpHistoryFetchContext = CoreDataStack.shared.newTaskContext()
+        pumpHistoryFetchContext.name = "HomeStateModel.fetchInsulin"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: PumpEventStored.self,
             onContext: pumpHistoryFetchContext,
@@ -65,6 +68,9 @@ extension Home.StateModel {
     }
 
     func fetchLastBolus() async throws -> NSManagedObjectID? {
+        let pumpHistoryFetchContext = CoreDataStack.shared.newTaskContext()
+        pumpHistoryFetchContext.name = "HomeStateModel.fetchLastBolus"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: PumpEventStored.self,
             onContext: pumpHistoryFetchContext,

+ 6 - 0
Trio/Sources/Modules/Home/HomeStateModel+Setup/TempTargetSetup.swift

@@ -19,6 +19,9 @@ extension Home.StateModel {
     }
 
     private func fetchTempTargets() async throws -> [NSManagedObjectID] {
+        let tempTargetFetchContext = CoreDataStack.shared.newTaskContext()
+        tempTargetFetchContext.name = "HomeStateModel.fetchTempTargets"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: TempTargetStored.self,
             onContext: tempTargetFetchContext,
@@ -57,6 +60,9 @@ extension Home.StateModel {
     }
 
     private func fetchTempTargetRunStored() async throws -> [NSManagedObjectID] {
+        let tempTargetFetchContext = CoreDataStack.shared.newTaskContext()
+        tempTargetFetchContext.name = "HomeStateModel.fetchTempTargetRunStored"
+
         let predicate = NSPredicate(format: "startDate >= %@", Date.oneDayAgo as NSDate)
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: TempTargetRunStored.self,

+ 0 - 10
Trio/Sources/Modules/Home/HomeStateModel.swift

@@ -128,16 +128,6 @@ extension Home {
         var minValueIobChart: Decimal = 0
         var maxValueIobChart: Decimal = 5
 
-        let taskContext = CoreDataStack.shared.newTaskContext()
-        let glucoseFetchContext = CoreDataStack.shared.newTaskContext()
-        let carbsFetchContext = CoreDataStack.shared.newTaskContext()
-        let fpuFetchContext = CoreDataStack.shared.newTaskContext()
-        let determinationFetchContext = CoreDataStack.shared.newTaskContext()
-        let tddFetchContext = CoreDataStack.shared.newTaskContext()
-        let pumpHistoryFetchContext = CoreDataStack.shared.newTaskContext()
-        let overrideFetchContext = CoreDataStack.shared.newTaskContext()
-        let tempTargetFetchContext = CoreDataStack.shared.newTaskContext()
-        let batteryFetchContext = CoreDataStack.shared.newTaskContext()
         let viewContext = CoreDataStack.shared.persistentContainer.viewContext
 
         // Queue for handling Core Data change notifications

+ 0 - 2
Trio/Sources/Modules/ISFEditor/ISFEditorStateModel.swift

@@ -22,8 +22,6 @@ extension ISFEditor {
         var therapyItems: [TherapySettingItem] = []
         var shouldDisplaySaving: Bool = false
 
-        let context = CoreDataStack.shared.newTaskContext()
-
         let timeValues = stride(from: 0.0, to: 1.days.timeInterval, by: 30.minutes.timeInterval).map { $0 }
 
         var rateValues: [Decimal] {

+ 0 - 2
Trio/Sources/Modules/NightscoutConfig/NightscoutConfigStateModel.swift

@@ -15,8 +15,6 @@ extension NightscoutConfig {
         @Injected() private var storage: FileStorage!
         @Injected() var apsManager: APSManager!
 
-        let coredataContext = CoreDataStack.shared.newTaskContext()
-
         @Published var url = ""
         @Published var secret = ""
         @Published var message = ""

+ 6 - 0
Trio/Sources/Modules/Stat/StatStateModel+Setup/BolusStatsSetup.swift

@@ -48,6 +48,9 @@ extension Stat.StateModel {
     /// 3. Calculates total insulin for each time period
     /// 4. Returns the processed statistics as (hourly: [BolusStats], daily: [BolusStats])
     private func fetchBolusStats() async throws -> (hourly: [BolusStats], daily: [BolusStats]) {
+        let bolusTaskContext = CoreDataStack.shared.newTaskContext()
+        bolusTaskContext.name = "StatStateModel.fetchBolusStats"
+
         // Fetch PumpEventStored entries from Core Data
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: BolusStored.self,
@@ -155,6 +158,9 @@ extension Stat.StateModel {
     ///
     /// This only needs to be called once during subscribe.
     private func calculateAndCacheBolusAveragesAndTotals() async {
+        let bolusTaskContext = CoreDataStack.shared.newTaskContext()
+        bolusTaskContext.name = "StatStateModel.calculateAndCacheBolusAveragesAndTotals"
+
         let calendar = Calendar.current
 
         // Calculate averages in context

+ 10 - 1
Trio/Sources/Modules/Stat/StatStateModel+Setup/LoopChartSetup.swift

@@ -81,6 +81,9 @@ extension Stat.StateModel {
     func fetchLoopStatRecords(for interval: StatsTimeIntervalWithToday) async throws
         -> ([NSManagedObjectID], [NSManagedObjectID])
     {
+        let loopTaskContext = CoreDataStack.shared.newTaskContext()
+        loopTaskContext.name = "StatStateModel.fetchLoopStatRecords"
+
         // Calculate the date range based on selected duration
         let now = Date()
         let startDate: Date
@@ -154,6 +157,9 @@ extension Stat.StateModel {
     ) async throws
         -> [LoopStatsProcessedData]
     {
+        let loopTaskContext = CoreDataStack.shared.newTaskContext()
+        loopTaskContext.name = "StatStateModel.getLoopStats"
+
         // Calculate the date range for glucose readings
         let now = Date()
         let startDate: Date
@@ -170,7 +176,7 @@ extension Stat.StateModel {
             startDate = now.addingTimeInterval(-90.days.timeInterval)
         }
 
-        // Get glucose statistics
+        // Get glucose statistics (uses its own local context)
         let totalGlucose = try await calculateGlucoseStats(from: startDate, to: now)
 
         // Get NSManagedObject
@@ -236,6 +242,9 @@ extension Stat.StateModel {
         from startDate: Date,
         to _: Date
     ) async throws -> Int {
+        let loopTaskContext = CoreDataStack.shared.newTaskContext()
+        loopTaskContext.name = "StatStateModel.calculateGlucoseStats"
+
         // Create predicate for glucose readings
         let glucosePredicate = NSPredicate(format: "date >= %@", startDate as NSDate)
 

+ 6 - 0
Trio/Sources/Modules/Stat/StatStateModel+Setup/MealStatsSetup.swift

@@ -48,6 +48,9 @@ extension Stat.StateModel {
     /// 3. Calculates total macronutrients for each time period
     /// 4. Returns the processed statistics as (hourly: [MealStats], daily: [MealStats])
     private func fetchMealStats() async throws -> (hourly: [MealStats], daily: [MealStats]) {
+        let mealTaskContext = CoreDataStack.shared.newTaskContext()
+        mealTaskContext.name = "StatStateModel.fetchMealStats"
+
         // Fetch CarbEntryStored entries from Core Data
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: CarbEntryStored.self,
@@ -116,6 +119,9 @@ extension Stat.StateModel {
     ///
     /// This only needs to be called once during subscribe.
     private func calculateAndCacheDailyAverages() async {
+        let mealTaskContext = CoreDataStack.shared.newTaskContext()
+        mealTaskContext.name = "StatStateModel.calculateAndCacheDailyAverages"
+
         let calendar = Calendar.current
 
         // Calculate averages in context

+ 10 - 4
Trio/Sources/Modules/Stat/StatStateModel+Setup/TDDSetup.swift

@@ -34,13 +34,16 @@ extension Stat.StateModel {
     /// - Returns: A tuple containing hourly and daily TDD statistics arrays
     /// - Note: Processes both hourly statistics for the last 10 days and complete daily statistics
     private func fetchTDDStats() async throws -> (hourly: [TDDStats], daily: [TDDStats]) {
+        let tddTaskContext = CoreDataStack.shared.newTaskContext()
+        tddTaskContext.name = "StatStateModel.fetchTDDStats"
+
         // MARK: - Fetch Required Data
 
         // Fetch data for daily statistics (TDDStored for week, month, total views)
-        let tddResults = try await fetchTDDStoredRecords()
+        let tddResults = try await fetchTDDStoredRecords(on: tddTaskContext)
 
         // Fetch data for hourly statistics (BolusStored and TempBasalStored for day view)
-        let (bolusResults, tempBasalResults, suspendEvents, resumeEvents) = try await fetchHourlyInsulinRecords()
+        let (bolusResults, tempBasalResults, suspendEvents, resumeEvents) = try await fetchHourlyInsulinRecords(on: tddTaskContext)
 
         // MARK: - Process Data on Background Context
 
@@ -77,7 +80,7 @@ extension Stat.StateModel {
     /// Fetches TDDStored records from CoreData for daily statistics
     /// - Returns: The results of the fetch request containing TDDStored records
     /// - Note: Fetches records from the last 3 months for week, month, and total views
-    private func fetchTDDStoredRecords() async throws -> Any {
+    private func fetchTDDStoredRecords(on tddTaskContext: NSManagedObjectContext) async throws -> Any {
         // Create a predicate to fetch TDD records from the last 3 months
         let threeMonthsAgo = Date().addingTimeInterval(-3.months.timeInterval)
         let predicate = NSPredicate(format: "date >= %@", threeMonthsAgo as NSDate)
@@ -96,7 +99,7 @@ extension Stat.StateModel {
     /// Fetches BolusStored and TempBasalStored records from CoreData for hourly statistics
     /// - Returns: A tuple containing the results of both fetch requests
     /// - Note: Fetches records from the last 20 days for detailed hourly view
-    private func fetchHourlyInsulinRecords() async throws -> (bolus: Any, tempBasal: Any, suspendEvents: Any, resumeEvents: Any) {
+    private func fetchHourlyInsulinRecords(on tddTaskContext: NSManagedObjectContext) async throws -> (bolus: Any, tempBasal: Any, suspendEvents: Any, resumeEvents: Any) {
         // Calculate date range for hourly statistics (last 20 days)
         let now = Date()
         let twentyDaysAgo = Calendar.current.date(byAdding: .day, value: -20, to: now) ?? now
@@ -498,6 +501,9 @@ extension Stat.StateModel {
     /// Calculates and caches the daily averages of Total Daily Dose (TDD) insulin values
     /// - Note: This function runs asynchronously and updates the tddAveragesCache on the main actor
     private func calculateAndCacheTDDAverages() async {
+        let tddTaskContext = CoreDataStack.shared.newTaskContext()
+        tddTaskContext.name = "StatStateModel.calculateAndCacheTDDAverages"
+
         // Get calendar for date calculations
         let calendar = Calendar.current
 

+ 3 - 5
Trio/Sources/Modules/Stat/StatStateModel.swift

@@ -77,12 +77,7 @@ extension Stat {
         var selectedMealChartType: MealChartType = .totalMeals
 
         // Fetching Contexts
-        let context = CoreDataStack.shared.newTaskContext()
         let viewContext = CoreDataStack.shared.persistentContainer.viewContext
-        let tddTaskContext = CoreDataStack.shared.newTaskContext()
-        let loopTaskContext = CoreDataStack.shared.newTaskContext()
-        let mealTaskContext = CoreDataStack.shared.newTaskContext()
-        let bolusTaskContext = CoreDataStack.shared.newTaskContext()
 
         override func subscribe() {
             setupGlucoseArray(for: .today)
@@ -128,6 +123,9 @@ extension Stat {
 
         private func fetchGlucose(for interval: StatsTimeIntervalWithToday) async -> [NSManagedObjectID] {
             do {
+                let context = CoreDataStack.shared.newTaskContext()
+                context.name = "StatStateModel.fetchGlucose"
+
                 let predicate: NSPredicate
 
                 switch interval {

+ 6 - 2
Trio/Sources/Modules/Treatments/TreatmentsStateModel.swift

@@ -122,8 +122,6 @@ extension Treatments {
         let now = Date.now
 
         let viewContext = CoreDataStack.shared.persistentContainer.viewContext
-        let glucoseFetchContext = CoreDataStack.shared.newTaskContext()
-        let determinationFetchContext = CoreDataStack.shared.newTaskContext()
 
         var isActive: Bool = false
 
@@ -778,6 +776,9 @@ extension Treatments.StateModel {
     }
 
     private func fetchGlucose() async throws -> [NSManagedObjectID] {
+        let glucoseFetchContext = CoreDataStack.shared.newTaskContext()
+        glucoseFetchContext.name = "TreatmentsStateModel.fetchGlucose"
+
         let results = try await CoreDataStack.shared.fetchEntitiesAsync(
             ofType: GlucoseStored.self,
             onContext: glucoseFetchContext,
@@ -847,6 +848,9 @@ extension Treatments.StateModel {
 
     private func mapForecastsForChart() async -> Determination? {
         do {
+            let determinationFetchContext = CoreDataStack.shared.newTaskContext()
+            determinationFetchContext.name = "TreatmentsStateModel.mapForecastsForChart"
+
             let determinationObjects: [OrefDetermination] = try await CoreDataStack.shared
                 .getNSManagedObject(with: determinationObjectIDs, context: determinationFetchContext)