fix(cycle): open cycles from Garmin and Oura period days

Both wearables wrote their period days with a bare create and so skipped
the seam every other cycle writer goes through: a first bleeding day never
opened its cycle and no day was attributed to one. An account whose
periods came from a watch or a ring held day-logs only, with no cycle
start, no lengths and no forecast.

The create now goes through one shared helper that keeps the
create-only-if-absent rule and then runs the same attribution and
`ensureCycleForBleedingDay` inference as the shared upsert. The hourly
legs and the newest-first Garmin backfill both use it; a finished Garmin
period also stamps its last day on a cycle that has no period end yet.

Rows imported before this change are repaired by a one-shot job sent from
boot discovery while candidates exist. It opens or attributes cycles
oldest first per account, touches no day-log content, and converges to an
empty candidate set.

Refs #1333
This commit is contained in:
Marc-André Bombeck committed 2026-11-04 22:02:48 +01:00
1 parent a35b77c147
commit 148af765c9
17 files changed
+901 -131

No files matched your search

@@ -1,5 +1,5 @@
{
"registeredQueueCount": 129,
"registeredQueueCount": 130,
"registeredQueues": [
"account-deletion-purge",
"achievement-unlock-sweep",
@@ -117,6 +117,7 @@
"supplement-nutrient-recompute",
"system-job-alert",
"tls-pin-monitor",
"wearable-cycle-repair",
"whoop-backfill",
"whoop-cycle-sync",
"whoop-oauth-state-cleanup",
@@ -1872,6 +1873,21 @@
"retry_delay_max": null,
"retry_limit": 2
},
{
"dead_letter": null,
"deletion_seconds": 604800,
"expire_seconds": 900,
"heartbeat_seconds": null,
"name": "wearable-cycle-repair",
"notify": false,
"partition": false,
"policy": "short",
"retention_seconds": 1209600,
"retry_backoff": false,
"retry_delay": 0,
"retry_delay_max": null,
"retry_limit": 2
},
{
"dead_letter": null,
"deletion_seconds": 604800,
@@ -3801,6 +3817,12 @@
"pollingIntervalSeconds": 30
}
},
{
"queue": "wearable-cycle-repair",
"options": {
"localConcurrency": 1
}
},
{
"queue": "whoop-backfill",
"options": {
+131
View File
@@ -77,6 +77,8 @@ const fake = vi.hoisted(() => ({
rateLimitHit: -1,
/** First day of the one logged cycle, relative to today. */
cycleStart: "",
/** Several logged cycles instead of the one; when set, `cycleStart` is unused. */
cycles: [] as Array<{ start: string; periodLength: number }>,
/**
* The weigh-in shape: `spec` is Garmin's document (kilograms, no
* `samplePk`, a string instant), `live` the shape seen on the live
@@ -260,6 +262,18 @@ function answer(path: string, q: URLSearchParams): unknown {
if (path.startsWith("/periodichealth-service/menstrualcycle/summary/")) {
if (fake.cycleStatus !== 200) return { status: fake.cycleStatus };
const day = path.split("/").pop()!;
if (fake.cycles.length > 0) {
const at = [...fake.cycles]
.sort((a, b) => b.start.localeCompare(a.start))
.find((c) => c.start <= day);
return at
? {
startDate: { localDate: at.start },
periodLength: at.periodLength,
predictedCycle: false,
}
: {};
}
const cycleStart = fake.cycleStart;
return day >= cycleStart
? { startDate: cycleStart, periodLength: 4, predictedCycle: false }
@@ -362,6 +376,7 @@ beforeEach(async () => {
fake.today = new Date().toISOString().slice(0, 10);
fake.historyFrom = addDays(fake.today, -20);
fake.cycleStart = addDays(fake.today, -15);
fake.cycles = [];
fake.weightShape = "spec";
fake.extraWeighDays = [];
fake.cycleStatus = 200;
@@ -596,6 +611,122 @@ describe("Garmin history backfill", () => {
});
});
describe("Garmin cycle history", () => {
async function backfillToEnd() {
const { runGarminBackfillForUser } =
await import("@/lib/jobs/garmin-backfill");
for (let slice = 0; slice < 20; slice++) {
const user = await getPrismaClient().user.findUnique({
where: { id: USER_ID },
select: { garminBackfillCompletedAt: true },
});
if (user?.garminBackfillCompletedAt) return;
await runGarminBackfillForUser(USER_ID, () => false, slice);
}
throw new Error("backfill did not finish");
}
async function liveCycles() {
return getPrismaClient().menstrualCycle.findMany({
where: { userId: USER_ID, deletedAt: null },
orderBy: { startDate: "asc" },
select: {
id: true,
startDate: true,
endDate: true,
lengthDays: true,
periodEndDate: true,
},
});
}
it("opens a cycle per back-filled period, newest first, with lengths and a forecast", async () => {
await connectUser();
fake.historyFrom = addDays(fake.today, -100);
const starts = [-80, -52, -24].map((n) => addDays(fake.today, n));
fake.cycles = starts.map((start) => ({ start, periodLength: 5 }));
// A day the person logged inside the middle period.
const ownDay = addDays(starts[1]!, 2);
const prisma = getPrismaClient();
await prisma.cycleDayLog.create({
data: { userId: USER_ID, date: ownDay, flow: "HEAVY" },
});
await backfillToEnd();
const cycles = await liveCycles();
expect(
cycles.map((c) => [
c.startDate,
c.endDate,
c.lengthDays,
c.periodEndDate,
]),
).toEqual([
[starts[0], addDays(starts[1]!, -1), 28, addDays(starts[0]!, 4)],
[starts[1], addDays(starts[2]!, -1), 28, addDays(starts[1]!, 4)],
[starts[2], null, null, addDays(starts[2]!, 4)],
]);
// Every Garmin day belongs to the period it is part of.
const days = await prisma.cycleDayLog.findMany({
where: { userId: USER_ID },
orderBy: { date: "asc" },
select: { date: true, source: true, flow: true, cycleId: true },
});
expect(days).toHaveLength(15);
for (const day of days) {
const owner = [...cycles].reverse().find((c) => c.startDate <= day.date);
expect(day.cycleId).toBe(owner?.id);
}
// The person's own day is theirs, as they logged it.
expect(days.find((d) => d.date === ownDay)).toMatchObject({
source: "MANUAL",
flow: "HEAVY",
});
const { getOrCreateCycleProfile } = await import("@/lib/cycle/profile");
await getOrCreateCycleProfile(USER_ID);
const { refreshPredictionCacheForUser } =
await import("@/lib/cycle/prediction-refresh");
expect(await refreshPredictionCacheForUser(USER_ID)).toBe("persisted");
const forecast = await prisma.cyclePrediction.findUnique({
where: { userId: USER_ID },
});
expect(forecast).not.toBeNull();
// A second full backfill changes nothing.
await prisma.user.update({
where: { id: USER_ID },
data: {
garminBackfillProgress: Prisma.DbNull,
garminBackfillCompletedAt: null,
},
});
await backfillToEnd();
expect(await liveCycles()).toEqual(cycles);
expect(await prisma.cycleDayLog.count({ where: { userId: USER_ID } })).toBe(
15,
);
});
it("opens the current cycle from the hourly sync and leaves its end open while bleeding", async () => {
await connectUser();
const start = addDays(fake.today, -1);
fake.cycles = [{ start, periodLength: 5 }];
const { syncUserGarmin } = await import("@/lib/garmin/sync");
await syncUserGarmin(USER_ID, { lookbackDays: 2 });
const cycles = await liveCycles();
expect(cycles).toHaveLength(1);
expect(cycles[0]).toMatchObject({ startDate: start, periodEndDate: null });
const days = await getPrismaClient().cycleDayLog.findMany({
where: { userId: USER_ID },
select: { cycleId: true },
});
expect(days).toHaveLength(2);
expect(days.every((d) => d.cycleId === cycles[0]!.id)).toBe(true);
});
});
describe("Garmin connect and disconnect", () => {
function post(url: string, body?: unknown) {
return new NextRequest(`http://localhost${url}`, {
@@ -0,0 +1,200 @@
/**
* The one-shot repair of wearable period days imported without the cycles
* they open (real Postgres).
*
* Garmin and Oura used to write their period days as bare rows, so an
* account whose periods came from a watch or a ring held day-logs and no
* cycle. The repair opens the cycles those rows start, attributes the rest,
* stamps the end of a finished Garmin period, and touches no day-log's own
* content. A day the cycle rule declines stays as it is and drops out of the
* candidate set, so the boot check converges; a second run changes nothing.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getPrismaClient, truncateAllTables } from "./setup";
const sends = vi.hoisted(() => [] as string[]);
vi.mock("@/lib/jobs/boss-instance", () => ({
getGlobalBoss: () => ({
send: async (queue: string) => {
sends.push(queue);
return `job-${sends.length}`;
},
}),
}));
import {
enqueueBootTimeWearableCycleRepair,
repairWearableCycleDays,
} from "@/lib/jobs/wearable-cycle-repair";
const GARMIN_USER = "user-wearable-repair-garmin";
const OURA_USER = "user-wearable-repair-oura";
const BLOCKED_USER = "user-wearable-repair-blocked";
const DAY_MS = 86_400_000;
const addDays = (day: string, n: number) =>
new Date(Date.parse(`${day}T00:00:00Z`) + n * DAY_MS)
.toISOString()
.slice(0, 10);
const GARMIN_STARTS = ["2026-07-01", "2026-07-29", "2026-08-26"];
async function seedUser(id: string) {
await getPrismaClient().user.create({
data: {
id,
username: id,
email: `${id}@example.test`,
timezone: "UTC",
gender: "FEMALE",
},
});
}
/** Day-logs as a v1.47.0 import left them: no cycle. */
async function orphanDays(
userId: string,
source: "GARMIN" | "OURA",
days: string[],
) {
await getPrismaClient().cycleDayLog.createMany({
data: days.map((date) => ({
userId,
date,
tz: "UTC",
source,
flow: "LIGHT" as const,
})),
});
}
async function liveCycles(userId: string) {
return getPrismaClient().menstrualCycle.findMany({
where: { userId, deletedAt: null },
orderBy: { startDate: "asc" },
select: {
id: true,
startDate: true,
endDate: true,
lengthDays: true,
periodEndDate: true,
syncVersion: true,
},
});
}
beforeEach(async () => {
const prisma = getPrismaClient();
await truncateAllTables(prisma);
sends.length = 0;
for (const id of [GARMIN_USER, OURA_USER, BLOCKED_USER]) await seedUser(id);
await orphanDays(
GARMIN_USER,
"GARMIN",
GARMIN_STARTS.flatMap((start) =>
[0, 1, 2, 3, 4].map((i) => addDays(start, i)),
).filter((d) => d !== "2026-07-31"),
);
// The person's own day inside the middle period, logged before any cycle.
await prisma.cycleDayLog.create({
data: {
userId: GARMIN_USER,
date: "2026-07-31",
flow: "HEAVY",
source: "MANUAL",
},
});
await orphanDays(OURA_USER, "OURA", ["2026-06-01", "2026-06-29"]);
// A Garmin day 15 days before a start the person tapped: too close to be a
// cycle of its own, too far to be the same period. The rule declines it.
await prisma.menstrualCycle.create({
data: { userId: BLOCKED_USER, startDate: "2026-09-16", tz: "UTC" },
});
await orphanDays(BLOCKED_USER, "GARMIN", ["2026-09-01"]);
});
describe("wearable cycle repair", () => {
it("gives orphaned wearable period days their cycles", async () => {
expect(await enqueueBootTimeWearableCycleRepair()).toEqual({
enqueued: true,
error: null,
});
const result = await repairWearableCycleDays();
expect(result).toMatchObject({ opened: 5, periodEnds: 2, accounts: 2 });
const garmin = await liveCycles(GARMIN_USER);
expect(
garmin.map((c) => [
c.startDate,
c.endDate,
c.lengthDays,
c.periodEndDate,
]),
).toEqual([
["2026-07-01", "2026-07-28", 28, "2026-07-05"],
// The person's day breaks the Garmin run, so the end is the day before.
["2026-07-29", "2026-08-25", 28, "2026-07-30"],
// Still open: the hourly sync stamps its end.
["2026-08-26", null, null, null],
]);
const prisma = getPrismaClient();
const days = await prisma.cycleDayLog.findMany({
where: { userId: GARMIN_USER },
orderBy: { date: "asc" },
});
for (const day of days) {
const owner = [...garmin].reverse().find((c) => c.startDate <= day.date);
expect(day.cycleId).toBe(owner!.id);
}
expect(days.find((d) => d.date === "2026-07-31")).toMatchObject({
source: "MANUAL",
flow: "HEAVY",
});
const oura = await liveCycles(OURA_USER);
expect(oura.map((c) => [c.startDate, c.lengthDays])).toEqual([
["2026-06-01", 28],
["2026-06-29", null],
]);
// The declined day stays as it was and no longer counts as work.
const blocked = await prisma.cycleDayLog.findFirst({
where: { userId: BLOCKED_USER },
});
expect(blocked?.cycleId).toBeNull();
expect(await liveCycles(BLOCKED_USER)).toHaveLength(1);
sends.length = 0;
expect(await enqueueBootTimeWearableCycleRepair()).toEqual({
enqueued: false,
error: null,
});
expect(sends).toEqual([]);
});
it("changes nothing on a second run", async () => {
await repairWearableCycleDays();
const before = await liveCycles(GARMIN_USER);
const daysBefore = await getPrismaClient().cycleDayLog.findMany({
where: { userId: GARMIN_USER },
orderBy: { date: "asc" },
select: { id: true, cycleId: true, syncVersion: true, flow: true },
});
const again = await repairWearableCycleDays();
expect(again).toMatchObject({ scanned: 0, opened: 0, attributed: 0 });
expect(await liveCycles(GARMIN_USER)).toEqual(before);
expect(
await getPrismaClient().cycleDayLog.findMany({
where: { userId: GARMIN_USER },
orderBy: { date: "asc" },
select: { id: true, cycleId: true, syncVersion: true, flow: true },
}),
).toEqual(daysBefore);
});
});