Test iOS autosave revision ordering on a cloud Mac

Test iOS autosave revision ordering on a cloud Mac

Test iOS autosave revision ordering on a cloud Mac

A customer makes two consecutive edits in the editor. The interface shows the newer version, only for an older autosave to overwrite it moments later. When a contract development studio temporarily adds a cloud Mac for pre-delivery regression testing, this should become a deterministic test—not an exercise in typing quickly and hoping to reproduce the bug. The standalone Swift fixture below checks save ordering without launching a simulator.

Define the save contract first

Each document maintains an increasing revision number, and the content snapshot must be created together with its revision. Assign the number within the isolation domain that owns the editing state—for example, a document model on the main thread. Do not wait until a background task starts running to assign it, or an older snapshot could receive a higher number.

This example assumes a single process and one store instance per document. Each save replaces the entire snapshot; there is no text merging:

  • Requests with a revision newer than the current one may write.
  • Older and duplicate revisions are rejected immediately.
  • The file stores both the content and the revision, so comparisons continue after a restart.
  • A failed write must not advance the saved revision held in memory.

A request with the same revision but different content is also rejected, and the caller must log it as a violation of the revision-numbering contract. If your application needs duplicate requests to return success, add a content-digest comparison rather than allowing them to overwrite the file.

Atomic replacement prevents readers from seeing a partially written file. Revision numbers prevent a complete older file from overwriting a complete newer one. Neither replaces the other.

Implement a write section with no suspension points

Create AutosaveCheck.swift on the cloud Mac and add the following code. You need a working Swift toolchain. Check the environment with swiftc --version, then keep its output with the acceptance-test records.

import Foundation

struct Snapshot: Codable, Sendable {
    let revision: UInt64
    let text: String
}

actor RevisionStore {
    private let url: URL
    private var savedRevision: UInt64?

    init(url: URL) throws {
        self.url = url
        if FileManager.default.fileExists(atPath: url.path) {
            let data = try Data(contentsOf: url)
            savedRevision = try JSONDecoder()
                .decode(Snapshot.self, from: data).revision
        }
    }

    func save(_ snapshot: Snapshot) throws -> Bool {
        if let current = savedRevision,
           snapshot.revision <= current {
            return false
        }

        let data = try JSONEncoder().encode(snapshot)
        try data.write(to: url, options: .atomic)
        savedRevision = snapshot.revision
        return true
    }
}

File writes are synchronous here, with no await between the comparison, replacement, and update of the saved-revision watermark. Another save request therefore cannot enter the same instance midway through a write. The trade-off is that file operations block the executing thread, so this approach is suitable for small documents with an explicit size limit. Large files need a dedicated serial writer; simply moving the write into an asynchronous task invalidates this reasoning.

If the existing file is corrupt, initialization throws instead of treating it as an empty document and overwriting it. The caller must also create the parent directory beforehand.

Reproduce a stale request with a fixed execution order

Append the entry point to the same file. Save revision two first, then submit revision one to simulate an older request delayed by scheduling. This is more reliable than adding random sleeps and does not depend on node load.

@main
struct AutosaveCheck {
    static func main() async throws {
        let root = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString)
        try FileManager.default.createDirectory(
            at: root,
            withIntermediateDirectories: true
        )
        defer { try? FileManager.default.removeItem(at: root) }

        let url = root.appendingPathComponent("document.json")
        let store = try RevisionStore(url: url)

        let fresh = try await store.save(
            Snapshot(revision: 2, text: "new")
        )
        let stale = try await store.save(
            Snapshot(revision: 1, text: "old")
        )
        let duplicate = try await store.save(
            Snapshot(revision: 2, text: "unexpected")
        )
        precondition(fresh && !stale && !duplicate)

        let restored = try RevisionStore(url: url)
        let replayed = try await restored.save(
            Snapshot(revision: 1, text: "replayed")
        )
        precondition(!replayed)

        let cleared = try await restored.save(
            Snapshot(revision: 3, text: "")
        )
        precondition(cleared)

        let disk = try JSONDecoder().decode(
            Snapshot.self,
            from: Data(contentsOf: url)
        )
        precondition(disk.revision == 3 && disk.text.isEmpty)
    }
}

Compile and run:

swiftc -parse-as-library AutosaveCheck.swift -o autosave-check
./autosave-check

Only a zero exit code means the assertions passed. The fixture deliberately avoids sleeps and does not treat “it worked several times” as an ordering guarantee. The new instance exists only to simulate a restart; no further requests are sent to the old instance.

Add failure and recovery checks

Acceptance testing must go beyond successful writes. Create a separate fixture, remove the test user's write permission from the directory containing an existing valid file, then submit a higher revision. The write should throw; after restoring permissions, retrying the same revision should succeed. Do not run this test as a privileged user, and restore permissions during exit cleanup.

Next, replace a separate test file with truncated JSON. Verify that initialization throws and that the bytes remain unchanged. An empty string, by contrast, is valid content. Revision three above already covers this case: clearing a document must not be mistaken for having nothing to save.

Atomic replacement is not a guarantee of durability after power loss, nor is it a substitute for backups. Products that require recovery from power loss must separately validate their filesystem and synchronization strategy.

Integrate with the editor and delivery pipeline

The interface's “Saved” indicator must be tied to the confirmed revision. If the user has already edited revision three when revision two finishes saving, the document as a whole must not be marked as saved. Canceling a debounce task also does not undo an operation that has already entered the file-writing stage; correctness still depends on revision comparisons.

For delivery, retain the toolchain version, commit hash, test exit code, and names of failure scenarios. Do not archive the contents of customer documents. After extracting the store type into a shared module, have application tests call that same implementation directly. This prevents the fixture from passing while the product still uses different save logic.

Finally, check the boundaries: multiple windows must share the same document instance; writes across processes require additional coordination; and reaching the maximum revision number must either block further editing or trigger an explicit migration, never wrap around. Put these constraints in the interface contract so autosave has a reproducible basis for acceptance testing.

Frequently asked questions

Can autosave requests arrive out of order when using an actor?

Yes. Actor isolation does not preserve the order in which a user created edits. Compare revision numbers at the save boundary, and revalidate state if the critical section suspends.

Does atomic file writing prevent stale overwrites?

No. Atomic replacement prevents readers from seeing a partially written destination file. Reject stale revisions separately and advance the in-memory revision only after a successful write.

Add a cloud Mac for your project

Dedicated Apple Silicon M4 physical nodes, available by the day, week, month, or quarter. Your rental stops at the end of the term—no idle machines after your project wraps up.

Choose a rental term

Rent a Mac for your project

Dedicated Apple Silicon M4 physical nodes, available by the day. Your rental stops at the end of the term.