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

@@ -3,7 +3,7 @@ import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
measurement: { findMany: vi.fn() },
measurement: { findMany: vi.fn(), findFirst: vi.fn() },
auditLog: { create: vi.fn() },
},
}));
@@ -76,6 +76,7 @@ function stage(
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.measurement.findFirst).mockResolvedValue(null as never);
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
});
@@ -138,12 +139,48 @@ describe("GET /api/sleep/night", () => {
stage("2026-06-02T03:00:00.000Z", "CORE", 200),
stage("2026-06-04T03:00:00.000Z", "CORE", 300),
] as never);
vi.mocked(prisma.measurement.findFirst).mockResolvedValue({
measuredAt: new Date("2026-06-04T03:00:00.000Z"),
} as never);
const res = await GET(req(""));
const body = await res.json();
expect(body.data.night).toBe("2026-06-04");
expect(body.data.main.asleepMinutes).toBe(300);
});
it("reads a night of any age from a day and a half either side of it", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
stage("2019-03-01T06:00:00.000Z", "CORE", 420),
] as never);
const res = await GET(req("date=2019-03-01"));
const body = await res.json();
// Years past any trailing window, the night is still served.
expect(body.data.main.asleepMinutes).toBe(420);
const where = vi.mocked(prisma.measurement.findMany).mock.calls[0][0]!
.where as { AND: Array<{ measuredAt: { gte: Date; lte: Date } }> };
expect(where.AND[0].measuredAt.gte.toISOString()).toBe(
"2019-02-27T12:00:00.000Z",
);
expect(where.AND[0].measuredAt.lte.toISOString()).toBe(
"2019-03-03T12:00:00.000Z",
);
});
it("answers a day of naps alone with its naps and no main night", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
// 13:00 to 14:00 UTC, nothing overnight.
stage("2026-06-04T14:00:00.000Z", "CORE", 60),
] as never);
const res = await GET(req("date=2026-06-04"));
const body = await res.json();
expect(body.data.night).toBe("2026-06-04");
expect(body.data.main).toBeNull();
expect(body.data.naps).toHaveLength(1);
expect(body.data.naps[0].asleepMinutes).toBe(60);
});
it("surfaces a daytime nap separately from the main night", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
@@ -169,7 +206,7 @@ describe("GET /api/sleep/night", () => {
expect(body.data.naps).toEqual([]);
});
// A5 — a reconstruction edge (a session of only bare ASLEEP / stage-less rows
// A reconstruction edge (a session of only bare ASLEEP / stage-less rows
// alongside a granular partition for the same span) must return a valid empty
// night, NEVER a 500 from the unguarded `segments[0]` access.
it("returns 200 + empty night on an IN_BED/AWAKE-only reconstruction, never 500", async () => {
+19 -41
View File
@@ -17,13 +17,16 @@
* (WHOOP) — the client renders the hypnogram but labels it an approximate
* layout. A real-series source (Apple Health / Withings / Fitbit) is false.
*
* `date` omitted → the most recent night in the trailing-year window.
* `date` omitted → the most recent night that holds sleep, however old.
*
* Only the stage rows within a day and a half of the night are read, as the
* list's drill-down reads them (`readNightSessions`), so any past night is
* answered and a long history never reaches the heap.
*
* Auth: cookie session OR Bearer token (`requireAuth`). Soft-delete-filtered.
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { prisma } from "@/lib/db";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import {
apiSuccess,
@@ -32,18 +35,18 @@ import {
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import {
reconstructSleepSessions,
pickMainNightAndNaps,
type SleepSession,
} from "@/lib/analytics/sleep-night";
import {
latestSleepNight,
readNightSessions,
} from "@/lib/measurements/list/sleep-nights";
import { loadUserSourcePriority } from "@/lib/rollups/measurement-read";
import { resolveUserTimezone } from "@/lib/tz/resolver";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { isCalendarDateKey } from "@/lib/tz/date-only";
/** Sleep is read row-per-stage, so the window is bounded to one year. */
const SLEEP_NIGHT_MAX_DAYS = 365;
const querySchema = z.object({
// Optional wake-day key; when omitted the latest night is returned.
date: z
@@ -127,36 +130,14 @@ export const GET = apiHandler(async (request: NextRequest) => {
loadUserSourcePriority(user.id),
]);
const since = new Date(Date.now() - SLEEP_NIGHT_MAX_DAYS * 86_400_000);
const rows = await prisma.measurement.findMany({
where: {
userId: user.id,
type: "SLEEP_DURATION",
deletedAt: null,
measuredAt: { gte: since },
},
orderBy: { measuredAt: "asc" },
select: {
value: true,
measuredAt: true,
sleepStage: true,
source: true,
// Writer-level collapse: two HealthKit apps behind one source (watch
// stages vs phone in-bed) must not blend into one night.
deviceType: true,
},
});
const sessions = reconstructSleepSessions(rows, tz, priorityJson);
// Resolve the target wake day: the requested `date`, else the most
// recent wake day that has a scorable session.
const scorable = sessions.filter((s) => s.asleepMinutes > 0);
const targetDay =
date ??
(scorable.length > 0 ? scorable[scorable.length - 1].night : undefined);
const daySessions = sessions.filter((s) => s.night === targetDay);
const { main, naps } = pickMainNightAndNaps(daySessions);
date ?? (await latestSleepNight(user.id, tz, priorityJson)) ?? undefined;
const { main, naps } = targetDay
? pickMainNightAndNaps(
(await readNightSessions(user.id, targetDay, tz, priorityJson))
.sessions,
)
: { main: null, naps: [] };
annotate({
action: { name: "sleep.night" },
@@ -167,13 +148,10 @@ export const GET = apiHandler(async (request: NextRequest) => {
},
});
if (!main) {
return apiSuccess({ night: targetDay ?? null, main: null, naps: [] });
}
// A day of naps alone answers with its naps and no main night.
return apiSuccess({
night: main.night,
main: serializeSession(main),
night: targetDay ?? null,
main: main ? serializeSession(main) : null,
naps: naps.map(serializeSession),
});
});