Skip to content

CloudKit data loss after deleting then re-inserting record with the same UUID #418

Closed

Description

@jsutula

Description

I stumbled across this issue after refactoring an ItemAsset-like table to no longer have its own UUID and instead use the foreign key into its parent table (Item.ID), as suggested in the documentation's uniqueness constraints section.

Pre-refactor (distinct ItemAsset.ID UUID field), the process to update an ItemAsset record consisted of two-steps:

  1. Delete all ItemAsset records having a specific itemID foreign key (there could be multiple records and the goal was to have just one)
  2. Insert a fresh ItemAsset record.

Post-refactor (combined PK/FK ItemAsset.itemID), the initial step to delete should no longer be necessary (only one ItemAsset record per Item record, enforced by new PK), however, I missed this, and the delete step remained in place. So the steps remained roughly the same:

  1. Delete ItemAsset record having a specific itemID PK+FK
  2. Upsert ItemAsset record.

With the new delete-then-reinsert setup, when an ItemAsset record exists and is updated, only the deletion of the record is synchronized to CloudKit, not the insert, resulting in unexpected data loss. The ItemAsset record remains visible on the device which performed the update, but will be deleted on all other devices after the next CloudKit sync.

I've reproduced this behavior with a simple addition to the CloudKitDemo example project (introducing a CounterAsset table and "Update asset" button):

  1. Draft PR with 100% repro setup: Repro CloudKit data loss on delete-then-reinsert #417
  2. Repro video
    • Observe alternating (data loss) -> (asset present) -> (data loss)... pattern. Presumably every other "Update asset" succeeds because there's no CloudKit record to delete anymore, so the insert makes its way through.

Note: another precondition of this behavior is that delete and reinsert events need to occur within a couple seconds of each other (to be part of the same sync batch). If they are spaced out further than that and end up in separate sync batches, the issue does not reproduce.

In my case, this behavior was easy to work around (just remove the unnecessary delete), but I think this still warrants either a fix or at least an update to documentation and Point-Free Way skills warning against this pattern.

Checklist

  • I have determined whether this bug is also reproducible in a vanilla SwiftUI project.
  • I have determined whether this bug is also reproducible in a vanilla GRDB project.
  • If possible, I've reproduced the issue using the main branch of this package.
  • This issue hasn't been addressed in an existing GitHub issue or discussion.

Expected behavior

Ideally, the local delete-then-reinsert events in this scenario should be collapsed to a single CloudKit update event (not delete). But if that's infeasible, or this really does just represent an anti-pattern, then there should be a developer-facing error/issue thrown when SyncEngine detects this situation.

Actual behavior

Copy/pasted from Description:

With the new delete-then-reinsert setup, when an ItemAsset record exists and is updated, only the deletion of the record is synchronized to CloudKit, not the insert, resulting in unexpected data loss. The ItemAsset record remains visible on the device which performed the update, but will be deleted on all other devices after the next CloudKit sync.

I've reproduced this behavior with a simple addition to the CloudKitDemo example project (introducing a CounterAsset table and "Update asset" button):

  1. Draft PR with 100% repro setup: Repro CloudKit data loss on delete-then-reinsert #417
  2. Repro video
    • Observe alternating (data loss) -> (asset present) -> (data loss)... pattern. Presumably every other "Update asset" succeeds because there's no CloudKit record to delete anymore, so the insert makes its way through.

Note: another precondition of this behavior is that delete and reinsert events need to occur within a couple seconds of each other (to be part of the same sync batch). If they are spaced out further than that and end up in separate sync batches, the issue does not reproduce.

Reproducing project

Draft PR: #417

SQLiteData version information

65502ac

Sharing version information

2.7.4

GRDB version information

7.9.0

Destination operating system

iOS 26

Xcode version information

Xcode 26.3

Swift Compiler version information

Activity

  1. added
    bug
    on Mar 8, 2026
  2. aehlke commented on May 9, 2026

    @aehlke

    Sorry to ping but is something blocking this from getting merged? It sounds like a pretty critical issue that is easy to repro and causes data loss. Thank you

  3. added a commit that references this issue on Jun 1, 2026
    399663a
  4. jonphillips commented on Jul 30, 2026

    @jonphillips

    First and foremost, love Pointfree and all you do. Ecstatic subscriber.

    We hit what looks like the same underlying defect from a different entry point — a server-side / restore path rather than a single-device delete-then-reinsert — and it causes silent cross-device data loss. Sharing the root-cause analysis in case it helps, since it points at one shared cause.

    Root cause: nothing ever resets _isDeleted to false in place

    Grepping the CloudKit sources (1.8.2), _isDeleted is only ever:

    • set to true — the user-delete and primary-key-change triggers (Triggers.swift, .update { $0._isDeleted = true }), and
    • cleared by hard-removing the whole metadata row — afterDeleteFromSyncEngine (.delete() when isSynchronizing).

    No code path sets _isDeleted = false on an existing metadata row. So whenever a primary key is re-materialized and the write lands on the existing (flagged) metadata row, the flag stays 1 and the engine continues to treat the live row as deleted. The two write paths that should clear it don't:

    • Local reinsert (this issue, Repro CloudKit data loss on delete-then-reinsert #417's repro): SyncMetadata.insert(new:) uses onConflictDoUpdate: { _ in } — an empty conflict clause — so the reinsert leaves _isDeleted = 1.
    • Server resurrection / restore (our case): upsertFromServerRecord's doUpdate sets only zoneName/ownerName (and later lastKnownServerRecord), never _isDeleted. So a record that returns from the server for a locally-tombstoned PK is written back alive but still flagged deleted.

    Our scenario (cross-device, via SyncEngine-backed backup/restore)

    App is a two-device iCloud-synced SQLite library with a local backup/restore feature (restore wipes the metadatabase → recordTypes empty → start() re-pushes the whole library).

    1. Device B deletes recipe R (recipe + child rows). The delete is committed locally but held un-sent (in our app a UI crash forces relaunch; equivalently: an offline or backgrounded device). At rest, B's metadata holds _isDeleted = 1 for R + children, each with a lastKnownServerRecord.
    2. Device A restores a backup containing R and re-enables sync — A authoritatively re-pushes R (alive) to the zone.
    3. B relaunches. Because syncChanges sends before it fetches, B pushes its held delete first, which wins the collision and removes R from the zone, overriding A's restore. R is then gone on every peer — B fetched back the other restored records but never R, confirming the zone no longer has it.

    Measured end-to-end in an isolated container (fresh Apple ID, two simulators): the restored recipe was silently re-deleted everywhere.

    Why it's the same bug

    Both are "a delete for a recordID dominates a save for the same recordID because the tombstone flag is never reconciled away when the record comes back." #418 surfaces it as a co-batched local reinsert; the restore path surfaces it as a resurrection losing to a stale/held tombstone — which is is rough because restore is exactly the recovery operation a user reaches for after data loss, and it gets stomped on.

    Suggested direction

    Clear _isDeleted (and drop any queued delete) wherever a primary key is re-materialized onto an existing metadata row — i.e. a non-empty onConflictDoUpdate in SyncMetadata.insert, and resetting _isDeleted = false in upsertFromServerRecord's doUpdate when the incoming server record re-materializes a tombstoned PK. Happy to share the isolated-container repro / measurements if useful.

  5. jsutula commented on Nov 9, 2026

    @jsutula
    ContributorAuthor

    Fixed by #575 which was included in 1.13.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions