fix(sleep): stop double-counting bare ASLEEP against granular stages

Apple Health (and some WHOOP shapes) write BOTH an unspecified ASLEEP
aggregate row AND the granular CORE/DEEP/REM breakdown for the same
sleep period. The per-night reconstruction summed both, so a real ~8 h
night surfaced as ~16 h across every sleep surface — the chart showed
~16-18 h points and the target-range 30-day average read ~16.4 h/day.

Prefer the granular partition: when any CORE/DEEP/REM stage is present
for a night/source, count only those; fall back to the bare ASLEEP (or
a stage-less legacy/manual) row only when no granular stage exists.
IN_BED and AWAKE stay excluded; dual-source nights still collapse to one
canonical source via the user's sleep priority ladder. The same rule
applies inside the per-source asleep tiebreak so a source writing both
shapes is not over-weighted.

Align the surfaces that bypassed the shared helper:

- insights/targets: SLEEP_DURATION was averaged as raw per-stage rows
  (minutes) and fed into a target band expressed in hours, producing the
  bogus 16.4 h/day. Reconstruct per-night time-asleep, convert to hours,
  and classify + roll up consistency on the nightly hour totals.
- coach snapshot: route the sleep block through reconstructSleepNights
  so the prompt narrates the same nightly numbers (was summing every
  stage row, including IN_BED + AWAKE).
- sleep card chart: read /api/measurements/series?kind=sleep (night
  reconstruction, hours) instead of the generic measurement
  daily-average path, and label the axis in hours instead of minutes.

Add regression fixtures: a night with both a bare ASLEEP row and the
granular breakdown asserts the granular total (no double-count); a
dual-source night with both shapes per source; and a multi-night 30-day
average that lands at ~8 h, not ~16 h.
This commit is contained in:
Marc-André Bombeck committed 2026-06-04 18:22:55 +02:00
1 parent e78e3df1b9
commit 2a7195601b
6 files changed
+358 -76

No files matched your search

+52
View File
@@ -622,7 +622,59 @@ export function HealthChart({
}
>();
// v1.11.5 — SLEEP_DURATION is stored one row per sleep STAGE per night
// (minutes). The generic `/api/measurements` daily-aggregate path
// averages those stage rows, which neither sums a night nor isolates
// the asleep stages — it surfaced a ~2× inflated, mislabeled chart. The
// `/api/measurements/series?kind=sleep` adapter reconstructs ONE point
// per night carrying the night's TIME-ASLEEP in HOURS (CORE + DEEP + REM,
// bare-ASLEEP only when no granular stage exists, IN_BED + AWAKE
// excluded, dual-source nights collapsed to one source). Routing the
// sleep chart through it keeps every sleep surface on the same
// reconstruction. One point per night → `sum/count` yields the night's
// hours unchanged.
async function fetchSleepNights() {
const sleepParams = new URLSearchParams();
sleepParams.set("kind", "sleep");
// The series route caps sleep at 365 days regardless; clamp the
// request so a longer comparison window still resolves.
sleepParams.set(
"days",
String(Math.max(1, Math.min(3650, Math.ceil(fetchWindow.windowDays)))),
);
const res = await fetch(`/api/measurements/series?${sleepParams}`);
if (!res.ok) return;
const json = await res.json();
const points = (json.data?.points ?? []) as Array<{
at: string;
value: number;
}>;
for (const point of points) {
const value = point.value * valueScale;
if (value == null || !Number.isFinite(value)) continue;
const dayKey = toDayKey(point.at, dayKeyFormatter);
const bucket = dailyAggregates.get(dayKey) ?? {
timestamp: dayKeyToTimestamp(dayKey),
values: {},
};
const current = bucket.values["SLEEP_DURATION"] ?? {
sum: 0,
count: 0,
min: null,
max: null,
};
current.sum += value;
current.count += 1;
bucket.values["SLEEP_DURATION"] = current;
dailyAggregates.set(dayKey, bucket);
}
}
async function fetchMeasurementsByType(type: string) {
if (type === "SLEEP_DURATION") {
await fetchSleepNights();
return;
}
const typeParams = new URLSearchParams();
typeParams.set("type", type);
typeParams.set("sortBy", "measuredAt");
@@ -5,20 +5,23 @@ import { useTranslations } from "@/lib/i18n/context";
import type { ComparisonBaseline } from "@/lib/dashboard-layout";
/**
* v1.4.25 W4c — total nightly sleep duration over time.
* v1.4.25 W4c — nightly TIME-ASLEEP over time.
*
* Thin wrapper around `<HealthChartDynamic>` so the sleep sub-page gets
* the same chart-cog parity (`chartKey="sleep"`) as the dashboard chart
* surfaces. SLEEP_DURATION rows from Apple Health are per-stage (one
* row per stage per night) — the analytics API aggregates per Berlin
* day before summarising, and `HealthChart` itself relies on the
* pre-aggregated `/api/measurements/series` payload, so we pass the
* raw type through and let the existing chart wire do the day-rollup.
* surfaces.
*
* Unit semantics: SLEEP_DURATION is canonically stored in MINUTES
* (v1.4.23 schema note). The chart shows the raw minutes value with a
* "min" unit suffix — the parent sub-page renders a separate
* "X h Y min" headline above the chart for the human-friendly read.
* Data path: SLEEP_DURATION rows are stored per-stage (one row per stage
* per night, in MINUTES). `<HealthChart>` special-cases SLEEP_DURATION to
* read `/api/measurements/series?kind=sleep`, which reconstructs ONE point
* per night carrying the night's TIME-ASLEEP in HOURS (CORE + DEEP + REM,
* bare-ASLEEP only when no granular stage exists, IN_BED + AWAKE excluded,
* dual-source nights collapsed to one source). The chart therefore renders
* a nightly trend in hours that matches every other sleep surface.
*
* Unit semantics: the chart plots HOURS — the same unit the series adapter
* returns and the `<SleepOverview>` headline shows — so the axis reads e.g.
* "8 h", not the inflated per-stage minutes the legacy path surfaced.
*
* v1.4.28 R3d (BK-F-M2) — the inline `dynamic()` call site was retired
* in favour of the shared `<HealthChartDynamic>` re-export so the
@@ -40,8 +43,8 @@ export function SleepDurationChart({
types={["SLEEP_DURATION"]}
title={t("charts.sleep")}
colors={["#8be9fd"]}
unit="min"
yAxisUnit="min"
unit="h"
yAxisUnit="h"
compareBaseline={compareBaseline}
userTimezone={userTimezone}
/>