Skip to content

feat(state): store bounded scalar history aggregates - #1290

Merged
frahlg merged 4 commits into
masterfrom
feat/ems-history-aggregates-20260917
Sep 17, 2026
Merged

frahlg merged 4 commits into
masterfrom
feat/ems-history-aggregates-20260917

Conversation

@frahlg

@frahlg frahlg commented Sep 17, 2026

Copy link
Copy Markdown
Member

Core currently writes every scalar poll and later copies those same rows to Parquet. This grows the live database and makes archiving and backup compete with useful EMS work. This change stores scalar measurements at 10-second resolution for 24 hours, one-minute Parquet for 30 days and five-minute Parquet for two years. It preserves original energy observations and the current driver/control cadence.

Each summary keeps count, sum, min/max, last value and observed time bounds. Reads report source resolution and weight means by count. Timestamp identities and existing commit receipts prevent duplicate contributions across batches, uncertain commits and restarts. Latest-value reads still return an actual reading. Missing intervals stay missing; bounds do not assert continuous coverage.

Archives publish only after a full readback matches their staged contents. SQLite wins during publication/prune overlap; pruning removes only matching complete minutes. Admission cannot overtake a pending tick at the archive boundary. Old Parquet conversion saves its source cursor with each staging transaction and independently checks counts, sums, extrema and time bounds before removing raw data. Separate aggregate hour contributions survive legacy hour rebuilding. Backups include all summary tables and files, omit mutable scratch, and preserve empty BLOBs during copying.

Schema 5 protects the new storage format from image-only rollback. A rollback needs a verified full backup and its matching Core. Stored cold_retention_days values no longer steer this policy; startup reports them. Hourly gauge summaries and existing energy totals remain after detailed history expires.

This is the scalar part of #1287. Dashboard rows and the older daily-energy/cost readers stay on their current path: those consumers require a separate original-interval integration change before their rows can be aggregated safely. Live-backup latency #1246 and control-loop IO isolation #1247 remain separate gates. This PR does not deploy or release a beta.

Validation: local make verify; state and backup packages; aggregate race tests repeated three times. Regressions cover irregular timestamps, short spikes, duplicates, out-of-order data, restart mid-bucket, pending admission at cutoff, partial-day archives, source changes, corrupt files, interrupted prune, resumed legacy conversion, mixed old/new hourly evidence, unchanged energy-ledger output and full backup/verify/restore with duplicate identities preserved.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-17T08:43:22.884463Z 737c77c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 737c77cb48

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

out[i] = SeriesPoint{TsMs: sm.TsMs, V: sm.Value, Min: sm.Value, Max: sm.Value, N: 1}
}
return out, nil
return s.mergedSeries(ctx, s.coldDir, driver, metric, sinceMs, untilMs, 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Expose aggregation metadata in CSV exports

When GET /api/series?...&points=0&format=csv spans data older than 24 hours, this path now returns one-minute or five-minute summaries rather than raw samples. Although JSON exposes resolution_ms, first_ms, and last, the CSV branch in go/internal/api/api.go still writes only ts_ms,driver,metric,v,min,max,n and documents points=0 as raw data, so spreadsheet and ML consumers silently interpret an aggregate mean at the bucket's last timestamp as an actual measurement. Add the aggregation metadata to CSV or prevent this raw-export mode from returning summaries.

Useful? React with 👍 / 👎.

Comment on lines +741 to +744
SELECT ts_ms,value FROM (
SELECT s.ts_ms,s.value FROM ts_samples s JOIN identity i USING(driver_id,metric_id)
UNION ALL SELECT b.last_ms,b.last_value FROM ts_buckets b JOIN identity i USING(driver_id,metric_id) WHERE b.resolution_ms=10000
) ORDER BY ts_ms DESC LIMIT 1`, driver, metric).Scan(&sm.TsMs, &sm.Value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retain latest readings after hot buckets are archived

For a metric that stops reporting for more than 24 hours, maintenance publishes its minute summary and deletes both the minute row and its 10-second source buckets, while aggregate-mode writes never enter ts_samples. This query searches only ts_samples and 10-second buckets, so LatestSample then returns sql.ErrNoRows even though retained Parquet history still contains the last observation; for example, InferDerKinds consequently forgets a device kind that it documents as having ever emitted telemetry. Persist or query a durable latest observation rather than limiting this lookup to the hot tier.

Useful? React with 👍 / 👎.

@frahlg
frahlg merged commit f9217d5 into master Sep 17, 2026
17 checks passed
@frahlg
frahlg deleted the feat/ems-history-aggregates-20260917 branch November 11, 2026 09:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant