fix(insights): read the all-time extremes from the tier only where it matches

The DAY tier is not recomputed on every path that removes readings: a
hard delete with no rollup recompute leaves a bucket counting readings
that are gone, and the extremes then repeated it. Those figures are what
the Coach snapshot checks its coarse history against, so they must stay
true to the live record.

A type is now folded from the tier only when the tier accounts for the
live record day by day: the same days, and per day the same reading
count. The live side is a count per day served by an index-only scan of
the live index, so the check reads no measurement rows. A type that
fails it is read raw, as before.
This commit is contained in:
Marc-André Bombeck committed 2026-10-20 22:48:24 +02:00
1 parent 652dd6943b
commit 7bbd7c3811
2 files changed
+63 -11

No files matched your search

@@ -318,4 +318,27 @@ describe("readAllTimeExtremes over the DAY tier", () => {
expect(actual.get("WEIGHT")?.max).toBe(reference.get("WEIGHT")?.max);
expect(actual.get("WEIGHT")?.min).toBe(reference.get("WEIGHT")?.min);
});
it("reads the raw rows for a type whose tier outlived a hard delete", async () => {
// Rebuild a clean tier, then delete the hottest pulse reading with no
// rollup recompute: its DAY row now counts a reading that is gone.
await recomputeUserRollups(USER, { granularities: ["DAY"] });
const hottest = await prisma.measurement.findFirst({
where: { userId: USER, type: "PULSE", deletedAt: null },
orderBy: { value: "desc" },
});
await prisma.measurement.delete({ where: { id: hottest!.id } });
const stale = await prisma.measurementRollup.findMany({
where: {
userId: USER,
type: "PULSE",
granularity: "DAY",
readingMaxValue: hottest!.value,
},
});
expect(stale.length).toBeGreaterThan(0);
await expectParity(null);
const out = await readAllTimeExtremes(USER, ["PULSE"]);
expect(out.get("PULSE")?.max).toBeLessThan(hottest!.value);
});
});