Salud: dos dispositivos, una caminata — el cubo guarda sus fuentes y muestra una
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

"En mi Apple Salud me dice 946 y en opengym 1700 y pico", y antes 499 contra 840. Ese factor —1,80 y
1,68— es la prueba: una suma de valores acumulados daría 12× o 24× al final del día, no 1,8×. Lo que
da 1,8× es **sumar dos dispositivos**. HealthKit de-duplica la misma caminata entre el Apple Watch y
el iPhone, la app Salud la cuenta una vez, y un payload que trae los dos como puntos separados no la
ha de-duplicado nadie. La tarjeta estaba leyendo dos cosas, exactamente como se sospechó.

Ahora cada cubo —una hora, y el día cuando el teléfono manda un total por día— **guarda sus fuentes
por separado y muestra una**: la que más reportó en ese cubo, después la más nueva, después la más
grande. No es una suma, no es un promedio y no es "el máximo": es el agregado propio de un
dispositivo, o sea el número que ese dispositivo muestra.

Y la elección es **por hora**, no por día, que es lo que hace correctas las dos situaciones a la vez:
una hora que solo registró el teléfono es del teléfono (no se pierde nada), y una hora que
registraron los dos se cuenta una vez (no se duplica nada). Con la elección por día, el caso
"caminata sin el reloj" se habría perdido.

Tres cosas que había que cuidar y están cubiertas por tests:

  · **Un payload sin `source`** —casi todos, y en iOS 27+ es lo normal para datos acumulados— vive en
    una sola fuente sin nombre, así que un cubo es el cubo y nada cambia para quien tiene un solo
    dispositivo. Los 22 tests que ya existían pasaron sin tocarlos, que es la evidencia de eso.
  · **Un cubo guardado antes de esto** se adopta como la fuente sin nombre en vez de tirarse: una
    actualización no pierde el día que ya tenía, y las dos compiten por cantidad de muestras.
  · **Reemplazar una hora borra solo la de esa fuente.** La hora en curso crece en cada envío de un
    automatismo de cinco minutos y por eso se reemplaza, pero reemplazar el cubo entero es cómo un
    dispositivo borraría en silencio el reporte del otro — que es lo contrario de lo que esto hace.

La hoja lo dice al final: `N días con datos · Apple Watch, iPhone · se usa Apple Watch`, para que el
número se pueda cotejar contra el dispositivo que lo produjo.

Cinco tests del merge más el orden de desempate. Mutation-check de las dos mitades: sin aplicar la
fuente ganadora fallan cuatro, y si reemplazar una hora borra la del otro dispositivo fallan tres.
API 267 en verde, frontend 1705, build OK.
This commit is contained in:
dsantillan committed 2026-09-23 18:29:56 -04:00
1 parent 309aba8766
commit f7b884be81
6 files changed
+317 -18

No files matched your search

