0

I'm experiencing the following error with my SwiftData container when running a build:

Code=134504 "Cannot use staged migration with an unknown model version."

Code Structure - Summary

I am using a versionedSchema to store multiple models in SwiftData. I started experiencing this issue when adding two new models in the newest Schema version. Starting from the current public version, V4.4.6, there are two migrations.

Migration Summary:

The first migration is to V4.4.7. This is a lightweight migration removing one attribute from one of the models. This was tested and worked successfully.

The second migration is to V5.0.0. This is a custom migration adding two new models, and instantiating instances of the two new models based on data from instances of the existing models. In the initial testing of this version, no issues were observed.

Issue and Steps to Reproduce

Reproduction of issue: Starting from a fresh build of the publicly released V4.4.6, I run a new build that contains both Schema Versions (V4.4.7 and V5.0.0), and their associated migration stages. This builds successfully, and the container successfully migrates to V5.0.0. Checking the default.store file, all values appear to migrate and instantiate correctly.

The second step in reproduction of the issue is to simply stop running the build, and then rebuild, without any code changes. This fails to initialize the model container every time afterwards. Going back to the simulator after successive builds are stopped in Xcode, the app launches and accesses/modifies the model container as normal.

Supplementary Issue: I have been putting up with the same, persistent issue in the Xcode Preview Canvas of "Failed to Initialize Model Container" This is a 5 in 6 build issue, where builds will work at random. In the case of previews, I have cleared all data associated with all previews multiple times. The only difference being that the simulator is a 100% failure rate after the initial, successful initialization. I assume this is due to the different build structure of previews. Lastly, of note, the Xcode previews fail at the same line in instantiating the model container as the simulator does. From my research into this issue, people say that the Xcode preview is instantiating from elsewhere. I do have a separate model container set up specifically for canvas previews, but the error does not occur in that container, but rather the app's main container.

Possible Contributing Factors & Tested Facts

iOS: While I have experienced issues with SwiftData and the complier in iOS 26, I can rule that out as the issue here. This has been tested on simulators running iOS 18.6, 26.0.1, and 26.1, all encountering failures to initialize model container. While in iOS 18, subsequent builds after the successful migration did work, I did eventually encounter the same error and crash. In iOS 26.0.1 and 26.1, these errors come immediately on the second build.

My Person Experience: This is my first migration involving the addition of new models to my schemas. I have experience with lightweight and custom migrations in versionedSchemas, but had difficulty when first building V5.0.0. While that code builds and migrates successfully, I believe I may be omitting some important code that is now causing issues.

Container Initialization for V4.4.6

do {
        container = try ModelContainer(
            for:
            Job.self,
            JobTask.self,
            Day.self,
            Charge.self,
            Material.self,
            Person.self,
            TaskCategory.self,
            Service.self,

            migrationPlan: JobifyMigrationPlan.self
        )
    } catch {
        fatalError("Failed to Initialize Model Container")
    }

Versioned Schema Instance for V4.4.6 (V4.4.7 differs only by versionIdentifier)

static var versionIdentifier = Schema.Version(4, 4, 6)

static var models: [any PersistentModel.Type] {
    [Job.self, JobTask.self, Day.self, Charge.self, Material.self, Person.self, TaskCategory.self, Service.self]
}

Container Initialization for V5.0.0

    do {
        
        let schema = Schema([Jobify.self,
                            JobTask.self,
                            Day.self,
                            Charge.self,
                            MaterialItem.self,
                            Person.self,
                            TaskCategory.self,
                            Service.self,
                            ServiceJob.self,
                            RecurerRule.self])
        
        container = try ModelContainer(
            for: schema, migrationPlan: JobifyMigrationPlan.self
        )
    } catch {
        fatalError("Failed to Initialize Model Container")
    }

Versioned Schema Instance for V5.0.0

static var versionIdentifier = Schema.Version(5, 0, 0)

static var models: [any PersistentModel.Type] {
    [
        JobifySchemaV500.Job.self,
        JobifySchemaV500.JobTask.self,
        JobifySchemaV500.Day.self,
        JobifySchemaV500.Charge.self,
        JobifySchemaV500.Material.self,
        JobifySchemaV500.Person.self,
        JobifySchemaV500.TaskCategory.self,
        JobifySchemaV500.Service.self,
        JobifySchemaV500.ServiceJob.self,
        JobifySchemaV500.RecurerRule.self
    ]
}

Migration Stages | V4.4.6 -> V4.4.7, V4.4.7 -> V5.0.0

static var migrateV446toV447 = MigrationStage.lightweight(fromVersion: JobifySchemeV446.self, toVersion: JobifySchemeV447.self)

static var V447toV500 = MigrationStage.custom(
    fromVersion: JobifySchemeV447.self,
    toVersion: JobifySchemaV500.self,
    willMigrate: nil,
    didMigrate: { context in
        
        var services: [JobifySchemaV500.Service] = []
        
        let descriptor: FetchDescriptor = FetchDescriptor<JobifySchemaV500.Service>(predicate: #Predicate { service in
            service.rawFrequency != 0
        })
        
        do {
            services = try context.fetch(descriptor)
        } catch {
            print("Failed to fetch JobifySchemaV500.Service from context")
        }
        
        var serviceJobs: [JobifySchemaV500.ServiceJob] = []
        
        for service in services {
            for job in service.jobs {
                
                /// If service contains charges for Job, create a new serviceJob following the rules of the existing Service
                
                if !service.charges.isEmpty && service.frequency != nil {
                    var serviceJob: JobifySchemaV500.ServiceJob = ServiceJob(from: job, and: service)
                    
                    serviceJobs.append(serviceJob)
                    
                }
            }
        }
        
        for serviceJob in serviceJobs {
            context.insert(serviceJob)
        }
        
        do {
            try context.save()
        } catch {
            print("Failed to save context after inserting [JobifySchemaV500.ServiceJob] during migration V447toV500")
        }
    }
)

Addressing Differences in Object Names

  1. Type-aliasing: All my model types are type-aliased for simplification in view components. All types are aliased as 'JobifySchemeV446.<#Name#>' in V.4.4.6, and 'JobifySchemaV500.<#Name#>' in V5.0.0

  2. Issues with iOS 26: My type-aliases dating back to iOS 17 overlapped with lower level objects in Swift, including 'Job' and 'Material'. These started to be an issue with initializing the model container when running in iOS 26. The type aliases have been renamed since, however the V4.4.6 build with the old names runs and builds perfectly fine in iOS 26

If there is any other code that may be relevant in determining where this error is occurring, I would be happy to add it. My current best theory is simply that I have mistakenly omitted code relevant to the SwiftData Migration.

5
  • Are you using iCloud with your model container? Commented Nov 25 at 11:15
  • I do not have iCloud enabled for this project. I plan on doing so at some point Commented Nov 25 at 13:45
  • 1
    That should make it at least a bit easier to solve the problem. Even though I had the same error myself I can’t tell you how to solve this because I tried so many things before I fixed the issue so I don’t know exactly what the right solution was. The problem isn’t uncommon though so I would recommend you google the error and try some of the solutions that worked for other people. Commented Nov 25 at 16:05
  • Nice to hear I'm not alone haha... was this an issue in development only, for you? I'm worried that this is an issue with my code that will affect builds I release Commented Nov 26 at 5:04
  • 1
    Yes development only. Commented Nov 26 at 6:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.