Salud: el total del día es el día, y un recibo que explica el número que no cuadra
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

"Las actualizaciones están llegando pero las tarjetas no tienen los mismos números que Salud." Las
actualizaciones llegan, entonces: el problema es qué se hace con ellas, y hay dos formas de que un día
salga más grande de lo que el reloj dice.

**El total del día leído como hora 00.** Si HAE manda el total del día con marca de medianoche en el
mismo payload que las horas, ese punto caía en el cubo de las 00:00 y la suma del día lo contaba
además de las horas — 499 declarados + 341 de horas = 840, que es exactamente el número reportado.
Ahora un punto de medianoche que vale más que todo el resto del payload junto es el total del día
(una hora no puede tener más que el día que la contiene) y nunca se convierte en hora 00; un 00:00
chico de verdad sigue siendo la primera hora y se suma como cualquier otra.

**Horas sumadas a un total que ya las contenía.** Con el día declarado por el teléfono, cada hora que
llegaba después se le sumaba encima — el mismo error, una capa más arriba. Ahora el total declarado
**es** el día y las horas nunca se le agregan: son la forma del día, no un segundo número. Su suma
queda al lado, en `hours_sum`, y la hoja de la métrica dice cuando los dos difieren, en palabras:
tanto el teléfono declaró, tanto suman las horas, y cuál de los dos estás viendo. Un total que no se
renueva en seis horas deja de mandar, así que cambiar una automatización de Días a Horas converge en
vez de congelarse para el resto del día.

Y para la otra forma — horas que en realidad son **totales acumulados** en vez de deltas, que también
suman de más — cada envío deja un **recibo por métrica**, visible en la hoja: cuántos datos llegaron,
cómo vienen marcados (un total por día, uno por hora, muestras sueltas o mezcla), de qué fuentes,
cuánto suman y los tres últimos valores. Una corrida de números que suben (340 → 420 → 499) es la
señal de que son acumulados, y eso es la diferencia entre 499 y 840 vista en la pantalla en vez de
deducida. Es un recibo, no una lectura: el campo que cita se elige por una lista fija porque este
módulo no tiene el catálogo, y nada de él entra en el cálculo de un día.

Seis tests nuevos del merge y del recibo, dos de las filas de la hoja y uno de render por la hoja
real. Mutation-check de las dos mitades del arreglo: leer el total como hora 00 falla, y sumarle las
horas al total declarado falla. API 261 en verde, frontend 1701, build OK.
This commit is contained in:
dsantillan committed 2026-09-23 17:55:17 -04:00
1 parent 81301523ab
commit 407d7c47c9
9 files changed
+373 -19

No files matched your search

