Skip to content

Persistence Subsystem ​

The optional pixelroot32::persistence module lets a game keep small data between runs: settings, high scores, unlocks and, where the medium allows, save slots. It ships behind PIXELROOT32_ENABLE_PERSISTENCE, defaults to 0, and contributes no symbols, no Engine bytes and no Scene vtable change when it is off.

The module has four adapters: ESP-IDF NVS and a FAT microSD slot store on the ESP32, one file per record on native (PC) builds, and fixed in-RAM tables for tests. Above them, RecordCodec wraps game payloads in a self-checking envelope and PersistenceService binds a settings store and a saves store to two roles.

Rule, stated once: the engine never writes in the background. Every set, erase and commit() is a call the game makes. On the ESP32 a flash write stalls flash-resident code on both cores for milliseconds, so save at a safe point - a menu, a pause screen, a level transition - never mid-gameplay.

For setup and usage, start with the Persistence guide.


1. Models and media ​

text
Game code
   |  settings(), saves()                (roles, bound at setup)
PersistenceService  ------------------  RecordCodec (envelope + CRC-32)
   |
   |-- IKeyValueStore    typed ints, blobs, erase, commit
   `-- ISlotStore        N numbered records, replace-or-keep per slot
          ^
Adapters (one per medium)
   |-- Esp32NvsKeyValueStore / Esp32NvsSlotStore   drivers/esp32   (ESP32)
   |-- SdSlotStore                                 drivers/esp32   (ESP32)
   |-- HostFileKeyValueStore / HostFileSlotStore   drivers/native  (PLATFORM_NATIVE)
   `-- MemoryKeyValueStore   / MemorySlotStore     persistence/    (any target)

A storage model is an interface describing the shape of the data: IKeyValueStore for small named values, ISlotStore for a fixed number of numbered records. A medium is an adapter that implements one or more models over one kind of storage.

The split exists so a game never names a medium in its game logic. Code that saves a settings record talks to an IKeyValueStore&; whether that is NVS on the board or a file on the PC is decided once, where the stores are constructed. Moving saves to another medium - NVS on the board, a FAT card through SdSlotStore, an I2C EEPROM - adds an adapter and leaves the interfaces and the game logic untouched.

LayerOwnsKnows nothing about
GameWhat is stored, its schema version, migration, when to commitMedia, NVS, files
PersistenceService + RecordCodecRoles, envelope, CRC, null-store fallbackMedia
IKeyValueStore, ISlotStoreShape of the dataEnvelope, game schema
AdaptersOne medium: mapping, atomicity, error translationGame data, envelope

Adapters move opaque bytes. The envelope is validated in one place, above them, so every medium gets the same corruption checks.

Ownership ​

Engine does not own any of it. The game constructs its stores and the service, calls each adapter's init(), and binds the stores at setup. A game may also skip the service and hold a store reference directly; the service only adds the envelope helpers and the never-null role accessors.


2. The storage models ​

IKeyValueStore ​

