Salud: a card opens onto the day, hour by hour, and onto the days before it
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera
presentarme una medida por hora, y no me da el histórico". Two separate things, and only one
of them was the app's fault.

**The history was the automation's setting.** With Date Range on its default (`Today`) every
sync carries today and nothing else, so there is exactly one day in the file to draw. That is
why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps
now say `Previous 7 Days` and say why.

**The hours were thrown away by us.** Even when the phone sends 288 readings a day, the
receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all
there could ever be — a number you cannot look into. Worse, the recommended setting was Time
Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived
in the first place. The recommendation is now `Hours`, and the storage keeps the hours.

The merge rule for them is the same shape as the day rule, for the same reason: a payload
whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress*
grows on every run of a five-minute automation, so it is replaced and never unioned — 500 +
900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as
the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and
which also makes switching an automation from Days to Hours mid-day converge instead of
double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now
land in their own hour, which is where intraday detail comes from when nothing is grouped.

Three things that would have been silent bugs, caught while writing it:

- The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute
  automation produces samples that sit exactly on the hour, and reading one of those as an hour
  total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in
  one payload, and it fails against the per-point version of the rule.
- A day that arrived as a day total keeps its hours beside it, and a day stored before this
  existed keeps its aggregate when the first hour shows up — recomputing it from hours it does
  not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a
  test).
- A payload grouped by hour writes the ledger row anyway, because a later payload with real
  minutes can describe the same instant and the union path can only see the ledger. Without it
  the raw-sample route test double-counts a single sample.

The hours are the bulky part of this data, so they are kept for a week (the day aggregates
still live the full 400 days), pruned when the night's file is written, and fetched one metric
and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none
of them; the day view carries only a count per day, which is what tells the sheet whether it
is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour
list to that day), and every field the watch sent; when the automation groups by Days it says
so instead of leaving a gap where a chart should be.

Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in
`api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31),
three render tests through the real sheet, the route documented in `api/openapi.yaml` and
`website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two
symptoms now in Troubleshooting.
This commit is contained in:
dsantillan committed 2026-09-23 13:28:58 -04:00
1 parent 34d28fa5c5
commit aa6ec8ef22
14 files changed
+839 -63

No files matched your search

