Carry the workout heart-rate curve to the end of the session

`durationSec` is a denormalised duration, and not every source reports
the elapsed one. Strava sends `moving_time` while the row's `endedAt` is
`startedAt + elapsed_time`, so a ride with twenty minutes of stops
carries a duration twenty minutes shorter than its own span. The curve
folded against that duration, which dropped every reading after the
moving-time mark: the tail of the session vanished with no gap and no
marker, and the detail page showed a complete-looking profile of an
incomplete session.

Fold over the span instead, with the duration as the floor for rows
whose `endedAt` is not after their `startedAt`. The bucket width tracks
the span too, so a stop-heavy ride keeps the same on-screen density as a
continuous one of the same length.

The reconstruction path also gets an integration suite over the real
route and a real Postgres. Two boundaries decide whether it is honest
and neither was provable against a mocked client: the query pads by five
minutes so a boundary reading still lands in the first or last bucket,
and a reading inside that pad must not extend the curve past the finish;
the measurement read is owner-scoped, and another account's pulse at the
same minute must not enter this curve. Both fixtures place a reading on
the far side with a bpm value no in-window reading has, so a leak shows
up in the numbers rather than only in a count. Verified by breaking each
boundary in turn and watching the matching assertion fail.
This commit is contained in:
Marc-André Bombeck committed 2026-08-07 14:41:24 +02:00
1 parent d5f176ac4d
commit 2f14379066
3 files changed
+382 -9

No files matched your search

