Repository navigation
Features Utilities Durable File Guarantees
This page defines what DurableFile promises today, what it does not promise, and the design
options for a stronger multi-file transaction API. It is the design record for
#1354.
- Scope
- Definitions
- Current guarantees
- Platform matrix
- Failure model
- Design options
- Recommendation
- Prototype plan
- Remaining acceptance
DurableFile stages a complete file in the destination directory, forces the staged bytes toward
storage, and publishes the staged file with a replacement primitive. It also owns a per-path
cooperating-writer lock. It does not own the destination format, the caller's schema, or writers
that bypass its API.
The design question is whether an opt-in API can give package-owned data stronger guarantees for one file and for a group of files while keeping existing saves and readers compatible.
- Atomicity means a reader observes either the old state or the new state, never a torn or partially published state.
- Consistency means the published state satisfies the caller's schema and digest rules. A complete file is not automatically a valid document.
- Isolation means concurrent cooperating operations do not observe each other's staged state. Isolation is not protection from tools that write the same path directly.
- Durability means a completed operation survives a process crash and, where the platform supports it, a power loss. File-data and directory-entry durability are separate barriers.
For a single file, a successful publication is atomic on supported local file systems, with optional directory-entry durability. A failed Windows restoration can leave the destination absent with only the named backup, so a failure is not an old-or-new atomic outcome. For several files, the current API provides ordered moves, not atomicity.
The existing API (TryWriteAllText, TryWriteAllBytes, TryCopy, TryReadAllBytes,
TryAppendAllText, TryDelete, TryCompareExchangeBytes, TryMoveWithSidecars) provides:
- Whole-file writes and copies stage unique sibling files and publish complete contents.
- A supported replacement preserves the previous destination until the new file is ready.
- On Windows, a failed replacement can retain a named backup and identify its path in the error.
- A failed staging cleanup can leave a sibling stage file. Public write and copy errors do not carry
that stage path; identify it by
DurableFile.TemporarySuffixin the destination directory. - Cooperating writes, copies, appends, deletes and compare-and-exchange operations serialize per destination in the process.
- On local Windows, macOS and Linux file systems that support the required locks, cooperating processes share the same destination lock. A competing owner reports failure and can retry.
-
TryCompareExchangeBytes(..., syncParentDirectory: true)waits for the directory update on supported Linux file systems and local Windows NTFS. If that directory barrier fails after the value was exchanged, the method returnsfalsewhilerestoredistrueand the new file stays live. Read the current state before retrying; the failed barrier does not reverse publication. - Ordinary writes on macOS request a hardware file flush where the volume supports it.
- Unsupported replacement reports failure and leaves the existing destination in place. An absent destination is created with an exclusive move.
It does not provide:
- Atomicity across several paths.
TryMoveWithSidecarsmoves the database first and each present sidecar afterward; a crash between moves can leave a mixed group. - A durable directory entry by default. A power loss can lose the rename even when the file data reached storage.
- Isolation from non-cooperating writers, network file systems, tools that replace the lock file, or writers that resolve the same path differently.
- Atomic append. An interrupted append can leave a partial final record.
- A browser storage contract. WebGL uses the browser's file-system shim, whose replacement and quota behavior is outside the desktop matrix.
Supported means the repository exercises the behavior in its platform controls. Best effort
means the API reports failure rather than claiming the guarantee, but the repository has not
qualified every runtime and file system. Unqualified means the path is untested here.
| Platform | Single-file replace | File-data barrier | Directory barrier | Cross-process lock | Multi-file transaction |
|---|---|---|---|---|---|
| Windows Editor/Standalone (local NTFS/ReFS) | Supported, with backup and sharing retries | Supported | Supported with syncParentDirectory: true on local NTFS |
Supported on local file systems | Not provided |
| Linux Editor/Standalone (ext4/XFS/Btrfs) | Supported; File.Replace for existing files, renameat2(RENAME_NOREPLACE) for exclusive create |
Supported | Supported with syncParentDirectory: true
|
Supported on local file systems | Not provided |
| macOS Editor/Standalone (APFS/HFS+) | Supported; File.Replace for existing files, renamex_np(RENAME_EXCL) for exclusive create |
Supported with a hardware flush where the volume allows | Unqualified; syncParentDirectory is unavailable |
Supported on local file systems | Not provided |
| Android (ext4/F2FS) | Best effort; Unix rename semantics | Best effort | Unqualified | Unqualified | Not provided |
| iOS (APFS) | Best effort; Unix rename semantics | Best effort | Unqualified | Unqualified | Not provided |
| WebGL (browser file-system shim) | Best effort; replacement may be unsupported | Best effort | Unqualified | Not applicable | Not provided |
The matrix intentionally separates file-data and directory-entry durability. A successful
Flush(true) does not prove that the directory entry survived a power loss. Only a platform and
file system that honor both barriers can make that claim.
| Boundary | Observed or possible state | Reader behavior | Recovery |
|---|---|---|---|
| Before staging | Destination is unchanged | Old document | Retry |
| During staging | A unique sibling stage exists; destination is unchanged | Old document | Remove the stage on retry; best-effort cleanup |
| After staging flush, before replace | Stage is complete; destination is unchanged | Old document | Retry publication or discard the stage |
| During replace | The platform either preserves the old name or leaves a named backup. On Windows, restoration can fail after the old name was moved aside. | Old or new document; on an unreported restoration failure the destination can be absent and only the named backup remains | Retry; inspect the backup path on Windows |
| After replace, before directory barrier | New document is visible; the directory entry may be lost on power failure | New document | Use syncParentDirectory where supported |
| During a multi-file group move | A caught failure can leave some paths moved; a process crash has no automatic recovery | Mixed group after a crash | Caught failures get best-effort RestoreSidecarMoves; a crash needs caller reconciliation |
| Browser quota or persistence failure | Publication may fail after the stage is written | Old document or a reported failure | Report failure; do not claim durability |
The supported failure model is fail-closed: an operation that cannot establish the promised state
returns false or an exception object and keeps the previous destination where possible. A Windows
replacement failure can name a retained backup; a staging cleanup failure can leave a sibling stage
without a path in the returned error. A caller must treat a failed multi-file operation as a
reconciliation problem, not as an automatic rollback.
Keep the single-file stage, flush and replace path. Add only documentation and narrower helpers.
Strengths: no format change, lowest latency and space, proven by the existing controls.
Limits: no group atomicity; recovery after a crash between group moves is the caller's job.
A journal that records only paths and operations cannot restore an overwritten file. The transaction must preserve a before-image for every destination before it changes that destination.
For each path, record whether the destination exists. If it exists, copy it to a unique, durably flushed undo file in the same directory and record that undo path; leave the destination untouched until the journal is durable. Do not move the destination before the journal is durable: a crash between the move and the journal write would leave no recoverable record. A hard link may substitute for the copy only when the file system supports it and the source is not modified in place. If the destination does not exist, record the absence so recovery can delete a partially published file. Write the versioned journal, including the intended operations, the undo paths, the existence flags and a digest of the group, then flush the journal and its directory entry. Only after that barrier may the transaction change a destination.
Apply the replacements, flush each new destination's file data and its parent directory entry, then flush the commit record. Retain the undo files until the commit record is durable. If a platform cannot flush the directory entry, the transaction reports a weaker durability outcome rather than claiming the stronger guarantee. Recovery reads the journal. With no commit record, it restores each undo file over its destination, deletes a destination that was recorded absent, verifies the digest, and removes the journal. With a commit record, it keeps the new files and removes the undo files only after confirming the destinations are durable; otherwise it restores the undo files. Recovery is idempotent, so a crash during recovery can rerun the same steps. An orphan undo file is identified by its transaction id and cleaned on a later open.
Strengths: works with existing file formats; bounded extra writes; restores the previous group after a crash; portable to desktop file systems; recovery can be idempotent and retried.
Limits: up to twice the live data is present during the transaction; one journal write and directory barrier per transaction; recovery must distinguish committed from uncommitted records; non-cooperating readers can observe intermediate files unless they also use the transaction API.
Write each new file under a generation-qualified name, flush them, then atomically replace one small commit record. Readers resolve the current generation from the commit record. The previous generation remains readable until the new one is committed.
Strengths: readers see a complete old or new generation; recovery is a matter of reading the commit record; no in-place rollback of data files.
Limits: roughly doubles space for the live set; requires readers to resolve a manifest; cleanup of old generations must tolerate crashes; the commit record still needs a directory barrier for durability.
Use SQLite's rollback journal or WAL for callers that can adopt a managed database format.
Strengths: mature ACID implementation, concurrent readers, proven crash recovery, single-file storage.
Limits: a native dependency with IL2CPP and WebGL complications; a format migration for existing saves; larger binary and memory cost; unsuitable for callers that must keep their existing files.
Proceed with option 2 (rollback journal with before-images) for an opt-in multi-file transaction API, starting on Windows, Linux and macOS. Keep every existing single-file API and on-disk format unchanged. Use the journal only when a caller explicitly opens a transaction.
Use option 3 later if measured read-mostly workloads show that generation files are cheaper or
simpler to recover than a journal. Keep option 4 consumer-owned: support SQLite users through
TryMoveWithSidecars and a documented reconciliation step, but do not add a SQLite dependency to
the package.
For WebGL, expose only the existing single-file API and report quota or persistence failures. Do not claim multi-file atomicity in the browser.
- Implement the transaction engine as real internal production code. The test assembly reaches it
through the existing
InternalsVisibleTodeclaration. The prototype has no public API, and no member exists solely for tests; production code owns the behavior. - Record a versioned journal with a stable schema name, a digest of the intended operations, each destination, each stage path, each before-image path, each destination's prior existence, and a commit marker. Flush the journal and its directory entry before changing any destination.
- Kill the process at each boundary: after the before-images are flushed, after journal write, after the first file replace, after all replaces but before destination durability, after destination durability but before the commit marker, after the commit marker, and during journal deletion.
- On the next open, recover idempotently: restore each uncommitted destination from its before-image (or delete it when it was absent), verify the digest, then remove the journal and undo files. Repeat recovery after a crash during recovery.
- Add upgrade and rollback fixtures for the journal format. An unknown version must be refused without touching destination files.
- Measure latency, write count, space and recovery time on representative saves, including a many-small-files case and a one-large-file case.
- Publish the guarantee matrix, failure model and recommendation (this page).
- Build the journal prototype and its kill-process controls.
- Qualify Android, iOS and WebGL behavior, or state the exact unsupported boundary.
- Measure the transaction cost and recovery time on representative saves.
- Review the public API shape before promoting it from the test-only entry point.
📦 Unity Helpers | 📖 Documentation | 🐛 Issues | 📜 MIT License
- Inspector Button
- Inspector Conditional Display
- Inspector Grouping Attributes
- Inspector Inline Editor
- Inspector Overview
- Inspector Selection Attributes
- Inspector Settings
- Inspector Validation Attributes
- Utility Components
- Visual Components
- Data Structures
- Durable File Guarantees
- Helper Utilities
- Math And Extensions
- Pooling Guide
- Random Generators
- Reference Identity
- Reflection Helpers
- Singletons
- Asset Change Detection
- Asset Validation
- Authored Asset Validation
- Build Profile Scenes
- Editor Tools Guide
- Failed Tests Exporter
- Scene Canonicalization
- Sprite Animation Motion
- Test Run Reporter
- Unity Method Analyzer
- Ai Model Backends
- Bundled Assembly Conflicts
- Devcontainer Persistence
- Mcp Ecosystem
- Mcp Local Setup
- Odin Migration Guide
- Unity Devcontainer Licensing
- Agent Iteration
- Analyzers
- Baseline Tests Performance
- Bendable Line Sampling
- Bit Lookup Tables
- Dictionary Key Performance
- Enum Helpers Performance
- Enumeration Audit
- Ilist Sorting Performance
- Json Codegen Performance
- Local Pools
- Ownership Audit
- Random Performance
- Reflection Performance
- Performance
- Singleton Policy Fixtures
- Tree 2d Performance
- Tree 3d Performance
- Sprite Bounds Row Scan
- Sprite Ink Traversal
- Sprite Region Read
- Synchronous Test Lifecycle