fix(api): give every offset-paged list a unique tiebreaker

`/api/measurements` and `/api/labs` sort on one non-unique column and
page with `skip`/`take`. When the sort key ties, Postgres does not
promise the same order for the query that fetches page N and the one
that fetches page N+1, so a client paging its own history can receive a
row twice and never receive another — silently, on both sides.

Ties are not hypothetical here. The partial unique index forbids two
live measurements of the same type at one instant, but the tie that
occurs in production is the cross-type one: a daily `stats:` rollup
posts steps, distance, flights and active energy at the identical
timestamp, and an unfiltered history list pages straight through the
block. A lab panel drawn in one sitting shares `takenAt` across every
analyte in it.

Appending `{ id: <same direction> }` to the `orderBy` makes the order
total. Same fix on the five siblings that page the same way — medication
intake history, illness day-logs, custom-metric entries, reminder
history, mental-health assessments — because the defect is the shape,
not the two routes it was found on. No wire change; `/api/sync/changes`
already ordered this way.

The fixtures seed ids in an order unrelated to insertion order, so the
assertion on order inside the tied block can only hold if the secondary
key is doing the work: with the tiebreaker removed the new file fails on
all three cases.
This commit is contained in:
Marc-André Bombeck committed 2026-09-10 04:01:14 +02:00
1 parent 08100b6207
commit 1d2744a109
8 files changed
+247 -8

No files matched your search

@@ -62,7 +62,9 @@ export const GET = apiHandler(
const [rows, total] = await Promise.all([
prisma.customMetricEntry.findMany({
where,
orderBy: { measuredAt: sortDir },
// Unique tiebreaker — see the measurements list: offset paging over
// a non-unique sort key can repeat and drop rows between pages.
orderBy: [{ measuredAt: sortDir }, { id: sortDir }],
take: limit,
skip: offset,
}),
@@ -88,7 +88,8 @@ export const GET = apiHandler(
const [rows, total] = await Promise.all([
prisma.illnessDayLog.findMany({
where,
orderBy: { date: sortDir },
// Unique tiebreaker — `date` is a calendar day and repeats.
orderBy: [{ date: sortDir }, { id: sortDir }],
take: limit,
skip: offset,
include: dayLogSymptomInclude,
+5 -1
View File
@@ -105,7 +105,11 @@ export const GET = apiHandler(async (request: NextRequest) => {
const [rows, total] = await Promise.all([
prisma.labResult.findMany({
where,
orderBy: { takenAt: sortDir },
// Unique tiebreaker: `takenAt` is a day-resolution timestamp, so a
// panel drawn in one sitting ties across every analyte in it. Offset
// paging over a non-unique sort key can repeat a row on one page and
// drop another, invisibly to both sides.
orderBy: [{ takenAt: sortDir }, { id: sortDir }],
take: limit,
skip: offset,
include: {
@@ -45,7 +45,8 @@ export const GET = apiHandler(
const [rows, total] = await Promise.all([
prisma.measurementReminderEvent.findMany({
where,
orderBy: { occurredAt: "desc" },
// Unique tiebreaker — several reminder events can share one instant.
orderBy: [{ occurredAt: "desc" }, { id: "desc" }],
take: limit,
skip: offset,
}),
+9 -1
View File
@@ -544,7 +544,15 @@ export const GET = apiHandler(async (request: NextRequest) => {
const [measurements, total] = await Promise.all([
prisma.measurement.findMany({
where,
orderBy: { [sortBy]: sortDir },
// `{ id: sortDir }` is the tiebreaker, not decoration. `measuredAt`
// is not unique here and ties are the normal case — an Apple Health
// import stamps long runs with one instant, and the
// `stats:<id>:YYYY-MM-DD` daily-rollup convention puts every daily
// total at the same one. Without a unique secondary key Postgres is
// free to order the tied block differently between the query for page
// N and the query for page N+1, so a client paging its own history
// silently gets one row twice and never gets another.
orderBy: [{ [sortBy]: sortDir }, { id: sortDir }],
take: limit,
skip: offset,
}),
+9 -2
View File
@@ -729,10 +729,17 @@ export const GET = apiHandler(
// the history view. Pinning them last keeps the descending order
// reading today → yesterday → … with real timestamps first. Other
// sort columns are non-null so they keep the simple shape.
// The trailing `{ id: sortDir }` is the unique tiebreaker. Scheduled
// slots share an instant by construction — a twice-daily medication puts
// every morning dose on the same `scheduledFor` — so offset paging over
// the primary key alone can repeat a row on one page and drop another.
const orderBy =
sortBy === "takenAt"
? { takenAt: { sort: sortDir, nulls: "last" as const } }
: { [sortBy]: sortDir };
? [
{ takenAt: { sort: sortDir, nulls: "last" as const } },
{ id: sortDir },
]
: [{ [sortBy]: sortDir }, { id: sortDir }];
const [events, total] = await Promise.all([
prisma.medicationIntakeEvent.findMany({
@@ -123,7 +123,9 @@ export const GET = apiHandler(async (request: NextRequest) => {
deletedAt: null,
...(instrument ? { instrument } : {}),
},
orderBy: { takenAt: "desc" },
// Unique tiebreaker — `takenAt` is day-resolution and two instruments
// taken in one sitting tie.
orderBy: [{ takenAt: "desc" }, { id: "desc" }],
take: limit ?? 100,
skip: offset ?? 0,
select: {