fix(sleep): read a night of any age and the whole series range

The night view read a year of stage rows whatever date it was asked
for, so an older night came back with no main session while a year of
rows sat in the heap; it now reads a day and a half either side of the
night, and the latest night from the latest asleep row. A day of naps
alone answers with its naps and main null.

The series cut "All" to a year for sleep without saying so. Postgres
now names the nights and the rows are reconstructed ninety nights at a
time, so the range reaches back as far as the history does.

The metric status read the latest 2190 stage rows, a few weeks on a
stage-rich watch, starting mid-night; it now reads the latest 365
nights the same way.
This commit is contained in:
Marc-André Bombeck committed 2026-10-20 04:23:10 +02:00
1 parent 3da72136ba
commit b7e48e933c
6 files changed
+125 -113

No files matched your search

@@ -110,6 +110,38 @@ function stubCompletion(
);
}
/**
* Postgres names the nights the sleep read reconstructs; answer the night
* page query with the one night the stage rows make, and every other raw
* query with nothing.
*/
function nightPageOver(rows: Array<{ value: number; measuredAt: Date }>) {
const start = Math.min(
...rows.map((r) => r.measuredAt.getTime() - r.value * 60_000),
);
const end = Math.max(...rows.map((r) => r.measuredAt.getTime()));
vi.mocked(prisma.$queryRaw).mockImplementation(((
_strings: TemplateStringsArray,
...values: unknown[]
) =>
Promise.resolve(
values.some((v) =>
String((v as { sql?: string })?.sql ?? "").includes("sess AS"),
)
? [
{
night: new Date(end).toLocaleDateString("sv-SE", {
timeZone: "Europe/Berlin",
}),
span_start: new Date(start),
span_end: new Date(end),
total: 1,
},
]
: [],
)) as never);
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.insightStatusCache.findUnique).mockResolvedValue(null);
@@ -167,6 +199,7 @@ describe("generateMetricStatus — SLEEP_DURATION night reconstruction (iOS E2)"
vi.mocked(prisma.measurement.findMany).mockResolvedValue(
stageRows as never,
);
nightPageOver(stageRows);
const capture = { systemPrompt: null, userPrompt: null } as {
systemPrompt: string | null;
@@ -190,7 +223,7 @@ describe("generateMetricStatus — SLEEP_DURATION night reconstruction (iOS E2)"
expect(prompt).not.toContain('"value": 90');
});
it("the snapshot graded series is the deduped night total, never the ~20 h raw-stage sum (A4)", async () => {
it("the snapshot graded series is the deduped night total, never the ~20 h raw-stage sum", async () => {
// The ~20.3 h symptom: a source writes BOTH a bare ASLEEP aggregate AND the
// granular CORE/DEEP/REM partition for the same span. Pre-fix the graded
// `series` came from `buildGradedSeriesWithRollups`, which folds bare + each
@@ -249,6 +282,7 @@ describe("generateMetricStatus — SLEEP_DURATION night reconstruction (iOS E2)"
vi.mocked(prisma.measurement.findMany).mockResolvedValue(
stageRows as never,
);
nightPageOver(stageRows);
const capture = { systemPrompt: null, userPrompt: null } as {
systemPrompt: string | null;
+11 -29
View File
@@ -71,10 +71,7 @@ import {
summarizeSeries,
} from "@/lib/insights/status-shared";
import { runStatusCompletion } from "@/lib/insights/status-provider";
import {
reconstructSleepNights,
type SleepStageRow,
} from "@/lib/analytics/sleep-night";
import { readSleepNights } from "@/lib/measurements/list/sleep-nights";
import { loadUserSourcePriority } from "@/lib/rollups/measurement-read";
import { resolveUserTimezone, userDayKey } from "@/lib/tz/resolver";
import {
@@ -295,31 +292,16 @@ export async function generateMetricStatus(args: {
const points: Array<{ measuredAt: Date; value: number }> = [];
let measurements: Array<{ measuredAt: Date }> = [];
if (isSleep) {
const [priorityJson, sleepRows] = await Promise.all([
loadUserSourcePriority(args.userId),
prisma.measurement.findMany({
where: {
userId: args.userId,
type: "SLEEP_DURATION",
deletedAt: null,
},
orderBy: { measuredAt: "desc" },
take: 365 * 6, // ≈ 5 stage rows/night × source-count for a year
// Writer-level collapse: two HealthKit apps behind one source
// (watch stages vs phone in-bed) must not blend into one night.
select: {
value: true,
measuredAt: true,
sleepStage: true,
source: true,
deviceType: true,
},
}),
]);
const nights = reconstructSleepNights(
sleepRows as SleepStageRow[],
userTz,
priorityJson,
// The latest 365 nights, the sleep twin of the 365 latest readings the
// other types read. A cut on stage rows instead (2190 of them) reached
// back a few weeks on a stage-rich watch and began mid-night.
const nights = (
await readSleepNights(
args.userId,
userTz,
await loadUserSourcePriority(args.userId),
{ maxNights: 365, newest: true },
)
).filter((n) => n.asleepMinutes > 0);
for (const n of nights) {
points.push({ measuredAt: n.measuredAt, value: n.asleepMinutes });