A cook archived a recipe on an iPhone and added structured servings, two features from version 4.0. That evening they opened the same recipe on an older iPad. The iPad cannot install iPadOS 27, so the App Store had given it the last compatible build, 3.9.

Version 3.9 decoded the recipe and met a status it had never seen: "archived". The repository wrapped decoding in try?, decided the record was corrupted, and “repaired” it with a fresh draft. Sync uploaded the repair. The iPhone received a newer modification and accepted it.

The archive was undone and the servings were gone. Nothing crashed. No log on any 4.0 device recorded a failure.

The question that owns this bug is not “what does 4.0 do?” It is “which binaries can still write this record?” Most teams can name one: the build they just tested.

Count the binaries, not the devices

Release notes describe one version. Your data is shared by several.

A synced record is read by the current build on this device, by older builds on the user’s other devices, and by the last compatible build on hardware that will never run your new minimum OS. It may also be read by a watch app on its own update schedule, by a widget reading an App Group container, and by a server answering clients from three releases ago.

Automatic updates do not close that gap. They arrive at different times on different devices, users can turn them off, and raising the deployment target guarantees that some devices stay on your last compatible build for good. A minimum-version bump creates a permanent population of old clients, and many of them share an iCloud account with someone’s new phone.

Three questions belong in every review of a model change:

  • Which older builds will read data written by this one?
  • What does each of them do with a value it does not recognize?
  • When an older build writes the record back, what does it erase?

Upgrade testing answers none of them. It moves old data into new code. The failure above moves new data into old code, and almost nobody keeps a device set up for that direction.

Unknown is not invalid

Synthesized Codable for a String-backed enum throws when it meets an unrecognized raw value. As a parser default, that is reasonable. As a policy for synced data, it is ruinous: a value this build does not understand is treated as a value nobody should keep.

Model the case you have not written yet:

SwiftGitHub
enum RecipeStatus: Sendable, Equatable {
    case draft, published
    case unrecognized(String)

    var rawValue: String {
        switch self {
        case .draft: "draft"
        case .published: "published"
        case .unrecognized(let raw): raw
        }
    }
}

extension RecipeStatus: Codable {
    init(from decoder: Decoder) throws {
        let raw = try decoder.singleValueContainer().decode(String.self)
        switch raw {
        case "draft": self = .draft
        case "published": self = .published
        default: self = .unrecognized(raw)
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValue)
    }
}

An .unrecognized status is a fact the interface still has to honor. Show the recipe read-only, hide actions whose meaning depends on the status, and offer an update. Do not collapse it to .draft because the switch wanted a default.

Now the uncomfortable part. This code protects 4.0’s data only if it shipped in 3.9. Forward compatibility is a property of the old binary. You cannot add it on the day you add the new status, because the build that needs it is already on the user’s iPad.

So the work happens one release before the feature exists. Every model change becomes two steps: ship a build that tolerates the new value, then ship the feature that writes it.

Round-trip what you do not understand

Synthesized Codable has a second, quieter habit. On decode it ignores keys it does not know. On encode it writes only the keys it does. Any older build that edits a record therefore deletes every field added after it was compiled.

The answer is to keep what you cannot interpret and write it back untouched:

SwiftGitHub
import Foundation

enum JSONValue: Codable, Equatable, Sendable {
    case string(String), number(Double), bool(Bool)
    case array([JSONValue]), object([String: JSONValue]), null

    init(from decoder: Decoder) throws {
        let c = try decoder.singleValueContainer()
        if c.decodeNil() { self = .null }
        else if let v = try? c.decode(Bool.self) { self = .bool(v) }
        else if let v = try? c.decode(Double.self) { self = .number(v) }
        else if let v = try? c.decode(String.self) { self = .string(v) }
        else if let v = try? c.decode([JSONValue].self) { self = .array(v) }
        else { self = .object(try c.decode([String: JSONValue].self)) }
    }

    func encode(to encoder: Encoder) throws {
        var c = encoder.singleValueContainer()
        switch self {
        case .string(let v): try c.encode(v)
        case .number(let v): try c.encode(v)
        case .bool(let v): try c.encode(v)
        case .array(let v): try c.encode(v)
        case .object(let v): try c.encode(v)
        case .null: try c.encodeNil()
        }
    }
}

struct FieldKey: CodingKey {
    let stringValue: String
    var intValue: Int? { nil }
    init(_ name: String) { stringValue = name }
    init?(stringValue: String) { self.stringValue = stringValue }
    init?(intValue: Int) { return nil }
}

