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
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:
1 parent
309aba8766
commit
f7b884be81
6 files changed
+317
-18
No files matched your search
+146
-15
@@ -327,6 +327,114 @@ function hourGrouped(points) {
|
||||
|
||||
const dayKeyOk = k => /^\d{4}-\d{2}-\d{2}$/.test(k);
|
||||
|
||||
/* ── Two devices, one walk ────────────────────────────────────────────────────────────────────
|
||||
*
|
||||
* HealthKit de-duplicates: the same walk recorded by an iPhone and an Apple Watch is one walk in the
|
||||
* Health app. A payload that carries both as separate points has been de-duplicated by nobody, so
|
||||
* adding them is what turns 946 steps into 1,700 — a live report, and a ratio of about 1.8, which is
|
||||
* exactly the share of the time only one of the two devices was recording.
|
||||
*
|
||||
* So a bucket keeps its sources *apart* and shows one of them: the source that reported most in that
|
||||
* bucket, which is the device that was actually being worn. Per bucket, never per day, because that
|
||||
* is what makes both cases right — an hour where only the phone recorded is the phone's hour, and an
|
||||
* hour where both recorded is counted once. A metric with a single source (most people, and every
|
||||
* metric whose payload has no `source` at all) behaves exactly as it did before: one sub-bucket,
|
||||
* which is the bucket.
|
||||
*
|
||||
* The choice is deliberately not a sum, not an average, and not a "max": it is one device's own
|
||||
* aggregate. A number that exists on the wrist is the number the wrist's app shows. */
|
||||
|
||||
/** This source's own aggregates inside a bucket, created on first sight. */
|
||||
function sourceBucket(bucket, source) {
|
||||
const all = bucket.s || (bucket.s = {});
|
||||
const key = source || '';
|
||||
return all[key] || (all[key] = { n: 0, lastTs: 0, f: {} });
|
||||
}
|
||||
|
||||
/** How much a source reports in a bucket — used only to break a tie, never to compute a value. */
|
||||
function totalOf(b) {
|
||||
const sums = Object.values(b.f || {}).map(v => v.sum).filter(v => typeof v === 'number');
|
||||
return sums.length ? Math.max(...sums) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The source a bucket shows: most samples, then the newest, then the largest total. Sample count
|
||||
* first because it says who was actually recording (a watch taking a reading every five minutes
|
||||
* against a phone that caught one); the newest next because a payload that stops mid-bucket leaves
|
||||
* the other device holding the end of it; the total last, which is the only tie-break left for a
|
||||
* day-level point from each device.
|
||||
*/
|
||||
export function pickSource(bucket) {
|
||||
const all = bucket && bucket.s;
|
||||
if (!all) return null;
|
||||
let best = null, bestN = -1, bestTs = -1, bestTotal = -1;
|
||||
for (const [key, b] of Object.entries(all)) {
|
||||
const total = totalOf(b);
|
||||
const better = b.n > bestN
|
||||
|| (b.n === bestN && b.lastTs > bestTs)
|
||||
|| (b.n === bestN && b.lastTs === bestTs && total > bestTotal);
|
||||
if (better) { best = key; bestN = b.n; bestTs = b.lastTs; bestTotal = total; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* A bucket written before this existed has an aggregate and no sources: it is adopted as the
|
||||
* unnamed source rather than thrown away, so an upgrade never loses the day it already had — and
|
||||
* the two then compete on samples like any other pair.
|
||||
*/
|
||||
function seedLegacy(bucket, ms) {
|
||||
if (!bucket.s && bucket.f && Object.keys(bucket.f).length) {
|
||||
bucket.s = { '': { n: bucket.n || 0, lastTs: bucket.lastTs || ms, f: bucket.f } };
|
||||
}
|
||||
}
|
||||
|
||||
/** Fold one sample into its own source's bucket, then show the winning one. */
|
||||
function addPoint(bucket, source, fields, ms) {
|
||||
seedLegacy(bucket, ms);
|
||||
const b = sourceBucket(bucket, source);
|
||||
addFields(b, fields);
|
||||
b.lastTs = Math.max(b.lastTs, ms);
|
||||
return applySource(bucket);
|
||||
}
|
||||
|
||||
/**
|
||||
* One datapoint that *is* a bucket — an hour HAE grouped itself, or a day it totalled — where that
|
||||
* source's earlier report of the same bucket is superseded rather than added to (the hour in
|
||||
* progress grows on every run of a five-minute automation).
|
||||
*
|
||||
* Only that source's sub-bucket is superseded. A device re-sending its own hour says nothing about
|
||||
* the other device's, and wiping the whole bucket is how one device's report would silently delete
|
||||
* the other's — which is the opposite of what this is for.
|
||||
*/
|
||||
function setPoint(bucket, source, fields, ms) {
|
||||
seedLegacy(bucket, ms);
|
||||
const b = sourceBucket(bucket, source);
|
||||
b.n = 0;
|
||||
b.f = {};
|
||||
b.lastTs = ms;
|
||||
addFields(b, fields);
|
||||
return applySource(bucket);
|
||||
}
|
||||
|
||||
/** What this source last reported for a bucket, whether the bucket knows about sources or not. */
|
||||
function sourceReport(bucket, source) {
|
||||
if (!bucket) return null;
|
||||
if (bucket.s) return bucket.s[source || ''] || null;
|
||||
return bucket;
|
||||
}
|
||||
|
||||
/** Make the bucket show its winning source; returns the key that won (or null). */
|
||||
function applySource(bucket) {
|
||||
const key = pickSource(bucket);
|
||||
if (key == null) return null;
|
||||
const b = bucket.s[key];
|
||||
bucket.src = key || null;
|
||||
bucket.n = b.n;
|
||||
bucket.f = b.f;
|
||||
return key;
|
||||
}
|
||||
|
||||
function addFields(bucket, fields) {
|
||||
for (const [k, v] of Object.entries(fields)) {
|
||||
const f = bucket.f[k] || (bucket.f[k] = { n: 0, sum: 0, min: v, max: v, last: v });
|
||||
@@ -371,6 +479,18 @@ function deriveDay(day) {
|
||||
day.f = f;
|
||||
day.n = n;
|
||||
day.hsum = sumHours(day);
|
||||
/* Which device the day is mostly made of. Each hour has already been reduced to one source (two
|
||||
devices recording the same hour are one hour), so the day's answer is the device that reported
|
||||
most of it — worth saying out loud on the sheet, because "the watch, mostly, plus two hours the
|
||||
phone had to itself" is what the number actually is. */
|
||||
const bySrc = {};
|
||||
for (const hb of Object.values(day.h || {})) {
|
||||
// `|| ''`: an hour stored before sources existed has none, and its samples are still the day's.
|
||||
const key = hb.src || '';
|
||||
bySrc[key] = (bySrc[key] || 0) + (hb.n || 0);
|
||||
}
|
||||
const winner = Object.entries(bySrc).sort((a, b) => b[1] - a[1])[0];
|
||||
day.src = winner ? (winner[0] || null) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -429,16 +549,20 @@ export function mergeVitals(doc, payload, now = Date.now()) {
|
||||
}
|
||||
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
|
||||
// Nothing to do when this source re-sends the value it already reported (the common case
|
||||
// for 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; }
|
||||
// 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, ownAt: now };
|
||||
cur.days[key].hsum = sumHours(cur.days[key]);
|
||||
const own = sourceReport(prev, p.source);
|
||||
if (own && own.n === 1 && sameFields(own.f, p.fields)) { stats.duplicates++; continue; }
|
||||
// The hours already stored for that day ride along, and so does any other source's total:
|
||||
// the phone's own number is the better day value, but it says nothing about the shape of
|
||||
// the day, and one device's total does not replace another's — the two are compared, and
|
||||
// the one that reported more wins (`own` records that the day's number is a declared total
|
||||
// rather than the sum of its hours; see below).
|
||||
const dayBucket = prev ? { ...prev, own: true, ownAt: now } : { h: {}, own: true, ownAt: now, n: 0, lastTs: p.at.ms, f: {} };
|
||||
cur.days[key] = dayBucket;
|
||||
setPoint(dayBucket, p.source, p.fields, p.at.ms);
|
||||
dayBucket.hsum = sumHours(dayBucket);
|
||||
stats.points++;
|
||||
continue;
|
||||
}
|
||||
@@ -446,11 +570,13 @@ export function mergeVitals(doc, payload, now = Date.now()) {
|
||||
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];
|
||||
// An hour the phone grouped itself: replaced — that source's hour, never unioned, because
|
||||
// the hour in progress grows on every run of a five-minute automation. Another device's
|
||||
// report of the same hour is a separate sub-bucket and is not touched.
|
||||
const prev = sourceReport(hours[hh], p.source);
|
||||
if (prev && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; }
|
||||
hours[hh] = bucketFrom(p.fields, p.at.ms);
|
||||
const hb = hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} });
|
||||
setPoint(hb, p.source, 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
|
||||
@@ -460,8 +586,9 @@ export function mergeVitals(doc, payload, now = Date.now()) {
|
||||
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);
|
||||
const hb = hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} });
|
||||
addPoint(hb, p.source, p.fields, p.at.ms);
|
||||
hb.lastTs = Math.max(hb.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
|
||||
@@ -648,6 +775,10 @@ export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) {
|
||||
// `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,
|
||||
// Which device the day is mostly made of, when more than one reported into it. Two devices
|
||||
// recording the same hour are one hour, and saying which one won is the difference between a
|
||||
// number somebody can check against their watch and a number they cannot.
|
||||
source: b.src || null,
|
||||
hours_sum: b.hsum || null,
|
||||
f: projectFields(b.f)
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user