fix(labs): re-derive a marker's analyte key when its name or unit changes

The key is a function of the marker's name and unit, but it was only ever
filled, never replaced, so a marker renamed from Glucose to Cholesterol kept
converting readings with the glucose factor. The marker edit now re-derives
it with the same match the creation paths use (clearing it when the new name
matches nothing), and the fill step a reading runs brings a stored key back in
line with the name, so a key written before this fix is corrected the first
time it matters. The scan review derives the key the same way as the commit.
This commit is contained in:
Marc-André Bombeck committed 2026-10-14 18:59:32 +02:00
1 parent 747e0964ad
commit cc0313c955
4 files changed
+216 -44

No files matched your search

+11
View File
@@ -17,6 +17,7 @@ import {
decryptContextFromBytes,
encryptContextToBytes,
} from "@/lib/labs/biomarker-store";
import { matchAnalyteKey } from "@/lib/labs/analyte-match";
import { annotate } from "@/lib/logging/context";
import { updateBiomarkerSchema } from "@/lib/validations/biomarkers";
import { effectiveBound, isInvertedRange } from "@/lib/validations/labs";
@@ -176,6 +177,16 @@ export const PUT = apiHandler(
if (d.upperBound !== undefined) data.upperBound = d.upperBound;
if (d.panel !== undefined) data.panel = d.panel;
if (d.hidden !== undefined) data.hidden = d.hidden;
// The analyte a marker is follows from its name and unit, the same match
// the creation paths use. A rename must move it, or a marker renamed from
// "Glucose" to "Cholesterol" would keep converting readings with the
// glucose factor; a name that now matches nothing clears it.
if (d.name !== undefined || d.unit !== undefined) {
data.analyteKey = matchAnalyteKey({
name: d.name ?? existing.name,
unit: d.unit ?? existing.unit,
});
}
// Inverted-range guard for a PARTIAL bound update. The schema refine only
// fires when both bounds arrive together; moving a single bound past the
+41 -25
View File
@@ -1,37 +1,53 @@
/**
* Link a marker to its analyte for the unit conversion.
*
* The key is set when a marker is created and, for a marker that already
* existed, the first time a reading needs it. It is never overwritten: a key a
* person (or an earlier pass) set stands, and `updateMany` is gated on the
* column still being null, so two concurrent writers converge. A marker whose
* name matches no analyte keeps a null key and gets no conversion.
* There is no manual choice of analyte: the key is a function of the marker's
* name and unit (`matchAnalyteKey`). It is set when a marker is created and
* re-derived whenever its name or unit changes, and this step brings a stored
* key back in line with that function the first time a reading needs it. So a
* marker that never had a key gets one, and a key that no longer agrees with
* the name (written before a rename re-derived it, or in an older form) is
* replaced, or cleared when the name now matches nothing. A key that agrees is
* left alone, so the step is idempotent.
*
* The write is gated on the column still holding what the caller read, so two
* concurrent writers converge, and a caller holding a stale copy re-reads the
* row rather than writing over a newer value.
*/
import type { PrismaClient } from "@/generated/prisma/client";
import { matchAnalyteKey } from "./analyte-match";
interface MarkerKeyState {
id: string;
name: string;
unit: string;
analyteKey?: string | null;
}
export async function ensureAnalyteKey(
client: Pick<PrismaClient, "biomarker">,
marker: {
id: string;
name: string;
unit: string;
analyteKey?: string | null;
},
marker: MarkerKeyState,
): Promise<string | null> {
if (marker.analyteKey) return marker.analyteKey;
const key = matchAnalyteKey({ name: marker.name, unit: marker.unit });
if (!key) return null;
const { count } = await client.biomarker.updateMany({
where: { id: marker.id, analyteKey: null },
data: { analyteKey: key },
});
if (count > 0) return key;
// Another writer set it first; read what stands.
const current = await client.biomarker.findUnique({
where: { id: marker.id },
select: { analyteKey: true },
});
return current?.analyteKey ?? null;
let current: MarkerKeyState = marker;
// Two rounds: the caller's copy, then the row as it stands if that copy was
// stale. A third writer racing both is vanishingly rare; the derived key is
// still the right answer for the name this call saw.
for (let round = 0; round < 2; round++) {
const derived = matchAnalyteKey({ name: current.name, unit: current.unit });
const stored = current.analyteKey ?? null;
if (stored === derived) return derived;
const { count } = await client.biomarker.updateMany({
where: { id: current.id, analyteKey: stored },
data: { analyteKey: derived },
});
if (count > 0) return derived;
const row = await client.biomarker.findUnique({
where: { id: current.id },
select: { id: true, name: true, unit: true, analyteKey: true },
});
if (!row) return null;
current = row;
}
return matchAnalyteKey({ name: current.name, unit: current.unit });
}
+7 -5
View File
@@ -146,16 +146,18 @@ export async function annotateRow(
// Biomarker match — case-insensitive on the catalog identity, presence-only.
const existingBiomarker = await prisma.biomarker.findFirst({
where: { userId, name: { equals: analyte, mode: "insensitive" } },
select: { id: true, name: true, unit: true, analyteKey: true },
select: { id: true, name: true, unit: true },
});
// The analyte the marker is, so the review can say whether a row in another
// unit converts. Read only: the key is filled when a reading is written.
// unit converts. Derived from the name and unit exactly as the commit derives
// it (a stored key is only that derivation, written down), so the review and
// the commit cannot disagree. Read only: the key is stored when a reading is
// written.
const markerAnalyteKey = existingBiomarker
? (existingBiomarker.analyteKey ??
matchAnalyteKey({
? matchAnalyteKey({
name: existingBiomarker.name,
unit: existingBiomarker.unit,
}))
})
: null;
// Duplicate check: a live lab_results row with the same analyte (fuzzy,