Skip to main content

Analytics (Mobile Step 5): Requirements & Implementation Plan

Status: Implemented in cse_tcp_be (2026-09-30), not yet deployed. Migrations 0038–0045 apply on the next tcpserver/persistence-worker start. §8 maps each part to its code and lists what still needs verifying on real data. Date: 2026-09-30 Owner: cse_tcp_be Source design: Claude Design project "CSE MOBILE APP", file Crown Solar App – Screens iOS 26, group 5 · Devices, detail and analytics, screens 39, 39b–39f, 40, 41 and the "Existing chart" Grid import/export note. Related: cse-http-be ADR 0008 ("Analytics served by TCP"), cse-http-be specs/009-analytics-reports/contracts/tcp-analytics-dependency.md (TCP-REQ-08/15).

This page does three things:

  1. Turns the mobile Analytics screens into backend requirements.
  2. Audits what exists today, database schema included, against those requirements.
  3. Describes the architecture that was built, and the verification still outstanding.

"Today", "current" and file references describe the repo as of the date above.


1. What the screens require​

1.1 Screen inventory​

#ScreenWhat it showsBackend implication
39Analytics, whole plant, DayPeriod control Day / Month / Year / Custom. Viewing: Entire Plant · 5 devices. Date pager (‹ Tuesday, 12 Aug · Today ›). Energy Summary: Generated 51.4, Consumed 33.8, Grid Import 4.2, Grid Export 12.4 kWh, "1 unit = 1 kWh", Peak solar 11.06 kW. Power chart 00–24 h with multi-select chips Solar / Load / Battery / Import / Export. Financial Summary (Estimated): Total Benefit PKR 3,031 = Electricity Savings 2,535 + Export Credit 496, with an Energy Rates row "Buy 65 · Export 40 PKR/unit". Footnote: "Savings cover the 39.0 kWh of solar used on site…". Last 7 Days generation bars (Wed–Tue).Per-plant, per-local-day energy totals; an intraday power series; daily peak PV power; a 7-day daily series; self-used energy (= generated − exported).
39bPartial dataBanner "Data May Be Incomplete — Secondary Inverter stopped reporting at 11:42 AM. Totals below cover the 2 devices still reporting." Selector shows 2 of 3 reporting. Summary marked partial. Inline note "Values exclude Secondary Inverter after 11:42 AM". Financial Summary marked Partial period.Per-device completeness: expected vs reporting devices, and the time each missing device went quiet. Must never be silent under-reporting.
39cMonthPager "August 2025 · 1–12 Aug so far". Summary 486 / 422 / 72 / 112 kWh, Best day 44.6 kWh. Daily bars 1…12 ("Daily generation, 1–12 Aug"). Financial PKR 28,790. No "Last 7 days" block.Local-day daily series for the month so far, and the month's best day. The same selector drives energy and money.
39dExport unsupportedThe fourth tile becomes Battery Charged 15.2 kWh. No Export chip. Financial shows Electricity Savings only plus "Solar used on site 39.0 kWh", with the note "This inverter does not report grid export…".Capability flags per scope. null (not reported) must be distinguishable from 0 (real zero).
39eRates not setEnergy is unchanged. Financial shows "Set electricity rate ›" / "Set export rate ›" and never PKR 0.Money depends on plant tariff metadata (owned by HTTP), not on telemetry.
39fEnergy Rates sheetElectricity Rate 65.00 PKR/unit, Export Rate 40.00 PKR/unit, Save Rates.Writes two rates. cse-http-be stores only electricityRate {amountPerKwh, currency} today and has no export rate (§4.5).
–Existing chart noteImport drawn solid, Export dashed: "never one ambiguous Grid line".Grid power is split into separate import and export series, never one signed line.
40"View Analytics For" sheetSearch. Entire Plant (aggregated across 5 devices). Grouped Inverters (Main, Secondary), Batteries (Battery 01 · 78 %), Meters (Main Smart Meter). "Scales to twenty inverters."Scope is either the whole plant or one device. The plant aggregate is computed server-side. Up to ~20 inverters per plant.
41Device scope"One of two inverters at Ghori Residence. Plant totals stay available under Entire Plant." Viewing: Secondary Inverter. Device totals 19.8 / 12.4 / 1.1 / 4.8 kWh, peak solar 4.31 kW, same chart. No Financial Summary.Per-device query with the same response shape. Money is plant-scope only.

Related screens in the same group:

  • 37 Device Detail: Overview / Performance / Info tabs, a Trends button and a "Today 32.8 kWh" solar tile. Trends deep-links into Analytics in device scope (screen 41).
  • 35 Devices: Plant total live kW.

Both are already served by get_devices plus the live watch stream, and aren't re-specified here.

Screens the design does not draw, and the behaviour assumed for them:

  • Year: 12 monthly bars plus a "Best month" tile, with the same summary and financial blocks.
  • Custom: a from/to range. The chart grain is chosen from the range length (§3.4).

Product should confirm both.

