SwiftData in-memory ModelContainer causes DefaultStore validation errors on consecutive xcodebuild test runs

When running parallel Swift Testing tests that each create their own in-memory ModelContainer, the first xcodebuild test run succeeds but all subsequent runs fail with DefaultStore save failed validation errors — unless DerivedData is deleted between runs.

Setup

Each test suite creates an isolated in-memory container with a unique name:

ModelConfiguration(UUID().uuidString, schema: schema, isStoredInMemoryOnly: true)

The @Model class has non-optional properties (e.g. var v: String, var entityDicMoveNr: Int) that are always set in init.

Symptoms on second run

SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=1560
"Multiple validation errors occurred."
NSValidationErrorKey=v, NSValidationErrorValue=null
NSValidationErrorKey=entityDicMoveNr, NSValidationErrorValue=null
NSValidationErrorKey=historyBackup, NSValidationErrorValue=null

The errors appear before test code executes — during SwiftData's internal DefaultStore auto-save. Properties that are always initialized in Swift show as nil in the Core Data layer.

What we verified

  • Each run uses a fresh xctest process (different PIDs)
  • Container creation succeeds (no errors in our ModelContainer init)
  • The @Model init always sets all fields — confirmed with debug prints
  • Deleting DerivedData before each run fixes it (but forces a full rebuild)

What didn't help

  • Using ModelContext(container) instead of container.mainContext
  • Setting autosaveEnabled = false on both mainContext and custom contexts
  • Using /dev/null URL instead of isStoredInMemoryOnly: true
  • build-for-testing + test-without-building
  • Clearing only Logs/Test or TestResults subdirectories

Why not run via swift test?

We can't fall back to swift test because our project uses RealityKit custom components, which silently fail to decode in CLI swift test. So xcodebuild test is our only option, making the DerivedData workaround especially costly.

Workaround

Delete DerivedData before each xcodebuild test invocation.

Environment

macOS 15.5, Xcode 16.4, Swift Testing with @Suite @MainActor parallel test suites.

Question

Is there a way to fully isolate in-memory ModelContainer instances so that no metadata leaks between xcodebuild test runs without requiring a full DerivedData clean?

Thanks for reporting the issue. Do you have a minimal project that reproduces the issue? If yes, I'd be intersted in taking a look.

Also, I am wondering if calling erase() before exiting your test case helps?

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

SwiftData in-memory ModelContainer causes DefaultStore validation errors on consecutive xcodebuild test runs
 
 
Q