Named values: int32_t, uint32_t and blobs. Strings go through blobs; floats are not stored as such (encode them in the game's record).

  • One value per key, last write wins. A set of any type replaces whatever the key held, so a typed get on a key that now holds another type answers NotFound.
  • A missing key is NotFound and leaves every output untouched.
  • Reads take a capacity. getBlob() never writes past capacity; when the blob is larger it answers TooLarge, writes nothing and reports the stored size. capacity == 0 is the size query.
  • commit() is the durability point, and the game's decision.

ISlotStore ​

A fixed number of numbered records, 0..slotCount()-1, each up to maxRecordSize() bytes.

  • Out-of-range slots answer InvalidArgument before the medium is touched.
  • An empty slot reads as NotFound with stored = 0. A zero-size record occupies its slot.
  • write() is replace-or-keep: after a failed or interrupted write, read() returns the previous record or the new one, never a mix. Each adapter states how it guarantees this (section 5). The one exception the interface allows is a medium that cannot replace atomically: on FAT (SdSlotStore) a power loss inside the remove-then-rename window can also leave the slot empty, which that adapter documents.

3. The record envelope ​

RecordCodec wraps a game payload in a 16-byte header, written byte by byte in little-endian order. Records are never sizeof(T) struct dumps: padding and layout differ between the host and the ESP32, and the envelope fixes byte order explicitly.

BytesFieldValue
0-3MagicASCII P R S T
4Envelope versionRecordCodec::kEnvelopeVersion (1)
5Reserved0
6-7Schema versionuint16_t, owned by the game
8-11Payload lengthuint32_t
12-15CRC-32Over bytes 0..11, then the payload
16..PayloadGame bytes

CRC coverage. The checksum is CRC-32/IEEE (the zlib/PNG CRC, reflected polynomial 0xEDB88320, check value 0xCBF43926 for "123456789"). It covers the first twelve header bytes as well as the payload, so a flipped schema version or length field is caught even though neither is compared against a fixed value. A 16-entry nibble table keeps its flash cost to 64 bytes.

Decode rejects a truncated record, a wrong magic, an unknown envelope version, a non-zero reserved byte, a length field that disagrees with the record size, and a CRC mismatch - all as Corrupt.

The schema version belongs to the game. The codec stores it and reports it on decode; it never judges it. A game that changes its record layout bumps its schema version, and on load it migrates an older version (or falls back to defaults) itself. There is no automatic migration.


4. Error model ​

Every store, adapter and codec call returns a StoreResult. There are no bare bool results and no exceptions, so a caller can always tell a missing record from a full medium or a damaged one.

StoreResultMeaningTypical cause
OkThe operation completed-
NotFoundThe key or slot holds no record; outputs untouchedFirst run, erased key, a typed get on a key of another type
TooLargeThe data does not fit the caller's buffer or the medium's limitRead buffer too small, blob above the store's maximum
NoSpaceThe medium is fullNVS partition full, disk full, memory table full
CorruptStored bytes failed validationEnvelope, length or CRC check; an NVS partition that needs an erase
IoErrorThe medium failed in a way the module cannot classify furtherFile system error, malformed host file, other NVS errors
UnavailableNo store is bound, or the medium is not initialisedUnbound role, init() not called or failed
InvalidKeyThe key or namespace breaks the key rulesToo long, empty, or a character outside [A-Za-z0-9_-]
InvalidArgumentA null pointer, an out-of-range slot or another bad parameterProgramming error

Unbound roles never dereference null. PersistenceService::settings() and saves() return a built-in null store (NullKeyValueStore, NullSlotStore) when nothing is bound. Every call on it answers Unavailable; the null slot store reports slotCount() == 0 and maxRecordSize() == 0. A game built for a target without storage keeps running with defaults.


5. Adapters and atomicity ​

AdapterMediumReplace-or-keep (S7)commit()
MemoryKeyValueStore<Entries, BlobBytes>, MemorySlotStore<Slots, RecordBytes>Fixed in-RAM tablesA write applies in full or not at allCounts calls, Ok
HostFileKeyValueStore, HostFileSlotStoreOne file per key or slotTemp file, flush and sync, then one replace-existing moveOk: every write is already in place
Esp32NvsKeyValueStore, Esp32NvsSlotStoreOne ESP-IDF NVS namespaceSame-type set: one NVS write; cross-type set: not atomic (below)nvs_commit
SdSlotStoreSD card (FAT)temp file + remove + renameno commit(); each write is flushed in place

The FAT replace is not atomic, so SdSlotStore is the one shipped adapter where the S7 old-or-new rule is weaker: a power loss between the remove and the rename leaves an empty slot, and a torn record is rejected by the envelope. Mounting is non-destructive (never formats, erases or repairs), and init() can run again after a card was removed: it probes the store directory, releases the dead volume (SD.end()) and mounts again.

Memory ​

Header-only templates with no heap: capacities are template parameters, and contents are lost with the object. They exist for tests and volatile use, and carry test hooks outside the interfaces: setFailWrites(), corruptByte(), writes() and (KV only) commits().

Host files ​

Files live under <rootDir>/<nameSpace>/ (KV) or <rootDir>/<prefix>/ (slots). A key's file name escapes each uppercase letter as ^ plus its lowercase letter, then .kv (Ab_C -> ^ab_^c.kv), because host file systems may ignore case and ^ is not a key character. A KV file holds a one-byte type tag (1 = i32, 2 = u32, 3 = blob) followed by the value; a slot file (2.slot) holds the record as is.

Every write goes to <file>.tmp, is flushed and synced (_commit on Windows, fsync on POSIX), closed, and moved over the final file in one step - MoveFileExA with MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH on Windows, rename() on POSIX. A crash leaves the old file or the new one, plus at worst a stale .tmp that reads never open and the next write overwrites. A malformed file (empty, truncated, unknown tag, oversized) reads as IoError, never as a silent NotFound.

init() creates the directory with its parents and must succeed before use; until then every operation answers Unavailable. Paths are built in fixed buffers of kHostFileMaxPathBytes (260, the Windows MAX_PATH, applied on every host).

Status: the POSIX branch (rename, mkdir, fsync, ENOSPC) has not yet been run outside Windows; Linux CI is its first check.

ESP32 NVS ​

Esp32NvsKeyValueStore stores integers as NVS I32/U32 items and blobs as NVS blobs, over one namespace on a configurable partition label (default nvs). Esp32NvsSlotStore stores slot i as the blob under key <prefix><i> (save0, save1, ...); init() checks that the longest such key fits 15 characters.

Same-type writes are replace-or-keep. A set is a single NVS write, and NVS writes the new entry (for a blob, its data chunks and then its index) before it marks the old one erased. After a power loss a read returns the old value or the new one. Slot writes are always same-type writes.

Cross-type writes are not. NVS can hold one item per type under the same key (observed on IDF 4.4.7: after nvs_set_i32 then nvs_set_blob on one key, both items stay and nvs_get_i32 still returns the old integer). To keep the one-value-per-key rule, a set probes the key and, when an item of another type is there, erases it before writing the new one. A power loss between that erase and the write loses the key. Games that never change a key's type are not affected.

init() never erases. It initialises the partition when nobody has yet (nvs_flash_init_partition; a partition the Arduino core already initialised is fine) and opens the namespace read-write. A partition NVS cannot use as it is (ESP_ERR_NVS_NO_FREE_PAGES, ESP_ERR_NVS_NEW_VERSION_FOUND) is reported as Corrupt and left alone: erasing it would wipe every namespace on it, which is the game's decision.

Error mapping: NOT_FOUND and TYPE_MISMATCH -> NotFound; NOT_ENOUGH_SPACE -> NoSpace; KEY_TOO_LONG and INVALID_NAME -> InvalidKey; INVALID_LENGTH and VALUE_TOO_LONG -> TooLarge; NOT_INITIALIZED and INVALID_HANDLE -> Unavailable; anything else -> IoError.

Compatibility with Preferences. A blob written by Arduino Preferences::putBytes(key, ...) in namespace N reads back byte-identically through getBlob() over namespace N, and the other way round (verified on the board). This is the migration path for records a game already stores with Preferences.


6. Writes and the ESP32 flash stall ​

Writes are explicit. No adapter, the service included, writes on its own: PersistenceService never calls commit(), and nothing is flushed from a timer or a destructor.

On the ESP32 every NVS write or page erase disables the flash cache on both cores for its duration. Anything executing from flash - the render loop, audio code not placed in IRAM, memory-mapped flash reads such as a WAD or asset container - stalls until it ends. NVS has no write-back cache, so the stall happens in the set or erase, not in commit().

Measured on the CYD (ESP32-2432S028, Arduino-ESP32 2.0.17 / IDF 4.4.7, 50 writes of a changing blob per size, tools/persist_nvs_smoke):

OperationMinMeanMax
setBlob, 8 B~1.7 ms~4 ms~13 ms
setBlob, 64 B~3 ms~4.3 ms~13.6 ms
commit()6 us12 us21 us

One set costs about a quarter of a 60 fps frame on average and most of one at worst, and a save of several values adds up. Save at a safe point - a menu, a pause screen, a level transition - and group the sets of one save together before one commit(). Never save from an audio callback, a timer or the middle of a gameplay frame.

boot_app0.bin and custom partition tables ​

The Arduino PlatformIO build always flashes boot_app0.bin (the 8 KB otadata image) at 0xE000. In the default tables that address is the otadata partition. In a custom table whose nvs partition covers 0xE000 - for example an nvs at 0x9000 with size 0x6000 (it spans 0x9000-0xF000) and no otadata - every upload overwrites the last NVS page and can destroy stored settings.

Either end the nvs row before 0xE000 (or add an otadata row there), or drop that image from the upload. tools/persist_nvs_smoke/keep_nvs.py is a PlatformIO extra script that does the latter; the smoke tool's README explains it.


7. Memory ​

No heap on the device path. Every buffer is caller-owned or a fixed array sized at compile time.

ItemSize
PersistenceServiceFour pointers (two store pointers, two null-store vtables): 16 B on ESP32, 32 B on a 64-bit host
Esp32NvsKeyValueStore24 B (handle, two string pointers, limits)
Esp32NvsSlotStore28 B
SdSlotStore20 B (two string pointers, the limits and a flag); the FATFS driver it links costs several KB
CRC table64 B of flash
Measured on the CYD, two NVS KV stores linked.dram0.bss +48 B, .dram0.data +0 B; flash +2,760 B text, +680 B rodata
HostFileKeyValueStore, HostFileSlotStoreOne 260-byte path buffer plus the limits each (native only)
MemoryKeyValueStore, MemorySlotStoreTheir template capacities

With the flag off the module costs nothing: every header body sits behind #if PIXELROOT32_ENABLE_PERSISTENCE.

The record helpers take a scratch buffer from the caller: it needs RecordCodec::kHeaderSize + payload size bytes. A stack array in the function that saves is the intended use.


8. Threading ​

Single-threaded contract: every call comes from one task, the game loop. Adapters and the service are not thread-safe and take no locks. A game that saves from another task must serialise all access itself.


9. Limits ​

IDLimit
L1Keys and namespaces are 1..15 bytes, each in [A-Za-z0-9_-] (kMaxKeyLength, isValidKey()). Fifteen is the NVS limit, applied to every medium so a key written on the host works on the board; the character set is safe as a file name on Windows and POSIX. An invalid key answers InvalidKey before the medium is touched.
L2NVS namespaces follow the same rule. Use one namespace per store and never share one with unrelated data; a slot store's <prefix><index> keys must also fit 15 characters.
L3NVS is for small records. Usable space is the nvs partition minus NVS overhead (the CYD's 24 KB partition holds about 20 KB). Large save games need the microSD adapter (SdSlotStore) or a raw-partition store.
L4Cross-type writes on NVS are not atomic (section 5).
L5Typed values are int32_t, uint32_t and blobs. Strings and floats go through the game's own record.
L6No automatic schema migration. The codec reports the version; the game migrates.
L7No wear accounting beyond what NVS does internally.
L8No IFileStore yet. SD slots now ship through SdSlotStore; streaming files remain the future work that interface waits for.
L9Arduino core range. The NVS adapter uses nvs_* calls common to IDF 4.4 and 5.x; it has been built and run on Arduino-ESP32 2.0.17. Arduino-ESP32 3.x has not yet been built locally.
L10SD slots hold large records with no NVS partition ceiling, at the cost of several KB of RAM for FATFS. The card is removable: a missing or unmountable card answers Unavailable at init(). A card pulled after init() is not detected up front (the Arduino SD library caches the card type at mount), so the next access answers IoError/NotFound; init() again after reinserting probes the directory and mounts the card again, with no reboot.

10. Future media ​

Each future medium is an adapter behind the existing interfaces. None of them changes IKeyValueStore, ISlotStore, RecordCodec or game code that saves through a store reference.

MediumModel(s)Replace-or-keepNotes
SD card (FAT)Slots (shipped as SdSlotStore); a future IFileStore for streaming filesTemp file + remove + rename; FAT is not power-safe, so a torn record is rejected by the envelope and a loss between remove and rename leaves the slot emptySeveral KB of RAM for FATFS; a missing card answers Unavailable, a removal after init() surfaces as IoError/NotFound until init() remounts
I2C EEPROM (AT24Cxx-class chip)Slots, small KVTwo copies per slot (A/B with a sequence number); the envelope picks the valid onePage-write limits and ~5 ms write cycles live in the adapter
Raw flash partitionSlotsA/B sectors per slot with a sequence numberThe route for large save games on boards with 16 MB of flash
Mirrored slot storeSlotsPer underlying storeA MirroredSlotStore implementing ISlotStore over two others, reporting each result - a "save to two media" policy without a new interface

IFileStore (open, read, write, close, remove, exists, size, replace) is still deliberately not shipped: an interface no backend validates would freeze an untested design. SD slots now ship through SdSlotStore; streaming files remain the future work that will validate the interface.


11. Testing ​

SuiteWhat it covers
test/unit/test_persist_flags/The flag and its mirrors match the build (runs flag on and flag off)
test/unit/test_persist_codec/Envelope round trip, each corruption class, CRC check value, key rules
test/unit/test_persist_contract/One adapter contract suite, run unchanged against every adapter in its table
test/unit/test_persist_service/Roles, null stores, record helpers
test/unit/test_persist_hostfile/Host file specifics: init(), file layout, case-distinct keys, interrupted writes, stale temp files, malformed files
tools/persist_sd_smoke/Board smoke: pio test -e smoke runs the same contract suite over SdSlotStore on the CYD; the report checks mount, round trip and an interactive card-out/card-back re-mount

The contract suite is the heart of it. It runs on the host against the memory and host-file adapters under native_test_persistence, and on the board against the NVS adapters through tools/persist_nvs_smoke and against SdSlotStore through tools/persist_sd_smoke (pio test -e smoke, which compiles the same test file from the engine's test/ folder). The NVS smoke firmware adds what only hardware can show: Preferences compatibility, raw IDF type behaviour, write timing and nvs_get_stats. The SD smoke adds the FAT round trip, the card size and sizeof(SdSlotStore), and then asks over serial for the card to be taken out and reinserted: the accesses made while it is out must fail visibly (NotFound/IoError, Unavailable from init() and from a write on the unmounted store), init() after the reinsert must mount again without a reboot, and a record seeded before the removal must read back intact. The unanswered prompts of that stage are reported as skipped, not failed, so an unattended flash still reports the rest.

bash
pio test -e native_test_persistence   # host: codec, contract, service, host files
cd tools/persist_nvs_smoke
pio test -e smoke                      # board: contract suite over NVS
pio run  -e smoke -t upload            # board: compatibility and timing report

12. Where to look ​

WhatWhere
Results, key rulesinclude/persistence/StoreTypes.h
Key-value modelinclude/persistence/KeyValueStore.h
Slot modelinclude/persistence/SlotStore.h
Envelope and CRCinclude/persistence/RecordCodec.h
Service and null storesinclude/persistence/PersistenceService.h
Memory adaptersinclude/persistence/MemoryStores.h
Host file adaptersinclude/drivers/native/HostFileStore.h
NVS adaptersinclude/drivers/esp32/Esp32NvsStore.h
microSD adapterinclude/drivers/esp32/SdStore.h, hardware in SdConfig.h
Contract suitetest/unit/test_persist_contract/
Board smoke tool (NVS)tools/persist_nvs_smoke/README.md
Board smoke tool (microSD)tools/persist_sd_smoke/README.md
Task-oriented guidePersistence guide
Conceptual APIPersistence API
Build flagConfiguration

Released under the MIT License.