> Snapshot of projects/edgestream-gw/design/decision-log.md — 28 Nov 2026

# EdgeStream-GW — Decision log (DAR / IEEE 1016)

## Decision 1 — Protocol collection: Build vs Reuse (South Drivers)

- **Criteria**: development speed, protocol compliance, hardware footprint.
- **Options**: proprietary C/Python drivers vs open-source reuse (`pymodbus`, Gurux DLMS).
- **Decision**: **REUSE**.
- **Rationale**: rebuilding compliant Modbus/DLMS stacks brings no strategic value and risks
  non-compliance. Requirements: REQ-004, REQ-008.

## Decision 2 — Data normalization: Build vs Reuse (Protocol Adapters)

- **Criteria**: "Fail-Fast" handling, TDD compliance, strict JSON schema alignment.
- **Options**: open-source parsers vs proprietary adapters.
- **Decision**: **BUILD FROM SCRATCH**.
- **Rationale**: open-source parsers silently fix bad data or let incomplete arrays through;
  in-house adapters raise `CorruptedPayloadError` and guarantee CMMI L3 quality.
  Requirement: REQ-004.

## Decision 3 — Store-and-Forward database

- **Criteria**: lightweight footprint on edge SSDs, power-loss resistance, open source.
- **Options**: proprietary binary files vs MongoDB vs SQLite.
- **Decision**: **REUSE SQLite**.
- **Rationale**: MongoDB is too heavy for the PS RAM limits; binary files risk corruption on
  power loss; SQLite is serverless, ACID and edge-appropriate. Requirements: REQ-002, REQ-008.

## Decision 4 — HW/SW partitioning boundary (Zynq UltraScale+)

- **Criteria**: < 50 ms response latency, CPU load optimization.
- **Options**: 100% software evaluation vs PS/PL split.
- **Decision**: **PS/PL SPLIT**.
- **Rationale**: routing high-frequency continuous signals through the Linux kernel (PS)
  introduces non-deterministic OS latency; delegating filtering and first threshold breaches
  to the PL guarantees sub-millisecond detection, leaving the PS to route only the
  asynchronous `ActionCommand`. Requirement: REQ-003.

## Decision 5 — First module for detailed specification

- **Criteria**: ease of implementation, testability (TDD), absence of external dependencies,
  strategic value, position in the dependency graph.
- **Options**: Protocol Adapters vs Edge Analytics PS vs Store-and-Forward vs modules of
  Fog-Crypto Core / NetSentry-IoT.
- **Decision**: **Protocol Adapters (EdgeStream-GW)** as the first module to be specified in detail.
- **Rationale**: pure Python transformation (`bytes → Frame`), deterministic and TDD-friendly,
  no hardware/network/database dependency; it is the proprietary brick mandated by Decision 2
  (build in-house); it defines the central `Frame` contract consumed by all downstream components.
- **Impacted requirements**: REQ-004 (Fail-Fast), REQ-008 (embedded footprint).
- **Status**: Accepted.

## Decision 6 — Schema validation engine

- **Criteria**: strictness, idiomatic Python, TDD ergonomics, performance.
- **Options**: Pydantic v2 vs pure `jsonschema`.
- **Decision**: **Pydantic v2** (strict mode, `extra="forbid"`).
- **Rationale**: type-safe, fast (compile-to-core), first-class with pytest/hypothesis, strict
  enforcement including bounded value ranges.
- **Status**: Accepted.

## Decision 7 — First protocol to implement

- **Criteria**: simplicity, alignment with the virtual test bench (50 energy meters),
  availability of reference vectors.
- **Options**: Modbus RTU vs Modbus TCP vs DLMS/COSEM.
- **Decision**: **Modbus RTU first** (FC 03 "read holding registers"), then Modbus TCP, then
  DLMS/COSEM, all behind the same `ProtocolAdapter` interface.
- **Rationale**: Modbus RTU is the simplest and matches the 50-meter bench; `pymodbus` provides
  reference vectors (Decision 1 — REUSE).
- **Status**: Accepted.

## Decision 8 — TDD tooling

- **Criteria**: deterministic unit testing, property-based testing, coverage, linting.
- **Options**: pytest + hypothesis vs alternative stacks.
- **Decision**: **pytest + hypothesis + pydantic v2 + pytest-cov + ruff**.
- **Rationale**: `hypothesis` enforces the "no other exception / no invalid Frame" invariant;
  `pytest-cov` for branch coverage; `ruff` for lint.
- **Status**: Accepted.

## Decision 9 — DLMS/COSEM adapter: defer to a dedicated specification phase

- **Criteria**: scope, protocol complexity, value delivered per iteration.
- **Options**: implement a full DLMS/COSEM adapter now vs defer it to a dedicated spec phase.
- **Decision**: **DEFER**. Implement Modbus RTU + TCP first (done); treat DLMS/COSEM as its own
  specification phase (framing choice HDLC vs COSEM-TCP, A-XDR decoding, OBIS code mapping).
