SwfitData Crashes after MigrationPlan Completed

There are multiple versions of VersionedSchema in my App. I used MigrationPlan to migrate data. It works well in Xcode, but in TestFlight and App Store, it always crashes when opening the App for the first time.

MeMigrationPlan Code:


import Foundation

import SwiftData



enum MeMigrationPlan: SchemaMigrationPlan {

    static var schemas: [any VersionedSchema.Type] {

        [MeSchemaV1.self, MeSchemaV2.self, MeSchemaV3.self, MeSchemaV4.self]

    }



    static var stages: [MigrationStage] {

        [migrateV1toV2, migrateV2toV3, migrateV3toV4]

    }

//migrateV1toV2, because the type of a data field in MeSchemaV1.TodayRingData.self is modified, the historical data is deleted during migration, and the migration work is successfully completed.

    static let migrateV1toV2 = MigrationStage.custom(

        fromVersion: MeSchemaV1.self,

        toVersion: MeSchemaV2.self,

        willMigrate: { context in

                      try context.delete(model: MeSchemaV1.TodayRingData.self)

                     },

        didMigrate: nil

    )

//migrateV2toV3, because a new Model was added, it would crash when starting up when TF and the official version were updated, so I tried to delete the historical data during migration, but the problem still exists.

    static let migrateV2toV3 = MigrationStage.custom(

        fromVersion: MeSchemaV2.self,

        toVersion: MeSchemaV3.self,

        willMigrate: { context in

                      try context.delete(model: MeSchemaV2.TodayRingData.self)

                      try context.delete(model: MeSchemaV2.HealthDataStatistics.self)

                      try context.delete(model: MeSchemaV2.SportsDataStatistics.self)

                      try context.delete(model: MeSchemaV2.UserSettingTypeFor.self)

                      try context.delete(model: MeSchemaV2.TodayRingData.self)

                      try context.delete(model: MeSchemaV2.TodayHealthData.self)

                      try context.delete(model: MeSchemaV2.SleepDataSource.self)

                      try context.delete(model: MeSchemaV2.WorkoutTargetData.self)

                      try context.delete(model: MeSchemaV2.WorkoutStatisticsForTarget.self)

                      try context.delete(model: MeSchemaV2.HealthDataList.self)

                     },

        didMigrate: nil

    )

//migrateV3toV4, adds some fields in MeSchemaV3.WorkoutList.self, and adds several new Models. When TF and the official version are updated, it will crash at startup. Continue to try to delete historical data during migration, but the problem still exists.

    static let migrateV3toV4 = MigrationStage.custom(

        fromVersion: MeSchemaV3.self,

        toVersion: MeSchemaV4.self,

        willMigrate: { context in

                      do {

                          try context.delete(model: MeSchemaV3.WorkoutList.self)

                          try context.delete(model: MeSchemaV3.HealthDataStatistics.self)

                          try context.delete(model: MeSchemaV3.SportsDataStatistics.self)

                          try context.delete(model: MeSchemaV3.UserSettingTypeFor.self)

                          try context.delete(model: MeSchemaV3.TodayRingData.self)

                          try context.delete(model: MeSchemaV3.TodayHealthData.self)

                          try context.delete(model: MeSchemaV3.SleepDataSource.self)

                          try context.delete(model: MeSchemaV3.WorkoutTargetData.self)

                          try context.delete(model: MeSchemaV3.WorkoutStatisticsForTarget.self)

                          try context.delete(model: MeSchemaV3.HealthDataList.self)

                          try context.delete(model: MeSchemaV3.SleepStagesData.self)

                          try context.save() 

                      } catch {



                          print("Migration from V3 to V4 failed with error: \(error)")

                          throw error

                      }

                     },

        didMigrate: nil

    )

}

ModelContainer init Code




import SwiftUI



import HealthKit



import SwiftData







@main



struct MeApp: App {



    @StateObject var viewModel  = ViewModel()



    @StateObject private var entitlementManager: EntitlementManager



    @StateObject private var purchaseManager: PurchaseManager



    @StateObject var sessionManager = SessionManager()



    let ShareMeData = UserDefaults(suiteName: "group.LDPWJGJD9Z.kookybread.me")



    let container: ModelContainer



    init() {



        let entitlementManager = EntitlementManager()



        let purchaseManager = PurchaseManager(entitlementManager: entitlementManager)



        self._entitlementManager = StateObject(wrappedValue: entitlementManager)



        self._purchaseManager = StateObject(wrappedValue: purchaseManager)



        do {



            let schema = Schema([



                WorkoutList.self,



                HealthDataStatistics.self,



                SportsDataStatistics.self,



                UserSettingTypeFor.self,



                TodayRingData.self,



                TodayHealthData.self,



                SleepDataSource.self,



                WorkoutTargetData.self,



                WorkoutStatisticsForTarget.self,



                HealthDataList.self,



                SleepStagesData.self,



                WorkoutDetailData.self,



                HeartZoneData.self,



                WorkoutSegmentData.self,



                WorkoutMaxMinRangeData.self,



                WorkoutHeartZoneData.self



            ])



            container = try ModelContainer(



                for: schema,



                migrationPlan: MeMigrationPlan.self



            )



            print("ModelContainer initialized successfully")



        } catch {



            print("Error initializing model container: \(error)")



            //The App always crashes here when it is started through TF update, but no error information can be obtained through TF. There is no error prompt in Xcode and it runs normally.



            fatalError("Failed to initialize model container.")



        }



    }



    



