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
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:
1 parent
34d28fa5c5
commit
aa6ec8ef22
14 files changed
+839
-63
No files matched your search
+95
-5
@@ -658,7 +658,7 @@ paths:
|
||||
step_count:
|
||||
units: count
|
||||
sources: [Apple Watch]
|
||||
days: [{ day: "2026-09-03", n: 1, lastTs: 1756900000000, f: { qty: { n: 1, sum: 12481, min: 12481, max: 12481, last: 12481, avg: 12481 } } }]
|
||||
days: [{ day: "2026-09-03", n: 1, lastTs: 1756900000000, hours: 0, f: { qty: { n: 1, sum: 12481, min: 12481, max: 12481, last: 12481, avg: 12481 } } }]
|
||||
heart_rate:
|
||||
units: bpm
|
||||
sources: [Apple Watch]
|
||||
@@ -682,6 +682,84 @@ paths:
|
||||
properties: { ok: { type: boolean } }
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/vitals/hours:
|
||||
get:
|
||||
tags: [health]
|
||||
operationId: vitalsHours
|
||||
summary: One metric's hours on one day
|
||||
description: |
|
||||
The detail behind a card: the hourly buckets the phone sent for a single metric on a single
|
||||
day, oldest first, each carrying the same per-field aggregates a day does.
|
||||
|
||||
This is a separate request on purpose. The hours are the bulky part of health data (24
|
||||
buckets per metric per day), and they are only interesting once somebody taps a card, so a
|
||||
screen listing forty metrics fetches none of them.
|
||||
|
||||
A day the automation grouped by Day has no hours and comes back as an empty list rather
|
||||
than a fabricated one: the honest answer to "what did the hours look like" for a payload
|
||||
that never carried hours is that the automation does not send them. Set Time Grouping to
|
||||
**Hours** in Health Auto Export to keep them — the day remains the sum of its hours, so
|
||||
nothing is counted twice.
|
||||
|
||||
Session only, like `GET /api/vitals`: the ingest key is write-only.
|
||||
parameters:
|
||||
- name: metric
|
||||
in: query
|
||||
required: true
|
||||
schema: { type: string }
|
||||
description: The metric name exactly as HAE wrote it (`step_count`, `heart_rate`…).
|
||||
- name: day
|
||||
in: query
|
||||
required: true
|
||||
schema: { type: string, example: "2026-09-03" }
|
||||
description: A calendar day, in the phone's own date, as `YYYY-MM-DD`.
|
||||
responses:
|
||||
'200':
|
||||
description: The hours stored for that metric and day (empty when there are none).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ok: { type: boolean }
|
||||
metric:
|
||||
type: string
|
||||
nullable: true
|
||||
description: Echoed when the profile has that metric, null otherwise.
|
||||
day:
|
||||
type: string
|
||||
nullable: true
|
||||
description: Echoed when the day exists for that metric, null otherwise.
|
||||
units: { type: string }
|
||||
hours:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
h:
|
||||
type: string
|
||||
description: "The hour as the phone wrote it: `00`–`23`."
|
||||
n: { type: integer, description: Samples folded into this hour. }
|
||||
ts: { type: integer, description: Epoch ms of the hour's newest sample. }
|
||||
f:
|
||||
type: object
|
||||
additionalProperties: { $ref: '#/components/schemas/VitalsField' }
|
||||
example:
|
||||
ok: true
|
||||
metric: step_count
|
||||
day: "2026-09-03"
|
||||
units: count
|
||||
hours:
|
||||
- h: "08"
|
||||
n: 12
|
||||
ts: 1756900000000
|
||||
f: { qty: { n: 12, sum: 512, min: 3, max: 120, last: 44, avg: 42.7 } }
|
||||
- h: "09"
|
||||
n: 12
|
||||
ts: 1756903600000
|
||||
f: { qty: { n: 12, sum: 1340, min: 8, max: 310, last: 96, avg: 111.7 } }
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/vitals/ingest:
|
||||
post:
|
||||
tags: [health]
|
||||
@@ -691,16 +769,21 @@ paths:
|
||||
The endpoint an iOS automation posts to. In Health Auto Export: Automation Type **REST
|
||||
API**, URL = this endpoint, header `Authorization: Bearer <ingest key>` (from
|
||||
`POST /api/vitals/key`), Export Format **JSON**, Export Version **2**, Summarize Data
|
||||
**On**, Time Grouping **Days**.
|
||||
**On**, Time Grouping **Hours** (or **Days** for totals with nothing behind them), Date
|
||||
Range **Previous 7 Days** — with the default range every sync carries today only, and the
|
||||
past is never in the file.
|
||||
|
||||
The merge is idempotent, which is what makes a five-minute cadence safe:
|
||||
|
||||
* A payload whose datapoints all sit on midnight is HAE's own day grouping, and a day total
|
||||
*replaces* the day it names — so the same day re-sent all afternoon converges on the
|
||||
day's total instead of adding up.
|
||||
* Anything else is a real sample (or an hour/minute grouping): a sample is identified by its
|
||||
instant plus its numbers and is counted once, so overlapping and disjoint windows both
|
||||
come out right. Repeats come back as `duplicates`.
|
||||
* A payload whose datapoints all sit on the hour is its hour grouping: the *hour* is
|
||||
replaced for the same reason (the hour in progress grows on every run), and the day is
|
||||
recomputed as the sum of its hours, so the day and the hourly detail can never disagree.
|
||||
* Anything else is a real sample: it is identified by its instant plus its numbers and is
|
||||
counted once, and it also lands in its own hour, which is where intraday detail comes
|
||||
from. Repeats come back as `duplicates`.
|
||||
|
||||
CSRF-exempt: the request carries its own credential in a header and has no session to
|
||||
borrow.
|
||||
@@ -1749,6 +1832,13 @@ components:
|
||||
day: { type: string, example: "2026-09-03" }
|
||||
n: { type: integer, description: Samples stored for this day. }
|
||||
lastTs: { type: integer, description: Epoch ms of the day's newest sample. }
|
||||
hours:
|
||||
type: integer
|
||||
description: >-
|
||||
How many hourly buckets this day has (0 or 1 when the automation grouped by Day, or
|
||||
when the samples arrived without an hour of their own). The buckets themselves are not
|
||||
in this response — `GET /api/vitals/hours` answers one metric and one day, because 24
|
||||
buckets × every metric × every day is not something a grid of cards should download.
|
||||
f:
|
||||
type: object
|
||||
description: Field name as HAE wrote it — `qty`, `Avg`, `asleep`, `systolic`…
|
||||
|
||||
+13
-1
@@ -19,7 +19,7 @@ import { startCadence } from './coach/cadence.js';
|
||||
import { startWarmup } from './coach/warmup.js';
|
||||
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
|
||||
import { verifyError } from './verify-error.js';
|
||||
import { parsePayload, mergeVitals, vitalsSeries, emptyVitals, RETENTION_DAYS } from './vitals.js';
|
||||
import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, emptyVitals, RETENTION_DAYS } from './vitals.js';
|
||||
import { hostAllowed, readCapped, parseMusicPage } from './music.js';
|
||||
|
||||
const PORT = +(process.env.PORT || 3000);
|
||||
@@ -1070,6 +1070,18 @@ const routes = {
|
||||
json(res, 200, { ok: true, days, key: user.healthKey || null, ...vitalsSeries(doc || emptyVitals(), { days }) });
|
||||
},
|
||||
|
||||
// One metric's hours on one day — the detail sheet, and only the detail sheet. It is a separate
|
||||
// request because the hours are the bulky part of this data (24 buckets per metric per day) and
|
||||
// a screen that lists forty cards needs none of it until somebody taps one. Session-only, like
|
||||
// the day view: the ingest key is write-only.
|
||||
'GET /api/vitals/hours': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const q = new URL(req.url, 'http://x').searchParams;
|
||||
const doc = readVitals(user.id);
|
||||
json(res, 200, { ok: true, ...vitalsHours(doc || emptyVitals(), { metric: q.get('metric'), day: q.get('day') }) });
|
||||
},
|
||||
|
||||
// Mint the ingest key on first use; a second call returns the one that exists rather than
|
||||
// silently invalidating the phone's configuration on a page reload.
|
||||
'POST /api/vitals/key': async (req, res) => {
|
||||
|
||||
@@ -211,6 +211,46 @@ test('a raw-sample automation accumulates a day without double counting, and a f
|
||||
assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), [today]);
|
||||
});
|
||||
|
||||
test('GET /api/vitals/hours opens one metric\'s day, and only with a session', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
const read = async q => (await (await fetch(`${h.api}/api/vitals/hours?${q}`, { headers: cookie('u_h1') }))).json();
|
||||
|
||||
// Signed out, and with the write-only ingest key, there is nothing to read here either.
|
||||
assert.equal((await fetch(`${h.api}/api/vitals/hours?metric=step_count&day=${today}`)).status, 401);
|
||||
assert.equal((await fetch(`${h.api}/api/vitals/hours?metric=step_count&day=${today}`, { headers: { Authorization: `Bearer ${key}` } })).status, 401);
|
||||
|
||||
// "Time Grouping: Hours" beside a metric the phone totals by day.
|
||||
await ingest(h, key, { data: { metrics: [
|
||||
{ name: 'step_count', units: 'count', data: [
|
||||
{ qty: 500, date: `${today} 08:00:00 +0000` },
|
||||
{ qty: 900, date: `${today} 09:00:00 +0000` }
|
||||
] },
|
||||
{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80.5, date: `${today} 00:00:00 +0000` }] }
|
||||
] } });
|
||||
|
||||
const hours = await read(`metric=step_count&day=${today}`);
|
||||
assert.equal(hours.ok, true);
|
||||
assert.deepEqual(hours.hours.map(x => x.h), ['08', '09'], 'oldest hour first');
|
||||
assert.deepEqual(hours.hours.map(x => x.f.qty.sum), [500, 900]);
|
||||
assert.equal(hours.units, 'count');
|
||||
|
||||
// The day view still reads a day as one number, and now says whether there is anything behind it.
|
||||
const day = (await (await fetch(`${h.api}/api/vitals?days=1`, { headers: cookie('u_h1') })).json()).metrics.step_count.days[0];
|
||||
assert.equal(day.f.qty.sum, 1400);
|
||||
assert.equal(day.hours, 2);
|
||||
|
||||
// A metric the phone grouped by day has no hours, and neither does a day nobody sent.
|
||||
assert.deepEqual((await read(`metric=weight_body_mass&day=${today}`)).hours, []);
|
||||
assert.deepEqual((await read(`metric=step_count&day=2000-01-01`)).hours, []);
|
||||
assert.equal((await read(`metric=step_count&day=2000-01-01`)).day, null);
|
||||
// A day that is not a date is not looked up at all (nothing here builds a path from input).
|
||||
const bogus = await read('metric=step_count&day=not-a-day');
|
||||
assert.equal(bogus.day, null);
|
||||
assert.deepEqual(bogus.hours, []);
|
||||
assert.equal((await read('metric=nope&day=' + today)).metric, null);
|
||||
});
|
||||
|
||||
test('DELETE /api/vitals wipes the health file and leaves the account, the key and the workouts alone', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
|
||||
+138
-5
@@ -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']);
|
||||
|
||||
|
||||
+169
-16
@@ -22,7 +22,13 @@
|
||||
* right here: the newer, larger total is the better answer, and re-sending the same
|
||||
* number is a no-op. Idempotent by construction, no ledger needed.
|
||||
*
|
||||
* otherwise real timestamps (raw samples, or grouped by hour/minute/second)
|
||||
* hourAggregated() every datapoint sits exactly on the hour ("Time Grouping: Hours")
|
||||
* → the *hour* bucket is replaced, for the same reason a day total is: the hour in progress
|
||||
* is re-sent with a larger value on every run, so union would count 512 steps as
|
||||
* 512 + 900 + 1340. The day is then recomputed as the sum of its hours (deriveDay), which
|
||||
* is what keeps the day number and the hourly detail from ever disagreeing.
|
||||
*
|
||||
* otherwise real timestamps (raw samples, or grouped by minute/second)
|
||||
* → union: a sample is identified by its instant plus its numbers and seen once. A repeat
|
||||
* is skipped, a genuinely new sample is added. Overlapping and disjoint windows both
|
||||
* come out right, because "have I seen this exact sample" is the question that does not
|
||||
@@ -32,8 +38,18 @@
|
||||
* overlapping window: the minute still in progress is re-sent with a larger value each time, so
|
||||
* it is a new sample by the union rule and its value is added twice. The error is bounded by one
|
||||
* partial minute of the cheapest metric (a handful of steps, a few hundredths of a kcal) and the
|
||||
* setup steps in docs/HEALTH.md say to group by Days. Being explicit about that beats a "smart"
|
||||
* rule that silently miscounts a whole day.
|
||||
* setup steps in docs/HEALTH.md say to group by Days or Hours. Being explicit about that beats a
|
||||
* "smart" rule that silently miscounts a whole day.
|
||||
*
|
||||
* ── Why the hours are kept at all ────────────────────────────────────────────────────────────
|
||||
*
|
||||
* A day total is the number people quote and the one thing a day is worth here, but it is also a
|
||||
* dead end: "8,123 steps today" is a figure you cannot look into, and the phone that sent it sent
|
||||
* 288 readings to build it. Grouping by Hours is the setting that keeps that shape — each hour
|
||||
* arrives as its own bucket with a real instant — and the buckets are stored beside the day, so
|
||||
* tapping a card can show the day hour by hour. Days grouping sends one point per metric per day
|
||||
* and there is no intraday detail in the payload to keep; that is a property of the automation,
|
||||
* not of this file, and the Salud screen says so rather than showing an empty hour list.
|
||||
*
|
||||
* ── What a stored document looks like ────────────────────────────────────────────────────────
|
||||
*
|
||||
@@ -49,7 +65,8 @@
|
||||
* step_count: {
|
||||
* units: 'count', sources: ['iPhone'],
|
||||
* days: { '2026-05-01': { n: 288, lastTs: 1699999999999,
|
||||
* f: { qty: { sum, min, max, last, n } } } },
|
||||
* f: { qty: { sum, min, max, last, n } },
|
||||
* h: { '13': { n: 12, lastTs: …, f: { qty: {…} } } } } },
|
||||
* seen: { '2026-05-01 13:05:00 +0200|qty:12': 1699999999999 }
|
||||
* }
|
||||
* },
|
||||
@@ -70,6 +87,13 @@ export const LEDGER_MS = 72 * 3600 * 1000;
|
||||
/** Days kept per metric. A little over a year, so "same day last year" still exists. */
|
||||
export const RETENTION_DAYS = 400;
|
||||
export const MAX_WORKOUTS = 300;
|
||||
/**
|
||||
* Days whose *hourly* buckets are kept. Detail is what makes a file grow (24 buckets × every
|
||||
* metric × every day), and it is only interesting for the last few days: "what did this morning
|
||||
* look like" is a question about today and yesterday, never about March. The day aggregates
|
||||
* survive this and live RETENTION_DAYS.
|
||||
*/
|
||||
export const HOURS_KEPT_DAYS = 7;
|
||||
/** Sources remembered per metric — decorative, but it answers "which watch sent this?" */
|
||||
const MAX_SOURCES = 4;
|
||||
const MAX_LEDGER_KEYS = 20000; // hard ceiling; the time-based prune is the real bound
|
||||
@@ -138,6 +162,8 @@ export function parseHaeDate(value) {
|
||||
|
||||
/** True when HAE grouped this datapoint onto a boundary rather than sampling it in real time. */
|
||||
const isMidnight = t => t.time === '00:00:00';
|
||||
/** ...and onto an hour: the shape "Time Grouping: Hours" produces, so each bucket is a total. */
|
||||
const onTheHour = t => t.time.slice(3) === '00:00';
|
||||
|
||||
// Fields on a datapoint that are not measurements. Everything else numeric is kept, so a metric
|
||||
// this file has never seen still stores its numbers instead of being dropped.
|
||||
@@ -255,6 +281,21 @@ function dayGrouped(points) {
|
||||
return points.length > 0 && points.every(p => isMidnight(p.at));
|
||||
}
|
||||
|
||||
/**
|
||||
* ...and does it look like its hour-by-hour one? Decided from the whole payload, never from a
|
||||
* single timestamp, because a raw 5-minute automation also has samples that sit exactly on the
|
||||
* hour: treating one of those as an hour *total* would wipe the hour it belongs to. Homogeneity
|
||||
* is the tell — HAE stamps every point the way its Time Grouping says, so a payload where the
|
||||
* minutes and seconds are all zero is grouping by hour, and one with a single stray minute is not.
|
||||
*
|
||||
* A raw payload that happens to be entirely on the hour is read as grouped, and that is benign:
|
||||
* for an hour being sent for the first time the two rules agree, and for one already stored HAE
|
||||
* would only re-send it identically.
|
||||
*/
|
||||
function hourGrouped(points) {
|
||||
return points.length > 0 && points.every(p => onTheHour(p.at));
|
||||
}
|
||||
|
||||
const dayKeyOk = k => /^\d{4}-\d{2}-\d{2}$/.test(k);
|
||||
|
||||
function addFields(bucket, fields) {
|
||||
@@ -274,6 +315,34 @@ const bucketFrom = (fields, ts) => {
|
||||
return b;
|
||||
};
|
||||
|
||||
/**
|
||||
* Recompute a day from its hours.
|
||||
*
|
||||
* A day with hours is not a bucket anybody increments — it is a *projection* of them, so the two
|
||||
* can never disagree: fourteen hourly buckets of 500 steps and "7,000 today" are the same number
|
||||
* by construction, and a partial hour replaced by a fuller one moves both. Aggregates are per
|
||||
* field the way the reading side wants them (`sum` for a counter, `n` so a rate averages), and
|
||||
* `last` comes from the newest hour that carried the field, because the hours are walked in order.
|
||||
*/
|
||||
function deriveDay(day) {
|
||||
const f = {};
|
||||
let n = 0;
|
||||
for (const hh of Object.keys(day.h || {}).sort()) {
|
||||
const hb = day.h[hh];
|
||||
n += hb.n || 0;
|
||||
for (const [k, v] of Object.entries(hb.f || {})) {
|
||||
const cur = f[k] || (f[k] = { n: 0, sum: 0, min: null, max: null, last: null });
|
||||
cur.n += v.n || 0;
|
||||
cur.sum += v.sum || 0;
|
||||
if (v.min != null && (cur.min == null || v.min < cur.min)) cur.min = v.min;
|
||||
if (v.max != null && (cur.max == null || v.max > cur.max)) cur.max = v.max;
|
||||
cur.last = v.last;
|
||||
}
|
||||
}
|
||||
day.f = f;
|
||||
day.n = n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold one parsed payload into a stored document. Pure: the input document is not modified.
|
||||
*
|
||||
@@ -289,6 +358,9 @@ export function mergeVitals(doc, payload, now = Date.now()) {
|
||||
const cur = out.metrics[m.name] || { units: '', sources: [], days: {}, seen: {} };
|
||||
if (m.units) cur.units = m.units;
|
||||
const replace = dayGrouped(m.points);
|
||||
// The hour rule only applies when the payload is not a day total: a day-grouped point is
|
||||
// midnight-stamped and would otherwise also read as "on the hour".
|
||||
const byHour = !replace && hourGrouped(m.points);
|
||||
// The ledger is only consulted by the union path, and only for instants recent enough to be
|
||||
// re-sent by the next automation run — anything older is pruned and can no longer be a repeat.
|
||||
pruneLedger(cur.seen, now);
|
||||
@@ -305,15 +377,53 @@ export function mergeVitals(doc, payload, now = Date.now()) {
|
||||
// every run after the first). `f` is compared as a whole because a day total and a
|
||||
// once-a-day gauge both live in it.
|
||||
if (prev && prev.n === 1 && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; }
|
||||
cur.days[key] = bucketFrom(p.fields, p.at.ms);
|
||||
// The hours already stored for that day ride along: the phone's own total is the better
|
||||
// day number, but it says nothing about the shape of the day and the hourly view is
|
||||
// built from what does. `own` records exactly that — this day's number is the phone's,
|
||||
// not the sum of its hours (see below).
|
||||
cur.days[key] = { ...bucketFrom(p.fields, p.at.ms), h: prev?.h || {}, own: true };
|
||||
stats.points++;
|
||||
continue;
|
||||
}
|
||||
const id = sampleId(p);
|
||||
if (cur.seen[id] != null) { stats.duplicates++; continue; }
|
||||
cur.seen[id] = p.at.ms;
|
||||
addFields(cur.days[key] || (cur.days[key] = { n: 0, lastTs: p.at.ms, f: {} }), p.fields);
|
||||
cur.days[key].lastTs = Math.max(cur.days[key].lastTs, p.at.ms);
|
||||
const day = cur.days[key] || (cur.days[key] = { n: 0, lastTs: p.at.ms, f: {}, h: {} });
|
||||
const hours = day.h || (day.h = {});
|
||||
const hh = p.at.time.slice(0, 2);
|
||||
if (byHour) {
|
||||
// An hour the phone grouped itself: replaced, never unioned, because the hour in progress
|
||||
// grows on every run of a five-minute automation.
|
||||
const prev = hours[hh];
|
||||
if (prev && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; }
|
||||
hours[hh] = bucketFrom(p.fields, p.at.ms);
|
||||
// The exact datapoint is remembered anyway: a payload grouped by hour and a later one
|
||||
// carrying real minutes can describe the same instant — the automation was reconfigured,
|
||||
// or two of them write to one profile — and the union path can only see the ledger, so
|
||||
// without this row it would count that instant a second time.
|
||||
cur.seen[sampleId(p)] = p.at.ms;
|
||||
} else {
|
||||
const id = sampleId(p);
|
||||
if (cur.seen[id] != null) { stats.duplicates++; continue; }
|
||||
cur.seen[id] = p.at.ms;
|
||||
addFields(hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} }), p.fields);
|
||||
hours[hh].lastTs = Math.max(hours[hh].lastTs, p.at.ms);
|
||||
}
|
||||
day.lastTs = Math.max(day.lastTs, p.at.ms);
|
||||
/* Recompute the day from its hours, which keeps this idempotent: the same hour arriving
|
||||
three times, or a partial hour replaced by a fuller one, leaves the same number behind.
|
||||
Two days are the exceptions, and both are days whose aggregate is not "the hours so far":
|
||||
own — the phone totalled this day itself (Days grouping). The hourly automation that
|
||||
then takes over re-sends the whole day, so its hours supersede the total and
|
||||
the day is derived from here on.
|
||||
!hc — a day stored by an older version of this file, whose samples have no hour
|
||||
attribution. Summing its (empty, or partly filled) hours would delete what is
|
||||
already there, so the new sample is added to the day the old way and the hours
|
||||
beside it stay what they honestly are: the part that has a time of its own. */
|
||||
if (day.own || day.hc || day.n === 0) {
|
||||
delete day.own;
|
||||
day.hc = true;
|
||||
deriveDay(day);
|
||||
} else {
|
||||
addFields(day, p.fields);
|
||||
}
|
||||
stats.points++;
|
||||
}
|
||||
pruneLedger(cur.seen, now, true);
|
||||
@@ -368,17 +478,43 @@ function pruneLedger(seen, now, enforceCap = false) {
|
||||
|
||||
function pruneDays(doc, now) {
|
||||
const oldest = new Date(now - RETENTION_DAYS * 86400000).toISOString().slice(0, 10);
|
||||
// Hours are the detail, and detail is what makes a file grow: 24 buckets × every metric × every
|
||||
// day of a year is a document nobody wants to load. A week of them is what "what did today look
|
||||
// like" needs — the day aggregates underneath are untouched and live out the full year.
|
||||
const hoursOldest = new Date(now - HOURS_KEPT_DAYS * 86400000).toISOString().slice(0, 10);
|
||||
for (const m of Object.values(doc.metrics)) {
|
||||
for (const day of Object.keys(m.days)) if (day < oldest) delete m.days[day];
|
||||
for (const [day, b] of Object.entries(m.days)) {
|
||||
if (day < oldest) { delete m.days[day]; continue; }
|
||||
if (b && b.h && day < hoursOldest) {
|
||||
// `hc` goes with them: it means "this day is the sum of its hours", and with the hours
|
||||
// gone that claim would make the next sample for that day rebuild it from nothing.
|
||||
delete b.h;
|
||||
delete b.hc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- reading ---------- */
|
||||
|
||||
/** One bucket's fields, as the client wants them: the count, the total, and the mean it implies. */
|
||||
function projectFields(f) {
|
||||
const out = {};
|
||||
for (const [k, v] of Object.entries(f || {})) {
|
||||
out[k] = { n: v.n, sum: v.sum, min: v.min, max: v.max, last: v.last, avg: v.n ? v.sum / v.n : null };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project a stored document into the compact series the view renders, oldest day first.
|
||||
* Aggregates are per *field* — `qty.sum` for a counter, `Avg.last` for a rate — so the client
|
||||
* never has to know how HAE grouped things.
|
||||
*
|
||||
* Each day also says how many hourly buckets it has. That count is the difference between a card
|
||||
* whose detail is a single number and one you can open up, and sending the number instead of the
|
||||
* buckets keeps this response the size of a card list: the hours themselves are one metric and
|
||||
* one day per request (vitalsHours below), fetched when somebody actually taps in.
|
||||
*/
|
||||
export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) {
|
||||
const d = normalizeDoc(doc);
|
||||
@@ -393,13 +529,30 @@ export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) {
|
||||
for (const day of Object.keys(m.days).sort()) {
|
||||
if (day < from) continue;
|
||||
const b = m.days[day];
|
||||
const f = {};
|
||||
for (const [k, v] of Object.entries(b.f || {})) {
|
||||
f[k] = { n: v.n, sum: v.sum, min: v.min, max: v.max, last: v.last, avg: v.n ? v.sum / v.n : null };
|
||||
}
|
||||
out.push({ day, n: b.n, lastTs: b.lastTs, f });
|
||||
out.push({ day, n: b.n, lastTs: b.lastTs, hours: Object.keys(b.h || {}).length, f: projectFields(b.f) });
|
||||
}
|
||||
if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out };
|
||||
}
|
||||
return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts };
|
||||
}
|
||||
|
||||
/**
|
||||
* One metric's hours on one day, oldest first — what the detail sheet opens.
|
||||
*
|
||||
* A day that HAE grouped itself (Days grouping) has no hours and comes back empty rather than
|
||||
* invented: the honest answer to "what did the hours look like" for a payload that never carried
|
||||
* hours is "the automation does not send them", and the screen says that instead.
|
||||
*/
|
||||
export function vitalsHours(doc, { metric, day } = {}) {
|
||||
const d = normalizeDoc(doc);
|
||||
const name = String(metric || '');
|
||||
const m = Object.prototype.hasOwnProperty.call(d.metrics, name) ? d.metrics[name] : null;
|
||||
const key = String(day || '');
|
||||
const b = m && dayKeyOk(key) ? m.days[key] : null;
|
||||
const hours = [];
|
||||
for (const hh of Object.keys((b && b.h) || {}).sort()) {
|
||||
const hb = b.h[hh];
|
||||
hours.push({ h: hh, n: hb.n, ts: hb.lastTs, f: projectFields(hb.f) });
|
||||
}
|
||||
return { metric: m ? name : null, day: b ? key : null, units: m ? m.units : '', hours };
|
||||
}
|
||||
Reference in new issue
Block a user