- **Rationale**: DLMS/COSEM is a substantial protocol; a rushed parser would violate the
  Fail-Fast quality guarantees. The `ProtocolAdapter` interface already accommodates it.
- **Status**: Accepted.

## Decision 10 — Edge Analytics PS aggregation output convention

- **Criteria**: keep the canonical `Frame` schema stable, preserve RMS/min/max trends,
  minimize churn and downstream impact.
- **Options**: (a) extend the `Frame`/`Measurement` schema with stats fields; (b) emit, per
  quantity, a primary measurement plus `.min`/`.max` suffixed measurements.
- **Decision**: **(b)** — one aggregated `Frame` per window; per quantity emit `<name>`
  (reducer, default `rms`), `<name>.min`, `<name>.max`. Reducer configurable among
  `rms` / `mean` / `last`.
- **Rationale**: keeps the canonical schema unchanged (no breaking change, no RTM churn) while
  preserving the SDD's "RMS, min/max trends"; N frames → 1 frame realizes the −75% volume KPI.
- **Impacted requirements**: REQ-001b.
- **Status**: Accepted.

## Decision 11 — Ingestion Core: async broker architecture

- **Criteria**: lossless delivery, back-pressure, producer/consumer decoupling,
  technological depth, testability.
- **Options**: (a) threaded broker with blocking queues; (b) `asyncio` fan-out broker
  with one bounded queue per subscriber; (c) full pub/sub with topic routing and
  persistence.
- **Decision**: **(b)** — `asyncio` fan-out broker: `publish(frame)` awaits
  `queue.put` on every subscriber's bounded `asyncio.Queue`, so a slow/disconnected
  publisher applies back-pressure to the producer once its queue is full; frames are
  never dropped (lossless) and per-subscriber order is preserved. Each subscriber is
  drained by its own worker task; a raising subscriber is isolated (recorded, delivery
  to others continues).
- **Rationale**: `asyncio` is stdlib (no new dependency, aligns with SDD §3.4
  "PS = asyncio"); a bounded queue with blocking `put` is the canonical lossless
  back-pressure primitive; topic-based routing belongs to the Northbound MQTT layer
  (Milestone 3), so the broker stays a thin, single routing point.
- **Impacted requirements**: REQ-007 (northbound routing), REQ-008 (bounded footprint).
- **Status**: Accepted.

## Decision 12 — Northbound MQTT + Sparkplug B: Build vs Reuse

- **Criteria**: protocol compliance, technological depth, TDD ergonomics.
- **Options**: (a) build an MQTT client + Sparkplug B Protobuf encoder in-house;
  (b) reuse Eclipse Paho (client) + the official `sparkplug_b.proto` schema, building
  only the thin `Frame`→namespace/metrics adapter.
- **Decision**: **(b)** — REUSE `paho-mqtt` (transport) and the Eclipse Sparkplug B
  Protobuf schema (payload, vendored + compiled); BUILD the thin adapter
  (`sparkplug.py` namespace + metric mapping, `publisher.py` wrapper).
- **Rationale**: MQTT and Protobuf are wire standards — hand-rolling them would raise
  tech depth and risk non-compliance, exactly what Decision 2 rejected for parsing;
  the proprietary value and Fail-Fast boundary is the `Frame`→Sparkplug mapping.
  Per-measurement mapping is one `Double` metric; `unit`/`quality` enrichment deferred
  to Phase 2 (Sparkplug `PropertySet`) to preserve the −75 % volume KPI.
- **Impacted requirements**: REQ-007.
- **Status**: Accepted.

## Decision 13 — Local Action Engine (PS): synchronous fast path

- **Criteria**: latency determinism, simplicity, no Cloud dependency.
- **Options**: (a) asyncio dispatch coroutine (event-loop yield on the critical path);
  (b) synchronous, non-blocking dispatch with an injectable driver + append-only log.
- **Decision**: **(b)** — the PS engine is a synchronous fast path: rule lookup →
  ``ActionCommand`` build → driver write, with no event-loop yield and no Cloud call.
  The ``ActuatorDriver`` is an injectable seam (mock in TDD; pymodbus REUSE in
  production, Decision 1). Traceability is an append-only JSONL ``ActionLog``.
- **Rationale**: the < 50 ms budget is dominated by OS/interrupt latency once on
  hardware; an in-process dispatch must not add scheduling latency. Synchronous
  dispatch keeps the path deterministic and measurable; the physical southbound
  write and PL interrupt are exercised at Milestones 7/8.
- **Impacted requirements**: REQ-003.
- **Status**: Accepted.

## Decision 14 — Store-and-Forward: SQLite FIFO buffer + resumable replay