+85 -6
View File
@@ -282,7 +282,7 @@ test('a raw sample that happens to sit on the hour does not wipe that hour', ()
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', () => {
test('the phone\'s own day total is the day, and hours never get added to it', () => {
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') }
@@ -290,22 +290,31 @@ test('a day total and an hour total for the same day agree on which number is th
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.
// A second automation grouped by Days sends the day itself: it is the number the Health app
// shows, so it becomes the day — and the hours 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.
// Then hour points arrive for the same day. The day does NOT become their sum: the declared total
// already contains the hours below it, and adding them is exactly how 499 steps became 840. The
// sum rides beside it instead, so a disagreement between the two is visible rather than silent.
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);
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 1500, 'the phone\'s total is still the day');
assert.equal(day.own, true);
assert.equal(Object.keys(day.h).length, 3, 'and the hours still landed');
assert.equal(day.hsum.qty, 1600, 'with their sum beside them, for the screen to compare');
// A newer total replaces it, as it always did.
assert.equal(merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1700, date: at('2026-05-01') }]))).doc
.metrics.step_count.days['2026-05-01'].f.qty.sum, 1700);
});
test('a day stored before hours existed keeps its samples when the first hour arrives', () => {
@@ -344,6 +353,76 @@ test('vitalsHours answers for one metric and one day, and invents nothing', () =
assert.equal(vitalsHours(emptyVitals(), { metric: 'step_count', day: '2026-05-01' }).metric, null);
});
test('a midnight total inside an hourly payload is the day, not hour zero', () => {
// The shape that produced "the watch says 499 and the app says 840": HAE sends the day's total
// stamped at midnight *and* the hours, in one payload. Read as hour 00, the total is added to the
// hours and the day doubles; read as what it is, the day is 499 and the hours are its shape.
const p = (qty, time) => ({ qty, date: at('2026-05-01', time) });
const payload = metric('step_count', 'count', [
p(499, '00:00:00'), // the day's own total, stamped at midnight
p(120, '08:00:00'), p(220, '09:00:00') // and two hours of it
]);
const doc = merge(emptyVitals(), parsePayload(payload)).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 499, 'the day is the total, not 499 + 340');
assert.equal(day.own, true);
assert.equal(day.h['00'], undefined, 'and the midnight point did not become hour 00');
assert.deepEqual(Object.keys(day.h).sort(), ['08', '09']);
assert.equal(day.hsum.qty, 340, 'the sum of the hours is kept beside it');
// The same payload again is a no-op on the day, and the hours converge.
const grew = merge(doc, parsePayload(metric('step_count', 'count', [
p(499, '00:00:00'), p(120, '08:00:00'), p(260, '09:00:00')
]))).doc.metrics.step_count.days['2026-05-01'];
assert.equal(grew.f.qty.sum, 499);
assert.equal(grew.h['09'].f.qty.sum, 260);
// A genuine 00:00 bucket — a handful of steps, less than the rest of the day — stays hour 00.
const small = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
p(3, '00:00:00'), p(300, '08:00:00'), p(400, '09:00:00')
]))).doc.metrics.step_count.days['2026-05-01'];
assert.equal(small.f.qty.sum, 703, 'a real first hour is summed like any other');
assert.equal(small.h['00'].f.qty.sum, 3);
assert.equal(small.own, undefined);
});
test('the receipt records what arrived, so a wrong number can be explained', () => {
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
{ name: 'step_count', units: 'count', data: [
{ qty: 120, date: at('2026-05-01', '08:00:00'), source: 'Apple Watch' },
{ qty: 220, date: at('2026-05-01', '09:00:00'), source: 'Apple Watch' },
{ qty: 90, date: at('2026-05-01', '09:30:00'), source: 'iPhone' }
] }
] }
}), NOW).doc;
const r = doc.shape.step_count;
assert.equal(r.points, 3);
assert.equal(r.stamps, 'mixed', 'a payload with an hour and a real instant says so');
assert.equal(r.field, 'qty');
assert.deepEqual(r.sources, ['Apple Watch', 'iPhone']);
assert.equal(r.sum, 430);
assert.equal(r.newest.value, 90);
assert.equal(r.tail.length, 3);
assert.equal(r.head.length, 3);
assert.equal(r.at, NOW);
// Hour-stamped and day-stamped payloads are labelled too, because that is the question the
// receipt exists to answer.
const hourly = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 120, date: at('2026-05-01', '08:00:00') }, { qty: 220, date: at('2026-05-01', '09:00:00') }
]))).doc;
assert.equal(hourly.shape.step_count.stamps, 'hour');
const dayly = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 499, date: at('2026-05-01') }]))).doc;
assert.equal(dayly.shape.step_count.stamps, 'day');
// Replaced on every sync, never accumulated.
const again = merge(dayly, parsePayload(metric('heart_rate', 'bpm', [{ Avg: 62, date: at('2026-05-01', '09:00:00') }]))).doc;
assert.equal(again.shape.step_count.points, 1, 'the metric that did not arrive keeps its receipt');
assert.equal(again.shape.heart_rate.field, 'Avg');
// It survives a reload of the file, and it is not read by anything that computes a number.
assert.equal(normalizeDoc(JSON.parse(JSON.stringify(again))).shape.step_count.points, 1);
});
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', [
+132 -11
View File
@@ -94,6 +94,13 @@ export const MAX_WORKOUTS = 300;
* survive this and live RETENTION_DAYS.
*/
export const HOURS_KEPT_DAYS = 7;
/**
* How long a day the phone totalled itself stays the day's number while hours keep arriving. In the
* shape this exists for the total is re-sent on every sync, so it never goes stale; an automation
* that was reconfigured to hours only stops sending it, and after this the sum of the hours takes
* over instead of the number freezing for the rest of the day.
*/
export const DECLARED_STALE_MS = 6 * 3600 * 1000;
/** 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
@@ -110,7 +117,10 @@ export function normalizeDoc(doc) {
updatedAt: Number(d.updatedAt) || 0,
last: d.last && typeof d.last === 'object' ? d.last : null,
metrics: {},
workouts: Array.isArray(d.workouts) ? d.workouts.filter(w => w && typeof w === 'object') : []
workouts: Array.isArray(d.workouts) ? d.workouts.filter(w => w && typeof w === 'object') : [],
// The last sync's receipt per metric (see receiptFor): replaced every time, never read by
// anything that computes a number.
shape: d.shape && typeof d.shape === 'object' && !Array.isArray(d.shape) ? d.shape : {}
};
const metrics = d.metrics && typeof d.metrics === 'object' && !Array.isArray(d.metrics) ? d.metrics : {};
for (const [name, m] of Object.entries(metrics)) {
@@ -276,6 +286,25 @@ function hrMax(samples) {
/* ---------- merging ---------- */
/**
* A midnight-stamped datapoint that carries more than everything else in its payload put together
* is the day's own total, not hour 00: an hour cannot hold more than the day it belongs to. Returns
* the day keys it applies to, so the loop can treat exactly those points as day totals.
*/
function declaredDay(points) {
const rest = points.filter(p => !isMidnight(p.at))
.map(p => headline(p.fields))
.filter(Boolean)
.reduce((n, h) => n + h.value, 0);
const keys = new Set();
for (const p of points) {
if (!isMidnight(p.at)) continue;
const h = headline(p.fields);
if (h && h.value > rest) keys.add(p.at.day);
}
return keys;
}
/** Does this metric payload look like HAE's own day-by-day grouping? */
function dayGrouped(points) {
return points.length > 0 && points.every(p => isMidnight(p.at));
@@ -341,6 +370,21 @@ function deriveDay(day) {
}
day.f = f;
day.n = n;
day.hsum = sumHours(day);
}
/**
* What a day's hours add up to, per field — kept beside the day whether or not the day's own number
* came from them. When the phone also declares a total the two can disagree, and that disagreement
* is the most useful thing there is to show: "the hours add up to 840 and the newest one says 499"
* explains a wrong number, where the wrong number alone explains nothing.
*/
function sumHours(day) {
const out = {};
for (const hb of Object.values(day.h || {})) {
for (const [k, v] of Object.entries(hb.f || {})) out[k] = Math.round(((out[k] || 0) + (v.sum || 0)) * 100) / 100;
}
return out;
}
/**
@@ -365,13 +409,25 @@ export function mergeVitals(doc, payload, now = Date.now()) {
// re-sent by the next automation run — anything older is pruned and can no longer be a repeat.
pruneLedger(cur.seen, now);
// The receipt is written once per metric, from the payload as it arrived.
out.shape[m.name] = receiptFor(m.points, now);
/* A midnight-stamped datapoint inside a payload that also carries hours is the day's own total,
not hour 00 of it — an hour cannot hold more than the day does. Reading it as an hour is what
turns "499 today" into 840, so when its value exceeds everything else in the payload added
together, it is taken as the day. Anything smaller is left where it is: a genuine 00:00 bucket
is a handful of steps, never more than the rest of the day. */
// A Set, and empty is not "yes": `declared.has(day)` is what the loop asks, because a truthy
// empty Set would turn every midnight point into a day total.
const declared = replace ? null : declaredDay(m.points);
for (const p of m.points) {
const key = p.at.day;
if (!dayKeyOk(key)) continue;
if (p.source && !cur.sources.includes(p.source)) {
cur.sources = [p.source, ...cur.sources].slice(0, MAX_SOURCES);
}
if (replace) {
if (replace || (declared && declared.has(p.at.day) && isMidnight(p.at))) {
const prev = cur.days[key];
// Nothing to do when the phone re-sends the value we already have (the common case for
// every run after the first). `f` is compared as a whole because a day total and a
@@ -381,7 +437,8 @@ export function mergeVitals(doc, payload, now = Date.now()) {
// 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 };
cur.days[key] = { ...bucketFrom(p.fields, p.at.ms), h: prev?.h || {}, own: true, ownAt: now };
cur.days[key].hsum = sumHours(cur.days[key]);
stats.points++;
continue;
}
@@ -409,16 +466,27 @@ export function mergeVitals(doc, payload, now = Date.now()) {
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.
Three days are the exceptions, and all three are days whose aggregate is not "the hours so
far":
own — the phone totalled this day itself. Its total is the number the Health app shows,
and hours were re-folded into it once already (that is the bug this replaced:
499 declared plus 341 of hours became 840). So the total stays the day, and the
hours stay the shape of it. The escape hatch is time: if no fresh total has
arrived for six hours while hours keep coming, the automation was clearly
reconfigured to hours only, and the day goes back to the sum of them.
!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;
const declaredStale = day.own && now - (day.ownAt || 0) > DECLARED_STALE_MS;
if (declaredStale) { delete day.own; delete day.ownAt; day.hc = true; }
if (day.own) {
/* The phone declared this day, so its number *is* the day: adding the hour to it would
count the morning twice, which is the whole failure this branch exists to prevent. The
hours still move — they are the shape of the day and the detail sheet draws them — and
the sum beside them moves with them so the two can be compared. */
day.hsum = sumHours(day);
} else if (day.hc || day.n === 0) {
day.hc = true;
deriveDay(day);
} else {
@@ -495,6 +563,48 @@ function pruneDays(doc, now) {
}
}
/* ---------- the receipt: what actually arrived ----------
*
* One entry per metric, replaced on every sync: how many datapoints came, how they were stamped
* (a day total, an hour, or a real instant), from which sources, what they add up to, and the first
* and last few values as the phone wrote them. It exists because "the number in the app does not
* match the Health app" is unanswerable from the number alone, and the answer is always in the
* shape of what arrived: hourly values that are really running totals add up to more than the day,
* and two devices recording the same walk add up to more than either.
*
* Bounded on purpose (three values at each end), and it is a *receipt*, not a reading: the headline
* field is picked by a fixed order rather than by the metric's meaning, because this module does not
* have the catalogue. Nothing here is used to compute a day. */
/** The field a receipt quotes for a point: the one a person would read if they had to pick one. */
const HEADLINE_FIELDS = ['qty', 'Avg', 'avg', 'value', 'asleep', 'totalSleep', 'systolic'];
function headline(fields) {
for (const k of HEADLINE_FIELDS) if (typeof fields[k] === 'number') return { field: k, value: fields[k] };
for (const [k, v] of Object.entries(fields)) if (typeof v === 'number') return { field: k, value: v };
return null;
}
const stampKind = t => (isMidnight(t) ? 'day' : onTheHour(t) ? 'hour' : 'sample');
function receiptFor(points, now) {
const kinds = new Set(points.map(p => stampKind(p.at)));
const valued = points.map(p => ({ at: p.at, h: headline(p.fields) })).filter(x => x.h);
const sum = valued.reduce((n, x) => n + x.h.value, 0);
const last = valued.length ? valued[valued.length - 1] : null;
const pair = x => [x.at.raw, x.h.value];
return {
at: now,
points: points.length,
field: valued.length ? valued[0].h.field : null,
stamps: kinds.size > 1 ? 'mixed' : [...kinds][0],
sources: [...new Set(points.map(p => p.source).filter(Boolean))].slice(0, MAX_SOURCES),
sum: Math.round(sum * 100) / 100,
newest: last ? { stamp: last.at.raw, value: last.h.value, ms: last.at.ms } : null,
head: valued.slice(0, 3).map(pair),
tail: valued.slice(-3).map(pair)
};
}
/* ---------- reading ---------- */
/** One bucket's fields, as the client wants them: the count, the total, and the mean it implies. */
@@ -529,9 +639,20 @@ 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];
out.push({ day, n: b.n, lastTs: b.lastTs, hours: Object.keys(b.h || {}).length, f: projectFields(b.f) });
out.push({
day,
n: b.n,
lastTs: b.lastTs,
hours: Object.keys(b.h || {}).length,
// `own`: this day's number is the total the phone declared, not the sum of its hours.
// `hours_sum`: what its hours add up to, so a disagreement between the two is visible
// instead of hidden — the screen shows it, and so does anybody debugging a wrong number.
own: !!b.own,
hours_sum: b.hsum || null,
f: projectFields(b.f)
});
}
if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out };
if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out, shape: d.shape[name] || null };
}
return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts };
}