+138 -5
View File
@@ -9,8 +9,8 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
parsePayload, mergeVitals, vitalsSeries, emptyVitals, parseHaeDate, normalizeDoc,
RETENTION_DAYS, LEDGER_MS
parsePayload, mergeVitals, vitalsSeries, vitalsHours, emptyVitals, parseHaeDate, normalizeDoc,
RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS
} from '../vitals.js';
const NOW = Date.parse('2026-05-01T23:30:00Z');
@@ -230,17 +230,150 @@ test('workouts dedupe on name+start+end, newest first, and a re-send adds nothin
assert.equal(again.doc.workouts.length, 2);
});
/* ---------- hours: the detail a day total throws away ---------- */
test('an hourly payload keeps its hours, and the day is exactly their sum', () => {
// "Time Grouping: Hours": every datapoint sits on the hour, so each one is that hour's total.
const hours = qty9 => metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00') },
{ qty: qty9, date: at('2026-05-01', '09:00:00') }
]);
const day = d => d.metrics.step_count.days['2026-05-01'];
const first = merge(emptyVitals(), parsePayload(hours(800)));
assert.equal(day(first.doc).f.qty.sum, 1300, 'the day is the sum of its hours');
assert.equal(day(first.doc).h['08'].f.qty.sum, 500);
assert.equal(day(first.doc).h['09'].f.qty.sum, 800);
assert.equal(day(first.doc).h['09'].f.qty.n, 1);
// The hour in progress grows on every run of a five-minute automation: replaced, never added,
// because 500 + 900 + 1,340 steps in one hour is a number the watch never recorded.
const grown = merge(first.doc, parsePayload(hours(1500)));
assert.equal(day(grown.doc).h['09'].f.qty.sum, 1500);
assert.equal(day(grown.doc).f.qty.sum, 2000, 'and the day moves with it');
assert.equal(grown.stats.duplicates, 1, 'the finished hour was an exact repeat');
assert.equal(grown.stats.points, 1);
const again = merge(grown.doc, parsePayload(hours(1500)));
assert.equal(again.stats.points, 0);
assert.equal(again.stats.duplicates, 2);
assert.equal(day(again.doc).f.qty.sum, 2000);
});
test('a raw sample that happens to sit on the hour does not wipe that hour', () => {
// Both stamps are real samples ("Since Last Sync" at a 5-minute cadence), and the first one is
// exactly on the hour. Reading that timestamp as an hour *total* would delete the samples
// already stored in 09 — which is why the rule is decided from the payload, not the point.
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 300, date: at('2026-05-01', '09:00:00') },
{ qty: 700, date: at('2026-05-01', '09:05:00') }
]))).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.h['09'].f.qty.sum, 1000);
assert.equal(day.h['09'].f.qty.n, 2);
assert.equal(day.f.qty.sum, 1000);
// ...and the same payload again is a no-op, on both levels.
const again = merge(doc, parsePayload(metric('step_count', 'count', [
{ qty: 300, date: at('2026-05-01', '09:00:00') },
{ qty: 700, date: at('2026-05-01', '09:05:00') }
])));
assert.equal(again.stats.duplicates, 2);
assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000);
});
test('a day total and an hour total for the same day agree on which number is the day', () => {
const hours = metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00') },
{ qty: 900, date: at('2026-05-01', '09:00:00') }
]);
let doc = merge(emptyVitals(), parsePayload(hours)).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1400);
// A second automation grouped by Days sends the day itself: it is the better day number, and
// the hours are a shape the total cannot contradict, so they stay for the sheet to draw.
const total = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }])));
doc = total.doc;
assert.equal(total.stats.points, 1);
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1500);
assert.equal(Object.keys(doc.metrics.step_count.days['2026-05-01'].h).length, 2, 'the hours rode along');
// Then the hourly automation sends the next hour: it re-sends the whole day, so from here the
// day is the hours again — the two rules converge instead of drifting apart.
doc = merge(doc, parsePayload(metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00') },
{ qty: 900, date: at('2026-05-01', '09:00:00') },
{ qty: 200, date: at('2026-05-01', '10:00:00') }
]))).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1600);
});
test('a day stored before hours existed keeps its samples when the first hour arrives', () => {
// A document written by an older version: the day has an aggregate and no hours, so its samples
// cannot be placed in an hour. Rebuilding the day from the hours it does not have would throw
// 2,000 steps away; the sample is added to the day the old way and the hour is what it is.
const legacy = normalizeDoc({
metrics: { step_count: { days: { '2026-05-01': { n: 4, lastTs: 0, f: { qty: { n: 4, sum: 2000, min: 100, max: 900, last: 900 } } } } } }
});
const r = merge(legacy, parsePayload(metric('step_count', 'count', [{ qty: 300, date: at('2026-05-01', '09:05:00') }])));
const day = r.doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 2300, 'nothing already stored was lost');
assert.equal(day.f.qty.n, 5);
assert.equal(day.h['09'].f.qty.sum, 300, 'and the hour holds only what has a time of its own');
});
test('vitalsHours answers for one metric and one day, and invents nothing', () => {
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00') },
{ qty: 900, date: at('2026-05-01', '09:00:00') }
]))).doc;
const got = vitalsHours(doc, { metric: 'step_count', day: '2026-05-01' });
assert.deepEqual(got.hours.map(x => x.h), ['08', '09'], 'oldest hour first');
assert.equal(got.units, 'count');
assert.equal(got.hours[0].f.qty.sum, 500);
assert.equal(got.hours[0].f.qty.avg, 500);
assert.ok(got.hours[0].ts > 0);
// A day the automation never grouped by hour — a day total, or a day that does not exist — is
// an empty list rather than a fabricated one; the screen says why instead of drawing zeros.
const grouped = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }]))).doc;
assert.deepEqual(vitalsHours(grouped, { metric: 'step_count', day: '2026-05-01' }).hours, []);
assert.deepEqual(vitalsHours(doc, { metric: 'step_count', day: '2026-04-01' }).hours, []);
assert.deepEqual(vitalsHours(doc, { metric: 'not_a_metric', day: '2026-05-01' }).hours, []);
assert.equal(vitalsHours(doc, { metric: 'step_count', day: 'not-a-day' }).day, null);
assert.equal(vitalsHours(emptyVitals(), { metric: 'step_count', day: '2026-05-01' }).metric, null);
});
test('the hourly detail is pruned after a week while the day aggregates live on', () => {
const start = Date.parse('2026-05-06T12:00:00Z');
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 100, date: at('2026-05-05', '08:00:00') },
{ qty: 200, date: at('2026-05-06', '08:00:00') }
])), start).doc;
assert.ok(doc.metrics.step_count.days['2026-05-05'].h, 'hours are stored while they are recent');
// A week later the sheet can still ask for today and yesterday, and nothing it could show is
// older than this: 24 buckets × every metric × every day of the year is what this avoids.
const later = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 300, date: at('2026-05-13', '08:00:00') }])), Date.parse('2026-05-13T12:00:00Z')).doc;
assert.equal(later.metrics.step_count.days['2026-05-05'].h, undefined, 'the hours of an old day are gone');
assert.equal(later.metrics.step_count.days['2026-05-05'].f.qty.sum, 100, 'the day itself stays');
assert.ok(later.metrics.step_count.days['2026-05-06'].h, 'and a day inside the window keeps its own');
assert.ok(HOURS_KEPT_DAYS >= 2 && HOURS_KEPT_DAYS <= RETENTION_DAYS);
});
/* ---------- housekeeping ---------- */
test('the dedupe ledger and the day buckets are both pruned, so the file stays bounded', () => {
const first = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }])), NOW);
// Five past the hour on purpose: a sample that sits exactly on the hour is indistinguishable
// from an hour bucket HAE grouped itself, and that shape has no ledger (see the hour tests).
const first = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:05:00') }])), NOW);
const seen = first.doc.metrics.step_count.seen;
assert.equal(Object.keys(seen).length, 1);
assert.equal(seen[Object.keys(seen)[0]], Date.parse('2026-05-01T09:00:00Z'));
assert.equal(seen[Object.keys(seen)[0]], Date.parse('2026-05-01T09:05:00Z'));
// A sync a week later: last week's sample can no longer be a repeat, so its ledger row goes
// while the day it belongs to stays.
const later = merge(first.doc, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-08', '09:00:00') }])), Date.parse('2026-05-08T12:00:00Z')).doc;
const later = merge(first.doc, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-08', '09:05:00') }])), Date.parse('2026-05-08T12:00:00Z')).doc;
assert.equal(Object.keys(later.metrics.step_count.seen).length, 1, 'the stale ledger row is gone');
assert.deepEqual(Object.keys(later.metrics.step_count.days), ['2026-05-01', '2026-05-08']);