From cbd5c2ba6f51c6e6b92c14563e49a63950b0f562 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 15 Jun 2026 02:02:12 +0200 Subject: [PATCH] fix(withings): key sleep re-sync on the stable externalId, not the shifting measuredAt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With measuredAt now stamped at the segment END, a night that Withings re-aggregates between syncs shifts its enddate, so the measuredAt-keyed lookup missed the prior row and the create then collided with the unique externalId — leaving the night stuck at its stale value. Key the lookup on the stable externalId and refresh value, measuredAt and stage on update. Caught by the withings-sleep-sync integration test against real Postgres. --- src/lib/withings/__tests__/sync-sleep.test.ts | 8 +++++++- src/lib/withings/sync-sleep.ts | 11 ++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/lib/withings/__tests__/sync-sleep.test.ts b/src/lib/withings/__tests__/sync-sleep.test.ts index 6ae04f3a1..6cee99863 100644 --- a/src/lib/withings/__tests__/sync-sleep.test.ts +++ b/src/lib/withings/__tests__/sync-sleep.test.ts @@ -240,9 +240,15 @@ describe("syncUserSleep — segment writes + idempotency", () => { const imported = await syncUserSleep("user-1"); expect(imported).toBe(1); expect(prisma.measurement.create).not.toHaveBeenCalled(); + // Re-sync keys on the stable externalId and refreshes value, the + // END-stamped measuredAt (enddate may shift) and the stage. expect(prisma.measurement.update).toHaveBeenCalledWith({ where: { id: "row-1" }, - data: { value: 60 }, + data: { + value: 60, + measuredAt: new Date(1715003600 * 1000), + sleepStage: "DEEP", + }, }); }); diff --git a/src/lib/withings/sync-sleep.ts b/src/lib/withings/sync-sleep.ts index 4b92080d2..27b643baf 100644 --- a/src/lib/withings/sync-sleep.ts +++ b/src/lib/withings/sync-sleep.ts @@ -275,20 +275,25 @@ export async function syncUserSleep( const externalId = `withings:sleep:${userId}:${segment.id ?? "no-id"}:${segmentIndex}`; try { + // Key the re-sync lookup on the STABLE `externalId` (segment id + + // index), not `measuredAt`. Withings re-aggregates a night between + // syncs, so a segment's `enddate` — and therefore its END-stamped + // `measuredAt` — shifts; keying on `measuredAt` would miss the prior + // row and then collide with the unique `externalId`, leaving the night + // stuck at the stale value. Update both `value` and `measuredAt`. const existing = await prisma.measurement.findFirst({ where: { userId, type: SLEEP_TYPE, - measuredAt, source: "WITHINGS", - sleepStage: stage, + externalId, }, select: { id: true }, }); if (existing) { await prisma.measurement.update({ where: { id: existing.id }, - data: { value: minutes }, + data: { value: minutes, measuredAt, sleepStage: stage }, }); } else { await prisma.measurement.create({