@@ -180,3 +180,74 @@ describe("buildWorkoutHrSeries", () => {
expect(findMany).not.toHaveBeenCalled();
});
});
/**
* `durationSec` is a denormalised DURATION, and not every source reports
* the elapsed one: Strava sends `moving_time` while the row's `endedAt`
* is `startedAt + elapsed_time`. A ride with 20 minutes of stops
* therefore carries a `durationSec` 20 minutes shorter than its own
* wall-clock span, and folding the curve against it drops every reading
* after the moving-time mark — the tail of the session vanishes with no
* gap, no marker, nothing that reads as missing.
*/
describe("buildWorkoutHrSeries — sessions whose duration is not their span", () => {
const SPAN_SEC = 3600;
const MOVING_SEC = 2400;
const strava = {
userId: "u1",
startedAt: START,
endedAt: new Date(startMs + SPAN_SEC * 1000),
durationSec: MOVING_SEC,
now: new Date(startMs + SPAN_SEC * 1000 + 1000),
};
it("carries a stored series to the end of the session, not to the moving-time mark", async () => {
const stored = Array.from({ length: SPAN_SEC / 15 }, (_, i) =>
storedSample(i * 15, 120 + (i % 20)),
);
const result = await buildWorkoutHrSeries({
...strava,
storedSamples: stored,
});
expect(result).not.toBeNull();
const lastTSec = result!.points[result!.points.length - 1].tSec;
// The final bucket sits within one bucket width of the session end.
expect(lastTSec).toBeGreaterThanOrEqual(SPAN_SEC - result!.bucketSec);
expect(lastTSec).toBeLessThan(SPAN_SEC);
});
it("carries a pulse-window series past the moving-time mark too", async () => {
const rows = Array.from({ length: SPAN_SEC / 20 }, (_, i) => ({
value: 125 + (i % 9),
measuredAt: new Date(startMs + i * 20_000),
externalId: null,
}));
findMany.mockResolvedValue(rows);
const result = await buildWorkoutHrSeries({
...strava,
storedSamples: null,
});
expect(result).not.toBeNull();
expect(result!.source).toBe("pulse_window");
const lastTSec = result!.points[result!.points.length - 1].tSec;
expect(lastTSec).toBeGreaterThan(MOVING_SEC);
// The rows sit 20 s apart, so the final one can miss the very last
// bucket; landing within a sample interval of the end is the claim.
expect(lastTSec).toBeGreaterThanOrEqual(SPAN_SEC - 20 - result!.bucketSec);
});
it("keeps the duration as the floor when the row carries no usable span", async () => {
const stored = Array.from({ length: 40 }, (_, i) =>
storedSample(i * 15, 130),
);
const result = await buildWorkoutHrSeries({
...strava,
// A row whose end is not after its start: the span is unusable, so
// the denormalised duration has to stay the fold window.
endedAt: START,
storedSamples: stored,
});
expect(result).not.toBeNull();
expect(result!.bucketSec).toBe(adaptiveBucketSec(MOVING_SEC));
});
});
+41 -9
View File
@@ -82,27 +82,55 @@ function median(values: number[]): number {
: sorted[mid];
}
/**
* The session's own length on the wall clock.
*
* `durationSec` is a denormalised DURATION, and not every source reports
* the elapsed one — Strava sends `moving_time` while the row's `endedAt`
* is `startedAt + elapsed_time` (`src/lib/strava/client.ts`). A ride with
* twenty minutes of stops therefore carries a `durationSec` twenty
* minutes shorter than its own span, and a curve folded against it ends
* at the moving-time mark with no gap and no marker: the tail of the
* session simply is not there. The curve covers the session, so the span
* is what it folds over.
*
* The duration stays the floor. A row whose `endedAt` is not after its
* `startedAt` (a manual entry saved with one timestamp, a provider that
* shipped an end it could not resolve) has no usable span, and every
* source that computes `endedAt` from the duration lands on the same
* number either way.
*/
export function sessionSpanSec(
startedAt: Date,
endedAt: Date,
durationSec: number,
): number {
const floor = Math.max(0, durationSec);
const span = Math.round((endedAt.getTime() - startedAt.getTime()) / 1000);
return Number.isFinite(span) && span > floor ? span : floor;
}
/**
* Fold raw HR samples into session-grain buckets. Samples outside the
* session window `[0, durationSec)` are dropped from the curve (they
* only widen the DB query so a boundary reading still lands in bucket
* 0 / the last bucket). Empty buckets stay as gaps — no interpolation.
* session window `[0, spanSec)` are dropped from the curve (they only
* widen the DB query so a boundary reading still lands in bucket 0 / the
* last bucket). Empty buckets stay as gaps — no interpolation.
* Pure; exported for unit testing.
*/
export function foldHrBuckets(
samples: readonly RawHrSample[],
startMs: number,
durationSec: number,
spanSec: number,
bucketSec: number,
): { points: HrSeriesPoint[]; bucketCount: number; medianDensity: number } {
const bucketCount = Math.max(1, Math.ceil(durationSec / bucketSec));
const bucketCount = Math.max(1, Math.ceil(spanSec / bucketSec));
const acc = new Map<
number,
{ sum: number; min: number; max: number; n: number }
>();
for (const s of samples) {
const rel = (s.tMs - startMs) / 1000;
if (rel < 0 || rel >= durationSec) continue;
if (rel < 0 || rel >= spanSec) continue;
const idx = Math.floor(rel / bucketSec);
const bucket = acc.get(idx);
if (bucket) {
@@ -171,7 +199,11 @@ export async function buildWorkoutHrSeries(
const { userId, startedAt, endedAt, durationSec, storedSamples } = input;
const now = input.now ?? new Date();
const startMs = startedAt.getTime();
const bucketSec = adaptiveBucketSec(durationSec);
// Fold over the session's span, not its duration — see `sessionSpanSec`.
// The bucket width tracks the span too, so a stop-heavy ride keeps the
// same on-screen point density as a continuous one of the same length.
const spanSec = sessionSpanSec(startedAt, endedAt, durationSec);
const bucketSec = adaptiveBucketSec(spanSec);
// 1. Stored series — the native, highest-fidelity path.
const stored = parseStoredSamples(storedSamples);
@@ -179,7 +211,7 @@ export async function buildWorkoutHrSeries(
const { points, medianDensity } = foldHrBuckets(
stored,
startMs,
durationSec,
spanSec,
bucketSec,
);
if (points.length >= 2) {
@@ -222,7 +254,7 @@ export async function buildWorkoutHrSeries(
const { points, bucketCount, medianDensity } = foldHrBuckets(
raw,
startMs,
durationSec,
spanSec,
bucketSec,
);