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

+1
View File
@@ -1407,6 +1407,7 @@ export default {
'Reset this measurement': 'Reiniciar esta medición',
// segunda opinión (Jev)
'The server is running an older API than this screen: the numbers may not match Apple Health, and the hourly detail and the sync receipt will not appear until the api container is updated.': 'El servidor está corriendo una api más vieja que esta pantalla: los números pueden no coincidir con Apple Health, y el detalle por hora y el recibo del último envío no van a aparecer hasta que se actualice el contenedor de la api.',
'using {0}': 'se usa {0}',
'What arrived last': 'Qué llegó en el último envío',
'Datapoints in the last sync': 'Datos en el último envío',
'How they were stamped': 'Cómo vienen marcados',
+7 -1
View File
@@ -233,7 +233,12 @@ function MetricSheet({ card, metric, close, onReset }) {
list is only worth a section when there is more than one (heart rate's Min/Avg/Max, sleep's
stages, an unknown metric's whatever-it-sent). */
const receipt = receiptRows(metric && metric.shape, { withValues: hourList.length === 0 })
const conflict = dayConflict(metric && metric.days ? metric.days.find(d => d.day === card.day) : null)
const dayObj = metric && Array.isArray(metric.days) ? metric.days.find(d => d.day === card.day) : null
const conflict = dayConflict(dayObj)
// When two devices reported into this day, which one the number is mostly made of. It is the
// difference between a number somebody can check against their watch and one they cannot: the
// watch and the phone record the same walk, and only one of them is counted in each hour.
const usedSource = dayObj && dayObj.source && (card.sources || []).length > 1 ? dayObj.source : null
const history = historyRows(card, { skip: card.day })
const val = r => fmtValue(r.value, card.dec) + (unitLabel(card.unit) ? ' ' + unitLabel(card.unit) : '')
@@ -292,6 +297,7 @@ function MetricSheet({ card, metric, close, onReset }) {
<div className="small dim" style={{ marginTop: 12 }}>
{t('{0} days with data in this range', card.days)}
{card.sources.length ? ' · ' + card.sources.join(', ') : ''}
{usedSource ? ' · ' + t('using {0}', usedSource) : ''}
</div>
{/* What the phone actually sent for this metric, last sync. It is here because "the number in
+20 -1
View File
@@ -430,7 +430,7 @@ describe('the detail sheet', () => {
},
days: [
{ ...day('2026-09-02', { qty: bucket(11000) }), hours: 24, own: false, hours_sum: { qty: 11000 } },
{ ...day('2026-09-03', { qty: bucket(499) }), hours: 3, own: true, hours_sum: { qty: 340 } }
{ ...day('2026-09-03', { qty: bucket(499) }), hours: 3, own: true, hours_sum: { qty: 340 }, source: 'Apple Watch' }
]
}
}
@@ -459,6 +459,9 @@ describe('the detail sheet', () => {
// The day keeps the phone's total, and the sheet says why the two numbers differ instead of
// leaving whoever noticed to guess.
expect(text).toContain('The phone declared 499 for this day, and its hours add up to 340')
// Two devices reported into this day, so the sheet says which one the number is mostly made of:
// the difference between a number somebody can check against their watch and one they cannot.
expect(text).toContain('using Apple Watch')
})
it('shows the values in the receipt when there are no hours to show them in', async () => {
@@ -489,6 +492,22 @@ describe('the detail sheet', () => {
expect(text).not.toContain('Hour by hour')
})
it('says which device the day came from when two reported', async () => {
const oneSource = () => ({
...VITALS,
metrics: { step_count: { units: 'count', sources: ['Apple Watch'], days: [
{ ...day('2026-09-03', { qty: bucket(946) }), hours: 0, source: 'Apple Watch' }
] } }
})
// One source: nothing to disambiguate, so the line stays as it was.
route(oneSource(), { ok: true, metric: 'step_count', day: '2026-09-03', hours: [] })
await mountWithSheets()
openSteps()
await act(async () => {})
expect(sheet()).toContain('Apple Watch')
expect(sheet()).not.toContain('using')
})
it('says the automation groups by day instead of drawing an empty hour list', async () => {
route(VITALS, HOURS)
await mountWithSheets()