chore(release): v1.4.40 — comprehensive Critical+High architecture closure plus iOS PB30 enablement

Eleven touch-disjoint waves landed on develop plus a six-axis QA
reconcile round before tagging. See CHANGELOG.md for the user-facing
prose; this commit message documents the wave + report inventory for
release-management traceability.

Waves shipped (each with a phase report under .planning/):

- phase-W-POOL-v1440-report.md — p-limit(4) wrapper around the
  analytics 15-way fan-out + pg.Pool max raised 10 -> 20. Closes the
  v1.4.39 empirical-trace finding #1 (Prisma pool starvation).
- phase-W-DELETED-v1440-report.md — 11 reader-tier helpers + 3
  integration contracts close audit Critical Finding #3 (soft-delete
  invisibility) across dashboard, analytics, summaries, rollup tiers,
  and the Coach snapshot path.
- phase-W-INSIGHTS-v1440-report.md — mood-rollup swap on the three
  /api/insights/{features,targets,cards} routes plus the
  compliance-rollup hook gap closure for bulk-projection mints; the
  post-QA reconcile patch closes the six remaining measurement.findMany
  sites in the cluster that still leaked tombstoned rows.
- phase-W-INFRA-v1440-report.md — rollup helper umbrella consolidation
  under src/lib/rollups/* with zero orphan re-exports; lint, typecheck,
  knip, and 93/93 rollup tests green post-restructure.
- phase-W-RSC-v1440-report.md — per-tile Suspense boundaries plus the
  queryKey factory-bypass walker test (extended to comparison/ in the
  reconcile pass).
- phase-W-PRIVACY-v1440-report.md — bilingual /privacy page with 17
  paired-section tests pinning the 9 SB-3 disclosure requirements.
- phase-W-AASA-v1440-report.md — /.well-known/apple-app-site-association
  endpoint pinned to S8WDX4W5KX.dev.healthlog.app with app-ID parity
  assertions guarding against split rotation.
- phase-W-APNS-NOTIFY-v1440-report.md — MEDICATION_REMINDER
  time-sensitive APNs payload (priority 10 + interruption-level)
  scoped via a parameterised test that pins all 6 other event-types
  do not bypass Focus. AP-2 .p8 install gates real delivery.
- phase-W-CONSENT-v1440-report.md — AI consent receipts CRUD with
  append-only invariant pinned in test; revoke-then-regrant leaves
  both rows; idempotent DELETE returns 200 + receipt: null.
- phase-W-WMY-WIRE-v1440-report.md — three previously-dead WMY readers
  (week/month/year) wired through summaries-slice and
  health-score-fast-path with a linear-composability parity test
  pinning the cross-consumer routing contract.
- phase-W-GHOSTS-v1440-report.md — ~1 177 lines of dead code removed
  across 9 atomic commits; startOfUtcDay + wallClockInTz consolidation
  eliminates a sibling-drift risk; knip whitelist trimmed to three
  files pending follow-up.

QA reconcile patches applied per the v1.4.40 QA round (six reports
under .planning/round-v1440-QA-*-findings.md):

- senior C1 — dashboard-suspense-boundaries regex aligned with the
  post-W-INFRA Thread 2 userTimezone-local lift.
- senior H1 — soft-delete filter added to the six remaining
  insights measurement.findMany sites.
- specialist H1 — Promise.allSettled around bulk-projection
  compliance recompute on both /api/medications/intake and
  /api/dashboard/summary.
- ux H1 — compare-toggle migrated to queryKeys.dashboardWidgets
  factory; walker test extended to src/components/comparison/.
- security M1 — consent artefact 64 KB cap enforced via
  Buffer.byteLength (UTF-8 bytes, not UTF-16 code units).

Quality gates green at tag: pnpm typecheck, pnpm lint, pnpm knip
--include files,dependencies,binaries,unlisted, pnpm test --run
(4726 passing / 1 skipped). Tests 4525 -> 4726 unit + 1 skipped over
the v1.4.39 -> v1.4.40 span.

User-facing prose: see CHANGELOG.md.
This commit is contained in:
Marc-André Bombeck committed 2026-05-21 12:48:02 +02:00
1 parent f9996552ed
commit 1114cf7e63
146 files changed
+8207 -2279

No files matched your search

-437
View File
@@ -1,437 +0,0 @@
/**
* v1.4.39 W-MOOD — unit tests for the persistent mood-rollup
* populator.
*
* `prisma` is mocked at the module level so we can pin:
* - the DAY-bucket sync recompute writes through the upsert path,
* - `recomputeMoodBucketsForEntry` is idempotent under re-run,
* - `enqueueMoodRollupRecompute` calls `boss.send` with the
* documented queue + singleton-key shape, and is a silent no-op
* when no boss is attached,
* - `ensureUserMoodRollupsFresh` short-circuits on fresh data and
* dedups concurrent callers onto one in-flight promise,
* - the boot-time backfill discovers users with mood entries but
* no rollup coverage and enqueues one job per uncovered user.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// vi.mock factories run BEFORE module-level statements due to hoisting,
// so the mock fns must live inside the factory closure. We re-export
// them through `vi.hoisted` so the test body can reach them after.
const mocks = vi.hoisted(() => ({
queryRaw: vi.fn(),
queryRawUnsafe: vi.fn(),
executeRaw: vi.fn(),
upsert: vi.fn(),
deleteMany: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
findFirstMoodEntry: vi.fn(),
bossSend: vi.fn(),
getGlobalBossMock: vi.fn(),
}));
vi.mock("@/lib/db", () => ({
prisma: {
$queryRaw: mocks.queryRaw,
$queryRawUnsafe: mocks.queryRawUnsafe,
$executeRaw: mocks.executeRaw,
moodEntryRollup: {
upsert: mocks.upsert,
deleteMany: mocks.deleteMany,
findFirst: mocks.findFirst,
findMany: mocks.findMany,
},
moodEntry: {
findFirst: mocks.findFirstMoodEntry,
},
},
}));
vi.mock("@/lib/jobs/boss-instance", () => ({
getGlobalBoss: () => mocks.getGlobalBossMock(),
}));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
}));
import { annotate } from "@/lib/logging/context";
const {
queryRaw,
queryRawUnsafe,
executeRaw,
upsert,
deleteMany,
findFirst,
findFirstMoodEntry,
bossSend,
getGlobalBossMock,
} = mocks;
// `findMany` is wired in so indirect lookups don't throw; the
// populator tests below exercise the `$queryRawUnsafe` + upsert
// paths so the reference stays unused inside this file.
void mocks.findMany;
void queryRaw;
import {
MOOD_ROLLUP_FULL_BACKFILL_QUEUE,
MOOD_ROLLUP_RECOMPUTE_QUEUE,
_resetEnsureUserMoodRollupsFreshInFlightForTests,
enqueueBootTimeMoodRollupBackfill,
enqueueMoodRollupRecompute,
ensureUserMoodRollupsFresh,
recomputeMoodBucketsForEntry,
} from "../rollups";
beforeEach(() => {
queryRaw.mockReset();
queryRawUnsafe.mockReset();
executeRaw.mockReset();
executeRaw.mockResolvedValue(0);
upsert.mockReset();
deleteMany.mockReset();
findFirst.mockReset();
mocks.findMany.mockReset();
findFirstMoodEntry.mockReset();
bossSend.mockReset();
getGlobalBossMock.mockReset();
// v1.4.39 — clear the per-userId in-flight map so a previous
// test's resolved promise does not short-circuit the next test.
_resetEnsureUserMoodRollupsFreshInFlightForTests();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("recomputeMoodBucketsForEntry", () => {
function bindValues(call: unknown[]): unknown[] {
return call.slice(1);
}
it("runs the atomic DAY upsert + DELETE pair and fires WEEK/MONTH/YEAR enqueues", async () => {
// QA F-H-02 (v1.4.39): the DAY pass is now a single atomic SQL
// statement (INSERT … SELECT … ON CONFLICT) plus a paired DELETE
// that gates on NOT EXISTS. No JS-side aggregate, no per-row
// upsert through the Prisma client.
getGlobalBossMock.mockReturnValue({ send: bossSend });
bossSend.mockResolvedValue("job-id");
await recomputeMoodBucketsForEntry(
"user-1",
new Date("2026-05-10T14:30:00.000Z"),
);
expect(executeRaw).toHaveBeenCalledTimes(2);
const insertBinds = bindValues(executeRaw.mock.calls[0]);
expect(insertBinds).toContain("user-1");
// bucket_start is bound twice (INSERT row + INSERT SELECT predicate
// are both inside the same CTE shape via the same parameter).
const dayStart = new Date("2026-05-10T00:00:00.000Z");
expect(
(insertBinds.filter((b) => b instanceof Date) as Date[]).some(
(d) => d.getTime() === dayStart.getTime(),
),
).toBe(true);
// QA F-H-03 — the enqueue is fire-and-forget; the response path
// never awaits the boss.send call. Wait a tick for the
// floating promise to flush before asserting.
await new Promise((r) => setImmediate(r));
expect(bossSend).toHaveBeenCalledTimes(3);
for (const call of bossSend.mock.calls) {
expect(call[0]).toBe(MOOD_ROLLUP_RECOMPUTE_QUEUE);
expect(call[1].userId).toBe("user-1");
expect(["WEEK", "MONTH", "YEAR"]).toContain(call[1].granularity);
}
});
it("issues the paired DELETE so a fully-cleared day removes its row", async () => {
getGlobalBossMock.mockReturnValue(null);
await recomputeMoodBucketsForEntry(
"user-1",
new Date("2026-05-10T14:30:00.000Z"),
);
// The DELETE always fires; its NOT EXISTS predicate matches zero
// rows on the populated-day branch and matches the row on the
// emptied-day branch. We can only assert the second statement
// fired here.
expect(executeRaw).toHaveBeenCalledTimes(2);
expect(deleteMany).not.toHaveBeenCalled();
expect(upsert).not.toHaveBeenCalled();
});
it("is idempotent under re-run for the same (user, day)", async () => {
getGlobalBossMock.mockReturnValue(null);
await recomputeMoodBucketsForEntry(
"user-1",
new Date("2026-05-10T14:30:00.000Z"),
);
await recomputeMoodBucketsForEntry(
"user-1",
new Date("2026-05-10T14:30:00.000Z"),
);
expect(executeRaw).toHaveBeenCalledTimes(4);
// Bind values for the INSERT statement match across both runs.
expect(bindValues(executeRaw.mock.calls[0])).toEqual(
bindValues(executeRaw.mock.calls[2]),
);
// Bind values for the DELETE statement match across both runs.
expect(bindValues(executeRaw.mock.calls[1])).toEqual(
bindValues(executeRaw.mock.calls[3]),
);
});
it("commits the strictest aggregate under concurrent recompute calls", async () => {
// QA F-H-02 race pin: two concurrent recomputes for the same
// (user, day) must both go through the atomic SQL path so each
// statement re-aggregates a snapshot taken after the prior commit
// released its row lock.
getGlobalBossMock.mockReturnValue(null);
await Promise.all([
recomputeMoodBucketsForEntry(
"user-1",
new Date("2026-05-10T14:30:00.000Z"),
),
recomputeMoodBucketsForEntry(
"user-1",
new Date("2026-05-10T14:30:00.000Z"),
),
]);
// 2 callers × 2 statements (INSERT + DELETE) each.
expect(executeRaw).toHaveBeenCalledTimes(4);
// No legacy JS-side aggregate ($queryRawUnsafe) fired on the DAY
// pass; no Prisma-API upsert / deleteMany were issued either.
expect(queryRawUnsafe).not.toHaveBeenCalled();
expect(upsert).not.toHaveBeenCalled();
expect(deleteMany).not.toHaveBeenCalled();
});
it("does not await the WEEK/MONTH/YEAR enqueue on the write-path response", async () => {
// QA F-H-03 (v1.4.39): the outer Promise.all is fire-and-forget so
// a slow pg-boss send never serialises the user's mood-write
// response. Pin that the helper resolves before the enqueue
// promise settles.
let resolveEnqueue: (() => void) | null = null;
const enqueueGate = new Promise<string>((resolve) => {
resolveEnqueue = () => resolve("job-late");
});
getGlobalBossMock.mockReturnValue({ send: () => enqueueGate });
await recomputeMoodBucketsForEntry(
"user-1",
new Date("2026-05-10T14:30:00.000Z"),
);
// The helper has resolved even though the boss.send promise is
// still pending. Resolve it after the assertion so the test does
// not leak a pending promise across the suite.
resolveEnqueue!();
await enqueueGate;
});
});
describe("enqueueMoodRollupRecompute", () => {
it("is a silent no-op when no boss is attached", async () => {
getGlobalBossMock.mockReturnValue(null);
await enqueueMoodRollupRecompute({
userId: "user-1",
granularity: "WEEK",
from: new Date("2026-05-04T00:00:00.000Z"),
to: new Date("2026-05-11T00:00:00.000Z"),
});
expect(bossSend).not.toHaveBeenCalled();
});
it("sends with the documented queue + singleton-key shape", async () => {
getGlobalBossMock.mockReturnValue({ send: bossSend });
bossSend.mockResolvedValue("job-1");
const from = new Date("2026-05-04T00:00:00.000Z");
await enqueueMoodRollupRecompute({
userId: "user-9",
granularity: "WEEK",
from,
to: new Date("2026-05-11T00:00:00.000Z"),
});
expect(bossSend).toHaveBeenCalledTimes(1);
const [queue, payload, opts] = bossSend.mock.calls[0];
expect(queue).toBe(MOOD_ROLLUP_RECOMPUTE_QUEUE);
expect(payload.userId).toBe("user-9");
expect(payload.granularity).toBe("WEEK");
expect(payload.from).toBe(from.toISOString());
expect(opts.singletonKey).toBe(`user-9|WEEK|${from.toISOString()}`);
});
});
describe("ensureUserMoodRollupsFresh", () => {
it("is a no-op when the user has no mood entries", async () => {
findFirst.mockResolvedValueOnce(null);
findFirstMoodEntry.mockResolvedValueOnce(null);
const result = await ensureUserMoodRollupsFresh("user-1");
expect(result.recomputed).toBe(false);
expect(queryRawUnsafe).not.toHaveBeenCalled();
});
it("is a no-op when the rollup is already ahead of the newest mood entry", async () => {
const rollupAt = new Date("2026-05-10T12:00:00.000Z");
const entryAt = new Date("2026-05-10T11:00:00.000Z");
findFirst.mockResolvedValueOnce({ computedAt: rollupAt });
findFirstMoodEntry.mockResolvedValueOnce({
updatedAt: entryAt,
moodLoggedAt: entryAt,
});
const result = await ensureUserMoodRollupsFresh("user-1");
expect(result.recomputed).toBe(false);
expect(queryRawUnsafe).not.toHaveBeenCalled();
});
it("triggers a DAY-window recompute when stale", async () => {
const rollupAt = new Date("2026-05-10T10:00:00.000Z");
const entryAt = new Date("2026-05-10T12:00:00.000Z");
findFirst.mockResolvedValueOnce({ computedAt: rollupAt });
findFirstMoodEntry.mockResolvedValueOnce({
updatedAt: entryAt,
moodLoggedAt: entryAt,
});
queryRawUnsafe.mockResolvedValueOnce([]);
const result = await ensureUserMoodRollupsFresh("user-1");
expect(result.recomputed).toBe(true);
expect(queryRawUnsafe).toHaveBeenCalledTimes(1);
});
it("swallows populator errors so the read path never fails", async () => {
findFirst.mockRejectedValueOnce(new Error("pool exhausted"));
findFirstMoodEntry.mockRejectedValueOnce(new Error("pool exhausted"));
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const result = await ensureUserMoodRollupsFresh("user-1");
expect(result.recomputed).toBe(false);
consoleSpy.mockRestore();
});
it("dedups concurrent callers for the same userId onto one in-flight promise", async () => {
const rollupAt = new Date("2026-05-10T10:00:00.000Z");
const entryAt = new Date("2026-05-10T12:00:00.000Z");
findFirst.mockResolvedValue({ computedAt: rollupAt });
findFirstMoodEntry.mockResolvedValue({
updatedAt: entryAt,
moodLoggedAt: entryAt,
});
queryRawUnsafe.mockResolvedValue([]);
const [a, b, c] = await Promise.all([
ensureUserMoodRollupsFresh("user-1"),
ensureUserMoodRollupsFresh("user-1"),
ensureUserMoodRollupsFresh("user-1"),
]);
expect(a.recomputed).toBe(true);
expect(b.recomputed).toBe(true);
expect(c.recomputed).toBe(true);
expect(queryRawUnsafe).toHaveBeenCalledTimes(1);
expect(findFirst).toHaveBeenCalledTimes(1);
expect(findFirstMoodEntry).toHaveBeenCalledTimes(1);
});
it("annotates the failure when the inner recompute throws", async () => {
const rollupAt = new Date("2026-05-10T10:00:00.000Z");
const entryAt = new Date("2026-05-10T12:00:00.000Z");
findFirst.mockResolvedValueOnce({ computedAt: rollupAt });
findFirstMoodEntry.mockResolvedValueOnce({
updatedAt: entryAt,
moodLoggedAt: entryAt,
});
queryRawUnsafe.mockRejectedValueOnce(new Error("deadlock detected"));
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const result = await ensureUserMoodRollupsFresh("user-1");
expect(result.recomputed).toBe(false);
expect(annotate).toHaveBeenCalledWith({
meta: {
mood_rollup_refresh_failed: true,
mood_rollup_refresh_error: "deadlock detected",
},
});
expect(consoleSpy).toHaveBeenCalled();
consoleSpy.mockRestore();
});
});
describe("enqueueBootTimeMoodRollupBackfill", () => {
it("is a silent no-op when no boss is attached", async () => {
getGlobalBossMock.mockReturnValue(null);
const result = await enqueueBootTimeMoodRollupBackfill();
expect(result).toEqual({ enqueued: 0, skipped: 0, error: null });
expect(queryRaw).not.toHaveBeenCalled();
expect(bossSend).not.toHaveBeenCalled();
});
it("enqueues one full-fold job per user with mood entries but no rollups", async () => {
getGlobalBossMock.mockReturnValue({ send: bossSend });
queryRaw.mockResolvedValueOnce([
{ id: "user-a" },
{ id: "user-b" },
{ id: "user-c" },
]);
bossSend
.mockResolvedValueOnce("job-a")
.mockResolvedValueOnce("job-b")
.mockResolvedValueOnce("job-c");
const result = await enqueueBootTimeMoodRollupBackfill();
expect(result).toEqual({ enqueued: 3, skipped: 0, error: null });
expect(bossSend).toHaveBeenCalledTimes(3);
for (const call of bossSend.mock.calls) {
expect(call[0]).toBe(MOOD_ROLLUP_FULL_BACKFILL_QUEUE);
}
expect(bossSend.mock.calls[0][2].singletonKey).toBe(
"mood-boot-backfill|user-a",
);
expect(bossSend.mock.calls[1][2].singletonKey).toBe(
"mood-boot-backfill|user-b",
);
expect(bossSend.mock.calls[2][2].singletonKey).toBe(
"mood-boot-backfill|user-c",
);
});
it("counts a `boss.send` returning null as 'skipped' (singleton coalesce)", async () => {
getGlobalBossMock.mockReturnValue({ send: bossSend });
queryRaw.mockResolvedValueOnce([{ id: "user-a" }, { id: "user-b" }]);
bossSend.mockResolvedValueOnce(null).mockResolvedValueOnce("job-b");
const result = await enqueueBootTimeMoodRollupBackfill();
expect(result).toEqual({ enqueued: 1, skipped: 1, error: null });
});
it("returns the error message when the discovery query throws", async () => {
getGlobalBossMock.mockReturnValue({ send: bossSend });
queryRaw.mockRejectedValueOnce(new Error("pool exhausted"));
const result = await enqueueBootTimeMoodRollupBackfill();
expect(result.enqueued).toBe(0);
expect(result.error).toBe("pool exhausted");
expect(bossSend).not.toHaveBeenCalled();
});
it("returns { enqueued: 0 } when no users need backfill", async () => {
getGlobalBossMock.mockReturnValue({ send: bossSend });
queryRaw.mockResolvedValueOnce([]);
const result = await enqueueBootTimeMoodRollupBackfill();
expect(result).toEqual({ enqueued: 0, skipped: 0, error: null });
expect(bossSend).not.toHaveBeenCalled();
});
});
-670
View File
@@ -1,670 +0,0 @@
/**
* v1.4.39 W-MOOD — persistent mood-rollup populator.
*
* Sits behind the 60-s `caches.moodAnalytics` LRU as the second cache
* tier on `/api/mood/analytics`. One row per
* `(userId, granularity, bucketStart)` in `mood_entry_rollups`,
* carrying `count` / `mean` / `min_score` / `max_score` / `sd`
* (population) folded via Postgres `AVG` / `MIN` / `MAX` / `STDDEV_POP`.
*
* The audit at `.planning/round-v1438-perf-analysis.md` §2.3 traced
* the 12.7 s cold mount on `/api/mood/analytics` to the unbounded
* `prisma.moodEntry.findMany({ where: { userId } })` that walked
* every mood row the user has ever written into Node only to
* bucket-average them in JS. This module mirrors the well-trodden
* `src/lib/measurements/rollups.ts` pattern so the read path can swap
* to a bounded `prisma.moodEntryRollup.findMany` with the daily mean
* already materialised.
*
* Write hooks:
* - Every mood-entry create/update/delete fires
* `recomputeMoodBucketsForEntry`. The DAY pass runs inline
* (cheap — single `(user, day)` aggregate) so the next read sees
* the fresh row without waiting on pg-boss.
* - WEEK / MONTH / YEAR are enqueued onto `mood-rollup-recompute`
* for the worker to fold. No current reader consumes them; the
* buckets exist so future cross-granularity readers ship without
* a backfill step.
* - Bulk endpoints (`/api/mood-entries/bulk`, restore) call
* `recomputeUserMoodRollups(userId)` once at the end of the
* batch instead of firing N per-row hooks.
*
* Reads:
* - `readMoodDayRollups(userId, since)` returns the persisted DAY
* rows. The reader-side fallback in `/api/mood/analytics` checks
* the rollup count and falls through to the legacy live findMany
* once when the user has mood entries but zero rollup rows;
* `enqueueBootTimeMoodRollupBackfill` mints the rollups on the
* next worker boot so subsequent reads converge on the fast path.
*/
import { prisma } from "@/lib/db";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
import { annotate } from "@/lib/logging/context";
import type {
Prisma,
PrismaClient,
RollupGranularity,
} from "@/generated/prisma/client";
/** Granularities that recompute asynchronously via pg-boss. */
const ASYNC_GRANULARITIES: RollupGranularity[] = ["WEEK", "MONTH", "YEAR"];
/** All granularities the rollup table tracks. */
export const ALL_MOOD_GRANULARITIES: RollupGranularity[] = [
"DAY",
"WEEK",
"MONTH",
"YEAR",
];
/** pg-boss queue name for per-bucket recompute jobs. */
export const MOOD_ROLLUP_RECOMPUTE_QUEUE = "mood-rollup-recompute";
/** Worker concurrency cap — recomputes are read-heavy on Postgres. */
export const MOOD_ROLLUP_RECOMPUTE_CONCURRENCY = 2;
/** pg-boss queue name for the boot-time backfill discovery. */
export const MOOD_ROLLUP_FULL_BACKFILL_QUEUE = "mood-rollup-full-backfill";
/** Boot-fold worker concurrency. Serial so we don't crowd the pool. */
export const MOOD_ROLLUP_FULL_BACKFILL_CONCURRENCY = 1;
/** Payload the worker queue carries. */
export interface MoodRollupRecomputePayload {
userId: string;
granularity: RollupGranularity;
/** ISO-8601 — the worker parses through `new Date(value)`. */
from: string;
/** ISO-8601 — the worker parses through `new Date(value)`. */
to: string;
/** Wall-clock kick-off for debugging only. */
enqueuedAt: string;
}
/** Payload the boot-time backfill helper enqueues. */
export interface MoodRollupFullBackfillPayload {
userId: string;
/** Wall-clock kick-off for debugging only. */
enqueuedAt: string;
}
/** Postgres `date_trunc` unit per granularity. */
const DATE_TRUNC_UNIT: Record<RollupGranularity, string> = {
DAY: "day",
WEEK: "week",
MONTH: "month",
YEAR: "year",
};
/** Raw row shape returned by the aggregate `$queryRawUnsafe`. */
interface MoodRollupRow {
bucket_start: Date;
count: bigint;
mean: number | null;
min_score: number | null;
max_score: number | null;
sd: number | null;
}
/**
* Tx-or-client surface the writer accepts. Mirrors the
* `measurement-rollups` write-path contract: when called from inside a
* `prisma.$transaction(async tx => …)` block, callers pass the `tx`
* client so the rollup write commits atomically with the parent
* mutation.
*/
type PrismaTxOrClient = Pick<
PrismaClient,
"$queryRawUnsafe" | "$executeRaw" | "moodEntryRollup"
>;
/**
* Recompute the rollup buckets for one user. Bounded by the optional
* `granularities` / `from` / `to` filters; defaults cover every
* granularity and the trailing 5 years.
*
* Idempotent: rows are upserted under the
* `(userId, granularity, bucketStart)` composite primary key, so
* re-running the call is a no-op for unchanged buckets and a refresh
* for changed ones.
*/
export async function recomputeUserMoodRollups(
userId: string,
opts: {
granularities?: RollupGranularity[];
from?: Date;
to?: Date;
} = {},
): Promise<{ rowsUpserted: number; durationMs: number }> {
const startedAt = Date.now();
const granularities = opts.granularities ?? ALL_MOOD_GRANULARITIES;
const fiveYearsAgo = new Date(Date.now() - 5 * 365 * 24 * 60 * 60 * 1000);
const from = opts.from ?? fiveYearsAgo;
const to = opts.to ?? new Date();
let rowsUpserted = 0;
for (const granularity of granularities) {
const rows = await runMoodRollupAggregate(prisma, {
userId,
granularity,
from,
to,
});
if (rows.length === 0) continue;
rowsUpserted += await persistMoodRollupRows(prisma, userId, granularity, rows);
}
return { rowsUpserted, durationMs: Date.now() - startedAt };
}
/**
* Synchronous DAY-bucket recompute for the write-path hooks plus an
* async enqueue of the WEEK / MONTH / YEAR recomputes.
*
* Scoped to the affected `(userId, day)` tuple — cheap, and avoids
* invalidating buckets that haven't changed.
*
* Pass `tx` when called from inside a `prisma.$transaction` block so
* the rollup write commits atomically with the parent mutation.
* Otherwise the global `prisma` client is used.
*/
export async function recomputeMoodBucketsForEntry(
userId: string,
moodLoggedAt: Date,
tx?: PrismaTxOrClient,
): Promise<void> {
const client = tx ?? prisma;
// DAY pass — synchronous. v1.4.39 hotfix (QA F-H-02): one atomic SQL
// statement re-aggregates inside the upsert subquery, closing the
// race window where two concurrent writes for the same (user, day)
// could interleave A-SELECT → B-SELECT → B-UPSERT (correct) →
// A-UPSERT (stale N-1). The trailing DELETE handles the "all entries
// for the day were removed" case in the same shot.
const dayStart = startOfUtcDay(moodLoggedAt);
const dayEnd = new Date(dayStart.getTime() + 24 * 60 * 60 * 1000);
await client.$executeRaw`
WITH aggregate AS (
SELECT
COUNT(*)::int AS count,
AVG(m."score")::double precision AS mean,
MIN(m."score")::integer AS min_score,
MAX(m."score")::integer AS max_score,
STDDEV_POP(m."score")::double precision AS sd
FROM "mood_entries" m
WHERE m."user_id" = ${userId}
AND m."mood_logged_at" >= ${dayStart}
AND m."mood_logged_at" < ${dayEnd}
)
INSERT INTO "mood_entry_rollups"
("user_id", "granularity", "bucket_start", "count", "mean", "min_score", "max_score", "sd", "computed_at")
SELECT
${userId},
'DAY',
${dayStart},
aggregate.count,
aggregate.mean,
aggregate.min_score,
aggregate.max_score,
aggregate.sd,
NOW()
FROM aggregate
WHERE aggregate.count > 0
ON CONFLICT ("user_id", "granularity", "bucket_start") DO UPDATE
SET "count" = EXCLUDED."count",
"mean" = EXCLUDED."mean",
"min_score" = EXCLUDED."min_score",
"max_score" = EXCLUDED."max_score",
"sd" = EXCLUDED."sd",
"computed_at" = EXCLUDED."computed_at"
`;
await client.$executeRaw`
DELETE FROM "mood_entry_rollups"
WHERE "user_id" = ${userId}
AND "granularity" = 'DAY'
AND "bucket_start" = ${dayStart}
AND NOT EXISTS (
SELECT 1
FROM "mood_entries" m
WHERE m."user_id" = ${userId}
AND m."mood_logged_at" >= ${dayStart}
AND m."mood_logged_at" < ${dayEnd}
)
`;
// WEEK / MONTH / YEAR — fire-and-forget enqueue. QA F-H-03 (v1.4.39):
// the outer await on this Promise.all used to serialise the write-path
// response on pg-boss latency. The DAY pass the read path depends on
// has already committed synchronously above; the queue is a hint, not
// a write-path invariant, so dropping the await keeps the response
// off the pg-boss critical path. Errors stay caught inside
// `enqueueMoodRollupRecompute` so the unhandled-rejection logger
// captures any pg-boss failure.
void Promise.all(
ASYNC_GRANULARITIES.map((granularity) => {
const { from, to } = bucketSpan(moodLoggedAt, granularity);
return enqueueMoodRollupRecompute({ userId, granularity, from, to }).catch(
(err: unknown) => {
const message = err instanceof Error ? err.message : String(err);
annotate({
meta: {
mood_rollup_enqueue_failed: true,
mood_rollup_enqueue_error: message,
},
});
console.error("[mood-rollups] async enqueue failed:", message);
},
);
}),
);
}
/**
* Best-effort pg-boss enqueue. Silent no-op when no boss is attached
* (route running in a context without the worker — typically the test
* suite). The reader-side fall-through still produces fresh data on a
* cache miss, so missing the enqueue is at-most a one-read cost
* rather than a correctness bug.
*/
export async function enqueueMoodRollupRecompute(input: {
userId: string;
granularity: RollupGranularity;
from: Date;
to: Date;
}): Promise<void> {
const boss = getGlobalBoss();
if (!boss) return;
const payload: MoodRollupRecomputePayload = {
userId: input.userId,
granularity: input.granularity,
from: input.from.toISOString(),
to: input.to.toISOString(),
enqueuedAt: new Date().toISOString(),
};
await boss.send(MOOD_ROLLUP_RECOMPUTE_QUEUE, payload, {
retryLimit: 3,
retryDelay: 30,
retryBackoff: true,
// Coalesce duplicate enqueues for the same bucket key — two writes
// inside the same week share one queued job.
singletonKey: `${input.userId}|${input.granularity}|${input.from.toISOString()}`,
});
}
/**
* Read DAY-granularity rollup rows for one user, sorted ascending by
* `bucketStart`. The read-path swap in `/api/mood/analytics` consumes
* these directly without any extra Node-side aggregation.
*
* `since` is an inclusive lower bound. Pass a 5-year-old `Date` from
* the route to mirror the legacy "unbounded" semantics; future
* consumers can narrow the window cheaply because the rollup table
* carries one row per day rather than one per entry.
*/
export async function readMoodDayRollups(
userId: string,
since: Date,
): Promise<
Array<{
bucketStart: Date;
count: number;
mean: number;
minScore: number;
maxScore: number;
sd: number | null;
computedAt: Date;
}>
> {
const rows = await prisma.moodEntryRollup.findMany({
where: {
userId,
granularity: "DAY",
bucketStart: { gte: since },
},
orderBy: { bucketStart: "asc" },
});
return rows.map((r) => ({
bucketStart: r.bucketStart,
count: r.count,
mean: r.mean,
minScore: r.minScore,
maxScore: r.maxScore,
sd: r.sd,
computedAt: r.computedAt,
}));
}
/**
* v1.4.39 — fire-and-forget warm-up for the DAY tier.
*
* Contract:
* - If at least one DAY rollup row exists for the user and it is
* fresh (newest rollup `computed_at` ≥ newest mood entry
* `updated_at`), this is a no-op.
* - Otherwise the helper kicks off a full
* `recomputeUserMoodRollups` over the trailing 5-year window so
* the next read of `/api/mood/analytics` lands on the rollup
* tier. Mood entries are typically 1/day so the recompute is
* bounded to a few thousand rows even for power users — cheaper
* than the 12.7 s legacy live walk by orders of magnitude.
* - Best-effort: thrown errors are swallowed so the read path
* never fails because of a populator hiccup.
* - Concurrent callers for the same `userId` share one in-flight
* promise so a cold fan-out can never queue N parallel
* recompute runs.
*/
const ensureUserMoodRollupsFreshInFlight = new Map<
string,
Promise<{ recomputed: boolean }>
>();
export async function ensureUserMoodRollupsFresh(
userId: string,
): Promise<{ recomputed: boolean }> {
const existing = ensureUserMoodRollupsFreshInFlight.get(userId);
if (existing) return existing;
const inflight = ensureUserMoodRollupsFreshImpl(userId).finally(() => {
ensureUserMoodRollupsFreshInFlight.delete(userId);
});
ensureUserMoodRollupsFreshInFlight.set(userId, inflight);
return inflight;
}
/**
* Test-only handle on the in-flight map. Mirrors the
* `_resetEnsureUserRollupsFreshInFlightForTests` pattern in
* `measurements/rollups.ts` — production code never calls this.
*/
export function _resetEnsureUserMoodRollupsFreshInFlightForTests(): void {
ensureUserMoodRollupsFreshInFlight.clear();
}
async function ensureUserMoodRollupsFreshImpl(
userId: string,
): Promise<{ recomputed: boolean }> {
try {
const [newestRollup, newestEntry] = await Promise.all([
prisma.moodEntryRollup.findFirst({
where: { userId, granularity: "DAY" },
orderBy: { computedAt: "desc" },
select: { computedAt: true },
}),
prisma.moodEntry.findFirst({
where: { userId },
orderBy: { updatedAt: "desc" },
select: { updatedAt: true, moodLoggedAt: true },
}),
]);
if (!newestEntry) {
// No mood entries — rollups are trivially fresh.
return { recomputed: false };
}
const watermark =
newestEntry.updatedAt > newestEntry.moodLoggedAt
? newestEntry.updatedAt
: newestEntry.moodLoggedAt;
if (newestRollup && watermark <= newestRollup.computedAt) {
return { recomputed: false };
}
// Stale — full 5-year DAY fold. Bounded because mood entries are
// typically 1/day, so even a multi-year power user materialises a
// few thousand rows tops.
await recomputeUserMoodRollups(userId, { granularities: ["DAY"] });
return { recomputed: true };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
annotate({
meta: {
mood_rollup_refresh_failed: true,
mood_rollup_refresh_error: message,
},
});
console.error("[mood-rollups] ensureUserMoodRollupsFresh failed:", message);
return { recomputed: false };
}
}
/**
* v1.4.39 — boot-time enqueue helper. Finds users with mood entries
* but zero `mood_entry_rollups` rows and enqueues one full-fold per
* account onto `MOOD_ROLLUP_FULL_BACKFILL_QUEUE`. Designed to be
* called once at worker boot so every self-hosted instance auto-
* converges on the persistent rollup tier without operator action.
*
* Idempotent across reboots:
* - the discovery query matches accounts with mood entries but
* zero rollup rows; once the fold completes the user drops off
* the list
* - pg-boss `singletonKey` coalesces duplicate sends within the
* queue, so a fast restart while a backfill is queued doesn't
* double up
*
* Best-effort: errors are swallowed and reported through the return
* value so the worker boot never fails because of a backfill miss.
*/
export async function enqueueBootTimeMoodRollupBackfill(): Promise<{
enqueued: number;
skipped: number;
error: string | null;
}> {
const boss = getGlobalBoss();
if (!boss) {
return { enqueued: 0, skipped: 0, error: null };
}
try {
// Users with mood entries but no rollup coverage. Anchored on the
// per-user `DISTINCT user_id` set so the planner uses the
// `(user_id, date)` index path; the LEFT JOIN onto
// `mood_entry_rollups` uses the
// `(user_id, granularity, bucket_start)` composite primary key.
// `r."bucket_start" IS NULL` (any column from the right side of
// the LEFT JOIN) marks the unmatched users.
const users = await prisma.$queryRaw<Array<{ id: string }>>`
SELECT DISTINCT mt."user_id" AS id
FROM (
SELECT DISTINCT m."user_id"
FROM mood_entries m
) mt
LEFT JOIN mood_entry_rollups r
ON r."user_id" = mt."user_id"
AND r."granularity" = 'DAY'
WHERE r."bucket_start" IS NULL
`;
if (users.length === 0) {
return { enqueued: 0, skipped: 0, error: null };
}
let enqueued = 0;
let skipped = 0;
for (const { id } of users) {
const payload: MoodRollupFullBackfillPayload = {
userId: id,
enqueuedAt: new Date().toISOString(),
};
const jobId = await boss.send(MOOD_ROLLUP_FULL_BACKFILL_QUEUE, payload, {
retryLimit: 3,
retryDelay: 60,
retryBackoff: true,
// Coalesce: if a backfill for this user is already queued and
// we restart, pg-boss returns null instead of duplicating.
singletonKey: `mood-boot-backfill|${id}`,
});
if (jobId) {
enqueued += 1;
} else {
skipped += 1;
}
}
return { enqueued, skipped, error: null };
} catch (err) {
return {
enqueued: 0,
skipped: 0,
error: err instanceof Error ? err.message : String(err),
};
}
}
// ─── internals ────────────────────────────────────────────
/**
* Pull the raw aggregates from Postgres. Groups by
* `date_trunc(<granularity>, mood_logged_at)` and folds the stats
* with `STDDEV_POP`. The `date_trunc` unit literal must be inlined
* because Postgres rejects a parameterised expression in a GROUP BY;
* the value comes from a closed enum (DATE_TRUNC_UNIT) so there's no
* injection surface — we still assert against the whitelist before
* splicing.
*/
async function runMoodRollupAggregate(
client: PrismaTxOrClient,
input: {
userId: string;
granularity: RollupGranularity;
from: Date;
to: Date;
},
): Promise<MoodRollupRow[]> {
const truncUnit = DATE_TRUNC_UNIT[input.granularity];
if (!["day", "week", "month", "year"].includes(truncUnit)) {
throw new Error(`unexpected granularity: ${input.granularity}`);
}
const dateTrunc = `date_trunc('${truncUnit}', m."mood_logged_at")`;
const sql = `
SELECT
${dateTrunc} AS bucket_start,
COUNT(*) AS count,
AVG(m."score")::double precision AS mean,
MIN(m."score")::integer AS min_score,
MAX(m."score")::integer AS max_score,
STDDEV_POP(m."score")::double precision AS sd
FROM mood_entries m
WHERE m."user_id" = $1
AND m."mood_logged_at" >= $2
AND m."mood_logged_at" < $3
GROUP BY ${dateTrunc}
`;
return client.$queryRawUnsafe<MoodRollupRow[]>(
sql,
input.userId,
input.from,
input.to,
);
}
/**
* UPSERT the aggregate rows into `mood_entry_rollups`. Returns the
* number of rows touched. Chunked so a multi-year fold doesn't blow
* the parameter cap on a single round-trip.
*/
async function persistMoodRollupRows(
client: PrismaTxOrClient,
userId: string,
granularity: RollupGranularity,
rows: MoodRollupRow[],
): Promise<number> {
if (rows.length === 0) return 0;
const CHUNK = 500;
let touched = 0;
for (let i = 0; i < rows.length; i += CHUNK) {
const slice = rows.slice(i, i + CHUNK);
// Run each upsert sequentially through the supplied client (which
// may be a transactional handle). Wrapping in `$transaction` here
// would crash when the caller already holds an interactive
// transaction, so we rely on the parent caller (or atomicity of
// the single upsert) for crash safety. The hot path is a single
// row per DAY recompute, so the round-trip cost is negligible.
for (const row of slice) {
const payload = {
count: Number(row.count),
mean: row.mean ?? 0,
minScore: row.min_score ?? 0,
maxScore: row.max_score ?? 0,
sd: row.sd,
computedAt: new Date(),
} satisfies Prisma.MoodEntryRollupUpdateInput;
await client.moodEntryRollup.upsert({
where: {
userId_granularity_bucketStart: {
userId,
granularity,
bucketStart: row.bucket_start,
},
},
create: {
userId,
granularity,
bucketStart: row.bucket_start,
...payload,
},
update: payload,
});
}
touched += slice.length;
}
return touched;
}
/**
* Truncate a `Date` to the start of its UTC day. The rollup table
* stores TIMESTAMPTZ values so we anchor on UTC to keep the bucket
* key deterministic across timezone-shifting consumers — same
* convention as `measurement-rollups`.
*/
function startOfUtcDay(d: Date): Date {
return new Date(
Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), 0, 0, 0, 0),
);
}
/**
* Span of the bucket containing `moodLoggedAt` at the given
* granularity. Mirrors `measurement-rollups` so the WEEK / MONTH /
* YEAR fold queries select the same set of rows the read-side
* `date_trunc` would group on.
*/
function bucketSpan(
moodLoggedAt: Date,
granularity: RollupGranularity,
): { from: Date; to: Date } {
switch (granularity) {
case "DAY": {
const from = startOfUtcDay(moodLoggedAt);
return { from, to: new Date(from.getTime() + 24 * 60 * 60 * 1000) };
}
case "WEEK": {
const day = startOfUtcDay(moodLoggedAt);
// Postgres ISO week: Monday is day 1. JS getUTCDay(): Sunday=0.
const dayOfWeek = day.getUTCDay();
const mondayOffset = (dayOfWeek + 6) % 7;
const from = new Date(
day.getTime() - mondayOffset * 24 * 60 * 60 * 1000,
);
return { from, to: new Date(from.getTime() + 7 * 24 * 60 * 60 * 1000) };
}
case "MONTH": {
const from = new Date(
Date.UTC(moodLoggedAt.getUTCFullYear(), moodLoggedAt.getUTCMonth(), 1),
);
const to = new Date(
Date.UTC(
moodLoggedAt.getUTCFullYear(),
moodLoggedAt.getUTCMonth() + 1,
1,
),
);
return { from, to };
}
case "YEAR": {
const from = new Date(Date.UTC(moodLoggedAt.getUTCFullYear(), 0, 1));
const to = new Date(Date.UTC(moodLoggedAt.getUTCFullYear() + 1, 0, 1));
return { from, to };
}
}
}