fix(medications): harden the slot upsert against races, downgrades, and double-decrements

Review of the slot-convergence change surfaced gaps that could mis-record
a dose. Fold the write logic into one shared `applyCanonicalSlotWrite`
used by both intake routes and close them:

- Concurrency: catch the unique-key race on insert and converge by
  re-finding the slot row and updating it, instead of returning 500 (and
  dropping the tap) or leaving a duplicate.
- No downgrade: a pending projection echo replayed onto a slot already
  marked taken or skipped is a no-op — it never clears `takenAt`. A
  recorded dose is immutable, so an offline re-sync cannot flip a taken
  dose back to missed.
- Inventory: decrement a medication's remaining count only on a genuine
  pending→taken transition, not on an idempotent re-post.
- Deterministic slot-row selection: prefer an existing actioned row, then
  the pending row, ordered by createdAt then id.
- Snap instant: derive the canonical instant via the same `localHmAsUtc`
  the projector and reminder worker mint with, so the value is identical
  by construction across a DST transition rather than only test-pinned.
- Cleanup job: isolate each slot's collapse in its own try/catch and
  guard the instant-normalisation against a tombstone collision, so one
  slot can no longer dead-letter a user's whole dedup pass.
This commit is contained in:
Marc-André Bombeck committed 2026-06-01 08:32:42 +02:00
1 parent 5047eb7a20
commit 710902a43c
11 files changed
+1385 -116

No files matched your search