- **Criteria**: durability, power-loss resistance, ordering, throttling, tech depth.
- **Options**: (a) in-memory queue (lost on crash); (b) SQLite FIFO buffer with
  delete-after-success replay; (c) a message broker (Redis/RabbitMQ) on the edge.
- **Decision**: **(b)** — stdlib ``sqlite3`` (Decision 3's REUSE), synchronous,
  one table ``buffer(seq AUTOINCREMENT, payload JSON)``; ``forward`` is pass-through
  when online or ``INSERT`` when offline; ``replay`` drains FIFO, throttled by a
  configurable ``min_interval``, and deletes each frame only after a successful
  forward.
- **Rationale**: SQLite is serverless + ACID → power-loss durable (REQ-002/008) with
  no extra dependency; delete-after-success makes replay lossless and resumable;
  a message broker would add an external service and violate the edge footprint.
- **Impacted requirements**: REQ-002, REQ-008.
- **Status**: Accepted.

## Decision 15 — Deployment: two-container stack + rolling OTA

- **Criteria**: zero-config deployment, OTA without stopping collection, tech depth.
- **Options**: (a) one monolith container; (b) `gateway` + `mosquitto` (REUSE broker),
  zero-config via ``${VAR:-default}`` + ``.env.example``, rolling OTA via
  ``docker compose up -d --no-deps --force-recreate gateway``.
- **Decision**: **(b)** — a `gateway` image runs the in-process pipeline (built from
  the source packages), the Eclipse Mosquitto image is the northbound broker. Every
  compose ``${VAR}`` carries a default, so `docker compose up` works with no ``.env``.
  OTA recreates only the gateway; the broker is untouched and the SQLite ``store_data``
  volume persists, so store-and-forward replays anything buffered during the recreate.
- **Rationale**: splitting the still-in-process pipeline into per-stage containers
  would require a network transport that does not exist yet; the two-container split
  already isolates the broker (the external dependency) and gives durable, non-lossy
  rolling updates. Finer per-microservice isolation is revisited when the runtime is
  decomposed (M7/M8).
- **Impacted requirements**: REQ-005, REQ-006.
- **Status**: Accepted.

## Decision 16 — DLMS/COSEM framing: COSEM-TCP first

- **Criteria**: alignment with the fleet, simplicity, testability.
- **Options**: COSEM-TCP wrapper (Ethernet) vs HDLC (serial optical/RS-485).
- **Decision**: **COSEM-TCP first**, HDLC deferred.
- **Rationale**: Ethernet/TCP matches the industrial-IoT fleet and the already-implemented
  Modbus TCP; the adapter is framing-agnostic because the REUSE south driver (Gurux) strips
  the wrapper, so the choice mainly orders the south-driver integration work.
- **Impacted requirements**: REQ-004, REQ-008.
- **Status**: Accepted.

## Decision 17 — DLMS/COSEM adapter: reference subset

- **Criteria**: spec completeness, correctness, tech depth, TDD ergonomics.
- **Options**: (a) implement the full xDLMS stack in-house; (b) implement a narrow,
  well-specified reference subset (A-XDR profile-read data + OBIS mapping) behind the
  `ProtocolAdapter` interface, REUSE-ing Gurux for everything else.
- **Decision**: **(b)** — BUILD the A-XDR decoder (tags 0x00/0x01/0x02/0x05/0x06/0x09/
  0x0F/0x10/0x11/0x12/0x18), the OBIS mapping, and the Fail-Fast `DlmsAdapter`; REUSE
  Gurux for framing/association/security/APDU.
- **Rationale**: a rushed full stack would violate the Fail-Fast guarantee (Decision 2);
  the subset proves the DLMS path end-to-end (OBIS → measurement) while keeping the
  proprietary parsing in-house and the compliance-critical stack a qualified REUSE.
- **Impacted requirements**: REQ-004.7.
- **Status**: Accepted.

## Decision 18 — Edge Analytics PL: moving-average decimator first

- **Criteria**: volume-reduction KPI, fast-path latency, tech depth, testability.
- **Options**: (a) start with the FFT; (b) start with a moving-average decimator +
  raw-sample threshold comparator on AXI4-Stream, defer the FFT to a follow-on block.
- **Decision**: **(b)** — `edge_filter.sv`: a parameterized moving-average decimator
  (accumulator + power-of-two shift) for REQ-001a, plus a raw-sample `breach` comparator
  for the REQ-003 fast path. The FFT is specified (same AXI4-Stream interface) but
  implemented in Phase 2.
- **Rationale**: the decimator carries the −75 % volume KPI with a trivially-closable
  adder path (DSP-free, low LUT/FF); the raw comparator gives the sub-sample trigger
  Decision 4 requires. A pipelined FFT is a much larger block that adds no volume
  reduction on its own — it belongs after the filter is proven.
- **Impacted requirements**: REQ-001a, REQ-003.
- **Status**: Accepted.
