1. Today's topic

Endurance describes the permitted number of erase/program cycles.

  • Retention describes how long previously written bits remain reliable under specified conditions.

This lesson examines latent corruption: damage that has occurred without yet disrupting normal operation. A fallback is useful only when its integrity is checked and a recovery procedure is defined.

2. Why this matters

A/B configuration may look healthy while active B is valid. But backup A may have been corrupted months ago. When B becomes unavailable, it turns out that the fallback has been gone for a long time. This is critical for:

text
phase thresholds
GPIO mapping
ADC calibration
APN
MQTT endpoint
certificates
identity metadata

3. Theory

Retention versus endurance

Flash stores charge, which degrades over time. Temperature and cycling history affect retention. For ESP32, take retention/endurance figures from the datasheet of the specific external SPI NOR Flash.

CRC and ECC

CRC detects defined classes of accidental logical-record corruption, not every possible change, and provides no authentication. Some MCUs use ECC that corrects a single-bit error and detects a double-bit word error; capabilities, signaling and safe responses depend on the series and memory. A corrected read does not mean the cells were repaired. ECC does not replace application CRC or reliably identify every interrupted Flash operation.

text
copy A dies -> unnoticed -> copy B dies -> ERROR

Periodic verification can detect a latent fault while a healthy copy still exists; successful repair requires a separate protocol:

text
copy A dies -> periodic CRC detects -> copy B still healthy -> repair A

Verification sweep vs repair scrub

Verification reads data and checks CRC, semantics and available ECC events. Repair relocates validated data into usable storage according to the medium’s rules. Simply rewriting without erase and programming-granularity rules is not a universal Flash repair.

Storage health

c
typedef enum {
    STORAGE_COPY_UNKNOWN = 0,
    STORAGE_COPY_VALID,
    STORAGE_COPY_CORRUPTED,
    STORAGE_COPY_MISSING,
} storage_copy_state_t;
typedef struct {
    storage_copy_state_t state;
    uint64_t generation;
    uint64_t last_verified_us;
    uint32_t verify_failures;
    uint32_t repair_count;
} storage_copy_health_t;

Health matrix: REDUNDANT means valid checked fallback records, not necessarily two mirrors of the latest version:

text
A valid + B valid     -> REDUNDANT
A valid + B invalid   -> DEGRADED
A invalid + B valid   -> DEGRADED
A invalid + B invalid -> FAILED

Equal generations with different payloads are a conflict and invariant violation. Different valid generations may provide rollback history rather than a mirror of current state. Compare logical fields or canonical encoding, not accidental structure padding.

Repair inactive copy

text
1. Read healthy copy.
2. Validate healthy copy fully.
3. Write damaged copy from healthy data.
4. Commit.
5. Read back.
6. CRC + semantic validation.
7. Mark redundancy HEALTHY.

Repair must not increase the logical configuration generation because the logical configuration has not changed.

Repair budget

Do not rewrite a repeatedly failing region indefinitely: bound attempts and report MEDIA_DEGRADED. Retain corrected-ECC counts and failing addresses; clearing a controller flag does not remove the cause. An uncorrectable ECC read requires the reference manual’s fault-handling path, not ordinary continuation.

4. Common mistakes

  1. Treating retention and endurance as the same parameter.
  2. Assuming successfully written data lasts forever.
  3. Checking the backup only after the active copy fails.
  4. Relying only on range checks without CRC.
  5. Treating CRC as a replacement for ECC.
  6. Treating ECC as a replacement for CRC.
  7. Ignoring corrected ECC events.
  8. Responding identically to single-bit and double-bit ECC errors.
  9. Moving an ECC ISR between STM32 families without consulting the RM.
  10. Scanning all Flash in a long loop in real-time firmware.
  11. Giving the scrubber high priority.
  12. Repairing without checking the healthy copy.
  13. Increasing configuration generation during physical repair.
  14. Repairing a degrading region indefinitely.
  15. Not reporting storage degradation to the supervisor.
  16. Assuming a read-only factory partition remains error-free forever.

5. Practical task

Use the already defined storage_copy_health_t for cfg_a/cfg_b. Do not define a second incompatible typedef with the same name in one translation unit. Example per-copy health records:

c
static storage_copy_health_t s_cfg_a_health;
static storage_copy_health_t s_cfg_b_health;

Implement verification:

c
static storage_copy_state_t config_verify_slot(const char *key, config_record_t *out)
{
    size_t size = sizeof(*out);
    esp_err_t err = nvs_get_blob(s_nvs, key, out, &size);
    if (err == ESP_ERR_NVS_NOT_FOUND) return STORAGE_COPY_MISSING;
    if (err != ESP_OK || size != sizeof(*out)) return STORAGE_COPY_CORRUPTED;
    if (config_record_check(out) != CONFIG_RECORD_OK) return STORAGE_COPY_CORRUPTED;
    return STORAGE_COPY_VALID;
}

If both records are valid at the same generation, their payloads must match. Serialize repair with configuration updates: the repair source must not change concurrently. Policy:

text
A valid, B invalid -> repair B from A
B valid, A invalid -> repair A from B
both invalid -> factory recovery / safe mode

Add storage health. On an isolated test copy, simulate B corruption and check detection before reboot, then repair and read back. Actual ECC fault experiments require the target reference manual’s supported method; do not corrupt operational device data.

6. What to try next

  • For STM32 with ECC, add counters: corrected ECC, uncorrectable ECC and last failing address.
  • Treat a physical mirror and rollback history as separate functions.
  • Add storage health to the supervisor: HEALTHY / DEGRADED_REDUNDANCY / MEDIA_DEGRADED / FAILED.

A short connection between lessons 51–60

These ten lessons form one architectural progression:

text
DMA ownership
 -> SPSC transfer
 -> immutable config publication
 -> deterministic replay
 -> state-machine fuzzing
 -> contracts
 -> supervisor recovery
 -> crash-consistent storage
 -> endurance budget
 -> latent corruption detection

The practical outcome for your ESP32/STM32 projects:

  1. The data path must be bounded: DMA buffers, handles and SPSC, without large memcpy() calls or mutexes in the hot path.
  2. The configuration path must be immutable: validate the candidate, publish atomically, use generations and avoid mixed configurations.
  3. State machines must be deterministic: events instead of direct hardware access, with replay and fuzzing.
  4. Contracts must formalise impossible states.
  5. The supervisor must recover the fault domain rather than immediately restart the whole MCU.
  6. Storage must be crash-consistent, with an endurance budget and periodic scrubbing.
A and B both pass validation and have the same generation, but their payloads differ. What should the lesson’s model report?

Exercise

A is fully valid at generation 42; B is invalid. Outline repair and the condition for reporting healthy redundancy. Should physical repair increment the logical generation? What if B repeatedly becomes corrupt?

Self-check criteria: Include validation, commit/read-back, unchanged logical generation and escalation for recurring media faults.

Show the supplied answer

Fully validate A, write B from A’s healthy data, commit, read back, then check CRC and semantics before marking redundancy healthy. Do not increment logical generation because configuration content has not changed. Repeated failures require a bounded repair budget and reporting MEDIA_DEGRADED to the supervisor rather than endless rewrites.