mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
chore(release): v1.4.39 — mood, medication-compliance, and cumulative-sum rollup tiers
Squashed merge of the v1.4.39 wave work from develop. The release extends the v1.4.38 fast-path posture to two more endpoints that still walked the source table on every cold mount and folds a cumulative `sum_value` column into the existing rollup tier so step / flight / distance / daylight / active-energy sparklines no longer re-derive their daily totals in Node. Raw measurements / mood_entries / medication_intake_events tables are byte-unchanged. Three new tiers (mood_entry_rollups, medication_compliance_rollups, measurement_rollups.sum_value) are derived caches that self-heal via boot-time backfill on first reach. Migrations 0070, 0071, 0072 are additive only. The sum_value column add is catalog-only DDL on PostgreSQL 11+ — no table rewrite, writes resume in milliseconds. No environment-variable change. No API contract break. No iOS contract change. Expected wins (live perf-verify rides the post-deploy window): - /api/mood/analytics cold 12.7 s -> ~200 ms - /api/medications/intake?scope=compliance cold 3.2 s -> ~200 ms - /api/dashboard/summary cumulative sparkline ~500 ms -> ~300 ms - /api/analytics live-fallback row cap 347 k -> ~5 k (425 d cap preserves the year-ago baseline tile) Tests 4 524 -> 4 640 (+116). Typecheck clean. Lint clean. See CHANGELOG.md for the full v1.4.39 entry.
This commit is contained in:
1 parent
8a8150d2bf
commit
d84922cdc3
59 files changed
+8272
-29
No files matched your search
@@ -43,6 +43,11 @@ import {
|
||||
summarizeBackup,
|
||||
type BackupSummary,
|
||||
} from "@/lib/validations/backup";
|
||||
import { recomputeUserMoodRollups } from "@/lib/mood/rollups";
|
||||
import {
|
||||
recomputeUserMedicationCompliance,
|
||||
MEDICATION_COMPLIANCE_BACKFILL_DAYS,
|
||||
} from "@/lib/medications/compliance-rollups";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -281,6 +286,11 @@ const handler = apiHandler(
|
||||
const moods = await tx.moodEntry.deleteMany({
|
||||
where: { userId: ownerId },
|
||||
});
|
||||
// v1.4.39 W-MOOD — wipe the persisted mood rollup partition
|
||||
// for this owner so the next analytics read doesn't surface
|
||||
// pre-restore daily means. The fold below mints fresh rows
|
||||
// from the restored mood entries.
|
||||
await tx.moodEntryRollup.deleteMany({ where: { userId: ownerId } });
|
||||
const channels = await tx.notificationChannel.deleteMany({
|
||||
where: { userId: ownerId },
|
||||
});
|
||||
@@ -410,6 +420,52 @@ const handler = apiHandler(
|
||||
return apiError("Restore failed", 500);
|
||||
}
|
||||
|
||||
// v1.4.39 W-MOOD — re-fold the mood rollup tier from the just-
|
||||
// restored entries. Runs outside the transaction so the (5-year)
|
||||
// fold can't hold a long write lock; best-effort so a populator
|
||||
// hiccup doesn't undo the restore. The boot-time backfill is the
|
||||
// safety net — if this fails the next worker boot mints the rows.
|
||||
if (payload.moodEntries.length > 0) {
|
||||
try {
|
||||
await recomputeUserMoodRollups(ownerId, { granularities: ["DAY"] });
|
||||
} catch (err) {
|
||||
annotate({
|
||||
meta: {
|
||||
mood_rollup_restore_failed: true,
|
||||
mood_rollup_restore_error:
|
||||
err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// v1.4.39 W-MED — re-fold the medication-compliance rollup tier
|
||||
// from the restored intake events. The medication delete inside the
|
||||
// transaction already cascaded the existing rollup partition for
|
||||
// this owner via the FK, so the fold mints fresh rows. Boot-time
|
||||
// backfill is the safety net if this best-effort call fails.
|
||||
if (payload.intakeEvents.length > 0) {
|
||||
try {
|
||||
const restoreUser = await prisma.user.findUnique({
|
||||
where: { id: ownerId },
|
||||
select: { timezone: true },
|
||||
});
|
||||
await recomputeUserMedicationCompliance(
|
||||
ownerId,
|
||||
MEDICATION_COMPLIANCE_BACKFILL_DAYS,
|
||||
restoreUser?.timezone ?? null,
|
||||
);
|
||||
} catch (err) {
|
||||
annotate({
|
||||
meta: {
|
||||
medication_compliance_rollup_restore_failed: true,
|
||||
medication_compliance_rollup_restore_error:
|
||||
err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const summary = summarizeBackup(payload);
|
||||
|
||||
await auditLog("admin.backups.restore", {
|
||||
|
||||
@@ -205,6 +205,43 @@ async function buildAnalyticsResponse(user: AuthedUser) {
|
||||
// when the column is null or malformed.
|
||||
const sourcePriorityJson = user.sourcePriorityJson;
|
||||
|
||||
// v1.4.39 W-SINCE — defense-in-depth row cap on the per-type live
|
||||
// read. The v1.4.38.8 per-type fast-path gate (commit 8a8150d2)
|
||||
// narrowed `isFullyCovered` from "all types covered" to "these
|
||||
// specific types covered" inside the three downstream fast-paths
|
||||
// (bp_in_target / health_score / correlations). That made the
|
||||
// unbounded `fetchMeasurementSeriesChunked` walk against
|
||||
// `measurements` unreachable in the common case — but only on those
|
||||
// three branches. This per-type loop (A2 in the v1.4.38 perf audit)
|
||||
// has no fast-path gate at all; it always runs live SQL.
|
||||
//
|
||||
// Before the cap: a power-user account with 347 k rows split across
|
||||
// 15 measurement types fanned out 70+ chunked round-trips of 5 000
|
||||
// rows each, dominating the cold full-slice critical path (Marc's
|
||||
// 74.6 s cold mount).
|
||||
//
|
||||
// After the cap: the trailing 425 days bound the per-type walk
|
||||
// while preserving `summarize().avg30LastYear` (points 365-395 days
|
||||
// ago) and `summarize().avg30LastMonth` (30-60 days ago) for the
|
||||
// dashboard's year-over-year and month-over-month comparison tiles.
|
||||
// Cumulative HealthKit types (ACTIVITY_STEPS, ACTIVE_ENERGY, …)
|
||||
// collapse to one-row-per-day after the per-day-sum pass downstream
|
||||
// so a 425-day window stays bounded (≤ ~25 k rows per type on a
|
||||
// saturated tenant).
|
||||
//
|
||||
// QA Specialist-H2 (v1.4.39): the original 90-day cap stripped the
|
||||
// year-ago window so `summary.avg30LastYear` returned null on every
|
||||
// fall-through path, making the "vs last year" tile render "no
|
||||
// prior data" on every cold mount. The 425-day cap (365 + 30 + 30
|
||||
// buffer) keeps the year-ago window populated; the slim slice
|
||||
// (`?slice=summaries`) and the rollup-backed comprehensive
|
||||
// aggregator already operate on tighter windows so this cap only
|
||||
// affects the legacy live-fallback path the fast-path gate misses.
|
||||
const ANALYTICS_LIVE_WINDOW_DAYS = 425;
|
||||
const liveSince = new Date(
|
||||
Date.now() - ANALYTICS_LIVE_WINDOW_DAYS * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
|
||||
// v1.4.34 IW-B — capture the most-recent `measuredAt` per type so the
|
||||
// dashboard tile strip can render an "Letzter Wert vor Xd" caption on
|
||||
// tiles whose latest reading is older than a week. The series read
|
||||
@@ -225,6 +262,11 @@ async function buildAnalyticsResponse(user: AuthedUser) {
|
||||
types.map((type) =>
|
||||
fetchMeasurementSeriesChunked(user.id, type, {
|
||||
includeSleepStage: true,
|
||||
// v1.4.39 W-SINCE — trailing 425-day floor for the live read.
|
||||
// Wide enough to populate `summarize().avg30LastYear` (the
|
||||
// year-ago comparison tile) while still bounding the per-type
|
||||
// row count. See comment block above.
|
||||
since: liveSince,
|
||||
}).then((measurements) => {
|
||||
totalRowsReadForAggregate += measurements.length;
|
||||
// v1.4.34 IW-B — record the freshest `measuredAt` for this type
|
||||
@@ -317,10 +359,19 @@ async function buildAnalyticsResponse(user: AuthedUser) {
|
||||
// v1.4.23 Sr-H1 — slow-query attribution. Total rows pulled across
|
||||
// every per-type chunked read so ops can spot outlier users whose
|
||||
// analytics requests dominate the route's tail latency.
|
||||
//
|
||||
// v1.4.39 W-SINCE — also surface `live_since` (ISO) so the next
|
||||
// perf-verify can see how far back the live-fallback read actually
|
||||
// went. With the 425-day cap in place this should be ~now-425d on
|
||||
// every full-slice request; an older value would signal that a
|
||||
// future refactor accidentally widened the window again.
|
||||
annotate({
|
||||
meta: {
|
||||
analytics: {
|
||||
bp_aggregate: { row_count: totalRowsReadForAggregate },
|
||||
bp_aggregate: {
|
||||
row_count: totalRowsReadForAggregate,
|
||||
live_since: liveSince.toISOString(),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -206,6 +206,93 @@ describe("GET /api/dashboard/summary", () => {
|
||||
expect(glucose?.lastSeenAt).toBe(tenDaysAgo.toISOString());
|
||||
});
|
||||
|
||||
it("paints the steps sparkline from rollup sum_value, not mean (v1.4.39 W-SUM)", async () => {
|
||||
// The ACTIVITY_STEPS tile renders the per-day SUM, not the
|
||||
// per-bucket MEAN. The sparkline query feeds the SQL aggregate
|
||||
// directly off the `measurement_rollups` row; pinning the
|
||||
// returned shape proves the route hands `sum_value` through
|
||||
// instead of reconstructing from `mean * count`.
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.measurement.groupBy).mockResolvedValue([
|
||||
{
|
||||
type: "ACTIVITY_STEPS",
|
||||
_count: { _all: 7 },
|
||||
_max: { measuredAt: new Date() },
|
||||
},
|
||||
] as never);
|
||||
// First call: latest7d. Second call: sparkline. Third call:
|
||||
// streakDays. Matches the Promise.all order documented in the
|
||||
// route's perf-comment.
|
||||
vi.mocked(prisma.$queryRaw)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
type: "ACTIVITY_STEPS",
|
||||
value: 9999,
|
||||
measured_at: new Date(),
|
||||
},
|
||||
] as never)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
type: "ACTIVITY_STEPS",
|
||||
bucket_start: new Date(),
|
||||
mean: 2000,
|
||||
count: 4,
|
||||
// 8000 ≠ mean × count (4 × 2000 = 8000) but the SUM is the
|
||||
// direct rollup column; the fallback path would also hit
|
||||
// 8000 here. Use 8120 to prove the route did NOT reconstruct
|
||||
// from mean × count.
|
||||
sum_value: 8120,
|
||||
},
|
||||
] as never)
|
||||
.mockResolvedValueOnce([] as never);
|
||||
|
||||
const res = await callGet(makeReq());
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
data: { metrics: Array<{ id: string; sparkline: number[] }> };
|
||||
};
|
||||
const steps = body.data.metrics.find((m) => m.id === "steps");
|
||||
expect(steps?.sparkline).toEqual([8120]);
|
||||
});
|
||||
|
||||
it("falls back to mean * count when the legacy sum_value is null (v1.4.39 W-SUM)", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.measurement.groupBy).mockResolvedValue([
|
||||
{
|
||||
type: "ACTIVITY_STEPS",
|
||||
_count: { _all: 7 },
|
||||
_max: { measuredAt: new Date() },
|
||||
},
|
||||
] as never);
|
||||
vi.mocked(prisma.$queryRaw)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
type: "ACTIVITY_STEPS",
|
||||
value: 9999,
|
||||
measured_at: new Date(),
|
||||
},
|
||||
] as never)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
type: "ACTIVITY_STEPS",
|
||||
bucket_start: new Date(),
|
||||
mean: 2000,
|
||||
count: 4,
|
||||
sum_value: null,
|
||||
},
|
||||
] as never)
|
||||
.mockResolvedValueOnce([] as never);
|
||||
|
||||
const res = await callGet(makeReq());
|
||||
const body = (await res.json()) as {
|
||||
data: { metrics: Array<{ id: string; sparkline: number[] }> };
|
||||
};
|
||||
const steps = body.data.metrics.find((m) => m.id === "steps");
|
||||
// 4 × 2000 — legacy fallback for the boot-backfill convergence
|
||||
// window keeps the chart non-empty for pre-v1.4.39 rows.
|
||||
expect(steps?.sparkline).toEqual([8000]);
|
||||
});
|
||||
|
||||
it("computes intake compliance for today", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockImplementation(((
|
||||
|
||||
@@ -43,6 +43,7 @@ import { annotate } from "@/lib/logging/context";
|
||||
import { prisma } from "@/lib/db";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import { measurementTypeEnum } from "@/lib/validations/measurement";
|
||||
import { CUMULATIVE_HK_TYPES } from "@/lib/measurements/apple-health-mapping";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { defaultLocale, type Locale } from "@/lib/i18n/config";
|
||||
import { userDayKey, DEFAULT_TIMEZONE } from "@/lib/tz/resolver";
|
||||
@@ -202,11 +203,19 @@ interface LatestIn7dRow {
|
||||
|
||||
/** v1.4.38 W-F — per-day measurement_rollup bucket inside the 7-day
|
||||
* window. At most 7 buckets per metric × N metrics — bounded by
|
||||
* `SPARK_DAYS * |measurementTypes|` rather than the raw row count. */
|
||||
* `SPARK_DAYS * |measurementTypes|` rather than the raw row count.
|
||||
*
|
||||
* v1.4.39 W-SUM — `sum_value` rides along so the cumulative tile
|
||||
* (ACTIVITY_STEPS) renders the daily SUM rather than the per-bucket
|
||||
* MEAN. Spot metrics ignore the column; cumulative tiles fall back to
|
||||
* `mean * count` when the legacy NULL hits (boot-backfill convergence
|
||||
* window). */
|
||||
interface SparklineRow {
|
||||
type: MeasurementType;
|
||||
bucket_start: Date;
|
||||
mean: number;
|
||||
count: number;
|
||||
sum_value: number | null;
|
||||
}
|
||||
|
||||
/** v1.4.38 W-F — distinct activity day-keys from the streak window.
|
||||
@@ -325,7 +334,9 @@ async function buildDashboardSummary(
|
||||
SELECT
|
||||
r."type" AS type,
|
||||
r."bucket_start" AS bucket_start,
|
||||
r."mean"::double precision AS mean
|
||||
r."mean"::double precision AS mean,
|
||||
r."count"::int AS count,
|
||||
r."sum_value"::double precision AS sum_value
|
||||
FROM measurement_rollups r
|
||||
WHERE r."user_id" = ${userId}
|
||||
AND r."granularity" = 'DAY'
|
||||
@@ -430,10 +441,27 @@ async function buildDashboardSummary(
|
||||
at: new Date(row.measured_at),
|
||||
});
|
||||
}
|
||||
// v1.4.39 W-SUM — cumulative tiles paint the daily SUM; spot tiles
|
||||
// keep the daily MEAN. Reading `sum_value` directly off the rollup
|
||||
// row eliminates the legacy `mean * count` reconstruction; the
|
||||
// fallback covers pre-v1.4.39 NULL rows during the boot-backfill
|
||||
// convergence window.
|
||||
const sparkByType = new Map<MeasurementType, number[]>();
|
||||
for (const row of sparkBuckets) {
|
||||
const list = sparkByType.get(row.type) ?? [];
|
||||
list.push(Number(row.mean));
|
||||
// QA Simplifier (v1.4.39): flatten the cumulative-vs-spot ternary
|
||||
// into a named branch per the CLAUDE.md "no nested ternaries"
|
||||
// rule. Cumulative tiles paint the daily SUM; spot tiles keep the
|
||||
// daily MEAN. The legacy NULL fallback covers pre-v1.4.39 rollup
|
||||
// rows the boot-backfill hasn't refreshed yet.
|
||||
const cumulativePoint =
|
||||
row.sum_value !== null
|
||||
? Number(row.sum_value)
|
||||
: Number(row.mean) * Number(row.count);
|
||||
const point = CUMULATIVE_HK_TYPES.has(row.type)
|
||||
? cumulativePoint
|
||||
: Number(row.mean);
|
||||
list.push(point);
|
||||
sparkByType.set(row.type, list);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
measurementTypeEnum,
|
||||
glucoseContextEnum,
|
||||
} from "@/lib/validations/measurement";
|
||||
import { recomputeUserMoodRollups } from "@/lib/mood/rollups";
|
||||
|
||||
// Derived from canonical enum so round-trip export → import covers every
|
||||
// type. Previous hardcoded subset silently dropped 4 of 11 types
|
||||
@@ -128,6 +129,25 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
}
|
||||
}
|
||||
|
||||
// v1.4.39 W-MOOD — one bounded re-fold per import is cheaper than
|
||||
// firing N per-row hooks. The mood rollup tier is keyed on the
|
||||
// user + day; the fold materialises every touched day from the
|
||||
// entries we just wrote. Best-effort: an importer hiccup must not
|
||||
// surface as a 5xx, the rollup is a cache tier.
|
||||
if (stats.moodEntries > 0) {
|
||||
try {
|
||||
await recomputeUserMoodRollups(userId, { granularities: ["DAY"] });
|
||||
} catch (err) {
|
||||
annotate({
|
||||
meta: {
|
||||
mood_rollup_import_failed: true,
|
||||
mood_rollup_import_error:
|
||||
err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await auditLog("import.upload", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
|
||||
@@ -12,6 +12,7 @@ import { hashToken } from "@/lib/auth/hmac";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { externalIntakeSchema } from "@/lib/validations/medication";
|
||||
import { isApiGloballyEnabled } from "@/lib/app-settings";
|
||||
import { recomputeMedicationComplianceForEvent } from "@/lib/medications/compliance-rollups";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
@@ -152,5 +153,19 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
annotate({ meta: { medication_id: medication.id, event_id: event.id } });
|
||||
|
||||
// v1.4.39 W-MED — refresh the compliance rollup for the ingested
|
||||
// event's user-day. The external ingest path runs without a User
|
||||
// record in scope; resolve the tz once for the recompute.
|
||||
const ingestUser = await prisma.user.findUnique({
|
||||
where: { id: apiToken.userId },
|
||||
select: { timezone: true },
|
||||
});
|
||||
await recomputeMedicationComplianceForEvent({
|
||||
userId: apiToken.userId,
|
||||
medicationId: medication.id,
|
||||
scheduledFor: event.scheduledFor,
|
||||
tz: ingestUser?.timezone ?? null,
|
||||
});
|
||||
|
||||
return apiSuccess(event, 201);
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import { moodLogWebhookPayloadSchema } from "@/lib/validations/moodlog";
|
||||
import { readMoodLogSecret } from "@/lib/moodlog-secret";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { recomputeMoodBucketsForEntry } from "@/lib/mood/rollups";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -124,6 +125,19 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// v1.4.39 W-MOOD — refresh the persisted rollup for the entry's
|
||||
// bucket. Inline best-effort: a failure here must not block the
|
||||
// webhook 200 response (the rollup is a cache tier, the source-of-
|
||||
// truth is the mood_entries write that already committed).
|
||||
try {
|
||||
await recomputeMoodBucketsForEntry(user.id, moodLoggedAt);
|
||||
} catch (rollupErr) {
|
||||
getEvent()?.addWarning(
|
||||
"Mood rollup recompute failed: " +
|
||||
(rollupErr instanceof Error ? rollupErr.message : String(rollupErr)),
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning("DB operation failed: " + err);
|
||||
}
|
||||
|
||||
@@ -233,6 +233,65 @@ describe("GET /api/measurements — all-time semantics (SD-H1)", () => {
|
||||
expect(json.data.meta.aggregate).toBe("daily");
|
||||
});
|
||||
|
||||
it("source=rollup cumulative path reads sum_value directly (v1.4.39 W-SUM)", async () => {
|
||||
// ACTIVITY_STEPS rollup row with sum_value populated. The route
|
||||
// must consume sumValue directly — NOT reconstruct from mean *
|
||||
// count. Use a sum that is NOT mean × count so the test
|
||||
// distinguishes the two paths.
|
||||
const buckets = Array.from({ length: 3 }, (_, i) => ({
|
||||
type: "ACTIVITY_STEPS",
|
||||
bucketStart: new Date(Date.UTC(2026, 4, 1 + i, 0, 0, 0)),
|
||||
mean: 2000, // would yield 10000 if multiplied by count=5
|
||||
count: 5,
|
||||
sumValue: 11000 + i * 250, // distinct from mean × count
|
||||
}));
|
||||
vi.mocked(prisma.measurementRollup.findMany).mockResolvedValue(
|
||||
buckets as never,
|
||||
);
|
||||
|
||||
const res = await GET(
|
||||
getRequest(
|
||||
"type=ACTIVITY_STEPS&from=2026-05-01T00:00:00Z&to=2026-05-05T00:00:00Z&aggregate=daily&source=rollup&limit=5000",
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: { measurements: Array<{ value: number }> };
|
||||
};
|
||||
expect(prisma.$queryRaw).not.toHaveBeenCalled();
|
||||
expect(json.data.measurements.map((m) => m.value)).toEqual([
|
||||
11000, 11250, 11500,
|
||||
]);
|
||||
});
|
||||
|
||||
it("source=rollup cumulative path falls back to mean*count when sum_value is NULL (v1.4.39 W-SUM)", async () => {
|
||||
// Pre-v1.4.39 row — boot-backfill hasn't converged yet. The
|
||||
// route falls back to mean × count so the chart never paints
|
||||
// a hole during the convergence window.
|
||||
const buckets = [
|
||||
{
|
||||
type: "ACTIVITY_STEPS",
|
||||
bucketStart: new Date(Date.UTC(2026, 4, 1)),
|
||||
mean: 2000,
|
||||
count: 5,
|
||||
sumValue: null,
|
||||
},
|
||||
];
|
||||
vi.mocked(prisma.measurementRollup.findMany).mockResolvedValue(
|
||||
buckets as never,
|
||||
);
|
||||
|
||||
const res = await GET(
|
||||
getRequest(
|
||||
"type=ACTIVITY_STEPS&from=2026-05-01T00:00:00Z&to=2026-05-05T00:00:00Z&aggregate=daily&source=rollup&limit=5000",
|
||||
),
|
||||
);
|
||||
const json = (await res.json()) as {
|
||||
data: { measurements: Array<{ value: number }> };
|
||||
};
|
||||
expect(json.data.measurements[0].value).toBe(10000);
|
||||
});
|
||||
|
||||
it("falls back to live date_trunc when source=rollup returns zero buckets", async () => {
|
||||
// Empty rollup ⇒ heavy aggregate runs so brand-new accounts still
|
||||
// see a correct chart on their first render.
|
||||
|
||||
@@ -285,19 +285,29 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
bucketStart: true,
|
||||
mean: true,
|
||||
count: true,
|
||||
// v1.4.39 W-SUM — the writer now populates `sum_value` on
|
||||
// every fold. The cumulative metric path consumes the column
|
||||
// directly instead of reconstructing `mean * count`; the
|
||||
// legacy fallback below covers the boot-backfill convergence
|
||||
// window when an existing bucket pre-dates v1.4.39.
|
||||
sumValue: true,
|
||||
},
|
||||
});
|
||||
if (rollupRows.length > 0) {
|
||||
// Cumulative metrics (steps, active energy, distance, flights,
|
||||
// daylight) store `mean` per bucket but the chart needs the
|
||||
// daily SUM. Reconstruct as `mean * count` — algebraically
|
||||
// equivalent to SUM(value) for a single-source day because
|
||||
// AVG = SUM / COUNT.
|
||||
// daily SUM. v1.4.39 W-SUM — read `sumValue` directly; fall back
|
||||
// to `mean * count` only when the legacy NULL surfaces (pre-
|
||||
// v1.4.39 rows still waiting for the boot-time backfill to
|
||||
// converge). `mean * count` is algebraically equivalent to
|
||||
// SUM(value) for a single-source day because AVG = SUM / COUNT.
|
||||
const useSum =
|
||||
type != null && CUMULATIVE_HK_TYPES.has(type as MeasurementType);
|
||||
const measurements = rollupRows.map((r) => ({
|
||||
type: r.type,
|
||||
value: useSum ? r.mean * r.count : r.mean,
|
||||
value: useSum
|
||||
? (r.sumValue ?? r.mean * r.count)
|
||||
: r.mean,
|
||||
measuredAt: r.bucketStart.toISOString(),
|
||||
count: r.count,
|
||||
}));
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from "@/lib/api-response";
|
||||
import { updateIntakeEventSchema } from "@/lib/validations/medication";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import { recomputeMedicationComplianceForEvent } from "@/lib/medications/compliance-rollups";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string; eventId: string }> };
|
||||
@@ -67,6 +68,28 @@ export const PUT = apiHandler(
|
||||
// caches so the next read reflects the edited event.
|
||||
invalidateUserMedications(user.id);
|
||||
|
||||
// v1.4.39 W-MED — refresh the rollup row for both the old + new
|
||||
// scheduledFor day-keys when the timestamp moved across a day
|
||||
// boundary; if only takenAt / skipped changed the second call
|
||||
// collapses to a no-op upsert.
|
||||
await recomputeMedicationComplianceForEvent({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
scheduledFor: event.scheduledFor,
|
||||
tz: user.timezone,
|
||||
});
|
||||
if (
|
||||
data.scheduledFor !== undefined &&
|
||||
data.scheduledFor.getTime() !== event.scheduledFor.getTime()
|
||||
) {
|
||||
await recomputeMedicationComplianceForEvent({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
scheduledFor: data.scheduledFor,
|
||||
tz: user.timezone,
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess(updated);
|
||||
},
|
||||
);
|
||||
@@ -107,6 +130,16 @@ export const DELETE = apiHandler(
|
||||
// caches so the next read reflects the deletion.
|
||||
invalidateUserMedications(user.id);
|
||||
|
||||
// v1.4.39 W-MED — refresh the rollup row for the day the deleted
|
||||
// event sat on. When that day now holds zero events the helper
|
||||
// drops the rollup row entirely.
|
||||
await recomputeMedicationComplianceForEvent({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
scheduledFor: event.scheduledFor,
|
||||
tz: user.timezone,
|
||||
});
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
},
|
||||
);
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
getClientIp,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import {
|
||||
recomputeMedicationComplianceForDay,
|
||||
dayKeyForScheduledFor,
|
||||
} from "@/lib/medications/compliance-rollups";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
@@ -51,6 +55,9 @@ export const POST = apiHandler(
|
||||
let imported = 0;
|
||||
let skippedDuplicates = 0;
|
||||
let skippedInvalid = 0;
|
||||
// v1.4.39 W-MED — collect distinct day-keys touched by the import
|
||||
// so the rollup pass fires once per day rather than once per row.
|
||||
const touchedDays = new Set<string>();
|
||||
|
||||
for (const entry of entries) {
|
||||
// Parse as local datetime first; if invalid, fall back to CET offset.
|
||||
@@ -88,6 +95,30 @@ export const POST = apiHandler(
|
||||
},
|
||||
});
|
||||
imported++;
|
||||
touchedDays.add(dayKeyForScheduledFor(takenAt, user.timezone));
|
||||
}
|
||||
|
||||
// v1.4.39 W-MED — fold the touched days into rollup rows after the
|
||||
// insert loop completes. Best-effort: a populator failure logs but
|
||||
// never rolls back the imported events.
|
||||
for (const dayKey of touchedDays) {
|
||||
try {
|
||||
await recomputeMedicationComplianceForDay(
|
||||
user.id,
|
||||
id,
|
||||
dayKey,
|
||||
user.timezone,
|
||||
);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
annotate({
|
||||
meta: {
|
||||
medication_compliance_rollup_import_failed: true,
|
||||
medication_compliance_rollup_import_error: message,
|
||||
medication_compliance_rollup_day: dayKey,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await auditLog("medication.intake.import", {
|
||||
|
||||
@@ -21,6 +21,13 @@ export const DELETE = apiHandler(
|
||||
where: { medicationId: id, userId: user.id },
|
||||
});
|
||||
|
||||
// v1.4.39 W-MED — drop every rollup row for this medication so the
|
||||
// next compliance read returns zero-filled buckets rather than the
|
||||
// last-known scheduled / taken totals for now-deleted events.
|
||||
await prisma.medicationComplianceRollup.deleteMany({
|
||||
where: { medicationId: id, userId: user.id },
|
||||
});
|
||||
|
||||
await auditLog("medication.intake.purge", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
|
||||
@@ -16,6 +16,7 @@ import { withIdempotency } from "@/lib/idempotency";
|
||||
import { consumeOneDose } from "@/lib/medications/inventory/service";
|
||||
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import { recomputeMedicationComplianceForEvent } from "@/lib/medications/compliance-rollups";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
@@ -159,6 +160,16 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
|
||||
// caches so the next read reflects the dose event.
|
||||
invalidateUserMedications(user.id);
|
||||
|
||||
// v1.4.39 W-MED — refresh the persistent compliance rollup for the
|
||||
// affected day. The hook is best-effort; failures annotate but never
|
||||
// block the user's POST response.
|
||||
await recomputeMedicationComplianceForEvent({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
scheduledFor: event.scheduledFor,
|
||||
tz: user.timezone,
|
||||
});
|
||||
|
||||
return apiSuccess(event, 201);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,10 +9,23 @@ vi.mock("@/lib/db", () => ({
|
||||
update: vi.fn(),
|
||||
},
|
||||
medication: { update: vi.fn() },
|
||||
medicationComplianceRollup: {
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
// v1.4.39 QA F-H-01 — coverage probe + atomic upsert use raw SQL.
|
||||
$queryRaw: vi.fn(),
|
||||
$executeRaw: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/jobs/boss-instance", () => ({
|
||||
getGlobalBoss: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
@@ -52,6 +65,22 @@ beforeEach(() => {
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
|
||||
[] as never,
|
||||
);
|
||||
// v1.4.39 W-MED — default the coverage probe to "uncovered" so the
|
||||
// legacy compliance test still exercises the live-fallback branch
|
||||
// and finds the legacy mocked intake events.
|
||||
vi.mocked(prisma.medicationComplianceRollup.findFirst).mockResolvedValue(
|
||||
null,
|
||||
);
|
||||
vi.mocked(prisma.medicationComplianceRollup.findMany).mockResolvedValue(
|
||||
[] as never,
|
||||
);
|
||||
// v1.4.39 QA F-H-01 — the coverage probe is now a single `$queryRaw`
|
||||
// aggregate returning `{ rolled_days, event_days }`. Default to
|
||||
// "zero rollups, zero events" (covered/trivial-empty) so tests that
|
||||
// don't care about coverage land on the rollup path.
|
||||
vi.mocked(prisma.$queryRaw).mockResolvedValue([
|
||||
{ rolled_days: BigInt(0), event_days: BigInt(0) },
|
||||
] as never);
|
||||
});
|
||||
|
||||
describe("GET /api/medications/intake", () => {
|
||||
@@ -154,6 +183,7 @@ describe("POST /api/medications/intake", () => {
|
||||
id: "e1",
|
||||
userId: "user-1",
|
||||
medicationId: "m1",
|
||||
scheduledFor: new Date("2026-05-18T10:00:00.000Z"),
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValue({
|
||||
id: "e1",
|
||||
@@ -168,3 +198,58 @@ describe("POST /api/medications/intake", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("v1.4.39 W-MED — compliance rollup read swap", () => {
|
||||
it("reads the rollup tier when coverage is present", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
// QA F-H-01 (v1.4.39): coverage probe returns
|
||||
// `{ rolled_days >= event_days }` so the route lands on the
|
||||
// rollup tier. Match the trailing-7-day window.
|
||||
vi.mocked(prisma.$queryRaw).mockResolvedValue([
|
||||
{ rolled_days: BigInt(7), event_days: BigInt(7) },
|
||||
] as never);
|
||||
vi.mocked(prisma.medicationComplianceRollup.findMany).mockResolvedValue([
|
||||
{ day: "2026-05-18", scheduled: 3, taken: 2, skipped: 1 },
|
||||
] as never);
|
||||
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
"http://localhost/api/medications/intake?scope=compliance&days=7",
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
data: Array<{ date: string; scheduled: number; taken: number }>;
|
||||
};
|
||||
expect(body.data).toHaveLength(7);
|
||||
const today = body.data[body.data.length - 1];
|
||||
expect(today.scheduled).toBe(3);
|
||||
expect(today.taken).toBe(2);
|
||||
// The legacy live aggregator must not have run when coverage is hot.
|
||||
expect(prisma.medicationIntakeEvent.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to the live aggregator on coverage miss", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
// QA F-H-01 (v1.4.39): partial coverage — events present but
|
||||
// rollups missing — forces fall-through to the live aggregator.
|
||||
vi.mocked(prisma.$queryRaw).mockResolvedValue([
|
||||
{ rolled_days: BigInt(0), event_days: BigInt(7) },
|
||||
] as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
|
||||
{
|
||||
scheduledFor: new Date(),
|
||||
takenAt: new Date(),
|
||||
skipped: false,
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
"http://localhost/api/medications/intake?scope=compliance&days=7",
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.medicationIntakeEvent.findMany).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -41,6 +41,10 @@ import {
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import {
|
||||
recomputeMedicationComplianceForDay,
|
||||
dayKeyForScheduledFor,
|
||||
} from "@/lib/medications/compliance-rollups";
|
||||
|
||||
const MAX_ENTRIES_PER_BATCH = 500;
|
||||
const BATCH_RATE_LIMIT_MAX = 60;
|
||||
@@ -126,6 +130,11 @@ async function postBulk(request: NextRequest): Promise<Response> {
|
||||
let inserted = 0;
|
||||
let duplicates = 0;
|
||||
const skipped: Array<{ index: number; reason: string }> = [];
|
||||
// v1.4.39 W-MED — collect distinct `(medicationId, dayKey)` pairs
|
||||
// touched by the batch so one rollup recompute fires per pair after
|
||||
// all inserts complete. Per-row recompute would balloon a 500-entry
|
||||
// batch into 500 sequential rollup hits.
|
||||
const touchedDays = new Map<string, { medicationId: string; dayKey: string }>();
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i];
|
||||
@@ -155,6 +164,11 @@ async function postBulk(request: NextRequest): Promise<Response> {
|
||||
});
|
||||
inserted += 1;
|
||||
results.push({ index: i, status: "inserted", id: row.id });
|
||||
const dayKey = dayKeyForScheduledFor(scheduledFor, user.timezone);
|
||||
touchedDays.set(`${entry.medicationId}|${dayKey}`, {
|
||||
medicationId: entry.medicationId,
|
||||
dayKey,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
// P2002 = unique-constraint violation; the idempotencyKey
|
||||
// already exists → "duplicate", not an error.
|
||||
@@ -213,6 +227,32 @@ async function postBulk(request: NextRequest): Promise<Response> {
|
||||
invalidateUserMedications(user.id);
|
||||
}
|
||||
|
||||
// v1.4.39 W-MED — refresh one rollup row per distinct
|
||||
// `(medicationId, dayKey)` touched by the batch. Best-effort: failures
|
||||
// are swallowed by the helper's `recomputeMedicationComplianceForEvent`
|
||||
// wrapper, but bulk callers wrap recompute directly to keep the
|
||||
// tight ingest loop unaffected by populator issues.
|
||||
for (const { medicationId, dayKey } of touchedDays.values()) {
|
||||
try {
|
||||
await recomputeMedicationComplianceForDay(
|
||||
user.id,
|
||||
medicationId,
|
||||
dayKey,
|
||||
user.timezone,
|
||||
);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
annotate({
|
||||
meta: {
|
||||
medication_compliance_rollup_bulk_failed: true,
|
||||
medication_compliance_rollup_bulk_error: message,
|
||||
medication_compliance_rollup_medication: medicationId,
|
||||
medication_compliance_rollup_day: dayKey,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return apiSuccess({
|
||||
processed: entries.length,
|
||||
inserted,
|
||||
|
||||
@@ -26,6 +26,13 @@ import { auditLog } from "@/lib/auth/audit";
|
||||
import { userDayKey, DEFAULT_TIMEZONE } from "@/lib/tz/resolver";
|
||||
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import {
|
||||
readMedicationCompliance,
|
||||
hasMedicationComplianceCoverage,
|
||||
recomputeMedicationComplianceForEvent,
|
||||
enqueueUserMedicationComplianceBackfill,
|
||||
type ComplianceBucket as RollupComplianceBucket,
|
||||
} from "@/lib/medications/compliance-rollups";
|
||||
|
||||
const querySchema = z.object({
|
||||
scope: z.enum(["today", "compliance"]),
|
||||
@@ -116,10 +123,16 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
// are slow-moving (intake events trickle in, yesterday's row doesn't
|
||||
// move). Cache key carries the userTz so a user who changes timezone
|
||||
// doesn't read another tz's bucketing.
|
||||
//
|
||||
// v1.4.39 W-MED — read path now consumes the persistent
|
||||
// `medication_compliance_rollups` tier. A coverage probe falls back
|
||||
// to the legacy live aggregator when the user has intake events but
|
||||
// zero rollup rows; the fallback fires a boot-backfill enqueue in the
|
||||
// background so the next request hits the rollup tier.
|
||||
const result = await cached(
|
||||
caches.medicationsIntake as ServerCache<ComplianceBucket[]>,
|
||||
`${user.id}|compliance|${days}|${userTz}`,
|
||||
() => buildComplianceBuckets(user.id, days, userTz),
|
||||
() => readComplianceBucketsWithFallback(user.id, days, userTz),
|
||||
annotate,
|
||||
);
|
||||
|
||||
@@ -131,6 +144,50 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
return apiSuccess(result);
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.4.39 W-MED — read from the persistent rollup tier when covered,
|
||||
* fall through to the legacy live aggregator on coverage miss. The
|
||||
* fallback fires the boot backfill in the background so subsequent
|
||||
* requests hit the rollup path; the current request still returns a
|
||||
* correct response built from the raw events.
|
||||
*/
|
||||
async function readComplianceBucketsWithFallback(
|
||||
userId: string,
|
||||
days: number,
|
||||
userTz: string,
|
||||
): Promise<ComplianceBucket[]> {
|
||||
const covered = await hasMedicationComplianceCoverage(userId, days, userTz);
|
||||
if (covered) {
|
||||
const buckets = await readMedicationCompliance(userId, days, userTz);
|
||||
annotate({
|
||||
meta: {
|
||||
medication_compliance_path: "rollup",
|
||||
medication_compliance_days: days,
|
||||
},
|
||||
});
|
||||
return buckets satisfies RollupComplianceBucket[];
|
||||
}
|
||||
|
||||
// Coverage miss — the legacy aggregator stays correct over an empty
|
||||
// rollup window. Fire a user-scoped backfill in the background so
|
||||
// the next request lands on the rollup tier; the current request
|
||||
// still returns the live-derived buckets.
|
||||
//
|
||||
// QA F-SEC-M-01 (v1.4.39): pre-fix this fired the cluster-wide
|
||||
// `enqueueBootTimeMedicationComplianceBackfill` on every coverage-
|
||||
// miss request, opening a soft-DoS amplifier (every authenticated
|
||||
// user could drive a multi-tenant `LEFT JOIN` scan on each hit).
|
||||
// The user-scoped helper enqueues exactly the caller's account.
|
||||
void enqueueUserMedicationComplianceBackfill(userId);
|
||||
annotate({
|
||||
meta: {
|
||||
medication_compliance_path: "live-fallback",
|
||||
medication_compliance_days: days,
|
||||
},
|
||||
});
|
||||
return buildComplianceBuckets(userId, days, userTz);
|
||||
}
|
||||
|
||||
interface ComplianceBucket {
|
||||
date: string;
|
||||
scheduled: number;
|
||||
@@ -194,6 +251,8 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
return apiError("Intake event not found", 404);
|
||||
}
|
||||
|
||||
const userTzForHook = user.timezone ?? DEFAULT_TIMEZONE;
|
||||
|
||||
let updated;
|
||||
if (status === "taken") {
|
||||
[updated] = await prisma.$transaction([
|
||||
@@ -238,5 +297,16 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
// caches for this user so the next read reflects the dose change.
|
||||
invalidateUserMedications(user.id);
|
||||
|
||||
// v1.4.39 W-MED — refresh the persistent compliance rollup row for
|
||||
// the affected day so the next read after the cache miss returns
|
||||
// the up-to-date `(scheduled, taken, skipped)` tuple. Best-effort:
|
||||
// a populator failure annotates ops without blocking the response.
|
||||
await recomputeMedicationComplianceForEvent({
|
||||
userId: user.id,
|
||||
medicationId: existing.medicationId,
|
||||
scheduledFor: existing.scheduledFor,
|
||||
tz: userTzForHook,
|
||||
});
|
||||
|
||||
return apiSuccess(updated);
|
||||
});
|
||||
@@ -15,6 +15,7 @@ import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { moodDateKey, DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
|
||||
import { invalidateUserMood } from "@/lib/cache/invalidate";
|
||||
import { recomputeMoodBucketsForEntry } from "@/lib/mood/rollups";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
@@ -112,6 +113,31 @@ export const PUT = apiHandler(
|
||||
// v1.4.34 IW-G — bust per-user mood + achievements + analytics caches.
|
||||
invalidateUserMood(user.id);
|
||||
|
||||
// v1.4.39 W-MOOD — refresh the persisted rollup for the new
|
||||
// bucket AND the old bucket when the entry's `moodLoggedAt`
|
||||
// changed. The two recomputes are independent (different
|
||||
// (user, day) tuples) so we fan them out in parallel. Best-
|
||||
// effort: rollup failures must not surface as 5xx.
|
||||
try {
|
||||
const targets = new Set<number>([entry.moodLoggedAt.getTime()]);
|
||||
if (existing.moodLoggedAt.getTime() !== entry.moodLoggedAt.getTime()) {
|
||||
targets.add(existing.moodLoggedAt.getTime());
|
||||
}
|
||||
await Promise.all(
|
||||
Array.from(targets).map((t) =>
|
||||
recomputeMoodBucketsForEntry(user.id, new Date(t)),
|
||||
),
|
||||
);
|
||||
} catch (rollupErr) {
|
||||
annotate({
|
||||
meta: {
|
||||
mood_rollup_write_failed: true,
|
||||
mood_rollup_write_error:
|
||||
rollupErr instanceof Error ? rollupErr.message : String(rollupErr),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess({ ...entry, tags: parseTags(entry.tags) });
|
||||
},
|
||||
);
|
||||
@@ -144,6 +170,21 @@ export const DELETE = apiHandler(
|
||||
// v1.4.34 IW-G — bust per-user mood + achievements + analytics caches.
|
||||
invalidateUserMood(user.id);
|
||||
|
||||
// v1.4.39 W-MOOD — refresh the persisted rollup for the
|
||||
// deleted entry's bucket; the recompute helper handles the
|
||||
// "now-empty day → drop the rollup row" branch internally.
|
||||
try {
|
||||
await recomputeMoodBucketsForEntry(user.id, existing.moodLoggedAt);
|
||||
} catch (rollupErr) {
|
||||
annotate({
|
||||
meta: {
|
||||
mood_rollup_write_failed: true,
|
||||
mood_rollup_write_error:
|
||||
rollupErr instanceof Error ? rollupErr.message : String(rollupErr),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
},
|
||||
);
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
} from "@/lib/validations/moodlog";
|
||||
import { moodDateKey, DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
|
||||
import { invalidateUserMood } from "@/lib/cache/invalidate";
|
||||
import { recomputeMoodBucketsForEntry } from "@/lib/mood/rollups";
|
||||
|
||||
const MAX_ENTRIES_PER_BATCH = 500;
|
||||
const BATCH_RATE_LIMIT_MAX = 60;
|
||||
@@ -218,6 +219,42 @@ async function postBulk(request: NextRequest): Promise<Response> {
|
||||
invalidateUserMood(user.id);
|
||||
}
|
||||
|
||||
// v1.4.39 W-MOOD — refresh the rollup tier for every distinct day
|
||||
// touched by this batch. The bulk endpoint is an iOS one-shot
|
||||
// backfill so the batch can span many days; we collapse to the
|
||||
// unique `(user, dayStart)` set first to bound the recompute count.
|
||||
// Best-effort: rollup failures must not surface as 5xx.
|
||||
if (inserted > 0 || duplicates > 0) {
|
||||
const touchedDayStarts = new Set<number>();
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const status = results[i]?.status;
|
||||
if (status === "inserted" || status === "duplicate") {
|
||||
const d = entries[i].moodLoggedAt;
|
||||
const dayStart = Date.UTC(
|
||||
d.getUTCFullYear(),
|
||||
d.getUTCMonth(),
|
||||
d.getUTCDate(),
|
||||
);
|
||||
touchedDayStarts.add(dayStart);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await Promise.all(
|
||||
Array.from(touchedDayStarts).map((t) =>
|
||||
recomputeMoodBucketsForEntry(user.id, new Date(t)),
|
||||
),
|
||||
);
|
||||
} catch (rollupErr) {
|
||||
annotate({
|
||||
meta: {
|
||||
mood_rollup_write_failed: true,
|
||||
mood_rollup_write_error:
|
||||
rollupErr instanceof Error ? rollupErr.message : String(rollupErr),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return apiSuccess({
|
||||
processed: entries.length,
|
||||
inserted,
|
||||
|
||||
@@ -18,6 +18,7 @@ import { annotate } from "@/lib/logging/context";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { moodDateKey, DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
|
||||
import { invalidateUserMood } from "@/lib/cache/invalidate";
|
||||
import { recomputeMoodBucketsForEntry } from "@/lib/mood/rollups";
|
||||
|
||||
function parseTags(tags: string | null): string[] {
|
||||
if (!tags) return [];
|
||||
@@ -129,6 +130,22 @@ async function postMoodEntry(request: NextRequest) {
|
||||
// v1.4.34 IW-G — bust per-user mood + achievements + analytics caches.
|
||||
invalidateUserMood(user.id);
|
||||
|
||||
// v1.4.39 W-MOOD — refresh the persisted DAY rollup for the
|
||||
// entry's bucket and enqueue the WEEK / MONTH / YEAR folds.
|
||||
// Best-effort: a failure here must not surface as a 5xx to the
|
||||
// user, the rollup is a cache tier, not a write-path invariant.
|
||||
try {
|
||||
await recomputeMoodBucketsForEntry(user.id, moodLoggedAt);
|
||||
} catch (rollupErr) {
|
||||
annotate({
|
||||
meta: {
|
||||
mood_rollup_write_failed: true,
|
||||
mood_rollup_write_error:
|
||||
rollupErr instanceof Error ? rollupErr.message : String(rollupErr),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess({ ...entry, tags: parseTags(entry.tags) }, 201);
|
||||
} catch (err) {
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
/**
|
||||
* v1.4.39 W-MOOD — integration coverage for the rollup-tier read swap
|
||||
* in `/api/mood/analytics`.
|
||||
*
|
||||
* Pins the parity contract the audit at
|
||||
* `.planning/round-v1438-perf-analysis.md` §2.3 calls for: the
|
||||
* response shape stays byte-identical when the rollup tier is warm,
|
||||
* and falls back to the legacy live walk once when a legacy account
|
||||
* has mood entries but no rollup rows yet.
|
||||
*
|
||||
* The fast path consumes `prisma.moodEntryRollup.findMany`; the
|
||||
* coverage fallback consumes `prisma.moodEntry.findMany` (legacy
|
||||
* shape). Both branches go through the `cached(caches.moodAnalytics)`
|
||||
* LRU so the second read in a test must observe the same response.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
moodEntry: {
|
||||
findMany: vi.fn(),
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
},
|
||||
moodEntryRollup: {
|
||||
findMany: vi.fn(),
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
},
|
||||
$queryRawUnsafe: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
// Stub the warm-up helper so test runs don't fire the real
|
||||
// `recomputeUserMoodRollups` aggregate. The warm-up is fire-and-
|
||||
// forget on the route so its return value is irrelevant for parity.
|
||||
vi.mock("@/lib/mood/rollups", async () => {
|
||||
const actual = await vi.importActual<typeof import("@/lib/mood/rollups")>(
|
||||
"@/lib/mood/rollups",
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
ensureUserMoodRollupsFresh: vi.fn().mockResolvedValue({ recomputed: false }),
|
||||
};
|
||||
});
|
||||
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
|
||||
|
||||
const SESSION_USER = {
|
||||
id: "user-mood-1",
|
||||
username: "marc",
|
||||
role: "USER" as const,
|
||||
timezone: "Europe/Berlin",
|
||||
heightCm: 180,
|
||||
dateOfBirth: new Date("1980-01-01T00:00:00Z"),
|
||||
sourcePriorityJson: null,
|
||||
};
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: SESSION_USER as never,
|
||||
};
|
||||
|
||||
const callGet = GET as unknown as (...args: never[]) => Promise<Response>;
|
||||
|
||||
interface MoodAnalyticsBody {
|
||||
data: {
|
||||
entries: Array<{ date: string; score: number; samples: number }>;
|
||||
summary: {
|
||||
count: number;
|
||||
latest: number | null;
|
||||
min: number | null;
|
||||
max: number | null;
|
||||
mean: number | null;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
__resetAllCachesForTests();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([] as never);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("GET /api/mood/analytics", () => {
|
||||
it("returns an empty envelope for a brand-new user with zero rollups and zero raw entries", async () => {
|
||||
// Both branches return an empty result: rollup tier empty, raw
|
||||
// mood-entry table empty. The legacy `entries` array is also
|
||||
// empty so the response is identical to the pre-swap shape.
|
||||
const res = await callGet();
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as MoodAnalyticsBody;
|
||||
expect(body.data.entries).toEqual([]);
|
||||
expect(body.data.summary.count).toBe(0);
|
||||
expect(body.data.summary.latest).toBeNull();
|
||||
expect(body.data.summary.min).toBeNull();
|
||||
expect(body.data.summary.max).toBeNull();
|
||||
expect(body.data.summary.mean).toBeNull();
|
||||
});
|
||||
|
||||
it("consumes the rollup tier when DAY rows exist and skips the raw findMany", async () => {
|
||||
// One DAY-rollup row per calendar day, three days running.
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2026-05-08T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 4,
|
||||
minScore: 4,
|
||||
maxScore: 4,
|
||||
sd: null,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2026-05-09T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 5,
|
||||
minScore: 5,
|
||||
maxScore: 5,
|
||||
sd: null,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2026-05-10T00:00:00.000Z"),
|
||||
count: 2,
|
||||
mean: 4.5,
|
||||
minScore: 4,
|
||||
maxScore: 5,
|
||||
sd: 0.5,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await callGet();
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
// The raw `moodEntry.findMany` must not fire on the fast path.
|
||||
expect(prisma.moodEntry.findMany).not.toHaveBeenCalled();
|
||||
|
||||
const body = (await res.json()) as MoodAnalyticsBody;
|
||||
expect(body.data.entries).toEqual([
|
||||
{ date: "2026-05-08", score: 4, samples: 1 },
|
||||
{ date: "2026-05-09", score: 5, samples: 1 },
|
||||
{ date: "2026-05-10", score: 4.5, samples: 2 },
|
||||
]);
|
||||
expect(body.data.summary.count).toBe(3);
|
||||
expect(body.data.summary.latest).toBe(4.5);
|
||||
expect(body.data.summary.min).toBe(4);
|
||||
expect(body.data.summary.max).toBe(5);
|
||||
});
|
||||
|
||||
it("falls back to the live findMany once when the rollup tier is empty but mood entries exist", async () => {
|
||||
// Coverage-fallback: legacy account with raw entries but no
|
||||
// rollup coverage yet. The route runs the legacy walk once;
|
||||
// the warm-up helper is supposed to fire asynchronously
|
||||
// (stubbed above).
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([
|
||||
{
|
||||
date: "2026-05-08",
|
||||
score: 4,
|
||||
moodLoggedAt: new Date("2026-05-08T12:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
date: "2026-05-09",
|
||||
score: 5,
|
||||
moodLoggedAt: new Date("2026-05-09T12:00:00.000Z"),
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await callGet();
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
// Live fallback fired exactly once.
|
||||
expect(prisma.moodEntry.findMany).toHaveBeenCalledTimes(1);
|
||||
|
||||
const body = (await res.json()) as MoodAnalyticsBody;
|
||||
expect(body.data.entries).toEqual([
|
||||
{ date: "2026-05-08", score: 4, samples: 1 },
|
||||
{ date: "2026-05-09", score: 5, samples: 1 },
|
||||
]);
|
||||
expect(body.data.summary.count).toBe(2);
|
||||
expect(body.data.summary.latest).toBe(5);
|
||||
});
|
||||
|
||||
it("pins the DST fall-back Berlin midnight slip — UTC bucket vs local day diverge by one calendar day", async () => {
|
||||
// QA Specialist-H1 (v1.4.39): 2025-10-25T23:30:00Z is 00:30 local
|
||||
// in Europe/Berlin on 2025-10-26 (one hour AFTER the fall-back
|
||||
// transition). The mood rollup writer anchors `bucketStart` on
|
||||
// UTC midnight (mirroring the measurement-rollup convention), so
|
||||
// a write logged at this instant materialises a rollup row keyed
|
||||
// on `2025-10-25T00:00:00Z` — the UTC-anchored day — even though
|
||||
// the user's local wall clock reads 2025-10-26. The route's
|
||||
// `utcDayLabel` emits the same day-key the rollup row carries.
|
||||
//
|
||||
// This pins the documented behaviour. The legacy live-fallback
|
||||
// path uses `MoodEntry.date` (TZ-anchored) and therefore emits
|
||||
// `2025-10-26` for the same instant — a slip we document in the
|
||||
// route's header comment as the cost of the cache-tier semantics.
|
||||
// The v1.5 per-user-tz bucketing (P7 in the v1.4.38 perf audit)
|
||||
// closes the gap by anchoring the rollup table on the same day-
|
||||
// key the legacy path uses. Until then this is the contract.
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2025-10-25T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 4,
|
||||
minScore: 4,
|
||||
maxScore: 4,
|
||||
sd: null,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await callGet();
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as MoodAnalyticsBody;
|
||||
// The rollup tier pins the entry on the UTC-anchored day-key,
|
||||
// NOT the user's local 2025-10-26 — same convention as the
|
||||
// measurement-rollup tier.
|
||||
expect(body.data.entries).toEqual([
|
||||
{ date: "2025-10-25", score: 4, samples: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("serves the cached envelope on a warm read without touching the DB", async () => {
|
||||
// First read populates the cache.
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2026-05-10T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 4,
|
||||
minScore: 4,
|
||||
maxScore: 4,
|
||||
sd: null,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
] as never);
|
||||
|
||||
const first = await callGet();
|
||||
expect(first.status).toBe(200);
|
||||
expect(prisma.moodEntryRollup.findMany).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Second read hits the LRU and never touches Prisma again.
|
||||
const second = await callGet();
|
||||
expect(second.status).toBe(200);
|
||||
expect(prisma.moodEntryRollup.findMany).toHaveBeenCalledTimes(1);
|
||||
|
||||
const firstBody = (await first.json()) as MoodAnalyticsBody;
|
||||
const secondBody = (await second.json()) as MoodAnalyticsBody;
|
||||
expect(secondBody).toEqual(firstBody);
|
||||
});
|
||||
|
||||
it("pre-aggregates the live fallback through daily averages so multi-entry days match the rollup-path summarize semantics", async () => {
|
||||
// QA UX-H1 (v1.4.39): two entries on the same day (score 3 + 5)
|
||||
// must produce identical `summary.count / latest / min / max /
|
||||
// mean` on the rollup tier (one DataPoint with mean=4) AND on the
|
||||
// live-fallback path (which used to pass per-entry points).
|
||||
const moodLoggedAt = new Date("2026-05-10T12:00:00.000Z");
|
||||
|
||||
// Live-fallback first: two entries on the same day.
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([
|
||||
{ date: "2026-05-10", score: 3, moodLoggedAt },
|
||||
{ date: "2026-05-10", score: 5, moodLoggedAt },
|
||||
] as never);
|
||||
const liveRes = await callGet();
|
||||
const liveBody = (await liveRes.json()) as MoodAnalyticsBody;
|
||||
|
||||
__resetAllCachesForTests();
|
||||
|
||||
// Rollup tier: one DAY row with count=2 / mean=4.
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2026-05-10T00:00:00.000Z"),
|
||||
count: 2,
|
||||
mean: 4,
|
||||
minScore: 3,
|
||||
maxScore: 5,
|
||||
sd: 1,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
] as never);
|
||||
const rollupRes = await callGet();
|
||||
const rollupBody = (await rollupRes.json()) as MoodAnalyticsBody;
|
||||
|
||||
// Both branches emit a single daily-average entry with score=4.
|
||||
expect(liveBody.data.entries).toEqual([
|
||||
{ date: "2026-05-10", score: 4, samples: 2 },
|
||||
]);
|
||||
expect(rollupBody.data.entries).toEqual([
|
||||
{ date: "2026-05-10", score: 4, samples: 2 },
|
||||
]);
|
||||
|
||||
// Summary stats now match across both branches — pre-v1.4.39 the
|
||||
// live path passed per-entry points so `count` was 2 (per entry)
|
||||
// and `mean` was the unweighted average over entries. After the
|
||||
// pre-aggregate the live path emits one DataPoint per day (mean=4)
|
||||
// exactly as the rollup tier does.
|
||||
expect(liveBody.data.summary.count).toBe(rollupBody.data.summary.count);
|
||||
expect(liveBody.data.summary.latest).toBe(rollupBody.data.summary.latest);
|
||||
expect(liveBody.data.summary.min).toBe(rollupBody.data.summary.min);
|
||||
expect(liveBody.data.summary.max).toBe(rollupBody.data.summary.max);
|
||||
expect(liveBody.data.summary.mean).toBe(rollupBody.data.summary.mean);
|
||||
});
|
||||
|
||||
it("emits byte-identical entries + summary shape between rollup tier and live fallback for the same canonical data", async () => {
|
||||
// Same one-entry-per-day series, surfaced once via the rollup
|
||||
// tier and once via the legacy live walk. Response shape is
|
||||
// expected to be byte-compatible — the rollup carries the
|
||||
// pre-aggregated daily mean which is precisely what
|
||||
// aggregateDailyAverages would produce from a single entry
|
||||
// per day.
|
||||
const canonicalEntries = [
|
||||
{
|
||||
date: "2026-05-08",
|
||||
score: 3,
|
||||
moodLoggedAt: new Date("2026-05-08T12:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
date: "2026-05-09",
|
||||
score: 4,
|
||||
moodLoggedAt: new Date("2026-05-09T12:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
date: "2026-05-10",
|
||||
score: 5,
|
||||
moodLoggedAt: new Date("2026-05-10T12:00:00.000Z"),
|
||||
},
|
||||
];
|
||||
|
||||
// Live-fallback request first (rollup empty + raw populated).
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue(
|
||||
canonicalEntries as never,
|
||||
);
|
||||
const liveRes = await callGet();
|
||||
const liveBody = (await liveRes.json()) as MoodAnalyticsBody;
|
||||
|
||||
// Bust the cache before the rollup-tier read so the second call
|
||||
// re-evaluates the read path with the rollup populated.
|
||||
__resetAllCachesForTests();
|
||||
|
||||
vi.mocked(prisma.moodEntryRollup.findMany).mockResolvedValue([
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2026-05-08T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 3,
|
||||
minScore: 3,
|
||||
maxScore: 3,
|
||||
sd: null,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2026-05-09T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 4,
|
||||
minScore: 4,
|
||||
maxScore: 4,
|
||||
sd: null,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
{
|
||||
userId: "user-mood-1",
|
||||
granularity: "DAY",
|
||||
bucketStart: new Date("2026-05-10T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 5,
|
||||
minScore: 5,
|
||||
maxScore: 5,
|
||||
sd: null,
|
||||
computedAt: new Date(),
|
||||
},
|
||||
] as never);
|
||||
const rollupRes = await callGet();
|
||||
const rollupBody = (await rollupRes.json()) as MoodAnalyticsBody;
|
||||
|
||||
// `entries` shape — date / score / samples — must be byte-identical.
|
||||
expect(rollupBody.data.entries).toEqual(liveBody.data.entries);
|
||||
// Summary core stats must match (count / min / max / mean /
|
||||
// latest). Slope windows depend on Date.now() so we don't compare
|
||||
// those — they are deterministic for the same input and the
|
||||
// input is identical here.
|
||||
expect(rollupBody.data.summary.count).toBe(liveBody.data.summary.count);
|
||||
expect(rollupBody.data.summary.latest).toBe(liveBody.data.summary.latest);
|
||||
expect(rollupBody.data.summary.min).toBe(liveBody.data.summary.min);
|
||||
expect(rollupBody.data.summary.max).toBe(liveBody.data.summary.max);
|
||||
expect(rollupBody.data.summary.mean).toBe(liveBody.data.summary.mean);
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,24 @@ import { summarize, type DataPoint } from "@/lib/analytics/trends";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import {
|
||||
ensureUserMoodRollupsFresh,
|
||||
readMoodDayRollups,
|
||||
} from "@/lib/mood/rollups";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* v1.4.39 W-MOOD — five-year window for the rollup-tier read.
|
||||
*
|
||||
* Mirrors the legacy "unbounded findMany" semantics in practice: the
|
||||
* legacy code passed every mood the user had ever logged into Node.
|
||||
* The rollup tier stores one row per day, so a five-year cap is
|
||||
* cheap (at most ~1 800 rows) and still covers every user the
|
||||
* product has historic data for.
|
||||
*/
|
||||
const ROLLUP_WINDOW_MS = 5 * 365 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Aggregate multiple mood entries per day into daily averages. */
|
||||
function aggregateDailyAverages(
|
||||
records: Array<{ date: string; score: number }>,
|
||||
@@ -33,9 +48,81 @@ interface MoodAnalyticsResult {
|
||||
entryCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the rollup bucket's UTC `bucket_start` as a YYYY-MM-DD
|
||||
* label. The legacy live path emitted the row's TZ-anchored `date`
|
||||
* column; the rollup tier anchors on UTC midnight (same convention
|
||||
* as the measurement rollup tier). For tenants within ±3 h of UTC
|
||||
* (Berlin year-round) the two labels agree on every entry whose
|
||||
* timestamp doesn't straddle the UTC boundary — i.e. every realistic
|
||||
* mood log, which a human submits during waking hours.
|
||||
*
|
||||
* Trade-off (QA Specialist-H1, v1.4.39): on DST fall-back nights the
|
||||
* UTC anchor and the user's local wall-clock day-key can diverge by
|
||||
* one calendar day. Example: `2025-10-25T23:30:00Z` is 00:30 local
|
||||
* in Europe/Berlin on `2025-10-26` (one hour after the fall-back
|
||||
* transition); the rollup row is keyed on `2025-10-25` (UTC) while
|
||||
* the legacy live-fallback path would emit `2025-10-26`. This is
|
||||
* pinned by the route-parity DST test. v1.5 per-user-tz bucketing
|
||||
* (audit P7) anchors the rollup on the same day-key the legacy path
|
||||
* uses, closing the gap.
|
||||
*/
|
||||
function utcDayLabel(d: Date): string {
|
||||
const yyyy = d.getUTCFullYear();
|
||||
const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||
const dd = String(d.getUTCDate()).padStart(2, "0");
|
||||
return `${yyyy}-${mm}-${dd}`;
|
||||
}
|
||||
|
||||
async function buildMoodAnalyticsResponse(
|
||||
userId: string,
|
||||
): Promise<MoodAnalyticsResult> {
|
||||
// v1.4.39 W-MOOD — fire-and-forget warm-up so the next cold mount
|
||||
// for this user lands on the rollup tier even when the boot-time
|
||||
// backfill hasn't reached them yet.
|
||||
void ensureUserMoodRollupsFresh(userId);
|
||||
|
||||
const since = new Date(Date.now() - ROLLUP_WINDOW_MS);
|
||||
const rollups = await readMoodDayRollups(userId, since);
|
||||
|
||||
if (rollups.length > 0) {
|
||||
// Fast path — one DAY-rollup row per calendar day. The legacy
|
||||
// `aggregateDailyAverages` collapse is unnecessary because the
|
||||
// rollup already carries the daily mean; we recreate its output
|
||||
// shape directly so the response stays byte-compatible.
|
||||
const entries = rollups
|
||||
.map((r) => ({
|
||||
date: utcDayLabel(r.bucketStart),
|
||||
score: Math.round(r.mean * 100) / 100,
|
||||
samples: r.count,
|
||||
}))
|
||||
.sort((a, b) => a.date.localeCompare(b.date));
|
||||
|
||||
// Summarize feeds the slope7/30/90 windows. One DataPoint per
|
||||
// day (mean) is the right resolution — the legacy path passed
|
||||
// per-entry points, but the slope-window outputs match because
|
||||
// a power user's mood is typically 1/day. Multi-entry days
|
||||
// contribute their daily mean exactly once, which is the same
|
||||
// semantic the dashboard tile renders.
|
||||
const dataPoints: DataPoint[] = rollups.map((r) => ({
|
||||
date: r.bucketStart,
|
||||
value: r.mean,
|
||||
}));
|
||||
const summary = summarize(dataPoints);
|
||||
const entryCount = rollups.reduce((s, r) => s + r.count, 0);
|
||||
|
||||
annotate({ meta: { mood_analytics_path: "rollup" } });
|
||||
|
||||
return { entries, summary, entryCount };
|
||||
}
|
||||
|
||||
// Coverage-fallback — the user has no rollup rows yet. Probe for
|
||||
// raw mood entries; when the table is empty for this user we
|
||||
// return the same empty envelope the legacy path emitted. When
|
||||
// mood entries exist but rollups don't (legacy account before the
|
||||
// boot-backfill has caught up), we run the legacy live walk ONCE
|
||||
// so the request still gets a correct response — the warm-up
|
||||
// fired above will mint the rollups for the next request.
|
||||
const moodEntries = await prisma.moodEntry.findMany({
|
||||
where: { userId },
|
||||
orderBy: { moodLoggedAt: "asc" },
|
||||
@@ -46,13 +133,28 @@ async function buildMoodAnalyticsResponse(
|
||||
moodEntries.map((e) => ({ date: e.date, score: e.score })),
|
||||
);
|
||||
|
||||
const dataPoints: DataPoint[] = moodEntries.map((e) => ({
|
||||
date: e.moodLoggedAt,
|
||||
// QA UX-H1 (v1.4.39): feed `summarize()` per-day means, not per-entry
|
||||
// scores. The rollup fast-path emits one DataPoint per calendar day
|
||||
// (the rollup's `mean`); the live fallback used to pass every raw
|
||||
// entry, which silently shifted `summary.count / latest / min / max
|
||||
// / mean / avg7 / avg30 / slope30` on power-user multi-entry days.
|
||||
// Pre-aggregating through `aggregateDailyAverages` keeps the two
|
||||
// branches byte-identical on multi-entry days too. Date anchor is
|
||||
// local-noon for the day so the slope x-axis spans whole-day units —
|
||||
// mirrors the dashboard tile's intuition (one number per day).
|
||||
const dataPoints: DataPoint[] = entries.map((e) => ({
|
||||
date: new Date(`${e.date}T12:00:00.000Z`),
|
||||
value: e.score,
|
||||
}));
|
||||
|
||||
const summary = summarize(dataPoints);
|
||||
|
||||
annotate({
|
||||
meta: {
|
||||
mood_analytics_path: moodEntries.length === 0 ? "rollup" : "live",
|
||||
},
|
||||
});
|
||||
|
||||
return { entries, summary, entryCount: moodEntries.length };
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,9 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
const moodEntries = await tx.moodEntry.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
// v1.4.39 W-MOOD — wipe the persisted rollup partition for this
|
||||
// user so the next analytics read returns an empty envelope.
|
||||
await tx.moodEntryRollup.deleteMany({ where: { userId } });
|
||||
const apiTokens = await tx.apiToken.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import { moodLogCredentialsSchema } from "@/lib/validations/moodlog";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { markDisconnected, markReconnected } from "@/lib/integrations/status";
|
||||
import { invalidateUserMood } from "@/lib/cache/invalidate";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -74,6 +75,13 @@ export const DELETE = apiHandler(async () => {
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
// v1.4.39 W-MOOD — every mood entry for this user just vanished, so
|
||||
// every persisted rollup row for them is stale. Drop the whole
|
||||
// (userId, *) partition so the next analytics read returns an
|
||||
// empty envelope instead of stale daily means.
|
||||
await prisma.moodEntryRollup.deleteMany({ where: { userId: user.id } });
|
||||
invalidateUserMood(user.id);
|
||||
|
||||
// Clear credentials
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
|
||||
@@ -13,6 +13,7 @@ import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { locales, type Locale } from "@/lib/i18n/config";
|
||||
import { recomputeMedicationComplianceForEvent } from "@/lib/medications/compliance-rollups";
|
||||
|
||||
interface TelegramUpdate {
|
||||
update_id: number;
|
||||
@@ -115,6 +116,9 @@ async function findTelegramUser(chatId: string) {
|
||||
id: true,
|
||||
telegramBotToken: true,
|
||||
locale: true,
|
||||
// v1.4.39 W-MED — pulled into the select so the post-write
|
||||
// compliance-rollup hook can anchor the user-day bucket.
|
||||
timezone: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -124,6 +128,7 @@ async function markMedicationTaken(
|
||||
medicationId: string,
|
||||
idempotencyKey: string,
|
||||
locale: Locale,
|
||||
userTz: string | null,
|
||||
): Promise<{ ok: boolean; message: string; medicationName?: string }> {
|
||||
const { t } = getServerTranslator(locale);
|
||||
const medication = await prisma.medication.findFirst({
|
||||
@@ -139,14 +144,16 @@ async function markMedicationTaken(
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
let scheduledFor: Date | null = null;
|
||||
if (!existing) {
|
||||
scheduledFor = new Date();
|
||||
await prisma.$transaction([
|
||||
prisma.medicationIntakeEvent.create({
|
||||
data: {
|
||||
userId,
|
||||
medicationId: medication.id,
|
||||
scheduledFor: new Date(),
|
||||
takenAt: new Date(),
|
||||
scheduledFor,
|
||||
takenAt: scheduledFor,
|
||||
skipped: false,
|
||||
source: "REMINDER",
|
||||
idempotencyKey,
|
||||
@@ -159,6 +166,18 @@ async function markMedicationTaken(
|
||||
]);
|
||||
}
|
||||
|
||||
// v1.4.39 W-MED — refresh the compliance rollup for the
|
||||
// affected day so the next read after the cache miss reflects the
|
||||
// new dose. Only fires when the create-path landed a new row.
|
||||
if (scheduledFor) {
|
||||
await recomputeMedicationComplianceForEvent({
|
||||
userId,
|
||||
medicationId: medication.id,
|
||||
scheduledFor,
|
||||
tz: userTz,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
message: existing
|
||||
@@ -205,6 +224,7 @@ async function handleCallback(update: TelegramUpdate) {
|
||||
medicationId,
|
||||
idempotencyKey,
|
||||
locale,
|
||||
user.timezone,
|
||||
);
|
||||
await answerTelegramCallbackQuery(botToken, callback.id, result.message);
|
||||
if (messageId) {
|
||||
@@ -289,16 +309,18 @@ async function handleCallback(update: TelegramUpdate) {
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
let skippedScheduledFor: Date | null = null;
|
||||
if (!existing) {
|
||||
const endOfDay = new Date();
|
||||
endOfDay.setHours(23, 59, 59, 999);
|
||||
skippedScheduledFor = new Date();
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.medicationIntakeEvent.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
medicationId: medication.id,
|
||||
scheduledFor: new Date(),
|
||||
scheduledFor: skippedScheduledFor,
|
||||
takenAt: null,
|
||||
skipped: true,
|
||||
source: "REMINDER",
|
||||
@@ -312,6 +334,18 @@ async function handleCallback(update: TelegramUpdate) {
|
||||
]);
|
||||
}
|
||||
|
||||
// v1.4.39 W-MED — refresh the compliance rollup for the skipped
|
||||
// event's user-day so the next read sees the (scheduled, skipped)
|
||||
// counts incremented.
|
||||
if (skippedScheduledFor) {
|
||||
await recomputeMedicationComplianceForEvent({
|
||||
userId: user.id,
|
||||
medicationId: medication.id,
|
||||
scheduledFor: skippedScheduledFor,
|
||||
tz: user.timezone,
|
||||
});
|
||||
}
|
||||
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
@@ -372,6 +406,7 @@ async function handleCallback(update: TelegramUpdate) {
|
||||
medicationId,
|
||||
idempotencyKey,
|
||||
locale,
|
||||
user.timezone,
|
||||
);
|
||||
await answerTelegramCallbackQuery(botToken, callback.id, result.message);
|
||||
if (messageId) {
|
||||
@@ -477,6 +512,7 @@ async function handleTextMessage(update: TelegramUpdate) {
|
||||
meds[0].id,
|
||||
idempotencyKey,
|
||||
locale,
|
||||
user.timezone,
|
||||
);
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
@@ -611,6 +647,7 @@ async function handleTextMessage(update: TelegramUpdate) {
|
||||
medicationId,
|
||||
idempotencyKey,
|
||||
locale,
|
||||
user.timezone,
|
||||
);
|
||||
const resp = await sendTelegramMessage(
|
||||
botToken,
|
||||
|
||||
Reference in new issue
Block a user