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

@@ -32,8 +32,8 @@ import {
recomputeBucketsForMeasurement,
recomputeUserRollups,
ALL_GRANULARITIES,
} from "@/lib/measurements/rollups";
import { aggregateBuckets } from "@/lib/measurements/rollup-read";
} from "@/lib/rollups/measurement-rollups";
import { aggregateBuckets } from "@/lib/rollups/measurement-read";
import { buildComprehensiveAggregate } from "@/lib/insights/comprehensive-aggregator";
vi.mock("@/lib/db-compat", () => ({
@@ -0,0 +1,310 @@
/**
* v1.4.40 W-DELETED — soft-delete invisibility across every reader tier.
*
* `Measurement.deletedAt` was set by the iOS sync path but ignored by
* every read path (Senior Infra+DB audit Critical Finding #3 in
* `.planning/round-v1439-arch-qa-infra-db.md`). The moment iOS soft-
* deleted its first reading, the tombstoned row would still contribute
* to dashboards, analytics fan-outs, the rollup populator's count, and
* the Coach snapshot the model grounds against.
*
* This test pins the tombstone-invisibility contract end-to-end against
* the real Postgres testcontainer. Three tiers are covered:
*
* 1. **Analytics summaries slice** — the rollup-fresh path's narrow
* aggregate + DISTINCT ON latest reads MUST exclude the soft-
* deleted row. The slim slice runs the live aggregator on this
* fixture (no rollup coverage yet) so the cold-fallback path is
* exercised in the same call.
*
* 2. **Dashboard summary** — the per-type `groupBy` aggregate +
* `latestIn7d` DISTINCT ON + streak-day raw SQL all need the
* filter. The fixture parks one soft-deleted row inside the 7-day
* window so the iOS Dashboard tile-strip can be checked for
* tombstone leakage.
*
* 3. **Rollup recompute** — `recomputeBucketsForMeasurement` must
* build the DAY bucket from live (non-deleted) rows only. The
* fixture seeds three same-day rows, soft-deletes one, recomputes,
* and asserts `count == 2` (not 3) on the resulting bucket.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
process.env.ENCRYPTION_KEY ??=
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
import { recomputeBucketsForMeasurement } from "@/lib/rollups/measurement-rollups";
import { cookieJar, headerJar } from "./mock-next-headers";
import { getPrismaClient, truncateAllTables } from "./setup";
vi.mock("next/headers", async () => {
const { cookieJar, headerJar } = await import("./mock-next-headers");
return {
headers: vi.fn(async () => ({
get: (name: string) => headerJar.get(name.toLowerCase()) ?? null,
})),
cookies: vi.fn(async () => ({
get: (name: string) => {
const value = cookieJar.get(name);
return value ? { name, value } : undefined;
},
set: (name: string, value: string) => {
cookieJar.set(name, value);
},
delete: (name: string) => {
cookieJar.delete(name);
},
})),
};
});
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
beforeEach(async () => {
await truncateAllTables(getPrismaClient());
cookieJar.clear();
headerJar.clear();
});
afterEach(() => {
vi.restoreAllMocks();
});
async function seedSession(username: string) {
const prisma = getPrismaClient();
const user = await prisma.user.create({
data: {
username,
email: `${username}@example.test`,
role: "USER",
},
});
const session = await prisma.session.create({
data: {
userId: user.id,
expiresAt: new Date(Date.now() + 60_000),
},
});
cookieJar.set("healthlog_session", session.id);
return user;
}
describe("Measurement.deletedAt — tombstone invisibility (v1.4.40 W-DELETED)", () => {
it("excludes soft-deleted measurements from the analytics summaries slice", async () => {
const prisma = getPrismaClient();
const user = await seedSession("soft-delete-analytics");
// Three same-type WEIGHT readings; the middle one (value 99) is the
// tombstone that must NOT contribute to count / min / max / mean.
const now = new Date();
const oneDayAgo = new Date(now.getTime() - 86_400_000);
const twoDaysAgo = new Date(now.getTime() - 2 * 86_400_000);
await prisma.measurement.createMany({
data: [
{
userId: user.id,
type: "WEIGHT",
value: 80.0,
unit: "kg",
source: "MANUAL",
measuredAt: twoDaysAgo,
},
{
userId: user.id,
type: "WEIGHT",
// Out-of-band sentinel — the test fails loudly if this row
// leaks into any aggregate (it would crash min/max + skew the
// mean by a huge margin).
value: 99.0,
unit: "kg",
source: "MANUAL",
measuredAt: oneDayAgo,
},
{
userId: user.id,
type: "WEIGHT",
value: 80.2,
unit: "kg",
source: "MANUAL",
measuredAt: now,
},
],
});
// Tombstone the middle row.
await prisma.measurement.updateMany({
where: { userId: user.id, value: 99.0 },
data: { deletedAt: new Date() },
});
const { GET } = await import("@/app/api/analytics/route");
const response = await (
GET as unknown as (req: Request) => Promise<Response>
)(new Request("http://localhost/api/analytics?slice=summaries"));
expect(response.status).toBe(200);
const envelope = (await response.json()) as {
data: {
summaries: Record<
string,
{ count: number; latest: number | null; min: number | null; max: number | null; mean: number | null }
>;
};
};
const weight = envelope.data.summaries.WEIGHT;
// The 99.0 sentinel must not contribute to any aggregate field.
expect(weight.count).toBe(2);
expect(weight.latest).toBeCloseTo(80.2, 2);
expect(weight.min).toBeCloseTo(80.0, 2);
expect(weight.max).toBeCloseTo(80.2, 2);
expect(weight.mean).toBeCloseTo(80.1, 2);
});
it("excludes soft-deleted measurements from the dashboard summary", async () => {
const prisma = getPrismaClient();
const user = await seedSession("soft-delete-dashboard");
const now = new Date();
const sixHoursAgo = new Date(now.getTime() - 6 * 60 * 60 * 1000);
const oneDayAgo = new Date(now.getTime() - 86_400_000);
await prisma.measurement.createMany({
data: [
{
userId: user.id,
type: "WEIGHT",
value: 80.0,
unit: "kg",
source: "MANUAL",
measuredAt: oneDayAgo,
},
{
userId: user.id,
// Most-recent row by wall-clock — if the tombstone leaks the
// tile's `latestValue` would surface 99.0 here.
type: "WEIGHT",
value: 99.0,
unit: "kg",
source: "MANUAL",
measuredAt: sixHoursAgo,
},
],
});
await prisma.measurement.updateMany({
where: { userId: user.id, value: 99.0 },
data: { deletedAt: new Date() },
});
const { GET } = await import("@/app/api/dashboard/summary/route");
const response = await (
GET as unknown as (req: Request) => Promise<Response>
)(new Request("http://localhost/api/dashboard/summary"));
expect(response.status).toBe(200);
const envelope = (await response.json()) as {
data: {
metrics: Array<{
kind: string;
latestValue: number | null;
allTimeCount: number;
}>;
};
};
const weightTile = envelope.data.metrics.find((m) => m.kind === "weight");
expect(weightTile).toBeDefined();
// Live row (80.0) is the only reading the tile sees; the 99.0
// tombstone must not leak into the latest value or the all-time
// count.
expect(weightTile!.latestValue).toBeCloseTo(80.0, 2);
expect(weightTile!.allTimeCount).toBe(1);
});
it("recomputeBucketsForMeasurement produces count=2 not 3 with one soft-deleted row", async () => {
const prisma = getPrismaClient();
const user = await seedSession("soft-delete-rollup");
// Three readings inside the same UTC calendar day. The middle one
// is tombstoned; the resulting DAY bucket must reflect only two
// live readings.
const noonUtc = new Date(
Date.UTC(
new Date().getUTCFullYear(),
new Date().getUTCMonth(),
new Date().getUTCDate(),
12,
0,
0,
),
);
const elevenUtc = new Date(noonUtc.getTime() - 60 * 60 * 1000);
const thirteenUtc = new Date(noonUtc.getTime() + 60 * 60 * 1000);
await prisma.measurement.createMany({
data: [
{
userId: user.id,
type: "WEIGHT",
value: 80.0,
unit: "kg",
source: "MANUAL",
measuredAt: elevenUtc,
},
{
userId: user.id,
type: "WEIGHT",
value: 99.0,
unit: "kg",
source: "MANUAL",
measuredAt: noonUtc,
},
{
userId: user.id,
type: "WEIGHT",
value: 80.4,
unit: "kg",
source: "MANUAL",
measuredAt: thirteenUtc,
},
],
});
await prisma.measurement.updateMany({
where: { userId: user.id, value: 99.0 },
data: { deletedAt: new Date() },
});
await recomputeBucketsForMeasurement(user.id, "WEIGHT", noonUtc);
const dayStartUtc = new Date(
Date.UTC(
noonUtc.getUTCFullYear(),
noonUtc.getUTCMonth(),
noonUtc.getUTCDate(),
),
);
const bucket = await prisma.measurementRollup.findUnique({
where: {
userId_type_granularity_bucketStart: {
userId: user.id,
type: "WEIGHT",
granularity: "DAY",
bucketStart: dayStartUtc,
},
},
});
expect(bucket).not.toBeNull();
expect(bucket!.count).toBe(2);
// Mean over the two live rows = (80.0 + 80.4) / 2 = 80.2. If the
// tombstone leaked the mean would land at ~86.5 — the assertion
// fails loudly.
expect(bucket!.mean).toBeCloseTo(80.2, 2);
expect(bucket!.minValue).toBeCloseTo(80.0, 2);
expect(bucket!.maxValue).toBeCloseTo(80.4, 2);
});
});