# Persistence Component Specification

**Component ID:** COMP-PERSIST  
**Version:** 1.0  
**Date:** 2025-01-19  
**Location:** `application_layer/DP_stack/persistence/`

## 1. Purpose

The Persistence component provides the sole interface for persistent storage access. It abstracts storage media (SD card, NVM), manages serialization/deserialization, implements wear-aware storage, and ensures data integrity.

## 2. Responsibilities

### 2.1 Primary Responsibilities

- Abstract storage media (SD card, NVM)
- Serialize/deserialize structured data
- Manage wear-aware storage (SD card)
- Ensure data integrity
- Coordinate data flush operations

### 2.2 Non-Responsibilities

- Business logic (data semantics owned by components)
- Hardware access (delegated to storage drivers)
- Data validation (components validate before persistence)

## 3. Public API

### 3.1 Sensor Data Persistence

```c
/**
 * @brief Write sensor data record
 * @param record Sensor data record
 * @return true if written, false on error
 */
bool persistence_writeSensorData(const sensor_data_record_t* record);

/**
 * @brief Read sensor data records
 * @param records Output buffer
 * @param count Input: buffer size, Output: records read
 * @param start_time Start timestamp filter (0 for all)
 * @param end_time End timestamp filter (0 for all)
 * @return true if read successful, false on error
 */
bool persistence_readSensorData(sensor_data_record_t* records, size_t* count, uint64_t start_time, uint64_t end_time);
```

### 3.2 Diagnostic Persistence

```c
/**
 * @brief Write diagnostic event
 * @param event Diagnostic event
 * @return true if written, false on error
 */
bool persistence_writeDiagnostic(const diagnostic_event_t* event);

/**
 * @brief Read diagnostic events
 * @param events Output buffer
 * @param count Input: buffer size, Output: events read
 * @param filter Filter criteria (severity, component, etc.)
 * @return true if read successful, false on error
 */
bool persistence_readDiagnostics(diagnostic_event_t* events, size_t* count, const diag_filter_t* filter);

/**
 * @brief Clear diagnostic log
 * @return true if cleared, false on error
 */
bool persistence_clearDiagnostics(void);
```

### 3.3 Machine Constants Persistence

```c
/**
 * @brief Write machine constants
 * @param mc Machine constants structure
 * @return true if written, false on error
 */
bool persistence_writeMachineConstants(const machine_constants_t* mc);

/**
 * @brief Read machine constants
 * @param mc Output buffer
 * @return true if read successful, false on error
 */
bool persistence_readMachineConstants(machine_constants_t* mc);
```

### 3.4 Flush Operations

```c
/**
 * @brief Flush all critical data to storage
 * @return true if flushed, false on error
 */
bool persistence_flushCriticalData(void);

/**
 * @brief Check if flush is complete
 * @return true if flush complete, false otherwise
 */
bool persistence_isFlushComplete(void);

/**
 * @brief Get flush progress (0-100%)
 * @return Flush progress percentage
 */
uint8_t persistence_getFlushProgress(void);
```

### 3.5 Storage Status

```c
/**
 * @brief Check storage availability
 * @param storage_type Storage type (SD_CARD, NVM)
 * @return true if available, false otherwise
 */
bool persistence_isStorageAvailable(storage_type_t storage_type);

/**
 * @brief Get storage usage statistics
 * @param storage_type Storage type
 * @param stats Output statistics
 * @return true if retrieved, false on error
 */
bool persistence_getStorageStats(storage_type_t storage_type, storage_stats_t* stats);
```

## 4. Data Types

### 4.1 Storage Types

```c
typedef enum {
    STORAGE_TYPE_SD_CARD = 0,
    STORAGE_TYPE_NVM,
    STORAGE_TYPE_COUNT
} storage_type_t;
```

### 4.2 Storage Statistics