@@ -38,6 +38,8 @@ vi.mock("@/lib/db", () => ({
findFirst: vi.fn(),
count: vi.fn(),
create: vi.fn(),
// v1.8.2 reconcile — the shared slot upsert updates in place.
update: vi.fn(),
},
auditLog: { create: vi.fn() },
$transaction: vi.fn(),
@@ -350,3 +352,184 @@ describe("POST /api/medications/[id]/intake — one-shot lifecycle", () => {
});
});
});
// ────────────────────────────────────────────────────────────────────
// v1.8.2 reconcile — slot-snap upsert invariants through the route
// ────────────────────────────────────────────────────────────────────
describe("POST /api/medications/[id]/intake — v1.8.2 reconcile (M2 inventory)", () => {
function postReq(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/medications/med-1/intake", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
// A scheduled med (07:00 / 19:00) so the resolver returns a canonical
// slot and the write routes through the shared upsert.
const SCHEDULED_MED = {
id: "med-1",
startsOn: null,
endsOn: null,
oneShot: false,
createdAt: new Date("2026-01-01T00:00:00Z"),
schedules: [
{
id: "s1",
windowStart: "07:00",
windowEnd: "07:00",
daysOfWeek: null,
timesOfDay: ["07:00", "19:00"],
reminderGraceMinutes: null,
rrule: null,
rollingIntervalDays: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
},
],
};
it("does NOT decrement inventory on a re-post of an already-taken slot (M2)", async () => {
const { consumeOneDose } = await import(
"@/lib/medications/inventory/service"
);
// Resolver load → scheduled med.
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(
SCHEDULED_MED as never,
);
// Slot find (shared upsert) → an existing TAKEN row at the 07:00 slot.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-taken",
takenAt: new Date("2026-06-15T05:01:00Z"),
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "WEB",
createdAt: new Date("2026-06-15T05:01:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-taken",
takenAt: new Date("2026-06-15T05:02:00Z"),
skipped: false,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "WEB",
} as never);
vi.mocked(prisma.medication.update).mockResolvedValue({} as never);
// Reconcile probes (non-one-shot → noop).
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
oneShot: false,
active: true,
} as never);
const res = await POST(
postReq({
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
}),
ROUTE_PARAMS,
);
expect(res.status).toBe(201);
// Re-post of an already-taken slot → no pending→taken transition →
// inventory must NOT be consumed.
expect(consumeOneDose).not.toHaveBeenCalled();
// The row was updated, not duplicated.
expect(prisma.medicationIntakeEvent.update).toHaveBeenCalledTimes(1);
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
});
it("DOES decrement inventory on a genuine pending→taken move (M2)", async () => {
const { consumeOneDose } = await import(
"@/lib/medications/inventory/service"
);
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(
SCHEDULED_MED as never,
);
// Slot find → a PENDING REMINDER row (no takenAt).
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-pending",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-pending",
takenAt: new Date("2026-06-15T05:02:00Z"),
skipped: false,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
} as never);
vi.mocked(prisma.medication.update).mockResolvedValue({} as never);
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
oneShot: false,
active: true,
} as never);
const res = await POST(
postReq({
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
}),
ROUTE_PARAMS,
);
expect(res.status).toBe(201);
expect(consumeOneDose).toHaveBeenCalledTimes(1);
});
it("re-finds and updates the slot when the create races a P2002 (C1)", async () => {
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(
SCHEDULED_MED as never,
);
// First slot find → empty. Create throws P2002. Re-find → the racing
// pending row. Update applies the taken write onto it.
vi.mocked(prisma.medicationIntakeEvent.findMany)
.mockResolvedValueOnce([] as never)
.mockResolvedValueOnce([
{
id: "row-raced",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.create).mockRejectedValueOnce(
Object.assign(new Error("unique"), { code: "P2002" }),
);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-raced",
takenAt: new Date("2026-06-15T05:02:00Z"),
skipped: false,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
} as never);
vi.mocked(prisma.medication.update).mockResolvedValue({} as never);
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
oneShot: false,
active: true,
} as never);
const res = await POST(
postReq({
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
}),
ROUTE_PARAMS,
);
// The dose tap is NOT dropped — converges to the racing row, 201.
expect(res.status).toBe(201);
expect(prisma.medicationIntakeEvent.update).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "row-raced" } }),
);
});
});
+50 -56
View File
@@ -19,7 +19,10 @@ import { reconcileOneShotState } from "@/lib/medications/lifecycle";
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { recomputeMedicationComplianceForEvent } from "@/lib/rollups/medication-compliance-rollups";
import { resolveSlotInstantForWrite } from "@/lib/medications/scheduling/slot-upsert";
import {
applyCanonicalSlotWrite,
resolveSlotInstantForWrite,
} from "@/lib/medications/scheduling/slot-upsert";
import { NextRequest } from "next/server";
type RouteParams = { params: Promise<{ id: string }> };
@@ -77,6 +80,15 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
const resolvedTakenAt = skipped ? null : (takenAt ?? new Date());
const incomingScheduledFor = scheduledFor ?? takenAt ?? new Date();
// C2 — the per-med route only ever carries an explicit user gesture:
// `resolvedTakenAt` is `now()` for any non-skip POST (there is no
// "mark pending" write on this route), so a non-skip is an explicit
// taken and a `skipped:true` body is an explicit skip. Neither is a
// pending projection echo, so the no-downgrade guard never trips here —
// it is the bulk/sync route that replays pending echoes. The flags are
// threaded through so the shared upsert applies last-write-wins.
const isExplicitTaken = !skipped;
const isExplicitSkip = skipped === true;
// v1.8.2 — source-agnostic slot snap. A twice-daily med carries a
// pending REMINDER row the projector/worker minted at the canonical
@@ -129,62 +141,38 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
}
let event;
// v1.8.2 reconcile — whether this write moved the slot pending→taken.
// Only that transition decrements pen inventory (M2). For the
// unscheduled/PRN branch a non-skip write always records a fresh dose,
// so it consumes when not skipped.
let consumedTransition = !skipped;
if (canonicalSlot) {
// Scheduled dose — find the slot row regardless of `source` (the
// pending REMINDER row, or any prior row for this slot) and update
// it in place; mirrors the status-toggle route. Falls through to a
// create when the slot has no row yet.
const existingSlotRow = await prisma.medicationIntakeEvent.findFirst({
where: {
userId: user.id,
medicationId: id,
scheduledFor: canonicalSlot,
deletedAt: null,
},
// Scheduled dose — converge onto the one canonical slot row regardless
// of `source` (the pending REMINDER row, or any prior row for this
// slot) through the shared upsert: H1 deterministic selection, C2
// no-downgrade guard, and a C1 race-safe create that re-finds + updates
// on a P2002 collision rather than 500-ing or duplicating.
const applied = await applyCanonicalSlotWrite({
client: prisma,
userId: user.id,
medicationId: id,
canonicalSlot,
takenAt: resolvedTakenAt,
skipped,
isExplicitTaken,
isExplicitSkip,
idempotencyKey: idempotencyKey ?? null,
createSource: "WEB",
});
if (existingSlotRow) {
[event] = await prisma.$transaction([
prisma.medicationIntakeEvent.update({
where: { id: existingSlotRow.id },
data: {
takenAt: resolvedTakenAt,
skipped,
syncVersion: { increment: 1 },
idempotencyKey:
idempotencyKey ?? existingSlotRow.idempotencyKey ?? null,
},
}),
...(!skipped
? [
prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
}),
]
: []),
]);
} else {
[event] = await prisma.$transaction([
prisma.medicationIntakeEvent.create({
data: {
userId: user.id,
medicationId: id,
scheduledFor: canonicalSlot,
takenAt: resolvedTakenAt,
skipped,
source: "WEB",
idempotencyKey: idempotencyKey ?? null,
},
}),
...(!skipped
? [
prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
}),
]
: []),
]);
event = applied.row;
consumedTransition = applied.consumedTransition;
// Reset the snooze when a dose is actually recorded (not on a
// no-downgrade no-op, which left the prior taken row untouched).
if (!skipped && !applied.noDowngradeNoOp) {
await prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
});
}
} else {
// Unscheduled / PRN / off-slot — keep the original insert behaviour.
@@ -218,8 +206,14 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
// meds). Failures here must never block the intake write, so
// errors are swallowed and logged — the intake is the source of
// truth, the inventory is an opt-in companion.
//
// v1.8.2 M2 — gate on an ACTUAL pending→taken transition. An idempotent
// re-post of an already-taken slot updates the row in place but must NOT
// decrement again, else a repeated iOS sync drifts the GLP-1 pen count
// down on every replay. `consumedTransition` is false when the slot was
// already taken (or on a no-downgrade no-op).
let inventoryOutcome: Awaited<ReturnType<typeof consumeOneDose>> = null;
if (!skipped) {
if (!skipped && consumedTransition) {
try {
inventoryOutcome = await consumeOneDose({
userId: user.id,
@@ -9,10 +9,15 @@ vi.mock("@/lib/db", () => ({
prisma: {
medication: {
findMany: vi.fn(),
// v1.8.2 — the slot resolver loads the med via findFirst.
findFirst: vi.fn(),
},
medicationIntakeEvent: {
create: vi.fn(),
findUnique: vi.fn(),
// v1.8.2 reconcile — shared slot upsert reads + updates in place.
findMany: vi.fn(),
update: vi.fn(),
},
auditLog: { create: vi.fn() },
},
@@ -151,3 +156,164 @@ describe("POST /api/medications/intake/bulk — 422 multi-issue (v1.4.43 W6)", (
expect(res.status).toBe(422);
});
});
// ────────────────────────────────────────────────────────────────────
// v1.8.2 reconcile — bulk slot-snap upsert invariants (C2 + C1)
// ────────────────────────────────────────────────────────────────────
describe("POST /api/medications/intake/bulk — v1.8.2 reconcile", () => {
const SCHEDULED_MED = {
id: "med-1",
startsOn: null,
endsOn: null,
oneShot: false,
createdAt: new Date("2026-01-01T00:00:00Z"),
schedules: [
{
id: "s1",
windowStart: "07:00",
windowEnd: "07:00",
daysOfWeek: null,
timesOfDay: ["07:00", "19:00"],
reminderGraceMinutes: null,
rrule: null,
rollingIntervalDays: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
},
],
};
beforeEach(() => {
vi.mocked(prisma.medication.findMany).mockResolvedValue([
{ id: "med-1" },
] as never);
vi.mocked(prisma.medication.findFirst).mockResolvedValue(
SCHEDULED_MED as never,
);
});
it("C2 — a pending echo onto an already-TAKEN slot is reported duplicate, NOT a downgrade", async () => {
// Existing TAKEN row at the 07:00 slot. The bulk entry is a pending
// echo (no takenAt, skipped false) — must NOT clear takenAt.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-taken",
takenAt: new Date("2026-06-15T05:01:00Z"),
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "WEB",
createdAt: new Date("2026-06-15T05:01:00Z"),
},
] as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:30.000Z",
// no takenAt, skipped defaults false → pending echo
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: {
duplicates: number;
updated: number;
entries: Array<{ status: string; id?: string }>;
};
};
expect(body.data.duplicates).toBe(1);
expect(body.data.updated).toBe(0);
expect(body.data.entries[0].status).toBe("duplicate");
// The recorded dose was NEVER touched — no update issued.
expect(prisma.medicationIntakeEvent.update).not.toHaveBeenCalled();
});
it("C2 — an explicit takenAt still applies onto a pending slot (status updated)", async () => {
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-pending",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-pending",
} as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { updated: number; entries: Array<{ status: string }> };
};
expect(body.data.updated).toBe(1);
expect(body.data.entries[0].status).toBe("updated");
});
it("C1 — a same-slot P2002 on create converges via re-find+update, not dropped as duplicate", async () => {
// First slot find empty → create races a P2002 → re-find returns the
// racing pending row → update applies the incoming takenAt.
vi.mocked(prisma.medicationIntakeEvent.findMany)
.mockResolvedValueOnce([] as never)
.mockResolvedValueOnce([
{
id: "row-raced",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.create).mockRejectedValueOnce(
Object.assign(new Error("unique"), { code: "P2002" }),
);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-raced",
} as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { updated: number; entries: Array<{ status: string; id?: string }> };
};
// The dose is APPLIED to the existing row, not silently dropped.
expect(body.data.updated).toBe(1);
expect(body.data.entries[0].status).toBe("updated");
expect(body.data.entries[0].id).toBe("row-raced");
expect(prisma.medicationIntakeEvent.update).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "row-raced" } }),
);
});
});
+50 -32
View File
@@ -47,7 +47,10 @@ import {
recomputeMedicationComplianceForDay,
dayKeyForScheduledFor,
} from "@/lib/rollups/medication-compliance-rollups";
import { resolveSlotInstantForWrite } from "@/lib/medications/scheduling/slot-upsert";
import {
applyCanonicalSlotWrite,
resolveSlotInstantForWrite,
} from "@/lib/medications/scheduling/slot-upsert";
const MAX_ENTRIES_PER_BATCH = 500;
const BATCH_RATE_LIMIT_MAX = 60;
@@ -198,38 +201,49 @@ async function postBulk(request: NextRequest): Promise<Response> {
const scheduledFor = canonicalSlot ?? incomingScheduledFor;
const existingSlotRow = canonicalSlot
? await prisma.medicationIntakeEvent.findFirst({
where: {
userId: user.id,
medicationId: entry.medicationId,
scheduledFor: canonicalSlot,
deletedAt: null,
},
select: { id: true, idempotencyKey: true },
})
: null;
// C2 — classify the incoming write. An offline-sync replay echoes a
// PENDING projection (no `takenAt`, `skipped:false`) for a slot the
// user may already have actioned; that echo must NEVER clear a
// recorded `takenAt`. An explicit `takenAt` or `skipped:true` is a
// real user action and applies last-write-wins.
const isExplicitTaken = !entry.skipped && entry.takenAt !== undefined;
const isExplicitSkip = entry.skipped === true;
if (existingSlotRow) {
// Scheduled dose with an existing slot row — update in place
// (keep the row's original `source`), report "updated".
const row = await prisma.medicationIntakeEvent.update({
where: { id: existingSlotRow.id },
data: {
takenAt: entry.takenAt ?? null,
skipped: entry.skipped,
syncVersion: { increment: 1 },
idempotencyKey:
entry.idempotencyKey ?? existingSlotRow.idempotencyKey ?? null,
},
if (canonicalSlot) {
// Scheduled dose — converge onto the one canonical slot row through
// the shared upsert: H1 deterministic selection, C2 no-downgrade
// guard, and a C1 race-safe create that re-finds + updates on a
// P2002 collision rather than misclassifying it as a duplicate and
// dropping the dose.
const applied = await applyCanonicalSlotWrite({
client: prisma,
userId: user.id,
medicationId: entry.medicationId,
canonicalSlot,
takenAt: entry.takenAt ?? null,
skipped: entry.skipped,
isExplicitTaken,
isExplicitSkip,
idempotencyKey: entry.idempotencyKey ?? null,
createSource: "API",
});
updated += 1;
results.push({ index: i, status: "updated", id: row.id });
if (applied.noDowngradeNoOp) {
// C2 — pending echo onto an already-actioned slot. Report it as a
// duplicate so the iOS cursor advances WITHOUT downgrading the
// recorded dose.
duplicates += 1;
results.push({ index: i, status: "duplicate", id: applied.row.id });
} else if (applied.outcome === "updated") {
updated += 1;
results.push({ index: i, status: "updated", id: applied.row.id });
} else {
inserted += 1;
results.push({ index: i, status: "inserted", id: applied.row.id });
}
} else {
// No existing slot row (fresh scheduled dose, or unscheduled /
// PRN) — insert. The idempotencyKey, when supplied, has a UNIQUE
// index; a re-submission returns the existing row via P2002 →
// status: "duplicate".
// Unscheduled / PRN — insert. The idempotencyKey, when supplied,
// has a UNIQUE index; a re-submission returns the existing row via
// P2002 → status: "duplicate".
const row = await prisma.medicationIntakeEvent.create({
data: {
userId: user.id,
@@ -250,8 +264,12 @@ async function postBulk(request: NextRequest): Promise<Response> {
dayKey,
});
} catch (err: unknown) {
// P2002 = unique-constraint violation; the idempotencyKey
// already exists → "duplicate", not an error.
// P2002 = unique-constraint violation. Two shapes reach here:
// 1. an idempotencyKey collision on the unscheduled/PRN insert →
// "duplicate" (the canonical-slot path already absorbs its own
// same-slot P2002 race inside `applyCanonicalSlotWrite`);
// 2. a same-slot collision on the unscheduled insert. In both
// cases we surface the existing row id so the cursor advances.
if (
typeof err === "object" &&
err !== null &&