struct Recipe: Codable, Equatable, Sendable {
    var id: UUID
    var title: String
    var status: RecipeStatus
    var writtenBySchema: Int
    private(set) var fieldsFromNewerVersions: [String: JSONValue] = [:]

    static let currentSchema = 3
    private static let knownFields: Set<String> =
        ["id", "title", "status", "writtenBySchema"]

    init(id: UUID, title: String, status: RecipeStatus) {
        self.id = id
        self.title = title
        self.status = status
        self.writtenBySchema = Self.currentSchema
    }

    init(from decoder: Decoder) throws {
        let c = try decoder.container(keyedBy: FieldKey.self)
        id = try c.decode(UUID.self, forKey: FieldKey("id"))
        title = try c.decode(String.self, forKey: FieldKey("title"))
        status = try c.decode(RecipeStatus.self, forKey: FieldKey("status"))
        writtenBySchema = try c.decodeIfPresent(
            Int.self, forKey: FieldKey("writtenBySchema")) ?? 1

        for key in c.allKeys where !Self.knownFields.contains(key.stringValue) {
            fieldsFromNewerVersions[key.stringValue] =
                try c.decode(JSONValue.self, forKey: key)
        }
    }

    func encode(to encoder: Encoder) throws {
        var c = encoder.container(keyedBy: FieldKey.self)
        for (name, value) in fieldsFromNewerVersions {
            try c.encode(value, forKey: FieldKey(name))
        }
        try c.encode(id, forKey: FieldKey("id"))
        try c.encode(title, forKey: FieldKey("title"))
        try c.encode(status, forKey: FieldKey("status"))
        try c.encode(Self.currentSchema, forKey: FieldKey("writtenBySchema"))
    }
}

Known fields are encoded after the preserved ones, so a value this build owns always wins. fieldsFromNewerVersions is private(set) because this build has no business editing data whose meaning it does not know.

JSONValue stores numbers as Double, so integers above 2⁵³ lose precision. Encode large identifiers and money as strings, as you should across any JSON boundary.

The same pattern serves CloudKit records, App Group files, and server payloads. The rule is the point: a build may rewrite only the fields it understands.

Send the edit, not the record

Preservation on the client has a limit: it protects data only in builds that already preserve it. The servings on the cook’s iPad were also exposed to a simpler path. The old build changed one field and sent the whole struct back to an endpoint that replaces the record. The decoder accepted the newer document. The encoder wrote the fields the old model knew. The server did exactly what its endpoint promised.

Two questions hide inside every Save. Which fields did the user intend to change? Is the copy they edited still current? A whole-record PUT answers neither, and a revision check answers only the second: the old build read revision 7, so its replacement is “current,” and it still erases the servings.

For a rename, the server should accept a rename:

SwiftGitHub
struct RenameRecipe: Encodable, Sendable {
    let title: String
    let expectedRevision: Int
}

struct StoredRecipe: Decodable, Equatable, Sendable {
    var title: String
    let status: String
    let servings: Int
    var revision: Int
}

enum RenameError: Error, Equatable {
    case revisionMismatch
}

actor RecipeStore {
    private var recipe: StoredRecipe

    init(_ recipe: StoredRecipe) {
        self.recipe = recipe
    }

    func rename(_ command: RenameRecipe) throws -> StoredRecipe {
        guard recipe.revision == command.expectedRevision else {
            throw RenameError.revisionMismatch
        }
        recipe.title = command.title
        recipe.revision += 1
        return recipe
    }

    func snapshot() -> StoredRecipe { recipe }
}

The actor makes the behavior executable in memory. In the service, the same rule is one conditional update in the database, scoped to a recipe the caller is authorized to edit. On a mismatch, return a conflict, keep the unsaved title in the editor, and show the latest title before offering a retry. Resubmitting automatically against the new revision would erase someone else’s rename.

Then look at the clients you have already shipped. If the oldest supported build can still replace whole records, a careful new client changes nothing for those installs. Where a legacy request’s intent is unambiguous, the server can translate it into a field-level change. Where it cannot tell what the request should preserve, it should refuse the write and give the user a way to recover. A document editor that genuinely writes the whole file needs a representation that preserves unknown content, or it should open newer documents read-only.

Preserving a field does not keep it correct

Preservation keeps the bytes. It does not keep the meaning.

Suppose 4.0 stores a searchTitle derived from title. Version 3.9 renames the recipe and faithfully writes back the old searchTitle. The field survived, and it is now wrong.

That is why the record says which schema last wrote it. Version 3.9 always writes writtenBySchema: 3, even when it carries 4.0’s fields. When 4.0 reads a record last written by schema 3, it knows its own fields may be stale and recomputes everything it can derive from the fields it shares with older builds.

