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

+28 -16
View File
@@ -30,8 +30,8 @@ so), open **Salud → ⚙**, and:
- **Export Version**: `2`
- **Data Type**: `Health Metrics` (add `Workouts` as a second automation, or include both)
- **Summarize Data**: `On`
- **Time Grouping**: `Days`
- **Date Range**: `Previous 7 Days` (or `Default`)
- **Time Grouping**: `Hours` (or `Days` if you only ever want one number a day)
- **Date Range**: `Previous 7 Days` (not `Today` — see below)
- **Sync Cadence**: whatever you like — 5 minutes, hourly, once a day.
4. **Manual Sync → Export** once, to prove it works. It runs in the foreground, so it works even
while iOS is being cautious about background time.
@@ -43,9 +43,9 @@ neither can see the other's, and the URL is the only thing they share.
| Setting | Value | Why |
| --- | --- | --- |
| Summarize Data | On | Sends day aggregates instead of every sample. Smaller payloads, and the numbers on the cards are the ones Apple already summarised. |
| Time Grouping | Days | Makes each sync carry the **whole day's total**, which the receiver can then replace rather than add up (see §2). Raw samples work too, at more bytes and the same result. |
| Date Range | Previous 7 Days / Default | Always re-sends the last few days, so a sync missed while the phone was locked or in Low Power Mode is filled in by the next one. |
| Summarize Data | On | Sends aggregates instead of every sample. Smaller payloads, and the numbers on the cards are the ones Apple already summarised. |
| Time Grouping | Hours | Each sync carries the hours of the day, so the day is the **sum of its hours** and the detail sheet can draw the day hour by hour. Every hour is replaced by the next report of it, so a five-minute cadence is still safe (see §2). `Days` is the smaller option: one total per day, exact, and with nothing behind it to look into. |
| Date Range | Previous 7 Days | How much history exists at all. With `Today` (the default) every sync carries today only, and yesterday is never in the file — the cards then have a single day to draw. `Previous 7 Days` re-sends the last week every time, which also fills in a sync missed while the phone was locked or in Low Power Mode. |
| Export Version | 2 | The current payload shape (`{"data":{"metrics":[…]}}`). Version 1 is also accepted. |
Apple's own limits apply and cannot be worked around: HAE cannot read Health data while the phone
@@ -67,7 +67,12 @@ configured for, so the rule is chosen per payload, from the payload's own shape:
| The payload looks like | What the receiver does | Safe with |
| --- | --- | --- |
| Every datapoint sits exactly on midnight (`00:00:00`) — HAE's **Days** grouping, i.e. a **total** per day | The day it names is **replaced** by it, in full. A day total only ever supersedes another day total, so re-sending the same day all afternoon converges on the day's total instead of accumulating. | Overlapping windows, disjoint windows, manual re-exports, first sync of a year of history. |
| Anything else (real sample timestamps, or Hour/Minute grouping) | Each sample is identified by its **instant plus its numbers** and stored once. A repeat is skipped and reported back as `duplicates`; a genuinely new sample is added. | Overlapping windows (repeats detected) and disjoint ones (new samples add). |
| Every datapoint sits exactly on the hour (`HH:00:00`) — HAE's **Hours** grouping, i.e. a **total** per hour | That **hour** is replaced, for the same reason: the hour in progress grows on every run. The day is then recomputed as the sum of its hours, so the day total and the hourly detail can never disagree. The hours are what the detail sheet draws (kept for 7 days; the day aggregates live on). | Overlapping windows, disjoint windows, and switching an automation from `Days` to `Hours` mid-day. |
| Anything else — real sample timestamps, or Minute grouping | Each sample is identified by its **instant plus its numbers** and stored once, in its own hour. A repeat is skipped and reported back as `duplicates`; a genuinely new sample is added. | Overlapping windows (repeats detected) and disjoint ones (new samples add). |
The hour rule is decided from the **whole payload**, never from a single timestamp: a five-minute
automation also produces samples that land exactly on the hour, and reading one of those as an hour
total would wipe the hour it belongs to.
Day keys come from the date **the phone wrote**, never from the server's clock. HAE stamps each
sample with its own local offset, so grouping by a server-local date would slide every evening's
@@ -76,8 +81,9 @@ steps into the next day for anyone not on UTC.
The one configuration neither rule rescues is **Minute** grouping with an 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 gets 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 grouping by `Days` removes it entirely. Being
explicit about that is better than a cleverer rule that silently miscounts a whole day.
a handful of steps, a few hundredths of a kcal — and grouping by `Days` (or `Hours`) removes it
entirely. Being explicit about that is better than a cleverer rule that silently miscounts a whole
day.
What every sync answers with is the receipt: how many points arrived, how many were recognised as
already stored, and what the profile holds now.
@@ -108,8 +114,10 @@ Inside, numbers are kept **per day and per field, generically**:
"last": { "ts": 1756900000000, "metrics": 12, "points": 40, "duplicates": 288, "workouts": 1 },
"metrics": {
"heart_rate": { "units": "bpm", "sources": ["Apple Watch"],
"days": { "2026-09-03": { "n": 288, "lastTs": 1756900000000,
"f": { "Avg": { "n": 288, "sum": 20000, "min": 55, "max": 96, "last": 72, "avg": 69.4 } } } },
"days": { "2026-09-03": { "n": 24, "lastTs": 1756900000000,
"f": { "Avg": { "n": 24, "sum": 1665.6, "min": 55, "max": 96, "last": 72, "avg": 69.4 } },
"h": { "08": { "n": 1, "lastTs": 1756900400000,
"f": { "Avg": { "n": 1, "sum": 62, "min": 62, "max": 62, "last": 62 } } } } } },
"seen": { "2026-09-03 09:05:00 +0200|Avg:70": 1756900000000 } } },
"workouts": [ { "name": "Walking", "start": 1756900000000, "durMin": 60, "avgHr": 128, "fields": {} } ] }
```
@@ -125,6 +133,7 @@ Bounds, all enforced on write:
| Kept | Limit | Why |
| --- | --- | --- |
| Days per metric | 400 | A little over a year, so "this time last year" still exists. |
| Hours per day | 7 days | Detail is what makes the file grow (24 buckets × every metric × every day of a year); it is also only interesting for the last few days, which is what the detail sheet opens. The day aggregates underneath keep the full 400. |
| Dedupe ledger per metric | 72 h | A repeat can only be recent — the next automation run is minutes away, not days. |
| Workouts | newest 300 | A wrist that records every walk produces thousands a year; nobody scrolls past the last few hundred. |
| Request body | 32 MB | A full-history export with Summarize off is tens of megabytes. Over it: `413` with a readable message. The bundled web container allows this **one route** the bigger body (`web/nginx.conf.template`); every other `/api` path stays at 5 MB. Behind your own reverse proxy, raise `client_max_body_size` there too, or it is your proxy's 413 the phone sees. |
@@ -164,9 +173,11 @@ and you have backed up your health file too.
| --- | --- |
| `401 invalid ingest key` | Wrong key, a revoked one, or the header is missing `Bearer `. The key is shown in Salud → ⚙; re-copy it rather than retyping. A disabled account also answers 401. |
| `400 not a Health Auto Export JSON export` | Export Format is set to **CSV**, or the URL points at something else. Set JSON. |
| `413 body too large` | A first sync with everything selected and Summarize off. Turn Summarize Data on, group by Days, or split the metrics across two automations. Behind your own reverse proxy (Caddy, Cloudflare, a second nginx), raise its body limit for this path as well — the bundled stack already does. |
| `413 body too large` | A first sync with everything selected and Summarize off. Turn Summarize Data on, group by Days or Hours, or split the metrics across two automations. Behind your own reverse proxy (Caddy, Cloudflare, a second nginx), raise its body limit for this path as well — the bundled stack already does. |
| `200` with `received.points: 0` every time | Working, with nothing to add: bring your phone to Health Auto Export → Manual Sync → Export, and check Date Range covers a day that has data. |
| Nothing on the screen | Salud fetches 30 days by default — widen the range. A metric HAE has no samples for is skipped rather than shown as a zero. |
| A card shows one day, and its sheet has nothing before it | The automation's **Date Range** is `Today`, so yesterday was never sent. Set it to `Previous 7 Days`; the past cannot be invented server-side. |
| The detail sheet says "arrived as one total a day", with no hour list | **Time Grouping** is `Days`: the payload has one number per day and no hours to draw. Set it to `Hours` — the day stays the sum of its hours, so nothing is double-counted, and the hour list appears from the next sync on. |
| Steps look half a day behind | HAE cannot read Health while the phone is locked. Open the app (or tap the Automations widget) and the day fills in. |
| A metric shows under **Other** | Marketing-free behaviour: the catalogue in `vitals-view.js` covers ~50 metrics by name. Anything else is still stored and still charted — humanised, with every field HAE sent listed in its detail sheet. Add a line to `METRICS` to give it a better label, unit and aggregate. |
| Workouts do not appear in History | By design. They are read-only in Salud; see the top of this file. |
@@ -174,13 +185,14 @@ and you have backed up your health file too.
## 6. For developers
- `api/vitals.js` — parsing, the merge rules of §2, retention. Pure; tests in `api/test/vitals.test.js`
cover the merge under overlapping, disjoint, day-grouped, raw, heart-rate, sleep and
blood-pressure payloads, plus pruning and timezone handling.
- `api/server.js` — the five routes and the ingest key. Route tests in `api/test/server-vitals.test.js`
cover the merge under overlapping, disjoint, day-grouped, hour-grouped, raw, heart-rate, sleep
and blood-pressure payloads, plus pruning (days and hours), the day-from-hours projection and
timezone handling.
- `api/server.js` — the six routes and the ingest key. Route tests in `api/test/server-vitals.test.js`
run the real server and check isolation between profiles, that the key cannot read, and that ten
re-sends of the same window change nothing.
- `frontend/src/lib/vitals-view.js` — the metric catalogue, the card model, the units and the
workout rows. Tests beside it.
- `frontend/src/lib/vitals-view.js` — the metric catalogue, the card model, the units, the hour
rows and the day history the detail sheet lists. Tests beside it.
- `frontend/src/views/Health.jsx` — the screen and its two sheets.
- Endpoints are documented in `api/openapi.yaml` (tag `health`); rebuild `website/api.html` after
changing them.