```c
typedef struct {
    uint64_t total_bytes;
    uint64_t used_bytes;
    uint64_t free_bytes;
    uint32_t write_count;
    bool is_healthy;
} storage_stats_t;
```

## 5. Threading Model

- **Owner Task:** Persistence Task (MEDIUM priority)
- **Thread Safety:** Thread-safe (all operations protected by mutex)
- **Blocking Operations:** Storage I/O operations (bounded by timing requirements)
- **ISR Access:** Not allowed (blocking operations)

## 6. Resource Ownership

- **SD Card Driver:** Owned exclusively by Persistence component
- **NVM Driver:** Owned exclusively by Persistence component
- **Storage Mutex:** Protects concurrent access
- **Write Buffers:** Pre-allocated static buffers

## 7. Error Model

### 7.1 Error Conditions

| Error | Condition | Response |
|-------|-----------|----------|
| `PERSIST_ERR_STORAGE_FULL` | Storage full | Trigger retention policy, log warning |
| `PERSIST_ERR_STORAGE_FAILED` | Storage failure | Enter SD_DEGRADED state, log error |
| `PERSIST_ERR_SERIALIZATION` | Serialization failure | Return false, log error |
| `PERSIST_ERR_INTEGRITY_CHECK` | Integrity check failed | Return false, log error, attempt recovery |

### 7.2 Diagnostics Emitted

- `DIAG-ST-PERSIST-0001`: Storage write failure (WARNING)
- `DIAG-ST-PERSIST-0002`: Storage full (WARNING)
- `DIAG-ST-PERSIST-0003`: Storage corruption detected (ERROR)
- `DIAG-ST-PERSIST-0004`: Storage failure (FATAL)

## 8. State-Dependent Behavior

### 8.1 All States

- Read operations allowed
- Write operations allowed (with restrictions)

### 8.2 TEARDOWN State

- Only authorized writes allowed (critical data flush)
- Read operations allowed

### 8.3 SD_DEGRADED State

- SD card writes disabled
- NVM writes allowed
- Read operations allowed (if storage accessible)

## 9. Dependencies

### 9.1 Required Components

- **SD Card Driver:** For SD card access
- **NVM Driver:** For NVM access
- **STM:** For state queries and transitions
- **Logger:** For diagnostic logging

### 9.2 Required Interfaces

- SD Card Driver interface
- NVM Driver interface
- STM state query interface
- Logger interface

## 10. Acceptance Tests

- **T-PERSIST-001:** Sensor data write/read operations
- **T-PERSIST-002:** Diagnostic event write/read operations
- **T-PERSIST-003:** Machine constants write/read operations
- **T-PERSIST-004:** Data flush completes within 200ms
- **T-PERSIST-005:** Storage failure handling (SD_DEGRADED state)
- **T-PERSIST-006:** Data integrity verification
- **T-PERSIST-007:** Wear-aware storage management

## 11. Traceability

- **SWR-DATA-001:** Persistent timestamped sensor data
- **SWR-DATA-004:** DP component as sole persistence interface
- **SWR-DATA-005:** Storage access isolation
- **SWR-DATA-006:** Structured data serialization
- **SWR-DATA-007:** Data flush before teardown
- **SWR-DATA-008:** Data integrity during updates
- **SWR-DATA-009:** Persistence verification
- **SWR-DATA-012:** SD card failure handling
- **SWR-DATA-013:** Wear-aware storage management
- **CFC-ARCH-01:** Hardware access via drivers only
- **CFC-DATA-01:** Single source of truth
- **CFC-DATA-02:** Data consistency during transitions

## 12. Implementation Notes

- Serialization SHALL use a well-defined format (e.g., CBOR, MessagePack, or custom binary)
- SD card writes SHALL be wear-aware (wear leveling, write frequency limits)
- Data integrity SHALL be verified using checksums or hashes
- Flush operations SHALL be coordinated with STM for state transitions
- Storage failures SHALL trigger state transitions (SD_DEGRADED)