1.2 State contract (from the design's STATE notes)​

  • analyticsScope = "plant" and plant = selectedPlantId. Analytics always opens on the whole selected plant. The device selector narrows the view locally and never writes the global selected plant.
  • range = "day" | "month" | "year" | "custom" (the API also has "total", for the per-inverter Historical Data screen, which isn't part of this screen; see historical-data.md). The range changes every number on the screen: summary, chart and financial block. There is no second period control.
  • period.complete = false, gapFrom = "11:42". Partial periods are marked as partial, not silently under-reported.
  • plant.exportSupported, plant.electricityRate = null, plant.exportRate = null. A missing capability hides the metric, and a missing rate becomes a call to action.

1.3 Functional requirements​

IDRequirement
FR-1Return, for scope ∈ {plant, device} and period ∈ {day, month, year, custom}, the energy summary: generated, consumed, grid import, grid export, battery charged, battery discharged and self-used kWh.
FR-2Day: an intraday power series with Solar, Load, Battery (charge and discharge), Grid import and Grid export as separate series. It must be dense enough for a smooth, scrubbable 24 h curve.
FR-3Day: the day's peak PV power, and the time it occurred.
FR-4Day: Last 7 days daily generation, ending on the selected day.
FR-5Month: a daily series for the local days of the month, up to today for the current month, plus the best day. Year: a monthly series plus the best month.
FR-6Custom: an arbitrary local-date range, with the series grain chosen by range length (§3.4).
FR-7Every day boundary is the plant's local midnight (IANA timezone), never UTC.
FR-8Completeness in every response: devices expected, devices reporting, and for each missing device its identity and last sample time. A partial flag drives the banner and the "partial" labels.
FR-9Capabilities per scope: grid export, battery and load metering supported or not. Unsupported metrics are null, never 0.
FR-10Plant scope aggregates across up to 20+ devices server-side, in one round trip per screen state.
FR-11Authorization: only the plant's owner can read its analytics (the same rule as get_devices).
FR-12Financial figures are estimates: savings = self-used kWh × buy rate, and export credit = grid export kWh × export rate. Money is plant scope only. A missing rate yields no money value (a call to action), never 0.

Check against the design's numbers: 51.4 − 12.4 = 39.0 kWh self-used, 39.0 × 65 = 2,535 PKR and 12.4 × 40 = 496 PKR. For the month, 486 − 112 = 374 kWh. The design's self-used definition is generated − exported, which is what telemetry_daily.self_used_kwh already uses.

1.4 Non-functional requirements​

IDRequirement
NFR-1p95 ≤ 300 ms server time for any single screen state at plant scope with 20 devices. One request per screen state.
NFR-2Day-boundary correctness with duplicates, out-of-order delivery, device reconnect catch-up and wrong device clocks (§3.2).
NFR-3Past, completed periods are immutable once finalised, so they can be cached. Today's period is fresh to ≤ 5 min, which is the default telemetry interval.
NFR-4Retention is explicit (§3.3). A request outside retention returns null plus a reason code, never an empty chart that looks like zero production.
NFR-5Analytics queries must not degrade ingest or device control. They use a bounded pool, statement timeouts and per-connection rate limits.

2. What exists today (audit)​

2.1 Pipeline​

Device → tcpserver, which polls every 5 min by default (30 s while a client is watching; one watched sample in ten is still stored as default) → buildFlatTelemetry → JetStream telemetry.<deviceKey> → persistence-worker → telemetry.

  • The row time is the server receive time, never the device clock (server/internal/storage/postgres/postgres.go).
  • Inserts are ON CONFLICT (device_id, time) DO NOTHING, so redelivery is idempotent. Every analytics table is keyed by device_id (devices.id) since migration 0072, so a device's analytics survive a logger swap; before it, by logger_id.
  • The canonical fields come from server/internal/canonical/canonical.go.

2.2 Schema relevant to analytics​

Migrations live in server/internal/storage/postgres/migrations/ (0001–0037).

ObjectDefinitionRetentionFilled?
telemetry (hypertable, 1-day chunks)readings JSONB, plus STORED generated columns: pv_power_w, load_power_w, pv_energy_today_kwh, load_energy_today_kwh, grid_import_energy_today_kwh, grid_export_energy_today_kwh, battery_charge_energy_today_kwh, battery_discharge_energy_today_kwh, battery_soc_pct. PK (logger_id, time).5 days (0004), no compressionYes
telemetry_daily (CAGG, 0005)time_bucket('1 day', time) in UTC. last() of each *_today_kwh counter, avg(battery_soc_pct), sample_count. No peak power.4 months (0007)Yes (hourly policy)
telemetry_monthly / telemetry_yearly (CAGGs on CAGGs, 0008/0010)Sums of the daily figuresnoneYes, but inherit the UTC days
daily_financials, tariff_ratesMoney per day, rates per device–No writer
devices.lifetime_* (7 kWh + 2 revenue columns)Lifetime totals–No writer. Always 0, yet get_devices returns them
devices.plant_id (0032)Client-supplied plant ULID, uppercase, no index–Yes
device_alert_state (0033)connected, connected_at, disconnected_at, plant_id–Yes

Also relevant:

  • There is no timezone anywhere in the TCP database. The plant timezone lives in cse-http-be DynamoDB (timezone, default Asia/Karachi).
  • There is no plant table in TCP.
  • docs/design/telemetry-db-schema.md is referenced from code comments but doesn't exist.

2.3 APIs​

  • No history or analytics API exists in either repo. ws-gateway's message set is: watch, unwatch, read_registers, get_registers, register, update_device (which replaced bind_new_logger), write, get_devices, get_activity, get_activity_detail, delete_device, confirm_delete_device, get_alerts and its companions, get_alert_catalog. None of them reads telemetry or any aggregate.
  • Patterns worth reusing:
    • checkOwnership for authorization.
    • The keyset pagination in activity.go and alerts.go.
    • The get_devices filter owner_user_id = $1 AND ($2 = '' OR plant_id = $2).
  • cse-http-be has plants and devices REST, and its ADR 0001 forbids it from touching telemetry. Analytics is therefore TCP's job (ADR 0008).

2.4 Defects and gaps that block the screens​

#GapEvidenceImpact on Analytics
G1UTC day buckets.telemetry_daily uses time_bucket('1 day', time) with no timezone. The *_today_kwh counters reset at the inverter's local midnight, which is 19:00 UTC for PKT. last() over a UTC day picks a post-reset sample from the next local day.Every daily, monthly and yearly figure is wrong for UTC+5. Blocking.
G2IP20 2–12 kW energy never polled.Its canonical sources pv_daily_generation@1180, grid_daily_consumption@1207, grid_daily_generation@1203, battery_daily_charge_energy@1187, battery_daily_discharge_energy@1191 and total_output_power@1159 are all "category": "config" in ip20-2kw-12kw.json. Profile.TelemetryRegisters() only polls ""/"telemetry" (modbus/registry.go).IP20 generated, consumed, import, export and battery kWh, plus load power, are NULL. Confirmed in code; not yet confirmed against DB rows (needs an approved read, §6).
G3IP20 maps grid_daily_consumption to both load and grid import.canonical.go IP20 mapConsumed = Import for IP20, which is wrong for any site with solar.
G4No battery power or grid power canonical fields.Only pv_power_w, load_power_w and SOC are canonical.The Battery, Import and Export chips have no data.
G5No intraday history past 5 days.Raw retention 5 d; no hourly or 15-min rollup.The Day view's ‹ pager fails for dates older than 5 days.
G6Daily rollup retained 4 months.0007The Year view and "last year" months become unregenerable, and monthly values are frozen from UTC days.
G7No peak power.Not in any CAGG"Peak solar 11.06 kW" has no data.
G8Rates: HTTP has electricityRate (buy) only.cse-http-be/packages/core/src/schemas.tsThe export rate and the Energy Rates sheet have nowhere to save.
G9Battery and meter are not TCP devices.One logger = one inverter; battery and meter data come through the inverter's registers.The screen 40 "Batteries" and "Meters" groups need a mapping (§4.4).
G10ws-gateway trusts the client-supplied userId (TODO(auth)).cmd/ws-gateway/main.goAnalytics would expose production history under the same known gap as get_devices. This isn't new, but it widens the exposure.
G11Lifetime columns always 0.§2.2Not needed by Step 5 but misleading. Fix or stop returning them.

3. Architecture​

3.1 Decision summary​

  1. Serve Analytics from ws-gateway as one new request/response message, get_analytics (§4). This follows ADR 0008, reuses the existing connection, ownership check and deployment, and adds no new service or load balancer.
  2. Add a UTC 15-minute continuous aggregate, telemetry_15m, over raw telemetry.
    • Fifteen-minute buckets align with every IANA offset (+5:00, +5:30, +5:45…), so any local day is an exact union of 96 buckets.
    • That lets one tz-agnostic aggregate serve every timezone, which Timescale's single-timezone CAGG time_bucket(..., timezone) can't.
    • It provides the Day chart, peak power and "today" totals.
  3. Add a regular table, energy_daily, keyed (device_id, local_date) (logger_id until 0072).
    • It holds finalised local-day energy per device, computed once from telemetry_15m after each local day ends, in that plant's timezone.
    • Month, Year, Custom and Last-7-days read it. It's tiny (≤ 366 rows per device per year) and kept indefinitely.
  4. Compute daily energy from lifetime-counter deltas (§3.2), not from the midnight-reset *_today counters. This makes the result independent of the inverter clock and the reset time, and robust to duplicates and out-of-order data.
  5. Plant timezone lives in a new TCP plants table. It's filled from the analytics request in v1 and from HTTP's plant.upserted.v1 projection later (§4.3).
  6. Money is computed by ws-gateway from rates the app passes in get_analytics (§4.5, confirmed). TCP stores no tariff. daily_financials / tariff_rates stay unused until they're either fed from an HTTP projection or dropped.

Rejected alternatives:

  • Rebucket the existing CAGG with a timezone argument. One CAGG per timezone doesn't scale to a multi-country fleet, and the today counters would still carry the device-clock problem.
  • Upsert daily rows on every ingest. That doubles write amplification on the hottest path (288 upserts per device per day).
  • Query raw telemetry for everything. Raw is kept only 5 days and is 3× denser than needed.
  • Serve Analytics from cse-http-be. ADR 0001 forbids it.

3.2 Daily energy: lifetime-counter deltas​

For each energy flow, the device exposes a cumulative lifetime counter. On Aotai (all telemetry category, 0.1 kWh):

FlowRegister
PVe_pv_all@16
Loade_load_all@234
Grid importe_buy_all@40
Grid exporte_sell_all@37
Battery chargee_charging_all@213
Battery dischargee_discharging_all@215

IP20 has total_pv_total_generation_h/l and totals in the 1180–1210 bank, which must be moved to telemetry category (Phase 1).

New canonical fields: pv_energy_total_kwh, load_energy_total_kwh, grid_import_energy_total_kwh, grid_export_energy_total_kwh, battery_charge_energy_total_kwh, battery_discharge_energy_total_kwh.

Daily energy for local day D:

E(D) = end_counter(D) − end_counter(baseline day)
end_counter(D) = the counter in D's latest 15-minute bucket that carried it

The baseline day is normally D−1. It is an earlier day if the device had no readings in between.

Why this form:

  • Clock-independent. The server time decides the day, so an inverter clock set to UTC or drifting doesn't matter.
  • Duplicate- and order-safe. A max over a bucket is idempotent.
  • Robust to one bad read. The day's value is its last bucket's value, not the day's maximum, so a single misread sample earlier in the day cannot inflate it. That case is covered by an integration test.
  • Self-healing after an outage. Energy produced while offline appears as soon as the device reconnects. It's attributed to the reconnect day if the outage spans midnight, which is a documented tradeoff. The alternative is losing it.
  • Lifetime comes for free: the latest counter value. That later fixes G11.

Guards:

  • A negative delta (counter reset, inverter replaced) → 0, with anomaly = 'counter_reset'.

  • A delta above MaxDailyKWh (400 kWh: a 12 kW inverter is 288 kWh at the physical limit) per day since the baseline day → discarded as a bad read, falling back to the daily counter, with anomaly = 'implausible'. The per-day scaling lets energy from an offline gap through (D2) without letting a misread counter add a multiple of a real day. There is no rated-power register mapped yet, so the cap is fleet-wide rather than per model.

  • Residual risk: a misread in a day's very last sample still sets that day's end. The next day then shows a counter_reset and falls back to its daily counter.

  • A model without lifetime counters falls back to max(*_today_kwh) within the local day (source = 'daily_counter'). max rather than last, because max is immune to a post-reset sample landing in the day.

  • Power integral (2026-09-30). Each flow's canonical power (pv_power_w, load_power_w, and the split grid_power_w/battery_power_w) is integrated over the day's telemetry_15m buckets: sum of bucket means × 15 min. It is an approximate lower bound on the flow's true energy. Buckets with no sample add nothing (hours offline count as 0). A bucket with any sample counts its mean for the full 15 min, which slightly overstates the buckets where a device connected or dropped mid-bucket. It replaces the counter's answer when:

    • there is no counter answer at all. Example: an Aotai with no meter, whose grid buy/sell counters are withheld. The day's source becomes power_integral, or mixed together with other kinds.
    • the counter is below integral × 1/1.25 − 0.2 kWh, i.e. the integral exceeds it by more than 25 % and 0.2 kWh together. The counter misses part of the flow, and the day records anomaly = 'counter_below_power'.
    • (since 2026-11-30, PV only) the PV counter reads 0 while the PV integral is above 0, however small: a dead counter, not noise. Also recorded as counter_below_power. Seen as a risk on the Yorker, whose pv_daily_generation (1180) sits in the parallel-summary bank and whose scale is unverified on hardware (see Yorker). Days already finalised are not recomputed by this change.

    Measured on the Aotai on logger i30000252761006466 on 29 Sep: its load counter moved 0.5 kWh while the back-up port drew 4.6 kWh, because the counter only counts what the inverter supplies off-grid. Its battery counters agreed with their integral within ~10 % (1.0 vs 1.08 kWh). The margin keeps that noise from ever displacing a correct counter; it is far below the 6–9× shortfall of a counter that misses a whole flow.

    An integral is used only for power fields the device's model supplies (analytics.DayAgg.DropUnsupportedPower, via the device's register-map key, COALESCE(devices.profile, devices.model)). The reason: telemetry_15m's greatest(x, 0) yields 0, not NULL, for a missing x, so a model with no battery_power_w would otherwise report a battery "integral" of 0 kWh. get_analytics capabilities count a power field as support for its flows.

3.3 Storage design​

Each TimescaleDB call sits alone in its own migration file, per the rule in 0001's header. The new canonical keys are read straight from readings JSONB, which avoids an ALTER TABLE … ADD COLUMN … GENERATED that would rewrite the hypertable.

MigrationObjectNotes
0038telemetry_15m continuous aggregatetime_bucket('15 minutes') in UTC, real-time (materialized_only = false). Per device per bucket: mean pv_w, load_w; battery_power_w split into battery_charge_w/battery_discharge_w and grid_power_w into grid_import_w/grid_export_w (each non-negative); pv_w_max; max and min of each of the six lifetime counters; max of each of the six daily counters; last SOC; samples, first_sample_at, last_sample_at.
0039refresh policystart_offset 4 days (inside the 5-day raw retention, so the first run backfills ~4 days), end_offset 15 minutes, every 15 minutes.
0040–0041compressionEnabled (segmented by the group-by key), compressed after 7 days: past the refresh window and the rollup's last re-run.
0042retention4 months (decision D3).
0043plantsplant_id PK, timezone (default Asia/Karachi), tz_source default/client/http_projection.
0044energy_dailyPK (logger_id, local_date), (device_id, local_date) since 0072; plant_id, timezone used; six *_kwh (NULL = not reported); six *_total_end_kwh end counters, carried forward through a day with no reading so the next delta always has a baseline; peak_pv_w/peak_pv_at; first/last sample; sample_count; source (total_delta/daily_counter/power_integral/mixed; power_integral added by 0048); anomalies (counter_reset, implausible, counter_below_power). FK to devices ON DELETE CASCADE; erasure also deletes it explicitly. No retention.
0045energy_rollup_runsPK (timezone, local_date, pass): which rollup passes are done.
0065, 0077–0082telemetry_15m rebuiltDropped and recreated grouped by device_id for the device-id re-key, with the same definition and policies. 0082 then refreshes it once over all raw telemetry (window ending 15 minutes ago, clear of the operator caveat below): the policy's 4-day window alone would leave the oldest day of the 5-day raw retention below the watermark and never materialised. Buckets older than raw telemetry's 5 days were lost once; energy_daily was re-keyed without loss.

| 0046 | plants_timezone_idx | For the rollup's non-default-zone lookup. | | 0047 | devices_plant_id_idx | Partial (plant_id IS NOT NULL), built CONCURRENTLY, for the same lookup and for the rollupTimezones probe. | | 0048 | energy_daily_source_check | Re-created to allow source = 'power_integral'. Only widens the check, on a small table. The down migration restores the old check NOT VALID, so rows already written survive a rollback. | | 0055 | energy_daily breakdown columns | Five nullable DOUBLE PRECISION columns: pv_to_load_kwh, pv_to_battery_kwh, pv_to_grid_kwh, battery_to_load_kwh, grid_to_load_kwh (§3.7). Catalog-only change, no rewrite. NULL = not measurable, or a day finalised before the column existed. |

The 0040 down migration is a deliberate no-op: disabling compression fails once any chunk is compressed, and 0038's down drops the aggregate anyway.

Retention after this change:

TierContentsRetention
HotRaw telemetry5 d (unchanged)
Warmtelemetry_15m4 months
Permanentenergy_dailyIndefinite (tiny)

telemetry_daily, telemetry_monthly and telemetry_yearly are unused. Migrations that drop them are in server/internal/storage/postgres/pending_migrations/ (not auto-applied), to be moved in once Analytics is verified in an environment.

3.4 Query shapes​

ViewSeries sourceSummary source
Day, todaytelemetry_15m for the local day (96 points)Lifetime-counter delta from telemetry_15m (live)
Day, past, within 4 monthstelemetry_15menergy_daily
Day, past, beyond 4 monthsnull + reason: PERIOD_OUTSIDE_RETENTIONenergy_daily (still available)
Production / Consumption–Breakdown columns of the same energy_daily rows (and, for Total, of the yearly sums), today live from telemetry_15m (§3.7)
Operation Statistics (Total)–Each logger's latest end counter (*_total_end_kwh) from the same Days read, else its last finalised row before them
Month / Yearenergy_daily grouped by local date / month; the current day is added liveSum of the same
Custom (calendar from/to)from = to → 15-min power for that day; ≤ 92 days → daily kWh; otherwise → monthly kWh. Max range 5 years; to may not be after today.Sum from energy_daily + today live
Total (Historical Data screen)Yearly kWh: years before the split summed in SQL from energy_daily, the rest as days (live included)Sum of the same

Plant scope = WHERE device_id = ANY($devices). The list comes from one devices lookup on (owner_user_id, plant_id), followed by a GROUP BY bucket. That's one statement per block, with no N+1 over devices.

3.5 Rollup worker​

persistence-worker runs postgres.Store.RunEnergyRollup at startup and then every 5 minutes (cmd/persistence-worker/rollup.go), under a Postgres advisory lock, so a second replica stays idle rather than double-computing.

Each tick covers the default zone plus every zone that has at least one non-revoked device. A plants row nobody owns a device in never adds a zone. For each zone:

  1. For each of the last 4 finished local days, it checks which of three passes are due: +30 min, +6 h and +24 h after that day's local midnight, minus those already recorded in energy_rollup_runs.
  2. If any pass is due, it computes the day once for every non-revoked device in that zone.
    • Finding the devices: the default zone walks devices by primary key (devices.id), each page starting strictly after the last id of the one before — the first after the nil UUID, which no device has — so every page is an index range scan, never a re-filter of the pages already done. Any other zone starts from plants_timezone_idx and joins through devices_plant_id_idx, so a small zone costs a few rows, not a fleet scan.
    • Computing: this is set-based, in keyset-paged batches of 1,000 devices: one aggregate query over telemetry_15m, one baseline lookup (a LATERAL primary-key probe per device for its latest energy_daily row), then a batched upsert. It then records every due pass.
  3. Days are processed oldest first, so a day's baseline is always the day before. The re-runs converge if a late reading changes an earlier day.
  4. Resilience:
    • A failing zone (for example a device deleted mid-batch, or a zone Postgres doesn't know) is reported and skipped; the other zones still run.
    • A (zone, date) that runs out of the tick's 15-minute budget resumes from its last finished batch on the next tick, so a fleet too large for one tick still completes. The checkpoint is in memory: after a restart the day starts over, which is idempotent.

A day with no readings gets no row. The next day's delta then covers it, which credits energy produced during an outage to the reconnect day (decision D2).

Because the lookback is 4 days, a worker that was down for up to 4 days catches up by itself, and so does the first deploy (the 15-minute aggregate starts with ~4 days of history). For anything longer, an operator runs deviceadmin backfill-energy --days N --yes (N ≤ 120).

  • It recomputes every zone's finished days in order, and ignores energy_rollup_runs.
  • It takes the same advisory lock, so it refuses to run while the scheduled rollup does.

The query path computes the same way: finalised energy_daily rows, plus the last 4 days and today computed live from telemetry_15m (analytics.ChainDays) wherever a finalised row does not exist yet. Today, and yesterday until 00:30, are therefore always current.

3.6 Canonical and register changes​

  • IP20 2–12 kW. The 54 read-only measurement registers at 1152–1210 (the WF_PARA sheet) are now telemetry category, so they are polled. The importer had tagged the whole sheet config.
    • This adds roughly one extra Modbus read block per 5-minute cycle.
    • They are not yet re-verified on hardware.
    • Load energy now comes from daily_output_energy / total_output_energy instead of grid_daily_consumption, which fixes G3.
  • New canonical fields (internal/canonical):
    • battery_soc_pct on IP20 comes from bms_soc_state_of_charge, not battery_capacity_percentage (2026-09-30). The workbook scales the latter 0.1 %, but the device sends whole percent: the IP20 on logger i20000283706146985 read 6.8 while its BMS reported 68. It is published only while bms_connection_status is 1, 2 or 3 (a BMS ID is locked, per the workbook). At 0 (still searching: no BMS, e.g. a lead-acid bank) SOC is omitted (null), not reported as 0 %.
    • battery_power_w (+ = charging): Aotai battery_exhibit_power, whose spec says "> 0 flows to the battery". Unmapped on IP20, because the sign of battery_power is undocumented there. The Battery chip therefore draws nothing for IP20 until the sign is verified on the bench IP20. The neighbouring positive_terminal_battery_current @1153 documents "> 0 charging", which is a lead, not proof.
    • grid_power_w (+ = importing): Aotai grid_exhibit_power ("> 0 flows to the inverter"), IP20 total_grid_power ("> 0 buying").
    • inverter_power_w: −grid_power_w on every model (owner rule, 2026-11-24, extending the Nexus rule below): + = feeding the grid, − = drawing from it, 0 at Balance. Present exactly when grid_power_w is (Supports follows grid). It was first (2026-11-02) the Aotai inverter_power register and unmapped on IP20; the app then summed grid and battery itself for models without it, which showed 2.32 kW on a Yorker 3.6 kW that was charging its battery from the grid. Live only (telemetry and group_telemetry); the analytics rollup does not read it (applyInverterFromGrid in internal/canonical).
    • Aotai exhibit registers can be dead (2026-09-30). On the Aotai on logger i30000252761006466, with no energy meter fitted, all four *_exhibit_power registers read 0 while 0.33 kW of load ran on the back-up port and 0.42 kW crossed the grid port. So load_power_w and grid_power_w published 0. Each exhibit field now falls back to raw measurements when it reads 0 and they do not:
      • pv_power_w ← dc_power_1 + dc_power_2.
      • load_power_w ← back_up_power + back_up2_power. This covers the back-up ports only: without a meter the inverter cannot see loads on its grid side.
      • grid_power_w ← −output_power (single phase only). The sign was worked out from that unit's data: with no PV and the battery near 0 W, the grid was the only source, and output_power read −0.42 kW. Without a meter it misses loads on the grid side of the inverter. The three-phase total_output_power has no observed sign, so it is not used.
      • battery_power_w ← battery_power signed by battery_current. battery_power is a magnitude: it never went negative across 5.5 h of discharge. battery_current is + while charging (15/15 rows) and − while discharging (61/62). Signed that way, it integrates to the device's own e_charging_day/e_discharging_day within 0.1 kWh.
    • Aotai grid power follows the inverter's grid status (2026-11-05). While grid_power_status (50) reads 0 (Balance), grid_power_w is published as 0, whichever source it came from. The inverter's LCD shows the grid at 0.00 kW then, but the −output_power fallback still carries the inverter's standby draw: QA saw the app show 0.16 kW (one unit) and 0.22 kW (parallel) against an LCD reading 0.00 kW and "Balance" (cse-mobile issue #98). At 1 (Sell) or 2 (Buy) the measured value stands, and with no status reading nothing changes. By the owner's rule for the same issue, inverter_power_w then follows the grid too: whenever grid_power_status is present it is −grid_power_w (Balance → 0; Buy → minus the grid import; Sell → the grid export), replacing the inverter_power reading, which showed 100 W with no load. Since 2026-11-24 this applies on every model with or without a status reading; with no grid_power_w it is absent. This feeds display, history and the group sum only, never an energy total.
    • Balance needs the meter, or a standby-sized reading (2026-11-12). Balance is only a measurement while the energy meter is online. With meter_com_status (127) not 1 the inverter cannot see the grid exchange and keeps reporting Balance under real load: logger i30000252761006466 (meter "Failure") reported Balance in every reading from 14:21 to 14:47 PKT while its grid port read 230–236 V, 2.9–3.3 A and output_power −0.49 to −0.55 kW, feeding 0.37–0.44 kW of back-up load with a full battery on standby. Zeroing that left the app's home load with no source. So Balance zeroes grid_power_w always while the meter is online, and otherwise only when the measured value is at most 250 W (standby draw; QA measured 160 W and 220 W). A larger reading is published as measured, and inverter_power_w follows it as under Buy/Sell.
    • Aotai grid energy needs the meter. e_buy_* and e_sell_* come from the external meter. With meter_com_status ≠ 1 they freeze or read 0 while the grid carries the load. So the four grid import/export fields (today and lifetime) are now omitted unless the meter is online. They become null ("not reported"), never a measured 0. canonical.Supports is unchanged: a metered Aotai does report them.
    • Six lifetime totals, *_energy_total_kwh:
      • Aotai: e_pv_all, e_load_all, e_buy_all, e_sell_all, e_charging_all, e_discharging_all.
      • IP20: total_output_energy, grid_total_consumption, grid_total_generation, battery_total_charge_energy, battery_total_discharge_energy.
      • IP20 has no single-register PV lifetime total (only an H/L word pair), so IP20 PV uses the daily counter.
      • IP20 totals are uint16 kWh and wrap at 65,536. A wrap shows up as a negative delta, which is treated as a reset and falls back to the daily counter.
  • Regression guard. A test (TestCanonicalSources_ArePolled) now fails if any canonical source register is not a polled telemetry register. This is exactly how the IP20 bug went unnoticed.
  • Lifetime columns. devices.lifetime_* kWh columns are now updated from the lifetime counters on each stored reading, keeping the last value when a reading lacks one. Self-used is generated − exported. The two revenue columns stay 0.

4. API contract​

4.1 get_analytics (client → ws-gateway)​

{
"type": "get_analytics",
"requestId": "c1",
"userId": "<owner uuid>",
"plantId": "01J…",
"deviceKey": null,
"view": "inverter",
"period": "day",
"date": "2025-08-12",
"timezone": "Asia/Karachi",
"rates": { "currency": "PKR", "buy": 65.0, "export": 40.0 }
}
  • deviceKey: null means plant scope. A device id means device scope; it must belong to plantId and to userId.
  • Device-only scope (2026-10-07): plantId omitted with a deviceKey reads that one inverter for any device userId owns, including one with no plant (devices.plant_id is nullable). It serves the per-inverter Historical Data screen (historical-data.md). Unknown or someone else's device → device_not_found. No plant timezone is recorded. Its finalised days are in the plant's rollup zone, which for a device with no plant is the default (Asia/Karachi).
  • Explicit scope and parallel groups (2026-10-28): an optional scope ("combined" / "individual") states what plantId/deviceKey imply and refuses a request where they disagree. A plant's devices are its parallel group: every device of the owner in the plant that is neither revoked nor deactivated (in the combined scope a deactivated device is no longer counted as a permanently missing inverter; asked for on its own, with plantId + deviceKey or deviceKey alone, its history is still served). The per-plant cap is GROUP_MAX_INVERTERS (default 50). When paralleled Yorker units are present (parallel_status ≠ 0), their system-bank energy and power (registers 1152–1210) are counted once per paralleled set, as the set's maximum, before aggregation (analytics.CollapseParallel / CombineBuckets); the reply lists scope.parallelSets and a PARALLEL_SET_COMBINED notice. ANALYTICS_PARALLEL_DEDUPE=off restores the per-unit sum. See Parallel inverters.
  • view applies only in device scope: inverter (the default) or battery. The battery is not a TCP device. battery reads the battery flows of the inverter behind deviceKey (§4.4). Smart meters are out of scope.
  • period is day / month / year / total / custom:
    • day takes date (YYYY-MM-DD).
    • month takes month (YYYY-MM).
    • year takes year (YYYY).
    • custom takes from/to, local dates picked in the app's calendar, inclusive.
    • total takes nothing. It returns yearly bars (grain: "year", date: "YYYY") from the first year with an energy_daily row to today. Years before the current one are summed in SQL (GROUP BY year over energy_daily); the current year is read as days through the same path as Year, live today included. Both reads split at the same date (postgres.TotalSplit): 1 January of the current year, or up to 4 days earlier during the first days of January, while the last days of December may not be finalised yet and only the live path computes them. No day is counted twice or dropped, and the rows read don't grow with device age. The period also widens to cover a live-only earliest day (a device first seen on 31 December, read on 1 January). Cost: the yearly sum scans one device's energy_daily rows before the split (~365 per year of age) through the primary key. If it ever shows up in the slow-request log, the fix is a small energy_yearly rollup.
  • timezone is required. It is the user's saved IANA zone name (never an offset) and is validated against pg_timezone_names (§4.3).
  • rates comes from the plant's saved rates. buy and export are each a number ≥ 0 or null when not set, and rates may itself be null. Rates apply to the whole requested period, so an estimate for a past period uses today's rate, not the historical one.

4.2 analytics (response)​

{
"type": "analytics",
"requestId": "c1",
"scope": { "plantId": "01J…", "deviceKey": null },
"period": { "kind": "day", "from": "2025-08-12", "to": "2025-08-12",
"timezone": "Asia/Karachi", "isCurrent": true, "complete": false },
"capabilities": { "generation": true, "load": true, "gridImport": true, "gridExport": true,
"battery": true, "batteryPower": true, "gridPower": true, "batterySoc": true },
"summary": {
"generatedKwh": 51.4, "consumedKwh": 33.8,
"gridImportKwh": 4.2, "gridExportKwh": 12.4,
"batteryChargeKwh": 15.2, "batteryDischargeKwh": 9.8,
"selfUsedKwh": 39.0,
"peakPvW": 11060, "peakPvAt": "2025-08-12T07:45:00Z",
"best": null,
"production": { "toLoadKwh": 19.6, "toBatteryKwh": 15.2, "toGridKwh": 12.4 },
"consumption": { "fromSolarKwh": 19.6, "fromBatteryKwh": 9.8, "fromGridKwh": 4.2 }
},
"series": {
"grain": "15m", "unit": "W",
"points": [ { "t": "2025-08-11T19:00:00Z", "pv": 0, "load": 812,
"batteryCharge": 0, "batteryDischarge": 640,
"gridImport": 172, "gridExport": 0 } ]
},
"completeness": {
"partial": true, "devicesExpected": 3, "devicesReporting": 2,
"missing": [ { "deviceKey": "<device id>", "lastSampleAt": "2025-08-12T06:42:00Z" } ]
},
"financial": {
"currency": "PKR", "selfUsedKwh": 39.0,
"savings": 2535.0, "exportCredit": 496.0, "total": 3031.0
},
"dataAsOf": "2025-08-12T09:40:00Z",
"dataStartsAt": "2025-03-14T04:10:00Z",
"unavailable": []
}

period: "total" adds lifetime (Operation Statistics), and day / month / year points carry revenue; see the integration page for both. last7Days was dropped on 2026-10-07 (the app no longer used it).

Rules:

  • Units are base units only (W, kWh). Timestamps are UTC ISO-8601; the client formats them in period.timezone.
  • null means not reported or not supported; 0 is a real zero (FR-9). An unsupported capability sets its summary fields and series values to null (the keys are always present) and its capabilities flag to false.
  • best is {date, kwh} for a month (best day) or a year (best month) and null otherwise.
  • series.grain is 15m (unit W; points t, pv, load, batteryCharge, batteryDischarge, gridImport, gridExport, soc), day, month or year (unit kWh; points date — YYYY-MM-DD, YYYY-MM or YYYY — generated, consumed, gridImport, gridExport, batteryCharge, batteryDischarge, one per date, month or year in the period, null where there is no data).
  • coverage appears only for a plant whose inverters differ in what they can report: {"gridExportKwh": {"devices": 1, "of": 2}} means the figure sums the one inverter that reports export.
  • Periods outside retention put { "block": "series", "reason": "PERIOD_OUTSIDE_RETENTION" } in unavailable; a day inside it with no 15-minute readings puts { "block": "series", "reason": "NO_READINGS" }. A period that ends before the first stored sample (or anything, when nothing is stored) is { "block": "all", "reason": "NO_DATA" }, and is not an outage (completeness.partial: false). A period that only starts before it carries a notice, notices: [{ "code": "NO_DATA_BEFORE", "from": <dataStartsAt> }] — notices qualify data that is present; unavailable means a block is missing.
  • capabilities are the model's field map narrowed by evidence: a flow is reported only if the inverter's last 288 readings carried one of its fields (§3.7). They never depend on the period, so one scope has the same capabilities on every tab.
  • Every timestamp is UTC (Z). Postgres hands timestamptz back in the server's local zone; the reply converts.
  • completeness:
    • A device counts as reporting if it has a sample in the last 15 min (current period), or samples covering the period (past period).
    • devicesExpected / devicesReporting count inverters (one inverter = one logger; confirmed). Batteries and meters are never counted.
  • financial appears only at plant scope; it is null at device scope (screen 41).
    • savings = selfUsedKwh × rates.buy and exportCredit = gridExportKwh × rates.export.
    • A null rate makes its figure null, never 0. The app then shows "Set … rate" and draws nothing for it (screen 39e).
    • total is the sum of the non-null parts, or null when both are null. A null gridExportKwh makes exportCredit null (screen 39d).
  • Errors are {"type": "analytics", "ok": false, "requestId", "code", "error"}. Codes: invalid_request, invalid_period (including an over-long custom range), invalid_timezone, invalid_rates, device_not_in_plant (also covers "not yours", so a logger id's existence is never confirmed), busy (one in flight per connection; gateway-wide cap of 8 concurrent), timeout (5 s), unavailable (no database, or migrations not applied), internal. The full client-facing reference is in WebSocket integration.

4.3 Timezone source​

  • v1 (confirmed): every get_analytics carries the user's saved timezone.
    • It is used directly for "today" and for all 15-minute series, which can be regrouped into any zone at query time.
    • It is written to plants(timezone, tz_source='client') only when the caller owns at least one device in that plant. So a request naming someone else's plant id, or a made-up one, can neither change its zone nor add a plants row.
    • Each gateway writes a given plant's zone once per change, not on every request (an in-process cache).
    • It must be known to Postgres's own tzdata (pg_timezone_names), checked on the request path (cached per zone) and again on write.
    • Two members of one plant with different saved zones overwrite each other: last writer wins. Keep the saved zone per plant, not per user, in the app.
    • The rollup uses the stored zone to finalise future local days in energy_daily. Already finalised days keep the zone they were computed in, so a change isn't retroactive.
    • period.timezone in the response echoes the zone actually used.
    • This trusts an owner-supplied value, but only for that owner's own plant. Asia/Karachi is the default before any request is seen.
  • v2: a consumer of HTTP's plant.upserted.v1 sets tz_source = 'http_projection', which takes precedence. From then on, client values are ignored.

4.4 Device selector mapping (screen 40)​

  • Inverters = the plant's TCP loggers (one logger = one inverter). Request: deviceKey=<logger>, view=inverter.
  • Batteries are HTTP device records whose parentDeviceId is an inverter. Request: deviceKey=<parent logger>, view=battery.
    • The summary is batteryChargeKwh and batteryDischargeKwh.
    • The series is battery charge/discharge power plus SOC (%).
    • PV, load and grid fields are omitted.
  • Meters are out of scope (confirmed). The app hides the Meters group, and plant totals are summed from the inverters only.

4.5 Money (server-side, rates passed in the request)​

savings = summary.selfUsedKwh × rates.buy (null if rates.buy is null)
exportCredit = summary.gridExportKwh × rates.export (null if rates.export or gridExportKwh is null)
total = sum of the non-null parts; null if both are null
  • A null value means the app draws nothing for it and shows the "Set … rate" call to action (screen 39e).
  • Partial periods keep completeness.partial = true, so the app labels them (39b).
  • ws-gateway validates the rates: finite, 0 ≤ rate ≤ 10,000 per kWh, and currency a 3-letter code. It echoes currency back and never stores rates.

Cross-repo note for cse-http-be (not edited from here): the app needs a saved export rate next to electricityRate, and a write path for the Energy Rates sheet (39f). Until that exists, the app sends export: null.


5. Capacity, scale and cost​

Assumptions:

  • 1 M devices at the 5-min default interval.
  • ~1 device per plant on average, with up to 20.
  • Evening peak: 10 % of plants open Analytics within 1 hour, 4 screen states each, giving ≈ 110 requests/s average and ≈ 500 requests/s in a burst (for example a push-notification-driven open).
ItemEstimate at 1 M devices
telemetry_15m rows96 M/day. At ~25 B/row compressed and 4 months retention: ~290 GB (gp3 ≈ $23/mo, plus refresh CPU). 400 d would be ~0.95 TB (≈ $80/mo).
CAGG refreshReads the ~288 M raw rows/day already ingested. Adds roughly 20–30 % to DB write/CPU load; it doesn't multiply it.
energy_daily365 M rows/yr, ~40 GB/yr uncompressed. Kept indefinitely; compress or convert to a hypertable when it passes ~100 GB.
RollupFinalises each device-day once, plus two idempotent re-runs: ~96 × 3 bucket reads per device per day ≈ 3.3 k rows/s averaged. Cheap.
Per-request DB workDay, plant of 5: ~480 bucket rows + ~35 daily rows. Year: ≤ 1,830 daily rows. At 500 requests/s that's ≲ 1 M index-range rows/s, which calls for a read replica at the 1 M stage, not before.
Dev (today)The existing t4g.micro TimescaleDB with a handful of devices. The added cost is effectively $0: no new instance, service, load balancer or NAT.

Cost levers, in order:

  1. D3: telemetry_15m retention. It is 4 months; ~35 d would cut storage to ~84 GB.
  2. Cache completed-period responses in ws-gateway, keyed (scope, period, tz): in-process LRU, 1 h TTL, invalidated only by a rollup re-run. Build it only once latency metrics show a need.
  3. Drop the three unused UTC CAGGs.

Protection (NFR-5):

  • A dedicated analytics pool in ws-gateway, max 4 connections per task in dev, sized from max_connections in prod.
  • SET LOCAL statement_timeout = '2s'.
  • A per-connection limit of 5 analytics requests/s, returning rate_limited.
  • Custom range capped at 5 years.

Quotas and limits:

  • The limit to watch is Postgres connections, not an AWS quota.
  • A move to RDS/Aurora later changes max_connections and makes the read replica a managed feature.
  • No new AWS resources are introduced by this plan.

Observability (added to ws-gateway / persistence-worker metrics and logs):

MetricLabels
analytics_requests_totalperiod, scope, result
analytics_query_seconds (histogram)–
analytics_partial_responses_total–
energy_rollup_lag_seconds–
energy_rollup_anomalies_totalkind
telemetry_15m refresh job failures–

Logs carry requestId, plantId, deviceKey and period, never userId tokens.


6. Plan and status​

PhaseStatus
0 Verify on real dataPartly done (results below). The counter-reset hour and the delta-vs-daily agreement need a producing site.
1 Data correctnessDone: IP20 categories and map, new canonical fields, regression test.
2 Storage and rollupDone: migrations 0038–0045, rollup in persistence-worker, deviceadmin backfill-energy, erasure.
3 APIDone: get_analytics in ws-gateway.
4 Docs, cleanupDone: docs updated; the drops of the UTC rollups are written as pending migrations. Still open: the cross-repo note to cse-http-be (export rate, Energy Rates write path).
5 Historical Data Month/Year/Total (2026-10-07)Done; running in local dev, not yet deployed to AWS: device-only scope, period: "total" (historical-data.md §3). Unit, gateway and Postgres integration tests (npm run test:db) pass.

Phase 0 results​

2026-09-30, local timescaledb container, dev_telemetry_db, read-only:

  • One device: logger i30000252760985713, Nexus, 85 rows between 29 Sep 12:00 and 30 Sep 11:59 PKT.
  • All nine canonical fields populated at the time.
  • Lifetime counters never decrease: e_pv_all, e_sell_all, e_load_all and e_buy_all show 0 decreases.
  • The bench inverter moves no energy. Every daily counter is 0 and every lifetime counter is flat (PV 1471.1, load 1355.1, import 0.1 kWh). The reset hour and the delta-vs-daily agreement can't be verified locally.
  • The device reports only while the bench is powered: no overnight samples, and a largest gap of 16 h 26 m.
  • There are no IP20 rows, so G2 was confirmed in code only.
  • Stored values carry float artefacts (1471.1000000000001), so the API rounds energy to 0.01 kWh and power to 1 W, and ComputeDay ignores negative deltas smaller than 1e-6.

Testing​

Unit tests (no database), all passing:

  • internal/analytics covers:
    • Periods: every kind, the grain boundaries, rejections.
    • Karachi and DST day boundaries.
    • Every ComputeDay branch: delta, first day, no lifetime counter, uint16 wrap, implausible values, float noise, NULL vs 0.
    • Offline catch-up across a missing day.
    • The design's own numbers (51.4 / 12.4 → 39.0 kWh, PKR 2,535 + 496 = 3,031).
    • Null rates, mixed-plant coverage, an unsupported model, IP20 without battery power, the battery view, month best day and gaps, year by month, outside retention, and the JSON shape.
  • internal/canonical covers source polling, IP20 load ≠ import, and the factors.
  • cmd/ws-gateway (analytics_test.go) covers the handler with a fake store: validation codes, device-not-in-plant, an empty plant, storage errors, no database, and the concurrency cap.

Database integration tests (internal/storage/postgres/analytics_integration_test.go) are gated on POSTGRES_TEST_DSN, like the package's other integration tests. They insert devices and telemetry, so they must run against a throwaway TimescaleDB, never one holding real data. They cover:

  • Migrations applying.
  • telemetry → telemetry_15m → rollup → energy_daily → the query path, including a duplicate, an out-of-order row, and a daily counter that disagrees with the lifetime delta.
  • Idempotent recompute.
  • The live "today" chain.
  • Grid import/export split.
  • Plant scoping by owner.
  • The three rollup passes.
  • The http_projection timezone precedence.

Results, 2026-09-30. These integration tests pass against a throwaway TimescaleDB container (migtest-tsdb, timescale/timescaledb:latest-pg16). Migrations 0001–0045 applied cleanly.

Operator caveat found while testing: never run refresh_continuous_aggregate('telemetry_15m', …) by hand with a window ending at or after the current 15-minute bucket.

  • A refresh moves the aggregate's watermark forward, and it never moves back.
  • Real-time aggregation only covers buckets above the watermark.
  • So readings that land in a bucket already marked materialised stay invisible until the next policy refresh (up to 15 minutes).
  • The policy's own end_offset of 15 minutes keeps it clear of this. So does deviceadmin backfill-energy, which never refreshes.

Still to verify before production:

  1. Run the integration tests on a throwaway container (done, passing).
  2. Bench-test the IP20: confirm that 1152–1210 read cleanly and that total_grid_power's sign is correct. Establish battery_power's sign, then map it.
  3. Compare a producing site's energy_daily against the inverter's own daily totals for a few days (read-only queries on the AWS dev DB).
  4. Watch persistence-worker's energy rollup finalised days log line and ws-gateway's slow get_analytics warnings after deploy.

7. Decisions​

Confirmed 2026-09-30:

#DecisionOutcome
D1Timezone sourceThe user's saved IANA timezone is passed in every get_analytics. It is stored per plant and is not retroactive for finalised days (§4.3).
D2Energy produced during an outage spanning midnightAttributed to the reconnect day (lifetime-delta method)
D3telemetry_15m retention (Day-view history depth)4 months
D4Selector scopesPlant, inverter, battery (the parent inverter's battery flows). Smart meter skipped.
D4b"N of M reporting"Counts inverters
D5Custom rangeCalendar from/to (inclusive local dates); grain per §3.4
D6MoneyRates passed in get_analytics; ws-gateway computes; null rate → null figure, nothing drawn
D7AuthSame userId model as get_devices; accepted for dev only. Realtime-ticket auth (ADR 0003) is a production prerequisite.

8. Where it lives​

ConcernCode
Daily-energy rules, periods, response assembly (pure, no DB)server/internal/analytics/ (energy.go, period.go, date.go, response.go, lifetime.go)
Data start, reported-field evidenceserver/internal/storage/postgres/analytics_meta.go
Canonical fields and IP20 mappingserver/internal/canonical/canonical.go, server/internal/modbus/specs/ip20-2kw-12kw.json
Queries, rollup, backfillserver/internal/storage/postgres/analytics.go
Lifetime columnsserver/internal/storage/postgres/postgres.go (StoreTelemetry)
Rollup loopserver/cmd/persistence-worker/rollup.go
get_analytics handlerserver/cmd/ws-gateway/analytics.go
Backfill CLIserver/cmd/deviceadmin/backfill.go
Erasure of analytics rowsserver/internal/erasure/erasure.go (energy_daily; telemetry_15m is found as a continuous aggregate)
Migrationsserver/internal/storage/postgres/migrations/0038–0048, 0055; pending drops of the UTC rollups in pending_migrations/

No CDK change: no new service, instance, queue or AWS resource. The binaries already deployed pick this up on their next image.

Deploy and rollback. Deploy through npm run deploy only. Every change is additive: new aggregate, new tables, new message, more polled IP20 registers. Existing clients are unaffected. Rollback means stopping calls to get_analytics and running the down migrations 0047→0038 (0040's is a deliberate no-op). Raw telemetry is untouched throughout. The IP20 category change is reverted by restoring the spec file.

Review, 2026-09-30​

An independent review of the change found no critical issues. It found 2 high, 6 medium and 9 low issues and 4 doc mismatches. All the code issues are fixed except a few low ones that are accepted as documented behaviour.

#IssueFix
H1Any request could write any plant's timezone and add plants rows, which multiplied rollup zones and fleet scansWritten only for plants the caller owns a device in, once per change. Zones come only from plants with devices. Indexed zone lookup (0046/0047).
H2The analytics concurrency cap (8) exceeded the pool (4 on dev hosts)Cap = half the pool, 1–8
M1One misread lifetime-counter sample could add up to 2400 kWh to a dayDay end = last bucket's value; cap 400 kWh per day of gap
M2lifetime_self_used_kwh reset to 0 when a reading lacked the PV total (greatest ignores NULL)CASE keeps the old value
M3The rollup couldn't resume a day that overran its tick, and scanned devices per zonePer-batch checkpoint; index-backed zones
M4One failing zone aborted every zone after it; Go and Postgres tzdata could disagreeZones fail independently; zones validated against pg_timezone_names
M5Plant size was unbounded for long rangesUp to 50 inverters per request
M6IP20 energy is 1 kWh resolution and unverified on hardwareDocumented; bench check still open
LowNon-UUID userId → internal; database error text sent to the client; malformed get_analytics got no reply; year as a number dropped the frame; needless IP20 recompute on every row; 0040 down couldn't run; backfill wrote unfinished days and could race the rollupAll fixed
Low (accepted)The plant's peak PV is the sum of each inverter's 15-minute maximum (an upper bound), and peakPvAt is the start of that slot. A concurrent device delete fails that rollup batch until the next tick. IP20 uint16 counter wrap. ws_gateway_readonly has no grants on the new tables (the gateway does not use that role).Documented

Backend gaps, 2026-10-07​

The mobile team compared the finished Analytics screen with live dev replies and listed 11 gaps (B1–B11). Root causes and what changed:

#GapRoot causeChange
B1No history before today; availableFrom promised 3 monthsNothing is filtered by date: the local dev database was rebuilt after a corruption on 7 Oct, so it really has no older rows. History is keyed by logger id, so a replaced logger's history does not follow the inverter. availableFrom was computed from the retention policy only.dataStartsAt on both replies; NO_DATA_BEFORE / NO_DATA blocks; availableFrom = later of the retention edge and the first stored reading
B2No Production / Consumption splitNot builtPer-bucket allocation (§3.7), stored per day (0055)
B3Lifetime 0 kWh while the inverter's counter says 1,471.1Total summed stored dayslifetime block added; CO₂ and tree factors configurable on ws-gateway. First built from the inverters' lifetime counters; changed on 2026-10-08 (decision) to the Total reply's own stored figures, numbers 0 instead of null, after the app found the two disagreeing
B4Load 0 while the battery discharges 56–84 W (Aotai)Not a bug: on the bench nothing is plugged into the back-up port and no grid is connected, so the battery feeds only the inverter's own standby draw, which no load register measuresNone. Deriving load from the energy balance was rejected: it would count inverter losses as household consumption and inflate savings on every Aotai
B5No revenue per barNot builtrevenue on day / month / year points
B6IP20 supported / capabilities true, data always nullA standalone IP20 refuses the parallel-system register bank (1152–1210) with a Modbus exception, and every IP20 energy counter, grid power, SOC and load mapping lived there. The flags were model-level onlySOC falls back to battery_charge_percentage and load to the per-phase output power (single registers, units verified). The capabilities and supported flags now also need the device to have sent the field recently. The per-unit energy counters are H/L word pairs with an unverified scale, so they are still unmapped
B7Inverter / Output parameters missingNot in the cataloginverter and output groups, 22 telemetry_params columns (0056). Output on Aotai is the back-up port. No PV temperature register exists
B8SOC only in the battery viewpowerPoints filled soc for the battery view onlyFilled in both views
B9Build-default gateway doesn't know the deviceEnvironment: device ownership is per database, and the bench device's deployed row was deleted on 2026-09-25None in code
B10Battery current sign—Documented: + charging, − discharging (Aotai, verified against its own counters)
B11last7Days unused; peakPvAt set at 0 W—last7Days dropped (and the 6 extra days it read); peakPvAt is null when the peak is 0 W

3.7 Production / Consumption breakdown and evidence​

Allocation. Per 15-minute bucket, from the bucket means: solar → load min(pv, load); solar → battery min(max(pv − load, 0), charge); solar → grid min(max(pv − load − charge, 0), export); battery → load min(max(load − pv, 0), discharge); grid → load min(max(load − pv − discharge, 0), import). Each leg is summed only over buckets where every power it reads is present. least/greatest skip NULLs, so an unguarded leg would read "load not measured" as "all solar went to the load". The day's legs are then scaled by day energy ÷ power integral of their base flow (generation or consumption), so they agree with the counter-based totals shown beside them, and each is then capped at the day's energy of its own sink (to grid ≤ export, battery → load ≤ discharge, …): the two counters can run ahead of their curves by different amounts, and a leg must never claim more than its sink measured. Legs whose power fields a model lacks are NULL: an IP20 has no battery power, so only solar → load is known. A period containing a day with energy but no breakdown (finalised before 0055) reports the leg as null rather than an understated sum. A day with 0 kWh of the base flow needs no breakdown: every leg of it is 0 (the bench IP20's 7 Oct, which predates its load reading, generated nothing). deviceadmin backfill-energy --days 120 --yes recomputes the last 4 months from telemetry_15m (a data rewrite: run it deliberately, once 0055 is applied). Older days stay without a breakdown.

Evidence. ReportedColumns reads, per logger, the last 288 rows of telemetry_params (about a day) and counts non-null values per canonical column: one LATERAL index scan per logger on the (logger_id, time) key, at most 50 loggers per request. A logger with no rows gives no evidence, and its model decides. Stored data does not count (decided 2026-10-08): the app found one IP20 showing export on Month but not on Day, because the month had stored values. Capabilities now describe the inverter, the same on every period; the cost is that a flow the inverter has stopped reporting (a meter removed) is hidden on past periods too. Note that telemetry_15m records a missing signed power as 0 W (greatest(NULL, 0)), so a standalone IP20 carries 0 kWh of grid import every day in energy_daily that it never measured; those rows stay as stored, and the reply hides them.

Cost and scale. No new service or AWS resource. Per get_analytics the gateway adds three small indexed reads: first sample (two probes per logger), the evidence scan (≤ 288 rows per logger), and on Total the last finalised row per logger. At 1M devices the 0055 columns add about 40 bytes per logger-day to energy_daily, roughly 15 GB a year before compression on a table that has no retention. 0056 adds 22 nullable REAL columns to telemetry_params, which compress to almost nothing while NULL; on devices that report them they add about 88 bytes per reading before compression.

Second report, 2026-10-08​

The mobile team re-tested against dev on 8 Oct. Much of what they saw came from synthetic history seeded into the local database that day by the dev seed-analytics tool (daily totals from 15 Jun, no 15-minute series, fake end counters), which the report read as real. What was a real defect, or a decision, and what changed:

#ReportVerdictChange
1No 15-minute chart before 7 OctSeeded days have totals only; real gap: no reason sentNO_READINGS series block for a day inside retention with no readings
2Negative IP20 load; SOC 57 → 92 %Load: the per-phase output power fallback is signed (−8/−16 W of noise at no load). SOC: real — the unit went from standby to running and its BMS connected at 05:30 UTCPV and load clamped at 0 in canonical (new readings) and in the reply (stored buckets); a load day integrating just below 0 is 0, not dropped
3Lifetime contradicts TotalCounter vs seeded historyDecision: lifetime = the Total reply's stored figures; numbers 0, never null
4Parts don't add upSeeded rows, the uncapped scaling (fixed earlier), and by design (losses in no leg)Decision: parts add up exactly. Measured legs (battery, grid) capped by their sinks; to load / from solar are the remainder (losses included), so the two differ; a null total nulls its parts; on a mixed plant or a model that cannot measure a leg, no remainder
5IP20 capabilities differ by periodStored (seeded) data turned flags onDecision: capabilities from the model and recent readings only
6last7Days emptyStale: dropped on the app team's earlier requestNone
7Before the first reading looks like an outageRealNO_DATA (all) and partial: false; a finished period's missing[].lastSampleAt is the last reading at or before its end (LastSampleBefore, two index probes per absent logger, read only when one is absent)
8No signal for gaps inside a periodFeature gapNot done yet
9Multi-inverter test plantEnvironment—
10Undocumented fieldsDocumented in this repo; the site is not redeployed—
11Timestamps +05:00Real: timestamptz scans in the server's zoneEvery reply timestamp converted to UTC
12NO_DATA_BEFORE under seriesDecisionMoved to notices; unavailable[].from removed
13Production gateway older than devDeploymentDeploy through npm run deploy