Sort new fields into two kinds as you design them:

  • Independent facts, such as servings, which an older build cannot invalidate because it never touches what they describe.
  • Derived or coupled values, which a newer build must revalidate after an older one writes.

A field that fits neither kind is usually coupled to an existing one in a way the old build will break.

Never repair what you cannot read

The most damaging line in the story was not the enum. It was the repair:

SwiftGitHub
let recipe = (try? decoder.decode(Recipe.self, from: data)) ?? Recipe.empty

That line turns “I do not understand this” into “this should be replaced.” Sync then carries the replacement to every device, including the one that understood the original.

A decoding failure on persisted or synced data should quarantine, never overwrite. Keep the original bytes, mark the record unreadable by this build, exclude it from writes, and report the schema version and failing key path without the user’s content. If the interface must show something, show that the item needs a newer version.

Repair is a legitimate feature. It requires knowing what the data was supposed to mean, and a build that cannot decode the record does not know.

The platform will not do this for you

Some infrastructure assumes the problem away. Some of it makes the problem permanent.

CloudKit’s production schema is additive. Once a field is deployed you cannot delete it or change its type, so a field shipped by mistake stays, and every later build lives with it. A SwiftData or Core Data migration plan describes how to move a store forward. Nothing in it tells yesterday’s binary how to read tomorrow’s data.

Servers have the same problem, with one advantage: they see every client version that calls them. Record the app version on each write, and before removing a field from a response, check whether a client still in use depends on it. A forced-update screen is a product decision with a cost to users. It should not be the only thing standing between you and a broken data model.

Test with data from the future

Keep a fixture written by a version you have not shipped yet: a new enum case, a new nested field, a higher schema number. Prove that today’s build reads it, edits it, and leaves what it does not own intact:

SwiftGitHub
import Foundation
import Testing

@Test func aNewerRecordSurvivesAnEditByThisBuild() throws {
    let fromVersion4 = Data("""
    {"id":"6F9619FF-8B86-D011-B42D-00C04FC964FF","title":"Ragù",
     "status":"archived","writtenBySchema":4,
     "servings":{"count":4,"unit":"people"}}
    """.utf8)

    var recipe = try JSONDecoder().decode(Recipe.self, from: fromVersion4)
    #expect(recipe.status == .unrecognized("archived"))

    recipe.title = "Ragù alla bolognese"
    let written = try JSONEncoder().encode(recipe)
    let fields = try JSONDecoder().decode([String: JSONValue].self, from: written)

    #expect(fields["servings"] == .object(["count": .number(4), "unit": .string("people")]))
    #expect(fields["status"] == .string("archived"))
    #expect(fields["writtenBySchema"] == .number(3))
}

And test what the old build actually sends, against the authority that keeps the record:

SwiftGitHub
@Test func aRenameLeavesNewerFieldsAlone() async throws {
    let payload = Data("""
    {"title":"Ragu","status":"archived","servings":4,"revision":7}
    """.utf8)
    let store = RecipeStore(try JSONDecoder().decode(StoredRecipe.self, from: payload))
    let command = RenameRecipe(title: "Ragù", expectedRevision: 7)

    let body = try JSONEncoder().encode(command)
    let sent = try #require(JSONSerialization.jsonObject(with: body) as? [String: Any])
    #expect(Set(sent.keys) == ["title", "expectedRevision"])

    let saved = try await store.rename(command)
    #expect(saved == StoredRecipe(title: "Ragù", status: "archived", servings: 4, revision: 8))

    await #expect(throws: RenameError.revisionMismatch) {
        try await store.rename(command)
    }
    #expect(await store.snapshot() == saved)
}

Cover the other direction as well. At every release, save a real, anonymized payload written by that build and keep it in the test target for good. Those files are the only record of what your old binaries actually wrote, and those binaries will still be writing long after you have forgotten them.

Test the failure nobody sees: decode a record with a corrupted field and assert that nothing was written back. A test that checks only the screen will miss a record that was overwritten.

Then keep one physical device on your last compatible OS. Sign it into the same iCloud account as your current device, and edit the same record on both, every release.

What to ask of your own code

  • Which shipped builds can still write this record, and what does each do with a value it does not recognize?
  • Does any decoding failure lead to a write?
  • Does Save send the change the user made, or the whole record the build happens to know?
  • Did the tolerance for this new field ship one release before the field?
  • Is there a fixture from the future in the test target?

The compiler checks one build at a time. Your users run all of them. The cook does not know which version is on which device; they only know whether the recipe they archived stayed archived.

References

If this edition sharpened your next review, you can buy me a coffee.