    var body: some Scene {



        WindowGroup {



            ContentView( switchSportsType: sst)



                .environmentObject(viewModel)



                .environmentObject(purchaseManager)



                .environmentObject(entitlementManager)



                .environmentObject(sessionManager)



                .modelContainer(container)



                .preferredColorScheme(darkModeSettings.isDarkModeEnabled ? .dark : nil)



                .task {



                    await loadImage()



                    await loadImage2()



                    await purchaseManager.updatePurchasedProducts()



                    sessionManager.startSession()



                }







        }



    }



}



TestFlight Crashlog








Exception Type:  EXC_BREAKPOINT (SIGTRAP)



Exception Codes: 0x0000000000000001, 0x00000001a45f58c0



Termination Reason: SIGNAL 5 Trace/BPT trap: 5



Terminating Process: exc handler [73915]







Triggered by Thread:  0











Thread 0 name:



Thread 0 Crashed:



0   libswiftCore.dylib            	0x00000001a45f58c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144)



1   Me                            	0x00000001053746e0 specialized MeApp.init() + 1780 (MeApp.swift:59)



2   Me                            	0x00000001053736d8 MeApp.init() + 8 (<compiler-generated>:0)



3   Me                            	0x00000001053736d8 protocol witness for App.init() in conformance MeApp + 28



4   SwiftUI                       	0x00000001a9e904c0 static App.main() + 116 (App.swift:114)



5   Me                            	0x000000010537374c static MeApp.$main() + 24 (MeApp.swift:0)



6   Me                            	0x000000010537374c main + 36



7   dyld                          	0x00000001c9399e4c start + 2240 (dyldMain.cpp:1298)







Thread 1:



0   libsystem_pthread.dylib       	0x0000000202b6c0c4 start_wqthread + 0 (:-1)







Thread 2:



0   libsystem_pthread.dylib       	0x0000000202b6c0c4 start_wqthread + 0 (:-1)







Thread 3:



0   libsystem_pthread.dylib       	0x0000000202b6c0c4 start_wqthread + 0 (:-1)







Thread 4:



0   libsystem_pthread.dylib       	0x0000000202b6c0c4 start_wqthread + 0 (:-1)







Thread 5:



0   libsystem_pthread.dylib       	0x0000000202b6c0c4 start_wqthread + 0 (:-1)











Thread 0 crashed with ARM Thread State (64-bit):



    x0: 0x800000010550e720   x1: 0x0000000000000000   x2: 0x0000000000000000   x3: 0x0000000302c122c0



    x4: 0x0000000000000000   x5: 0x000000016ae7f390   x6: 0x000000000000002e   x7: 0x0000000000000000



    x8: 0x0000000000000100   x9: 0x00000000000000ff  x10: 0x0000000000002280  x11: 0x0000000087a010be



   x12: 0x00000000000007fb  x13: 0x00000000000007fd  x14: 0x0000000087c0188b  x15: 0x000000000000008b



   x16: 0x0000000087a010be  x17: 0x0000000000001800  x18: 0x0000000000000000  x19: 0x000000010550e734



   x20: 0x800000010550e720  x21: 0x0000000000000000  x22: 0x000000000000000b  x23: 0x000000000000000e



   x24: 0x000000000000003b  x25: 0x000000010550e725  x26: 0xd000000000000025  x27: 0x0000000000000000



   x28: 0xd00000000000001e   fp: 0x000000016ae7f570   lr: 0x00000001a45f58c0



    sp: 0x000000016ae7f4a0   pc: 0x00000001a45f58c0 cpsr: 0x60001000



   esr: 0xf2000001 (Breakpoint) brk 1











Binary Images:



        0x104f80000 -         0x105613fff Me arm64  <7b33921c92b636cebdc0a3adc35d813e> /private/var/containers/Bundle/Application/103ADA5E-4672-4132-8400-E5815C58D83F/Me.app/Me



        0x105850000 -         0x10585bfff libobjc-trampolines.dylib arm64e  <2e2c05f8377a30899ad91926d284dd03> /private/preboot/Cryptexes/OS/usr/lib/libobjc-trampolines.dylib



        0x1a45bc000 -         0x1a4b0bfff libswiftCore.dylib arm64e  <d9ad5cc1ca2c3f0a8091652b0df56d14> /usr/lib/swift/libswiftCore.dylib



        0x1a9ae4000 -         0x1ab882fff SwiftUI arm64e  <c1325fda9da239d2ab83a338b4d8a884> /System/Library/Frameworks/SwiftUI.framework/SwiftUI



        0x1c935d000 -         0x1c93e9ef7 dyld arm64e  <71846eacee653697bf7d790b6a07dcdb> /usr/lib/dyld



        0x202b6b000 -         0x202b77ff3 libsystem_pthread.dylib arm64e  <1196b6c3333d3450818ff3663484b8eb> /usr/lib/system/libsystem_pthread.dylib







EOF



SwfitData Crashes after MigrationPlan Completed
 
 
Q