+141 -1
View File
@@ -10,7 +10,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, parseHaeDate,
normalizeDoc, RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS
normalizeDoc, pickSource, RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS
} from '../vitals.js';
const NOW = Date.parse('2026-05-01T23:30:00Z');
@@ -230,6 +230,146 @@ test('workouts dedupe on name+start+end, newest first, and a re-send adds nothin
assert.equal(again.doc.workouts.length, 2);
});
/* ---------- two devices, one walk ----------
*
* Reported live: the Health app said 946 steps and the card said 1,700 — a ratio of about 1.8, which
* is the share of the day only one of the two devices was recording. HealthKit de-duplicates the
* same walk across an iPhone and an Apple Watch; a payload that carries both as separate points has
* been de-duplicated by nobody, so adding them counts the walk twice. Each bucket now keeps its
* sources apart and shows the one that reported most in it. */
const bySource = (name, source, points) => ({
name, units: 'count',
data: points.map(([time, qty]) => ({ qty, date: at('2026-05-01', time), source }))
});
test('the same hour from two devices is counted once, not twice', () => {
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
bySource('step_count', 'Apple Watch', [['08:00:00', 120], ['09:00:00', 220]]),
bySource('step_count', 'iPhone', [['08:00:00', 90], ['09:00:00', 140]])
] }
})).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
// 946 against 1,700: the watch was on the wrist for both hours, so the day is the watch's.
assert.equal(day.f.qty.sum, 340, 'the day is one device, not the sum of two');
assert.equal(day.n, 2);
assert.equal(day.h['08'].f.qty.sum, 120);
assert.equal(day.h['09'].f.qty.sum, 220);
assert.equal(day.src, 'Apple Watch', 'and the bucket says which device it used');
// Both are still remembered as having reported — the footer of the sheet lists them.
assert.deepEqual(doc.metrics.step_count.sources, ['iPhone', 'Apple Watch']);
});
test('an hour only the phone recorded is the phone\'s hour', () => {
// The choice is per bucket, and that is what makes the disjoint case right: a walk without the
// watch is not lost, because nothing competes with it in those hours.
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
bySource('step_count', 'Apple Watch', [['14:00:00', 500]]),
bySource('step_count', 'iPhone', [['09:00:00', 400], ['14:00:00', 60]])
] }
})).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.h['09'].f.qty.sum, 400, 'the phone had that hour to itself');
assert.equal(day.h['09'].src, 'iPhone');
assert.equal(day.h['14'].f.qty.sum, 500, 'and the watch won the hour it shares');
assert.equal(day.h['14'].src, 'Apple Watch');
assert.equal(day.f.qty.sum, 900, 'so the day is both, each counted once');
});
test('two day totals for one day is one day, and the larger one is the truth', () => {
// Days grouping with a point per source: replacing is what the day rule does, and picking the
// larger is what HealthKit would show — the union of both devices is not the smaller total.
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
{ name: 'step_count', units: 'count', data: [
{ qty: 946, date: at('2026-05-01'), source: 'Apple Watch' },
{ qty: 754, date: at('2026-05-01'), source: 'iPhone' }
] }
] }
})).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 946, 'not 1,700');
assert.equal(day.src, 'Apple Watch');
assert.equal(day.own, true);
// A newer, larger total from either device replaces it, as a day always did.
const later = merge(doc, parsePayload({
data: { metrics: [{ name: 'step_count', units: 'count', data: [
{ qty: 1200, date: at('2026-05-01'), source: 'Apple Watch' },
{ qty: 1300, date: at('2026-05-01'), source: 'iPhone' }
] }] }
})).doc.metrics.step_count.days['2026-05-01'];
assert.equal(later.f.qty.sum, 1300, 'the day is one of them, never both added');
assert.equal(later.src, 'iPhone');
});
test('a payload with no source at all behaves exactly as it always did', () => {
// Every metric HAE sends without a `source` (iOS 27+ omits it for cumulative data, and older
// exports never had it) lives in one unnamed source, so one bucket is the whole story.
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
bySource('step_count', undefined, [['08:00:00', 120], ['09:00:00', 220]]),
bySource('step_count', undefined, [['14:00:00', 500]])
] }
})).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 840, 'three samples, one device, added');
assert.equal(day.src, null, 'no source to name');
assert.equal(day.n, 3);
});
test('an hour stored before sources existed competes like any other', () => {
// An upgrade must not throw away what it already had: an aggregate with no sources is adopted as
// the unnamed source, and the two then compete on samples like any pair — the day does not silently
// become whatever the phone sent last.
// A fresh copy each time: `mergeVitals` is pure in what it *returns*, but the buckets it is given
// are the ones it writes into, so a second merge off the same object would see the first one's work.
const legacy = () => normalizeDoc({ metrics: { step_count: { units: 'count', days: {
'2026-05-01': { n: 12, lastTs: Date.parse('2026-05-01T09:00:00Z'), f: { qty: { n: 12, sum: 900, min: 1, max: 90, last: 40 } },
h: { '08': { n: 12, lastTs: Date.parse('2026-05-01T09:00:00Z'), f: { qty: { n: 12, sum: 900, min: 1, max: 90, last: 40 } } } } }
} } } });
const doc = merge(legacy(), parsePayload({
data: { metrics: [{ name: 'step_count', units: 'count', data: [{ qty: 4, date: at('2026-05-01', '15:00:00'), source: 'iPhone' }] }] }
}), NOW).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.h['08'].f.qty.sum, 900, 'the hour it already had is untouched');
assert.equal(day.h['15'].f.qty.sum, 4, 'the phone\'s sample landed in its own hour');
assert.equal(day.f.qty.sum, 904, 'the day is both hours, each counted once');
// The day's own source is *undecided* here on purpose: a legacy day with no hours has nothing to
// attribute, so the reader reports null rather than inventing a device.
assert.equal(day.src, undefined);
// Same hour, both sources: the one with more samples that hour wins. Three new samples do not
// outweigh an aggregate of twelve, so the hour it already had stands...
const three = merge(legacy(), parsePayload(metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00'), source: 'Apple Watch' },
{ qty: 500, date: at('2026-05-01', '08:05:00'), source: 'Apple Watch' },
{ qty: 500, date: at('2026-05-01', '08:10:00'), source: 'Apple Watch' }
]))).doc.metrics.step_count.days['2026-05-01'];
assert.equal(three.h['08'].f.qty.sum, 900, 'twelve samples beat three');
assert.equal(three.h['08'].f.qty.n, 12);
// ...and a device that genuinely reports more of the hour does take it.
const caughtUp = merge(legacy(), parsePayload(metric('step_count', 'count', Array.from({ length: 14 },
(_, i) => ({ qty: 60, date: at('2026-05-01', `08:${String(i * 4).padStart(2, '0')}:00`), source: 'Apple Watch' }))))).doc
.metrics.step_count.days['2026-05-01'];
assert.equal(caughtUp.h['08'].src, 'Apple Watch', 'fourteen samples against twelve');
assert.equal(caughtUp.h['08'].f.qty.sum, 840);
});
test('the source a bucket shows is picked by samples, then recency, then size', () => {
const bucket = s => ({ s });
assert.equal(pickSource(bucket({ a: { n: 2, lastTs: 1, f: {} }, b: { n: 3, lastTs: 0, f: {} } })), 'b', 'most samples');
assert.equal(pickSource(bucket({ a: { n: 2, lastTs: 9, f: {} }, b: { n: 2, lastTs: 1, f: {} } })), 'a', 'then newest');
assert.equal(pickSource(bucket({
a: { n: 1, lastTs: 5, f: { qty: { n: 1, sum: 10 } } },
b: { n: 1, lastTs: 5, f: { qty: { n: 1, sum: 99 } } }
})), 'b', 'then the larger total');
assert.equal(pickSource({}), null);
assert.equal(pickSource({ s: {} }), null);
});
/* ---------- hours: the detail a day total throws away ---------- */
test('an hourly payload keeps its hours, and the day is exactly their sum', () => {