mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
Merge pull request #1399 from mailuminatti/fix/scoped-feature-read
fix(insights): restrict the scoped feature bulk read to the requested blocks' types
This commit is contained in:
59 files changed
+1043
-314
No files matched your search
@@ -12,6 +12,7 @@
|
||||
### Fixed
|
||||
|
||||
- A lab marker created from a text result, such as "negative" on a scanned report or a CSV row without a unit, can be edited again. It opens with "No unit" ticked, a rename saves without touching the unit, and the unit can be set while the marker holds only text results. The unit stays locked once numbers are stored under it, and writing the same unit another way (`mg/dl` for `mg/dL`) no longer counts as a change. (#1393)
|
||||
- On an account with a watch sending heart rate every few seconds, weight, blood pressure and other occasional readings went missing from the MCP metric series, the Coach and the insights, because the heart rate filled every read before they were reached. Each kind of reading now gets its own share, so they all show up again. (#1398)
|
||||
|
||||
### Security
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$comment": "Production files over 800 lines and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
|
||||
"count": 84,
|
||||
"total": 93819,
|
||||
"total": 93816,
|
||||
"entries": {
|
||||
"app/medications/page-client.tsx": 842,
|
||||
"components/charts/mood-chart.tsx": 1166,
|
||||
@@ -57,11 +57,11 @@
|
||||
"lib/import/unzip-export-xml.ts": 825,
|
||||
"lib/insights/comprehensive-aggregator.ts": 868,
|
||||
"lib/insights/comprehensive-generate.ts": 1670,
|
||||
"lib/insights/correlation-channel-series.ts": 1339,
|
||||
"lib/insights/correlation-channel-series.ts": 1330,
|
||||
"lib/insights/correlation-discovery.ts": 1240,
|
||||
"lib/insights/correlations.ts": 1026,
|
||||
"lib/insights/features.ts": 1875,
|
||||
"lib/insights/mood-aggregates.ts": 1053,
|
||||
"lib/insights/features.ts": 1874,
|
||||
"lib/insights/mood-aggregates.ts": 1036,
|
||||
"lib/integrations/status.ts": 1448,
|
||||
"lib/jobs/coach-nudge.ts": 1084,
|
||||
"lib/jobs/insight-pregenerate.ts": 1192,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$comment": "Production functions over 200 lines, keyed \"file :: name\", and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
|
||||
"count": 335,
|
||||
"total": 109058,
|
||||
"total": 109025,
|
||||
"entries": {
|
||||
"app/achievements/page.tsx :: AchievementsPage": 206,
|
||||
"app/api/admin/backups/upload/route.ts :: apiHandler(arg)": 275,
|
||||
@@ -280,8 +280,8 @@
|
||||
"lib/import/labs-csv.ts :: importLabsCsv > flush": 227,
|
||||
"lib/insights/comprehensive-aggregator.ts :: buildFromRollups": 217,
|
||||
"lib/insights/comprehensive-generate.ts :: generateComprehensiveInsight": 872,
|
||||
"lib/insights/features.ts :: extractFeatures": 794,
|
||||
"lib/insights/mood-aggregates.ts :: fetchMoodAggregates": 246,
|
||||
"lib/insights/features.ts :: extractFeatures": 772,
|
||||
"lib/insights/mood-aggregates.ts :: fetchMoodAggregates": 227,
|
||||
"lib/insights/status-provider.ts :: runStatusCompletion": 215,
|
||||
"lib/integrations/connection-health-load.ts :: loadConnectionFacts": 229,
|
||||
"lib/integrations/status.ts :: recordSyncFailure": 292,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$comment": "Comment lines that open with a release version, per file under src/. Maintained by src/__tests__/version-stamp-ratchet.test.ts.",
|
||||
"count": 2863,
|
||||
"total": 9118,
|
||||
"total": 9112,
|
||||
"entries": {
|
||||
"__tests__/account-payload-consumer-guard.test.ts": 2,
|
||||
"__tests__/acting-account-boundary-guard.test.ts": 7,
|
||||
@@ -1667,7 +1667,7 @@
|
||||
"lib/ai/coach/snapshot-blocks/sleep-block.ts": 2,
|
||||
"lib/ai/coach/snapshot-blocks/workouts-block.ts": 3,
|
||||
"lib/ai/coach/snapshot-cache.ts": 2,
|
||||
"lib/ai/coach/snapshot-prelude.ts": 17,
|
||||
"lib/ai/coach/snapshot-prelude.ts": 15,
|
||||
"lib/ai/coach/snapshot-series.ts": 5,
|
||||
"lib/ai/coach/snapshot.ts": 41,
|
||||
"lib/ai/coach/source-measurement-types.ts": 1,
|
||||
@@ -2186,7 +2186,7 @@
|
||||
"lib/insights/exclude-filter.ts": 1,
|
||||
"lib/insights/feature-blocks.ts": 5,
|
||||
"lib/insights/feature-cache.ts": 2,
|
||||
"lib/insights/features.ts": 33,
|
||||
"lib/insights/features.ts": 32,
|
||||
"lib/insights/general-status.ts": 5,
|
||||
"lib/insights/glp1-plateau.ts": 2,
|
||||
"lib/insights/graded-series.ts": 3,
|
||||
@@ -2202,7 +2202,7 @@
|
||||
"lib/insights/metric-signal.ts": 1,
|
||||
"lib/insights/metric-status-registry.ts": 5,
|
||||
"lib/insights/metric-status.ts": 8,
|
||||
"lib/insights/mood-aggregates.ts": 37,
|
||||
"lib/insights/mood-aggregates.ts": 34,
|
||||
"lib/insights/mood-crosstab.ts": 2,
|
||||
"lib/insights/mood-dimension-series.ts": 1,
|
||||
"lib/insights/mood-narratives.ts": 3,
|
||||
|
||||
@@ -346,8 +346,10 @@ describe("dense measurement reads stay bounded (#1023)", () => {
|
||||
|
||||
it("finds the reads it is meant to police", () => {
|
||||
// Guard against a matcher that silently matches nothing.
|
||||
// Pinned below the counts on 2026-10-01 (82 / 45 / 37 / 33).
|
||||
expect(all).toBeGreaterThanOrEqual(75);
|
||||
// Pinned below the counts on 2026-10-01 (82 / 45 / 37 / 33). Seven
|
||||
// capped multi-type findMany reads moved to the per-type raw read
|
||||
// (#1398), leaving 71 on 2026-11-16.
|
||||
expect(all).toBeGreaterThanOrEqual(65);
|
||||
expect(untaken.length).toBeGreaterThanOrEqual(40);
|
||||
expect(raw.length).toBeGreaterThanOrEqual(33);
|
||||
expect(raw.filter((r) => r.folds).length).toBeGreaterThanOrEqual(30);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* A stand-in for `@/lib/measurements/newest-per-type` in unit tests whose
|
||||
* Prisma mock serves measurement rows through `measurement.findMany`.
|
||||
*
|
||||
* The real read is one raw statement (a capped index descent per type), which
|
||||
* a `findMany` mock never sees. These suites were written against the
|
||||
* `findMany` the reads used before, routing rows by `where.type` and counting
|
||||
* calls, so the stand-in issues exactly that call, once per read, and applies
|
||||
* what the statement does in memory: the requested types only, newest first
|
||||
* up to the cap per type, the fair cut to the total when one is given, then
|
||||
* oldest first. The span probe answers from the
|
||||
* rows the same build's read was served, without a second call, so call counts
|
||||
* stay what the suites pin.
|
||||
*
|
||||
* Use as
|
||||
* vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
* (await import("@/__tests__/helpers/newest-per-type-mock")).newestPerTypeMock(),
|
||||
* );
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import type {
|
||||
NewestPerTypeRead,
|
||||
NewestPerTypeRow,
|
||||
} from "@/lib/measurements/newest-per-type";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
|
||||
type LooseRow = Partial<NewestPerTypeRow> & {
|
||||
type: string;
|
||||
value: number;
|
||||
measuredAt: Date;
|
||||
};
|
||||
|
||||
export function newestPerTypeMock() {
|
||||
let lastServed: Promise<NewestPerTypeRow[]> = Promise.resolve([]);
|
||||
|
||||
async function readNewestRowsPerType(
|
||||
userId: string,
|
||||
types: readonly MeasurementType[],
|
||||
options: { perTypeCap: number; totalCap?: number; since?: Date | null },
|
||||
): Promise<NewestPerTypeRead> {
|
||||
const wanted = [...new Set(types)];
|
||||
if (wanted.length === 0) {
|
||||
lastServed = Promise.resolve([]);
|
||||
return { rows: [], cappedTypes: [] };
|
||||
}
|
||||
const since = options.since ?? null;
|
||||
const served = (
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: { in: wanted },
|
||||
deletedAt: null,
|
||||
...(since ? { measuredAt: { gte: since } } : {}),
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
// A read with a total returns at most that many rows.
|
||||
...(options.totalCap !== undefined ? { take: options.totalCap } : {}),
|
||||
}) as unknown as Promise<LooseRow[] | undefined>
|
||||
).then((rows) =>
|
||||
(rows ?? []).map((r): NewestPerTypeRow => ({
|
||||
type: r.type as MeasurementType,
|
||||
value: r.value,
|
||||
measuredAt: r.measuredAt,
|
||||
source: r.source ?? ("MANUAL" as NewestPerTypeRow["source"]),
|
||||
deviceType: r.deviceType ?? null,
|
||||
sleepStage: r.sleepStage ?? null,
|
||||
glucoseContext: r.glucoseContext ?? null,
|
||||
})),
|
||||
);
|
||||
lastServed = served;
|
||||
const rows = await served;
|
||||
const perType = new Map<string, NewestPerTypeRow[]>();
|
||||
for (const row of rows) {
|
||||
if (!wanted.includes(row.type)) continue;
|
||||
const list = perType.get(row.type) ?? [];
|
||||
list.push(row);
|
||||
perType.set(row.type, list);
|
||||
}
|
||||
const ranked: Array<{ row: NewestPerTypeRow; rank: number }> = [];
|
||||
const readOf = new Map<string, number>();
|
||||
for (const type of wanted) {
|
||||
const list = [...(perType.get(type) ?? [])]
|
||||
.sort((a, b) => b.measuredAt.getTime() - a.measuredAt.getTime())
|
||||
.slice(0, options.perTypeCap);
|
||||
readOf.set(type, list.length);
|
||||
list.forEach((row, i) => ranked.push({ row, rank: i + 1 }));
|
||||
}
|
||||
if (options.totalCap !== undefined) {
|
||||
ranked.sort(
|
||||
(a, b) =>
|
||||
a.rank - b.rank ||
|
||||
b.row.measuredAt.getTime() - a.row.measuredAt.getTime() ||
|
||||
a.row.type.localeCompare(b.row.type),
|
||||
);
|
||||
ranked.splice(options.totalCap);
|
||||
}
|
||||
const kept = ranked.map((r) => r.row);
|
||||
const keptOf = new Map<string, number>();
|
||||
for (const row of kept) {
|
||||
keptOf.set(row.type, (keptOf.get(row.type) ?? 0) + 1);
|
||||
}
|
||||
const cappedTypes = wanted.filter((t) => {
|
||||
const n = keptOf.get(t) ?? 0;
|
||||
return n >= options.perTypeCap || n < (readOf.get(t) ?? 0);
|
||||
});
|
||||
kept.sort((a, b) => a.measuredAt.getTime() - b.measuredAt.getTime());
|
||||
return { rows: kept, cappedTypes };
|
||||
}
|
||||
|
||||
async function readLiveMeasurementSpan(): Promise<{
|
||||
oldest: Date | null;
|
||||
newest: Date | null;
|
||||
}> {
|
||||
const rows = await lastServed;
|
||||
if (rows.length === 0) return { oldest: null, newest: null };
|
||||
const times = rows.map((r) => r.measuredAt.getTime());
|
||||
return {
|
||||
oldest: new Date(Math.min(...times)),
|
||||
newest: new Date(Math.max(...times)),
|
||||
};
|
||||
}
|
||||
|
||||
return { readNewestRowsPerType, readLiveMeasurementSpan };
|
||||
}
|
||||
@@ -1,6 +1,13 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
// v1.44 — the extended channel families (intake, training, room climate).
|
||||
|
||||
@@ -29,6 +29,13 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
userSourcePriority: { findMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({ prisma: prismaMock }));
|
||||
|
||||
import { readCoachCorrelations } from "../tools/correlations-read";
|
||||
|
||||
@@ -21,6 +21,13 @@ vi.mock("@/lib/modules/gate", () => ({
|
||||
// The record's map feeds the matrix mask; every module on by default.
|
||||
resolveModuleMap: vi.fn(async () => moduleMap.value),
|
||||
}));
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
// v1.44 — the extended channel families (intake, training, room climate).
|
||||
|
||||
@@ -7,6 +7,13 @@ import {
|
||||
import { coachDataClusterEnum } from "@/lib/validations/coach-prefs";
|
||||
import { coachScopeSourceSchema } from "../types";
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
measurement: { findMany: vi.fn() },
|
||||
|
||||
@@ -5,6 +5,13 @@ import {
|
||||
buildCoachSnapshot,
|
||||
} from "../snapshot";
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
measurement: { findMany: vi.fn() },
|
||||
|
||||
@@ -10,6 +10,13 @@ import {
|
||||
import { eventStorage } from "@/lib/logging/context";
|
||||
import { WideEventBuilder } from "@/lib/logging/event-builder";
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
measurement: { findMany: vi.fn() },
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import { readNewestRowsPerType } from "@/lib/measurements/newest-per-type";
|
||||
import { parseCoachPrefs } from "@/lib/validations/coach-prefs";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/tz/resolver";
|
||||
import { locales, defaultLocale, type Locale } from "@/lib/i18n/config";
|
||||
@@ -56,10 +57,14 @@ export const MAX_SNAPSHOT_CHARS = 14_000;
|
||||
* (`lastYear` / `allTime`) across high-frequency types (PULSE / glucose are
|
||||
* 200k-row-class), but the prompt only renders ~21 daily + ~10 weekly buckets
|
||||
* per metric, so an uncapped read loaded a year of rows to discard almost all
|
||||
* of them. 6000 keeps the recent-daily + weekly window exact even with several
|
||||
* dense types active (≈ a year of multi-daily readings on one type, or a
|
||||
* handful of types at a few readings/day) while bounding the worst case; the
|
||||
* coarse MONTH/YEAR tail comes from the rollup tier, not this read.
|
||||
* of them. 6000 keeps a year of multi-daily readings of a type exact while
|
||||
* bounding a dense one; the coarse MONTH/YEAR tail comes from the rollup
|
||||
* tier, not this read.
|
||||
*
|
||||
* #1398 — the cap applies per type. Shared across the read's types, a dense
|
||||
* stream filled it within hours and the weight and blood pressure timelines
|
||||
* came back empty. Worst case: this times the number of types read, reached
|
||||
* only by types that each write more than 6000 rows inside the window.
|
||||
*/
|
||||
const SNAPSHOT_MEASUREMENT_ROW_CAP = 6000;
|
||||
|
||||
@@ -251,51 +256,28 @@ export function resolveSnapshotCutoffs(
|
||||
/**
|
||||
* The windowed measurement read the timeline blocks share.
|
||||
*
|
||||
* Single fetch for all measurement types — Prisma's filter pushes
|
||||
* the type list into one SQL `WHERE type IN (…)` so we don't pay
|
||||
* per-metric round-trips.
|
||||
* One statement for all measurement types, each type read newest-first up to
|
||||
* its own cap (`readNewestRowsPerType`), so a dense stream cannot push a
|
||||
* sparse type's rows out of the read and a single-source build sees exactly
|
||||
* the rows the full build gives that source. Oldest first. `glucoseContext`
|
||||
* rides along so the glucose block can split fasting / postprandial / random
|
||||
* / bedtime without a second query; NULL on every non-glucose row.
|
||||
*/
|
||||
export function readSnapshotMeasurementRows(
|
||||
export async function readSnapshotMeasurementRows(
|
||||
userId: string,
|
||||
wantedTypes: readonly MeasurementType[],
|
||||
cutoff: Date,
|
||||
) {
|
||||
if (wantedTypes.length === 0) return Promise.resolve([]);
|
||||
return (
|
||||
prisma.measurement
|
||||
.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: { in: [...wantedTypes] },
|
||||
measuredAt: { gte: cutoff },
|
||||
deletedAt: null,
|
||||
},
|
||||
// v1.18.10 — read NEWEST-first + cap. PULSE / glucose are
|
||||
// 200k-row-class types and the window can reach 365 days
|
||||
// (lastYear / allTime), so an uncapped read pulled the entire
|
||||
// year of high-frequency rows into memory just to fold them into
|
||||
// ~21 daily + ~10 weekly buckets the prompt actually shows. The
|
||||
// newest-first cap keeps the recent-daily timeline exact and only
|
||||
// sheds the deepest weekly buckets on an extreme-volume account;
|
||||
// the coarse MONTH/YEAR tail is read separately from the rollup
|
||||
// tier (`buildCoarseTimelineTail`), so deep history survives.
|
||||
orderBy: { measuredAt: "desc" },
|
||||
take: SNAPSHOT_MEASUREMENT_ROW_CAP,
|
||||
// v1.7.0 — `glucoseContext` rides along so the glucose block
|
||||
// can split fasting / postprandial / random / bedtime without
|
||||
// a second query. NULL on every non-glucose row.
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
measuredAt: true,
|
||||
glucoseContext: true,
|
||||
},
|
||||
})
|
||||
// Downstream bucketers re-sort/group internally, but restore
|
||||
// ascending order so any order-sensitive consumer sees the same
|
||||
// shape as before the cap.
|
||||
.then((rows) => rows.reverse())
|
||||
);
|
||||
const { rows } = await readNewestRowsPerType(userId, wantedTypes, {
|
||||
perTypeCap: SNAPSHOT_MEASUREMENT_ROW_CAP,
|
||||
since: cutoff,
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
type: row.type,
|
||||
value: row.value,
|
||||
measuredAt: row.measuredAt,
|
||||
glucoseContext: row.glucoseContext,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
* source's own reads only, and hands back the same section and the same
|
||||
* reference grounding. Each block reads exactly what the full build reads for
|
||||
* it: the core clinical aggregates come from `extractFeatures` scoped to the
|
||||
* one block (whose bulk read keeps its all-type cap, so the rows a block sees
|
||||
* are unchanged), the timelines from the same windowed read, the coarse tail
|
||||
* from the same rollup reader.
|
||||
* one block (whose bulk read caps each type on its own, so that block's types
|
||||
* get the rows the full read gives them), the timelines from the same
|
||||
* windowed read, the coarse tail from the same rollup reader.
|
||||
*
|
||||
* Two cases go to the full builder instead:
|
||||
*
|
||||
|
||||
@@ -8,6 +8,13 @@ vi.mock("@/lib/measurements/day-aggregates", async () => ({
|
||||
).fakeReadDayAggregates,
|
||||
}));
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: vi.fn() },
|
||||
|
||||
@@ -30,6 +30,13 @@ const measurementFindMany = vi.fn();
|
||||
const rollupFindMany = vi.fn();
|
||||
const userFindUnique = vi.fn();
|
||||
const queryRaw = vi.fn();
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
measurement: { findMany: (a: unknown) => measurementFindMany(a) },
|
||||
|
||||
@@ -8,6 +8,13 @@ const environmentFindMany = vi.fn();
|
||||
const userFindUnique = vi.fn(async () => ({
|
||||
environmentAirQualityEnabled: true,
|
||||
}));
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: () => userFindUnique() },
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* The feature extraction's bulk read asks for the types in
|
||||
* `FEATURE_ROW_TYPES` and nothing else (#1398: each type is capped on its
|
||||
* own, so the read has to name them). A block that starts folding another
|
||||
* type through `byType("…")` would get no rows and quietly stop being built,
|
||||
* so every type a block reads must be on the list, including the signals of
|
||||
* the day, which are handed the same `byType`.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { readSource } from "@/__tests__/helpers/source-files";
|
||||
|
||||
const src = readSource("src/lib/insights/features.ts", [
|
||||
"const FEATURE_ROW_TYPES",
|
||||
"computeSignalsOfDay(\n byType,",
|
||||
]);
|
||||
const signals = readSource("src/lib/insights/signals-of-day.ts", [
|
||||
"byType: (type: string)",
|
||||
]);
|
||||
|
||||
describe("feature extraction row types", () => {
|
||||
it("reads every type a block folds", () => {
|
||||
const list = /const FEATURE_ROW_TYPES[^=]*=\s*\[([\s\S]*?)\];/.exec(src);
|
||||
expect(list).not.toBeNull();
|
||||
const listed = new Set(
|
||||
[...list![1].matchAll(/"([A-Z_]+)"/g)].map((m) => m[1]),
|
||||
);
|
||||
const folded = new Set(
|
||||
[src, signals].flatMap((text) =>
|
||||
[...text.matchAll(/\bbyType\(\s*"([A-Z_]+)"\s*\)/g)].map((m) => m[1]),
|
||||
),
|
||||
);
|
||||
// A matcher that finds nothing would pass the subset check below.
|
||||
expect(folded.size).toBeGreaterThanOrEqual(10);
|
||||
expect([...folded].filter((t) => !listed.has(t))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,13 @@ vi.mock("@/lib/modules/gate", async (importActual) => {
|
||||
};
|
||||
});
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: vi.fn() },
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
// v1.44 — the extended channel families (intake, training, room climate).
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
insightStatusCache: {
|
||||
|
||||
@@ -27,9 +27,10 @@ describe("prompt reads exclude tombstoned rows", () => {
|
||||
});
|
||||
|
||||
it("weight-status filters its measurement read", () => {
|
||||
const src = read("../weight-status.ts");
|
||||
expect(src).toMatch(
|
||||
/measurement\s*\n?\s*\.findMany\(\{\s*where:\s*\{[\s\S]{0,300}?\bdeletedAt:\s*null/,
|
||||
// The weight series reads through the per-type newest-rows query.
|
||||
expect(read("../weight-status.ts")).toMatch(/readNewestRowsPerType\(/);
|
||||
expect(read("../../measurements/newest-per-type.ts")).toMatch(
|
||||
/readNewestRowsPerType[\s\S]*?m\."deleted_at" IS NULL/,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -8,6 +8,13 @@ vi.mock("@/lib/measurements/day-aggregates", async () => ({
|
||||
).fakeReadDayAggregates,
|
||||
}));
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
insightStatusCache: {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { readNewestRowsPerType } from "@/lib/measurements/newest-per-type";
|
||||
import { readRecentMoodScores } from "@/lib/mood/recent-scores";
|
||||
import {
|
||||
getBloodPressureSystemPrompt,
|
||||
@@ -326,27 +327,14 @@ async function buildBloodPressureSnapshot(
|
||||
*/
|
||||
async function readBpChannels(userId: string, userTz: string) {
|
||||
// v1.4.28 — cap the snapshot input. The downstream
|
||||
// `applyPayloadBudget` trims further; this `take` keeps the read
|
||||
// bounded for Apple-Health-rich accounts. BP captures three types
|
||||
// per reading day so 1095 = 365 d × 3 channels.
|
||||
const measurements = await prisma.measurement
|
||||
.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
type: {
|
||||
in: ["WEIGHT", "BLOOD_PRESSURE_SYS", "BLOOD_PRESSURE_DIA"],
|
||||
},
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
take: 1095,
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
measuredAt: true,
|
||||
},
|
||||
})
|
||||
.then((rows) => rows.reverse());
|
||||
// `applyPayloadBudget` trims further; the cap keeps the read bounded for
|
||||
// Apple-Health-rich accounts: 1095 = 365 d × 3 channels. #1398: shared
|
||||
// fairly across the three channels, so no channel pushes another out.
|
||||
const { rows: measurements } = await readNewestRowsPerType(
|
||||
userId,
|
||||
["WEIGHT", "BLOOD_PRESSURE_SYS", "BLOOD_PRESSURE_DIA"],
|
||||
{ perTypeCap: 1095, totalCap: 1095 },
|
||||
);
|
||||
|
||||
const now = new Date();
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
* fabricating a constant.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { readNewestRowsPerType } from "@/lib/measurements/newest-per-type";
|
||||
import { triggersRestMode } from "@/lib/illness/rest-mode";
|
||||
import {
|
||||
buildComplianceMedicationContext,
|
||||
@@ -529,8 +530,9 @@ export interface MeasurementWindowFetch {
|
||||
* period narrative. Hoisted here so a fourth independently-maintained copy
|
||||
* can't drift the way the period-narrative one did.
|
||||
*
|
||||
* Orders DESC + caps at {@link MEASUREMENT_READ_CAP}, then re-sorts ASC in
|
||||
* JS so a dense account's cap falls on the OLDEST rows, never the newest —
|
||||
* Reads newest-first under {@link MEASUREMENT_READ_CAP}, shared fairly
|
||||
* across the types, and returns ASC, so a dense account's cap falls on the
|
||||
* OLDEST rows of the densest types, never the newest —
|
||||
* the inverse of a naive `orderBy asc, take N`, which silently drops the
|
||||
* NEWEST reads once an account's in-window row count crosses the cap
|
||||
* (exactly backwards for a recent-window read, e.g. the Coach's emerging-
|
||||
@@ -545,30 +547,19 @@ export async function fetchMeasurementWindowSeries(
|
||||
since: Date,
|
||||
types: MeasurementType[],
|
||||
): Promise<MeasurementWindowFetch> {
|
||||
const rowsDesc = await prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
measuredAt: { gte: since },
|
||||
type: { in: types },
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
take: MEASUREMENT_READ_CAP,
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
measuredAt: true,
|
||||
source: true,
|
||||
deviceType: true,
|
||||
sleepStage: true,
|
||||
},
|
||||
// #1398: the cap is shared fairly across the types (each keeps at least its
|
||||
// share, a sparse one all of its window). Newest-first across all of them,
|
||||
// a dense pulse stream filled it within days and starved every sparse
|
||||
// channel out of the window.
|
||||
const { rows, cappedTypes } = await readNewestRowsPerType(userId, types, {
|
||||
perTypeCap: MEASUREMENT_READ_CAP,
|
||||
totalCap: MEASUREMENT_READ_CAP,
|
||||
since,
|
||||
});
|
||||
const measurementsCapped = rowsDesc.length >= MEASUREMENT_READ_CAP;
|
||||
const measurementsCapped = cappedTypes.length > 0;
|
||||
|
||||
const byType = new Map<string, MeasurementSeriesRow[]>();
|
||||
for (const m of [...rowsDesc].sort(
|
||||
(a, b) => a.measuredAt.getTime() - b.measuredAt.getTime(),
|
||||
)) {
|
||||
for (const m of rows) {
|
||||
const list = byType.get(m.type) ?? [];
|
||||
list.push({
|
||||
value: m.value,
|
||||
|
||||
@@ -33,6 +33,13 @@ vi.mock("@/lib/modules/gate", () => ({
|
||||
resolveModuleMap: vi.fn(async () => ({})),
|
||||
}));
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
// v1.44 — the extended channel families (intake, training, room climate).
|
||||
|
||||
@@ -63,6 +63,10 @@ import type {
|
||||
MeasurementType,
|
||||
RollupGranularity,
|
||||
} from "@/generated/prisma/client";
|
||||
import {
|
||||
readLiveMeasurementSpan,
|
||||
readNewestRowsPerType,
|
||||
} from "@/lib/measurements/newest-per-type";
|
||||
|
||||
import {
|
||||
resolveEffectiveBpTargets,
|
||||
@@ -705,7 +709,9 @@ export interface AggregatedFeatures {
|
||||
context: {
|
||||
heightCm: number | null;
|
||||
hasBpTargets: boolean;
|
||||
/** Readings the blocks were built from (capped per type). */
|
||||
totalMeasurements: number;
|
||||
/** First to last reading of any type inside the window. */
|
||||
dataSpanDays: number;
|
||||
oldestMeasurementDaysAgo: number | null;
|
||||
newestMeasurementDaysAgo: number | null;
|
||||
@@ -1041,11 +1047,11 @@ async function readMoodFeature(
|
||||
|
||||
/**
|
||||
* v1.25 — newest-first row cap on the bulk measurement read in
|
||||
* `extractFeatures`. Mirrors the Coach snapshot's `SNAPSHOT_MEASUREMENT_ROW_CAP`
|
||||
* (6000): the prompt / insights aggregates only ever fold this read into a
|
||||
* bounded set of summaries, so a year of dense PULSE / glucose rows is wasted
|
||||
* I/O on the shared pool for a heavy-data tenant. Full-history extremes come
|
||||
* from `readAllTimeExtremes`, not this read, so the cap stays correct.
|
||||
* `extractFeatures`: the aggregates fold it into a bounded set of summaries,
|
||||
* so a year of dense PULSE / glucose rows is wasted I/O. It applies to each
|
||||
* type on its own (#1398): shared across types, a dense stream filled it
|
||||
* within hours and every sparse type fell out of the read. Worst case: this
|
||||
* times the 12 `FEATURE_ROW_TYPES`, 72,000 rows.
|
||||
*/
|
||||
const FEATURE_MEASUREMENT_ROW_CAP = 6000;
|
||||
|
||||
@@ -1055,6 +1061,22 @@ const FEATURE_MEASUREMENT_ROW_CAP = 6000;
|
||||
*/
|
||||
export type ScopedFeatureBlock = "weight" | "bloodPressure" | "pulse" | "mood";
|
||||
|
||||
/** The types the blocks and the signals of the day read; nothing else is. */
|
||||
const FEATURE_ROW_TYPES: readonly MeasurementType[] = [
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"BLOOD_PRESSURE_DIA",
|
||||
"PULSE",
|
||||
"BODY_FAT",
|
||||
"GRIP_STRENGTH",
|
||||
"WAIST_CIRCUMFERENCE",
|
||||
"PAIN_NRS",
|
||||
"SLEEP_DURATION",
|
||||
"ACTIVITY_STEPS",
|
||||
"BLOOD_GLUCOSE",
|
||||
"RESTING_HEART_RATE",
|
||||
];
|
||||
|
||||
const SCOPED_BLOCK_TYPES: Readonly<
|
||||
Record<ScopedFeatureBlock, readonly MeasurementType[]>
|
||||
> = {
|
||||
@@ -1071,9 +1093,10 @@ export async function extractFeatures(
|
||||
sinceDays?: number;
|
||||
/**
|
||||
* Build only these blocks (plus `context`) and return. Each block is
|
||||
* identical to the one the full extraction builds: the bulk read keeps its
|
||||
* all-type newest-first cap, so the rows a block sees do not change. Used
|
||||
* by the single-metric Coach read, which reads one block and nothing else.
|
||||
* identical to the one the full extraction builds: the bulk read caps
|
||||
* each type on its own, so reading only the requested blocks' types
|
||||
* leaves every one of them with the rows the full read gives it. Used by
|
||||
* the single-metric Coach read, which reads one block and nothing else.
|
||||
*/
|
||||
only?: ReadonlySet<ScopedFeatureBlock>;
|
||||
/**
|
||||
@@ -1116,41 +1139,21 @@ export async function extractFeatures(
|
||||
typeof sinceDays === "number" && sinceDays > 0
|
||||
? new Date(now - sinceDays * 24 * 60 * 60 * 1000)
|
||||
: null;
|
||||
// v1.25 — newest-first cap on the bulk feature read, mirroring the Coach
|
||||
// snapshot (`SNAPSHOT_MEASUREMENT_ROW_CAP`). Callers pass windows of 365-400
|
||||
// days, and PULSE / glucose are 200k-row-class types, so an uncapped read
|
||||
// pulled hundreds of thousands of rows per Coach turn and nightly briefing
|
||||
// only to fold them into a handful of summaries. Read newest-first, cap, then
|
||||
// reverse so every downstream consumer (`byType`, `summarize`, BP pairing,
|
||||
// sleep reconstruction, oldest/newest span) still sees ascending order. The
|
||||
// cap is safe even unbounded: the genuine all-time extremes are sourced
|
||||
// separately via `readAllTimeExtremes` on the bounded branch, so capping only
|
||||
// sheds the deepest rows of the bulk read and never relabels an extreme.
|
||||
const measurements = !needsMeasurementRows
|
||||
? []
|
||||
: await prisma.measurement
|
||||
.findMany({
|
||||
where: sinceCutoff
|
||||
? { userId, measuredAt: { gte: sinceCutoff }, deletedAt: null }
|
||||
: { userId, deletedAt: null },
|
||||
orderBy: { measuredAt: "desc" },
|
||||
take: FEATURE_MEASUREMENT_ROW_CAP,
|
||||
// Project only the columns every downstream consumer reads (`byType`,
|
||||
// `summarize`, BP pairing, and `reconstructSleepNights`'s `SleepStageRow`).
|
||||
// The PULSE / glucose windows are 200k-row-class; pulling every column
|
||||
// (notes, externalId, …) is pure wasted I/O on the shared Prisma pool.
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
measuredAt: true,
|
||||
sleepStage: true,
|
||||
source: true,
|
||||
deviceType: true,
|
||||
},
|
||||
})
|
||||
// Restore ascending order so order-sensitive consumers (oldest/newest span,
|
||||
// BP pairing, sleep reconstruction) see the same shape as before the cap.
|
||||
.then((rows) => rows.reverse());
|
||||
// Newest-first, capped per type (`FEATURE_MEASUREMENT_ROW_CAP`), oldest
|
||||
// first on return. A scoped read asks for its blocks' types only and each
|
||||
// gets the rows the full read gives it. The all-time extremes come from
|
||||
// `readAllTimeExtremes`, so the cap never relabels an extreme.
|
||||
const rowTypes = only ? allTimeTypes : FEATURE_ROW_TYPES;
|
||||
const [measurements, span] = !needsMeasurementRows
|
||||
? [[], { oldest: null, newest: null }]
|
||||
: await Promise.all([
|
||||
readNewestRowsPerType(userId, rowTypes, {
|
||||
perTypeCap: FEATURE_MEASUREMENT_ROW_CAP,
|
||||
since: sinceCutoff,
|
||||
}).then((read) => read.rows),
|
||||
// The account's span, any type; capped rows shrink it to hours.
|
||||
readLiveMeasurementSpan(userId, sinceCutoff),
|
||||
]);
|
||||
|
||||
// v1.18.11 — when the bulk read is bounded to a recent window, the
|
||||
// windowed `summarize()` no longer covers the full history, so the `allTime*`
|
||||
@@ -1180,12 +1183,8 @@ export async function extractFeatures(
|
||||
user && resolveEffectiveBpTargets(user, user.thresholdsJson);
|
||||
|
||||
// Compute overall data span
|
||||
const oldestMeasurement =
|
||||
measurements.length > 0 ? measurements[0].measuredAt : null;
|
||||
const newestMeasurement =
|
||||
measurements.length > 0
|
||||
? measurements[measurements.length - 1].measuredAt
|
||||
: null;
|
||||
const oldestMeasurement = span.oldest;
|
||||
const newestMeasurement = span.newest;
|
||||
const overallSpanDays =
|
||||
oldestMeasurement && newestMeasurement
|
||||
? Math.round(
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
* importing from here unchanged.
|
||||
*/
|
||||
|
||||
import { readNewestRowsPerType } from "@/lib/measurements/newest-per-type";
|
||||
import {
|
||||
computeMoodPatterns,
|
||||
moodPatternsWire,
|
||||
@@ -276,8 +277,9 @@ export interface CrossMetricMeasurement {
|
||||
* Apple + Fitbit + WHOOP) blew past it. The crosstab/correlation only
|
||||
* need per-day values, but the read stays raw because the DAY rollup
|
||||
* buckets on UTC midnight while these aggregates key on the user's
|
||||
* Berlin calendar day — see the read comment. Exported so the read's
|
||||
* `take` and the truncation-annotation threshold share one constant.
|
||||
* Berlin calendar day — see the read comment. Shared fairly across the
|
||||
* channels (#1398). Exported so the read's cap and the truncation
|
||||
* annotation share one constant.
|
||||
*/
|
||||
export const MOOD_CROSS_METRIC_ROW_CAP = 50_000;
|
||||
|
||||
@@ -885,64 +887,45 @@ export async function fetchMoodAggregates(
|
||||
}));
|
||||
});
|
||||
|
||||
const measurements = await prisma.measurement
|
||||
.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
measuredAt: { gte: windowCutoff },
|
||||
// v1.8.5 — single-sourced from CORRELATION_METRICS so the fetched
|
||||
// channels and the computed correlations never drift apart.
|
||||
// v1.12.0 — union the crosstab metric channels so the tag × metric
|
||||
// board has its measurements without a second query.
|
||||
type: {
|
||||
in: Array.from(
|
||||
new Set<MeasurementType>([
|
||||
...(Object.values(CORRELATION_METRICS) as MeasurementType[]),
|
||||
...CROSSTAB_METRIC_TYPES,
|
||||
// v1.14.0 — union the factor-crosstab vital channels (RHR /
|
||||
// HRV / steps / sleep / weight / BP-sys) so the factor board
|
||||
// has its measurements without a second query.
|
||||
...FACTOR_CROSSTAB_METRIC_TYPES,
|
||||
]),
|
||||
),
|
||||
},
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
// v1.12.1 — scope the cap to the worst-case row count over the
|
||||
// 365-day window instead of the old flat 5,000. The crosstab +
|
||||
// correlation channels are per-day aggregates, but the read is raw
|
||||
// because the DAY rollup buckets on UTC midnight while the crosstab
|
||||
// / correlations key on the user's Berlin calendar day — feeding a
|
||||
// UTC-bucketed metric series against a Berlin-bucketed mood series
|
||||
// would skew the day pairing by up to a few hours at the boundary.
|
||||
// So we stay on raw rows but lift the cap above the realistic worst
|
||||
// case: SLEEP_DURATION (~6 stage rows/night) and PULSE / HRV ingest
|
||||
// the most rows/day, and a user syncing several sources multiplies
|
||||
// that — a flat 5,000 silently dropped the oldest months (the order
|
||||
// is `measuredAt desc`). The cap is the floor that keeps a full
|
||||
// data-rich year intact; if it is ever hit we annotate `truncated`
|
||||
// so the drop is observable rather than silently recency-biased.
|
||||
take: MOOD_CROSS_METRIC_ROW_CAP,
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
measuredAt: true,
|
||||
// v1.12.1 — source + deviceType drive the crosstab's canonical
|
||||
// per-day pick so a cumulative metric reported by two sources on
|
||||
// the same day (Fitbit + Apple steps, Fitbit + WHOOP sleep) is
|
||||
// summed once, not double-counted.
|
||||
source: true,
|
||||
deviceType: true,
|
||||
},
|
||||
})
|
||||
.then((rows) => rows.reverse());
|
||||
// v1.12.1 — the read is raw because the DAY rollup buckets on UTC midnight
|
||||
// while the crosstab / correlations key on the user's calendar day, and
|
||||
// feeding a UTC-bucketed metric series against a locally bucketed mood
|
||||
// series would skew the day pairing at the boundary. The cap keeps a full
|
||||
// data-rich year intact; when it is hit, the drop is annotated rather than
|
||||
// silently recency-biased. #1398: the cap is shared fairly across the
|
||||
// channels (each keeps at least its share, a sparse one all of its year),
|
||||
// because newest-first across all of them a dense pulse stream filled it
|
||||
// within days and every sparse channel fell out of the pairing.
|
||||
// `source` + `deviceType` drive the crosstab's canonical per-day pick so a
|
||||
// cumulative metric reported by two sources on the same day is summed once.
|
||||
const crossMetricRead = await readNewestRowsPerType(
|
||||
userId,
|
||||
// v1.8.5 — single-sourced from CORRELATION_METRICS so the fetched
|
||||
// channels and the computed correlations never drift apart; the crosstab
|
||||
// and factor-crosstab channels ride the same read.
|
||||
[
|
||||
...(Object.values(CORRELATION_METRICS) as MeasurementType[]),
|
||||
...CROSSTAB_METRIC_TYPES,
|
||||
...FACTOR_CROSSTAB_METRIC_TYPES,
|
||||
],
|
||||
{
|
||||
perTypeCap: MOOD_CROSS_METRIC_ROW_CAP,
|
||||
totalCap: MOOD_CROSS_METRIC_ROW_CAP,
|
||||
since: windowCutoff,
|
||||
},
|
||||
);
|
||||
const measurements = crossMetricRead.rows.map((row) => ({
|
||||
type: row.type,
|
||||
value: row.value,
|
||||
measuredAt: row.measuredAt,
|
||||
source: row.source,
|
||||
deviceType: row.deviceType,
|
||||
}));
|
||||
|
||||
if (measurements.length >= MOOD_CROSS_METRIC_ROW_CAP) {
|
||||
// The read hit the cap — the oldest rows in the 365-day window were
|
||||
// dropped (order is `measuredAt desc`). Surface it on the wide event
|
||||
// so a silently-truncated, recency-biased crosstab/correlation is at
|
||||
// least observable instead of looking like clean data.
|
||||
if (crossMetricRead.cappedTypes.length > 0) {
|
||||
// The oldest rows of a channel in the 365-day window were dropped.
|
||||
// Surface it on the wide event so a truncated, recency-biased
|
||||
// crosstab/correlation is at least observable.
|
||||
annotate({
|
||||
action: { name: "mood.insights.cross_metric.truncated" },
|
||||
meta: { rows: measurements.length, cap: MOOD_CROSS_METRIC_ROW_CAP },
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
type StatusTextResult,
|
||||
} from "@/lib/insights/status-pipeline";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { readNewestRowsPerType } from "@/lib/measurements/newest-per-type";
|
||||
import { createCustomLabelResolver } from "@/lib/mood/custom-tags";
|
||||
import { loadUserSourcePriority } from "@/lib/rollups/measurement-read";
|
||||
|
||||
@@ -412,8 +413,8 @@ async function readCrossMetricMeasurements(userId: string, now: Date) {
|
||||
// `deviceType` ride along so the crosstab's per-day canonical-source pick
|
||||
// de-dups a cumulative metric reported by two sources on the same day.
|
||||
// The crosstab + correlations only pair against the ~365-day window, so
|
||||
// bound the read to that window: it lets Postgres use the (userId,
|
||||
// measuredAt) index, caps memory to rows that can actually pair, and stops a
|
||||
// bound the read to that window: it caps memory to rows that can actually
|
||||
// pair, and stops a
|
||||
// data-rich Apple-Health account from spending the 50k cap on a recency-
|
||||
// biased all-recent slice. `deletedAt: null` keeps soft-deleted rows (common
|
||||
// on HRV/RHR/steps re-sync) out of the FDR-gated factor deltas the model
|
||||
@@ -421,39 +422,38 @@ async function readCrossMetricMeasurements(userId: string, now: Date) {
|
||||
const crossMetricWindowStart = new Date(
|
||||
now.getTime() - 365 * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
// #1398: capped per type, the total kept. Shared newest-first across the
|
||||
// channels, a dense pulse stream filled the cap within days and weight and
|
||||
// blood pressure fell out of the pairing. Each channel now keeps at least
|
||||
// its share of the cap, a sparse one all of its year.
|
||||
const CROSS_METRIC_ROW_CAP = 50_000;
|
||||
const measurements = await prisma.measurement
|
||||
.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
measuredAt: { gte: crossMetricWindowStart },
|
||||
type: {
|
||||
in: [
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"PULSE",
|
||||
"RESTING_HEART_RATE",
|
||||
"HEART_RATE_VARIABILITY",
|
||||
"ACTIVITY_STEPS",
|
||||
"SLEEP_DURATION",
|
||||
],
|
||||
},
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
take: CROSS_METRIC_ROW_CAP,
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
measuredAt: true,
|
||||
source: true,
|
||||
deviceType: true,
|
||||
},
|
||||
})
|
||||
.then((rows) => rows.reverse());
|
||||
if (measurements.length >= CROSS_METRIC_ROW_CAP) {
|
||||
const { rows, cappedTypes } = await readNewestRowsPerType(
|
||||
userId,
|
||||
[
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"PULSE",
|
||||
"RESTING_HEART_RATE",
|
||||
"HEART_RATE_VARIABILITY",
|
||||
"ACTIVITY_STEPS",
|
||||
"SLEEP_DURATION",
|
||||
],
|
||||
{
|
||||
perTypeCap: CROSS_METRIC_ROW_CAP,
|
||||
totalCap: CROSS_METRIC_ROW_CAP,
|
||||
since: crossMetricWindowStart,
|
||||
},
|
||||
);
|
||||
if (cappedTypes.length > 0) {
|
||||
annotate({ meta: { cross_metric_truncated: true } });
|
||||
}
|
||||
const measurements = rows.map((row) => ({
|
||||
type: row.type,
|
||||
value: row.value,
|
||||
measuredAt: row.measuredAt,
|
||||
source: row.source,
|
||||
deviceType: row.deviceType,
|
||||
}));
|
||||
|
||||
return measurements;
|
||||
}
|
||||
|
||||
@@ -36,6 +36,13 @@ vi.mock("@/lib/modules/gate", () => ({
|
||||
resolveModuleMap: vi.fn(async () => moduleMap.value),
|
||||
}));
|
||||
|
||||
// The per-type measurement read is raw SQL; serve it from the findMany mock.
|
||||
vi.mock("@/lib/measurements/newest-per-type", async () =>
|
||||
(
|
||||
await import("@/__tests__/helpers/newest-per-type-mock")
|
||||
).newestPerTypeMock(),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
// v1.44 — the extended channel families (intake, training, room climate).
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { readNewestRowsPerType } from "@/lib/measurements/newest-per-type";
|
||||
import { readRecentMoodScores } from "@/lib/mood/recent-scores";
|
||||
import {
|
||||
getWeightSystemPrompt,
|
||||
@@ -432,28 +433,14 @@ async function readWeightSeries(
|
||||
mass: DisplayTransform,
|
||||
userTz: string,
|
||||
) {
|
||||
// v1.4.28 — cap the snapshot input. BP captures three types
|
||||
// per day so 1095 = 365 d × 3 channels. Order desc + reverse so we
|
||||
// keep the most recent year of rows.
|
||||
const measurements = await prisma.measurement
|
||||
.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: {
|
||||
in: ["WEIGHT", "BLOOD_PRESSURE_SYS", "BLOOD_PRESSURE_DIA"],
|
||||
},
|
||||
// Soft-deleted rows must never reach the prompt snapshot.
|
||||
deletedAt: null,
|
||||
},
|
||||
take: 1095,
|
||||
orderBy: { measuredAt: "desc" },
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
measuredAt: true,
|
||||
},
|
||||
})
|
||||
.then((rows) => rows.reverse());
|
||||
// v1.4.28 — cap the snapshot input: 1095 = 365 d × 3 channels, the
|
||||
// newest rows, oldest first on return. #1398: shared fairly across the
|
||||
// three channels, so frequent cuff readings cannot push weight out.
|
||||
const { rows: measurements } = await readNewestRowsPerType(
|
||||
userId,
|
||||
["WEIGHT", "BLOOD_PRESSURE_SYS", "BLOOD_PRESSURE_DIA"],
|
||||
{ perTypeCap: 1095, totalCap: 1095 },
|
||||
);
|
||||
|
||||
const now = new Date();
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* The newest rows of each of several measurement types, capped per type.
|
||||
*
|
||||
* The bulk reads that feed the insight aggregates and the Coach snapshot used
|
||||
* to read newest-first across all their types at once under a single row cap.
|
||||
* The cap then belonged to whichever type wrote fastest: a watch sending heart
|
||||
* rate every few seconds fills 6,000 rows within hours, and every weight or
|
||||
* blood pressure reading older than those hours fell out of the read, so a
|
||||
* block reported no data for a metric with years of it (#1398).
|
||||
*
|
||||
* Here the cap applies to each type on its own. A dense type is still bounded
|
||||
* at `perTypeCap` rows, which is what the cap is for, and a sparse type keeps
|
||||
* its newest rows whatever the other types write. So each type sees exactly
|
||||
* the rows it would see if it were read alone, which is what lets a block
|
||||
* built from one type's read equal the block a read of many types builds.
|
||||
* The worst case is `perTypeCap` rows times the number of distinct types,
|
||||
* reached only when every one of them is denser than the cap.
|
||||
*
|
||||
* A read with no single-type block to match can keep its old total instead
|
||||
* (`totalCap`): every type's rows are ranked newest first within the type and
|
||||
* the `totalCap` lowest ranks are kept, so each type keeps at least
|
||||
* `totalCap / types` rows (all of them, if it has fewer), and the room a
|
||||
* sparse type leaves goes to the dense ones. No type is starved and the rows
|
||||
* returned never exceed the total.
|
||||
*
|
||||
* One statement: one index descent per type on the partial live index
|
||||
* `measurements_live_covering_idx (user_id, type, measured_at DESC) WHERE
|
||||
* deleted_at IS NULL`, each stopping at the cap, so the rows touched track the
|
||||
* rows returned, never the length of a dense stream. The driving relation is
|
||||
* aliased `mt`, as in `readLatestReadingsPerType`, so the i18n call-site
|
||||
* scanner does not read the SQL as a translation call.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import {
|
||||
Prisma,
|
||||
type GlucoseContext,
|
||||
type MeasurementSource,
|
||||
type MeasurementType,
|
||||
type SleepStage,
|
||||
} from "@/generated/prisma/client";
|
||||
|
||||
export interface NewestPerTypeRow {
|
||||
type: MeasurementType;
|
||||
value: number;
|
||||
measuredAt: Date;
|
||||
source: MeasurementSource;
|
||||
deviceType: string | null;
|
||||
sleepStage: SleepStage | null;
|
||||
glucoseContext: GlucoseContext | null;
|
||||
}
|
||||
|
||||
export interface NewestPerTypeRead {
|
||||
/** Every type's rows, oldest first. */
|
||||
rows: NewestPerTypeRow[];
|
||||
/** The types that reached the cap, so older rows of theirs were left out. */
|
||||
cappedTypes: MeasurementType[];
|
||||
}
|
||||
|
||||
export async function readNewestRowsPerType(
|
||||
userId: string,
|
||||
types: readonly MeasurementType[],
|
||||
options: { perTypeCap: number; totalCap?: number; since?: Date | null },
|
||||
): Promise<NewestPerTypeRead> {
|
||||
const distinct = [...new Set(types)];
|
||||
if (distinct.length === 0) return { rows: [], cappedTypes: [] };
|
||||
const { perTypeCap, totalCap } = options;
|
||||
// A total below the type count would cut whole types, the thing this read
|
||||
// exists to prevent.
|
||||
for (const cap of [perTypeCap, totalCap ?? distinct.length]) {
|
||||
if (!Number.isInteger(cap) || cap < distinct.length || cap <= 0) {
|
||||
throw new RangeError(
|
||||
"row caps must be integers of at least one per type",
|
||||
);
|
||||
}
|
||||
}
|
||||
const since = options.since ?? null;
|
||||
const sinceSql =
|
||||
since === null ? Prisma.empty : Prisma.sql`AND m."measured_at" >= ${since}`;
|
||||
// With a total, each row's rank within its type orders the cut, and the
|
||||
// count per type says whether the cut reached it.
|
||||
const fairShare = totalCap !== undefined;
|
||||
const shareColumns = fairShare
|
||||
? Prisma.sql`,
|
||||
row_number() OVER (
|
||||
PARTITION BY mt."type" ORDER BY x."measured_at" DESC, x."id" DESC
|
||||
)::int AS "rank",
|
||||
(count(*) OVER (PARTITION BY mt."type"))::int AS "read"`
|
||||
: Prisma.sql`, 0 AS "read"`;
|
||||
const shareCut = fairShare
|
||||
? Prisma.sql`ORDER BY "rank" ASC, x."measured_at" DESC, mt."type" ASC
|
||||
LIMIT ${totalCap}`
|
||||
: Prisma.empty;
|
||||
const raw = await prisma.$queryRaw<
|
||||
Array<{
|
||||
type: string;
|
||||
value: number;
|
||||
measured_at: Date;
|
||||
source: string;
|
||||
device_type: string | null;
|
||||
sleep_stage: string | null;
|
||||
glucose_context: string | null;
|
||||
read: number;
|
||||
}>
|
||||
>`
|
||||
SELECT y."type", y."value", y."measured_at", y."source", y."device_type",
|
||||
y."sleep_stage", y."glucose_context", y."read"
|
||||
FROM (
|
||||
SELECT mt."type" AS "type", x."id", x."value", x."measured_at",
|
||||
x."source"::text AS "source", x."device_type",
|
||||
x."sleep_stage"::text AS "sleep_stage",
|
||||
x."glucose_context"::text AS "glucose_context"
|
||||
${shareColumns}
|
||||
FROM unnest(${distinct}::text[]) AS mt("type")
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT m."id", m."value", m."measured_at", m."source",
|
||||
m."device_type", m."sleep_stage", m."glucose_context"
|
||||
FROM measurements m
|
||||
WHERE m."user_id" = ${userId}
|
||||
AND m."type" = mt."type"::measurement_type
|
||||
AND m."deleted_at" IS NULL
|
||||
${sinceSql}
|
||||
ORDER BY m."measured_at" DESC
|
||||
LIMIT ${perTypeCap}
|
||||
) x
|
||||
${shareCut}
|
||||
) y
|
||||
ORDER BY y."measured_at" ASC, y."id" ASC
|
||||
`;
|
||||
|
||||
const kept = new Map<string, number>();
|
||||
const read = new Map<string, number>();
|
||||
const rows = raw.map((r) => {
|
||||
kept.set(r.type, (kept.get(r.type) ?? 0) + 1);
|
||||
read.set(r.type, Number(r.read));
|
||||
return {
|
||||
type: r.type as MeasurementType,
|
||||
value: Number(r.value),
|
||||
measuredAt: new Date(r.measured_at),
|
||||
source: r.source as MeasurementSource,
|
||||
deviceType: r.device_type,
|
||||
sleepStage: r.sleep_stage as SleepStage | null,
|
||||
glucoseContext: r.glucose_context as GlucoseContext | null,
|
||||
};
|
||||
});
|
||||
// Capped: the type filled its own cap, or the total cut it short.
|
||||
const cappedTypes = distinct.filter((t) => {
|
||||
const n = kept.get(t) ?? 0;
|
||||
return n >= perTypeCap || n < (read.get(t) ?? 0);
|
||||
});
|
||||
return { rows, cappedTypes };
|
||||
}
|
||||
|
||||
/**
|
||||
* The oldest and newest live reading of any type from `since` on (the whole
|
||||
* history when `since` is null), so the span a capped read reports is the
|
||||
* account's, not the hours a dense stream fills of the read. One index probe
|
||||
* at each end of every type on the partial live index, each stopping at its
|
||||
* first row. The type-less `(user_id, measured_at)` index would answer in two
|
||||
* probes, but on a table without statistics the planner took the live
|
||||
* partial index instead and sorted every row of the account.
|
||||
*/
|
||||
export async function readLiveMeasurementSpan(
|
||||
userId: string,
|
||||
since: Date | null,
|
||||
): Promise<{ oldest: Date | null; newest: Date | null }> {
|
||||
const sinceSql =
|
||||
since === null ? Prisma.empty : Prisma.sql`AND m."measured_at" >= ${since}`;
|
||||
const [row] = await prisma.$queryRaw<
|
||||
Array<{ oldest: Date | null; newest: Date | null }>
|
||||
>`
|
||||
SELECT min(o."at") AS "oldest", max(n."at") AS "newest"
|
||||
FROM unnest(enum_range(NULL::measurement_type)) AS mt("type")
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT m."measured_at" AS "at" FROM measurements m
|
||||
WHERE m."user_id" = ${userId} AND m."type" = mt."type"
|
||||
AND m."deleted_at" IS NULL ${sinceSql}
|
||||
ORDER BY m."measured_at" ASC LIMIT 1
|
||||
) o ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT m."measured_at" AS "at" FROM measurements m
|
||||
WHERE m."user_id" = ${userId} AND m."type" = mt."type"
|
||||
AND m."deleted_at" IS NULL ${sinceSql}
|
||||
ORDER BY m."measured_at" DESC LIMIT 1
|
||||
) n ON true
|
||||
`;
|
||||
return {
|
||||
oldest: row?.oldest ? new Date(row.oldest) : null,
|
||||
newest: row?.newest ? new Date(row.newest) : null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
/**
|
||||
* A dense stream must not starve a sparse type out of a capped bulk read.
|
||||
*
|
||||
* The feature extraction and the Coach snapshot each read measurements
|
||||
* newest-first under a row cap. Read across every type at once, the cap
|
||||
* belongs to whichever type writes fastest: a watch sending heart rate every
|
||||
* few seconds fills 6,000 rows within hours, and every weight and blood
|
||||
* pressure reading older than those hours falls out of the read. The blocks
|
||||
* then report no weight at all on an account with years of it, while the
|
||||
* availability probe (uncapped aggregates) sees the rows and calls the miss
|
||||
* "unavailable in scope".
|
||||
*
|
||||
* The account below has heart rate every ten seconds, more rows than either
|
||||
* cap on their own and all of them newer than the sparse history, plus two
|
||||
* months of daily weight and twice-daily blood pressure. Every read that
|
||||
* builds a weight or blood pressure block must still see them: the
|
||||
* single-metric MCP read, the full feature extraction, and the full Coach
|
||||
* snapshot. The scoped and the full extraction must also agree block for
|
||||
* block, which is what the single-metric read promises.
|
||||
*
|
||||
* The per-type read and the span probe are also run under `EXPLAIN ANALYZE`
|
||||
* on the unanalysed table: the rows their plans touch must track the rows
|
||||
* they return, not the size of the dense stream, so the cap still bounds the
|
||||
* I/O it exists for.
|
||||
*/
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { getPrismaClient, truncateAllTables } from "./setup";
|
||||
import { prisma as appPrisma } from "@/lib/db";
|
||||
import { MCP_TOOLS } from "@/lib/mcp/tools";
|
||||
import type { McpAuthContext } from "@/lib/mcp/auth";
|
||||
import {
|
||||
__resetCoachSnapshotCacheForTests,
|
||||
buildCoachSnapshot,
|
||||
} from "@/lib/ai/coach/snapshot";
|
||||
import { COACH_SOURCE_SNAPSHOT_KEY } from "@/lib/ai/coach/tools/source-keys";
|
||||
import {
|
||||
extractFeatures,
|
||||
type AggregatedFeatures,
|
||||
} from "@/lib/insights/features";
|
||||
import {
|
||||
readLiveMeasurementSpan,
|
||||
readNewestRowsPerType,
|
||||
} from "@/lib/measurements/newest-per-type";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
|
||||
vi.mock("@/lib/jobs/boss-instance", () => ({
|
||||
getGlobalBoss: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const HOUR_MS = 3_600_000;
|
||||
/** Above both 6,000-row caps on its own. */
|
||||
const PULSE_ROWS = 9_000;
|
||||
const PULSE_STEP_MS = 10_000;
|
||||
const SPARSE_DAYS = 60;
|
||||
|
||||
let userId = "";
|
||||
|
||||
function ctx(): McpAuthContext {
|
||||
return {
|
||||
userId,
|
||||
tokenId: "token-int",
|
||||
scopes: ["health:read"],
|
||||
binding: `${userId}:token-int`,
|
||||
canRead: true,
|
||||
canWrite: false,
|
||||
};
|
||||
}
|
||||
|
||||
function tool(name: string) {
|
||||
const def = MCP_TOOLS.find((t) => t.name === name);
|
||||
if (!def) throw new Error(`tool ${name} not registered`);
|
||||
return def;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
const prisma = getPrismaClient();
|
||||
await truncateAllTables(prisma);
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
username: "dense-stream-sparse",
|
||||
email: "dense-stream-sparse@example.test",
|
||||
timezone: "Europe/Berlin",
|
||||
dateOfBirth: new Date("1980-05-01T00:00:00Z"),
|
||||
heightCm: 180,
|
||||
},
|
||||
});
|
||||
userId = user.id;
|
||||
const now = Date.now();
|
||||
|
||||
const rows: Array<{
|
||||
userId: string;
|
||||
type: MeasurementType;
|
||||
value: number;
|
||||
unit: string;
|
||||
source: "APPLE_HEALTH" | "WITHINGS";
|
||||
measuredAt: Date;
|
||||
}> = [];
|
||||
// Heart rate every ten seconds for the last 25 hours: every row is newer
|
||||
// than the newest sparse reading below.
|
||||
for (let i = 0; i < PULSE_ROWS; i++) {
|
||||
rows.push({
|
||||
userId,
|
||||
type: "PULSE",
|
||||
value: 60 + ((i * 7) % 25),
|
||||
unit: "bpm",
|
||||
source: "APPLE_HEALTH",
|
||||
measuredAt: new Date(now - 60_000 - i * PULSE_STEP_MS),
|
||||
});
|
||||
}
|
||||
for (let d = 2; d < 2 + SPARSE_DAYS; d++) {
|
||||
rows.push({
|
||||
userId,
|
||||
type: "WEIGHT",
|
||||
value: 81 + (d % 6) * 0.3,
|
||||
unit: "kg",
|
||||
source: "WITHINGS",
|
||||
measuredAt: new Date(now - d * DAY_MS - 2 * HOUR_MS),
|
||||
});
|
||||
for (const h of [8, 20]) {
|
||||
const at = new Date(now - d * DAY_MS - h * HOUR_MS);
|
||||
rows.push(
|
||||
{
|
||||
userId,
|
||||
type: "BLOOD_PRESSURE_SYS",
|
||||
value: 118 + ((d * 7 + h) % 15),
|
||||
unit: "mmHg",
|
||||
source: "WITHINGS",
|
||||
measuredAt: at,
|
||||
},
|
||||
{
|
||||
userId,
|
||||
type: "BLOOD_PRESSURE_DIA",
|
||||
value: 76 + ((d * 5 + h) % 9),
|
||||
unit: "mmHg",
|
||||
source: "WITHINGS",
|
||||
measuredAt: at,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
await prisma.measurement.createMany({ data: rows });
|
||||
// No ANALYZE: a fresh import below the autoanalyze threshold is what a
|
||||
// production account looks like right after its first sync.
|
||||
}, 120_000);
|
||||
|
||||
describe("a dense stream beside sparse history", () => {
|
||||
it("answers get_metric_series for weight on every window", async () => {
|
||||
for (const window of [
|
||||
"last7days",
|
||||
"last30days",
|
||||
"last90days",
|
||||
"lastYear",
|
||||
"allTime",
|
||||
] as const) {
|
||||
__resetCoachSnapshotCacheForTests();
|
||||
const result = (await tool("get_metric_series").run(ctx(), {
|
||||
metric: "weight",
|
||||
window,
|
||||
})) as { present: boolean; reason?: string };
|
||||
expect({ window, present: result.present }).toEqual({
|
||||
window,
|
||||
present: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("builds the weight and blood pressure blocks in the full extraction", async () => {
|
||||
for (const options of [{ sinceDays: 400 }, { sinceDays: 90 }, {}]) {
|
||||
const full = (await extractFeatures(
|
||||
userId,
|
||||
false,
|
||||
options,
|
||||
)) as AggregatedFeatures;
|
||||
expect(full.weight?.coverage?.count).toBe(SPARSE_DAYS);
|
||||
expect(full.bloodPressure?.coverage?.count).toBeGreaterThan(0);
|
||||
expect(full.pulse).toBeDefined();
|
||||
// The span covers the sparse history, not the hours the dense stream
|
||||
// fills on its own.
|
||||
expect(full.context.dataSpanDays).toBeGreaterThanOrEqual(SPARSE_DAYS);
|
||||
}
|
||||
});
|
||||
|
||||
it("builds each scoped block exactly as the full extraction does", async () => {
|
||||
const full = (await extractFeatures(userId, false, {
|
||||
sinceDays: 400,
|
||||
})) as AggregatedFeatures;
|
||||
for (const block of ["weight", "bloodPressure", "pulse"] as const) {
|
||||
const scoped = (await extractFeatures(userId, false, {
|
||||
sinceDays: 400,
|
||||
only: new Set([block]),
|
||||
})) as AggregatedFeatures;
|
||||
expect(scoped[block]).toBeDefined();
|
||||
expect(JSON.stringify(scoped[block])).toBe(JSON.stringify(full[block]));
|
||||
}
|
||||
});
|
||||
|
||||
it("carries the weight and blood pressure timelines in the full Coach snapshot", async () => {
|
||||
__resetCoachSnapshotCacheForTests();
|
||||
const snapshot = await buildCoachSnapshot(userId, {
|
||||
sources: ["pulse", "weight", "bp"],
|
||||
window: "last90days",
|
||||
});
|
||||
const weight = snapshot.sections[COACH_SOURCE_SNAPSHOT_KEY.weight!] as
|
||||
{ timeline?: { recent?: unknown[]; weekly?: unknown[] } } | undefined;
|
||||
const bp = snapshot.sections[COACH_SOURCE_SNAPSHOT_KEY.bp!] as
|
||||
{ timeline?: { recent?: unknown[]; weeklySys?: unknown[] } } | undefined;
|
||||
expect(weight?.timeline?.recent?.length ?? 0).toBeGreaterThan(0);
|
||||
expect(weight?.timeline?.weekly?.length ?? 0).toBeGreaterThan(0);
|
||||
expect(bp?.timeline?.recent?.length ?? 0).toBeGreaterThan(0);
|
||||
expect(bp?.timeline?.weeklySys?.length ?? 0).toBeGreaterThan(0);
|
||||
|
||||
// The single-metric read answers the section the full snapshot carries.
|
||||
__resetCoachSnapshotCacheForTests();
|
||||
const single = (await tool("get_metric_series").run(ctx(), {
|
||||
metric: "weight",
|
||||
window: "last90days",
|
||||
})) as { present: boolean; data?: { section?: unknown } };
|
||||
expect(JSON.stringify(single.data?.section)).toBe(JSON.stringify(weight));
|
||||
});
|
||||
|
||||
it("reads each type by its own index descent, bounded by the cap", async () => {
|
||||
const cap = 6_000;
|
||||
const types: MeasurementType[] = [
|
||||
"PULSE",
|
||||
"WEIGHT",
|
||||
"BLOOD_PRESSURE_SYS",
|
||||
"BLOOD_PRESSURE_DIA",
|
||||
];
|
||||
const [result, plans] = await withPlans(() =>
|
||||
readNewestRowsPerType(userId, types, { perTypeCap: cap }),
|
||||
);
|
||||
const counts = new Map<string, number>();
|
||||
for (const row of result.rows) {
|
||||
counts.set(row.type, (counts.get(row.type) ?? 0) + 1);
|
||||
}
|
||||
expect(Object.fromEntries(counts)).toEqual({
|
||||
PULSE: cap,
|
||||
WEIGHT: SPARSE_DAYS,
|
||||
BLOOD_PRESSURE_SYS: SPARSE_DAYS * 2,
|
||||
BLOOD_PRESSURE_DIA: SPARSE_DAYS * 2,
|
||||
});
|
||||
expect(result.cappedTypes).toEqual(["PULSE"]);
|
||||
// Ascending, the order every consumer folds in.
|
||||
for (let i = 1; i < result.rows.length; i++) {
|
||||
expect(result.rows[i].measuredAt.getTime()).toBeGreaterThanOrEqual(
|
||||
result.rows[i - 1].measuredAt.getTime(),
|
||||
);
|
||||
}
|
||||
|
||||
expect(plans).toHaveLength(1);
|
||||
expect(JSON.stringify(plans[0])).not.toContain("Seq Scan");
|
||||
// Every row the plan's measurement scans returned or threw away, over all
|
||||
// their loops: a plan that walked the dense stream would touch all 9,000
|
||||
// pulse rows, the descent stops at the cap.
|
||||
expect(scanRowVisits(plans[0])).toBeLessThanOrEqual(
|
||||
result.rows.length + types.length,
|
||||
);
|
||||
});
|
||||
|
||||
it("takes the overall span from index probes, not from the rows", async () => {
|
||||
const [span, plans] = await withPlans(() =>
|
||||
readLiveMeasurementSpan(userId, new Date(Date.now() - 400 * DAY_MS)),
|
||||
);
|
||||
expect(span.oldest).not.toBeNull();
|
||||
expect(span.newest).not.toBeNull();
|
||||
expect(
|
||||
(span.newest!.getTime() - span.oldest!.getTime()) / DAY_MS,
|
||||
).toBeGreaterThan(SPARSE_DAYS);
|
||||
expect(plans).toHaveLength(1);
|
||||
expect(JSON.stringify(plans[0])).not.toContain("Seq Scan");
|
||||
// One row at each end of each of the four seeded types.
|
||||
expect(scanRowVisits(plans[0])).toBeLessThanOrEqual(8);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Run `read`, then run every `$queryRaw` it issued again under `EXPLAIN
|
||||
* ANALYZE` and hand back the plans beside the reader's own result.
|
||||
*/
|
||||
async function withPlans<T>(read: () => Promise<T>): Promise<[T, unknown[]]> {
|
||||
const original = appPrisma.$queryRaw.bind(appPrisma) as (
|
||||
...args: unknown[]
|
||||
) => Promise<unknown>;
|
||||
const statements: Array<[TemplateStringsArray, unknown[]]> = [];
|
||||
vi.spyOn(appPrisma, "$queryRaw").mockImplementation(((
|
||||
strings: TemplateStringsArray,
|
||||
...values: unknown[]
|
||||
) => {
|
||||
statements.push([strings, values]);
|
||||
return original(strings, ...values);
|
||||
}) as never);
|
||||
let result: T;
|
||||
try {
|
||||
result = await read();
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
const plans: unknown[] = [];
|
||||
for (const [strings, values] of statements) {
|
||||
const head = "EXPLAIN (ANALYZE, FORMAT JSON) ";
|
||||
const explain = Object.assign([head + strings[0], ...strings.slice(1)], {
|
||||
raw: [head + strings.raw[0], ...strings.raw.slice(1)],
|
||||
});
|
||||
const [{ "QUERY PLAN": plan }] = await appPrisma.$queryRaw<
|
||||
Array<{ "QUERY PLAN": unknown }>
|
||||
>(explain, ...values);
|
||||
plans.push(plan);
|
||||
}
|
||||
return [result, plans];
|
||||
}
|
||||
|
||||
interface PlanNode {
|
||||
"Node Type"?: string;
|
||||
"Relation Name"?: string;
|
||||
"Actual Rows"?: number;
|
||||
"Actual Loops"?: number;
|
||||
"Rows Removed by Filter"?: number;
|
||||
"Rows Removed by Index Recheck"?: number;
|
||||
Plans?: PlanNode[];
|
||||
Plan?: PlanNode;
|
||||
}
|
||||
|
||||
/** Rows the scans of `measurements` produced or discarded, over all loops. */
|
||||
function scanRowVisits(plan: unknown): number {
|
||||
const walk = (node: PlanNode): number => {
|
||||
const own =
|
||||
node["Relation Name"] === "measurements"
|
||||
? ((node["Actual Rows"] ?? 0) +
|
||||
(node["Rows Removed by Filter"] ?? 0) +
|
||||
(node["Rows Removed by Index Recheck"] ?? 0)) *
|
||||
(node["Actual Loops"] ?? 1)
|
||||
: 0;
|
||||
return own + (node.Plans ?? []).reduce((sum, p) => sum + walk(p), 0);
|
||||
};
|
||||
const root = (plan as PlanNode[])[0];
|
||||
return walk(root.Plan ?? root);
|
||||
}
|
||||
@@ -5,9 +5,9 @@
|
||||
* builder on real rows: for every seeded source, across windows, the tool's
|
||||
* result serialises to exactly what `buildCoachSnapshot` scoped to that source
|
||||
* yields for the same section and grounding — the result `get_metric_series`
|
||||
* returned before. A dense series pushes the feature extraction's all-type row
|
||||
* cap into play, a year of blood pressure is large enough to go back to the
|
||||
* full builder, and an absent source stays an explicit absence.
|
||||
* returned before. A dense series pushes the feature extraction's per-type
|
||||
* row cap into play, a year of blood pressure is large enough to go back to
|
||||
* the full builder, and an absent source stays an explicit absence.
|
||||
*/
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -148,8 +148,8 @@ beforeAll(async () => {
|
||||
}
|
||||
};
|
||||
// Hourly pulse for 400 days: more than the feature extraction's 6000-row
|
||||
// all-type cap on its own, so the cap decides which weight rows the core
|
||||
// aggregates see, in both builds.
|
||||
// cap on its own, so pulse is capped in both builds while every other type
|
||||
// keeps its rows.
|
||||
add("PULSE", "bpm", 400 * 24, HOUR_MS, (i) => 60 + ((i * 7) % 25));
|
||||
add("RESTING_HEART_RATE", "bpm", 400, DAY_MS, (i) => 52 + (i % 9));
|
||||
add("HEART_RATE_VARIABILITY", "ms", 400, DAY_MS, (i) => 40 + (i % 13));
|
||||
|
||||
+2
-2
@@ -85,7 +85,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -249,7 +249,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+2
-2
@@ -84,7 +84,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -248,7 +248,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+2
-2
@@ -84,7 +84,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -248,7 +248,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+2
-2
@@ -85,7 +85,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -250,7 +250,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+2
-2
@@ -80,7 +80,7 @@
|
||||
"timeoutMs": 180000
|
||||
},
|
||||
"promptChars": 39012,
|
||||
"promptSha256": "9b74ece939faf8f6643d894cc718bd3e0925133e2c6c12d98dfb3f9d68c82d61"
|
||||
"promptSha256": "fe27fbfa60a4e13470e1545a6a778f94404774212ca8ed4006862dba63a4ea7f"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -244,7 +244,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "c98e2d8e9f112318293af870eaa7c15d342f7f37a12047b0fd4e2a7f66d84676",
|
||||
"snapshotHash": "6e6dd1b4e6fd65294b8b340e40505eaed27b4cb324228626d4072963fb943ce6",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+2
-2
@@ -87,7 +87,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34783,
|
||||
"promptSha256": "2aeca4de2fc6397815465ac4de27a2267fdfc69cd4a607b2e19d7b06502bc040"
|
||||
"promptSha256": "a4c99e4df4c9610126cdb7f9030ea97f74c146fdbb8dcdcd8abb8b258f67261f"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -251,7 +251,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+2
-2
@@ -87,7 +87,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34193,
|
||||
"promptSha256": "f11bae5de41f1344113977970c832df38427bcdf4b24a6f7fb8b05cef899c5af"
|
||||
"promptSha256": "54a7cb6909644975b8ccc521b333ee46547b1470d742e3362c3f8c3d0db43741"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -251,7 +251,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "11a4fb0ae0188e5a95cbe69124afaccdb326b76ea8e8ad73affbc819255a01cc",
|
||||
"snapshotHash": "488c3eab37beb28d7dafdb0e7eaf8dc47921e3afa4be6bf79062ad7366bf5907",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+3
-3
@@ -85,7 +85,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -104,7 +104,7 @@
|
||||
"timeoutMs": 180000
|
||||
},
|
||||
"promptChars": 35302,
|
||||
"promptSha256": "2b3978fcf41077f56835864a67264bea403c0dc31a6bd211ecc469afa16d8a7d"
|
||||
"promptSha256": "2f6469a061699ad965357dbc0a7bad2b6ac3b58cd3f5b3dd4b8f7f5e8cddfe06"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -268,7 +268,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+3
-3
@@ -78,7 +78,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -97,7 +97,7 @@
|
||||
"timeoutMs": 180000
|
||||
},
|
||||
"promptChars": 35302,
|
||||
"promptSha256": "2b3978fcf41077f56835864a67264bea403c0dc31a6bd211ecc469afa16d8a7d"
|
||||
"promptSha256": "2f6469a061699ad965357dbc0a7bad2b6ac3b58cd3f5b3dd4b8f7f5e8cddfe06"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -253,7 +253,7 @@
|
||||
},
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.generate",
|
||||
|
||||
+3
-3
@@ -74,7 +74,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -93,7 +93,7 @@
|
||||
"timeoutMs": 180000
|
||||
},
|
||||
"promptChars": 35302,
|
||||
"promptSha256": "2b3978fcf41077f56835864a67264bea403c0dc31a6bd211ecc469afa16d8a7d"
|
||||
"promptSha256": "2f6469a061699ad965357dbc0a7bad2b6ac3b58cd3f5b3dd4b8f7f5e8cddfe06"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -255,7 +255,7 @@
|
||||
"dailyBriefing": null,
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.briefing-failure",
|
||||
|
||||
+3
-3
@@ -74,7 +74,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -93,7 +93,7 @@
|
||||
"timeoutMs": 180000
|
||||
},
|
||||
"promptChars": 35302,
|
||||
"promptSha256": "2b3978fcf41077f56835864a67264bea403c0dc31a6bd211ecc469afa16d8a7d"
|
||||
"promptSha256": "2f6469a061699ad965357dbc0a7bad2b6ac3b58cd3f5b3dd4b8f7f5e8cddfe06"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -255,7 +255,7 @@
|
||||
"dailyBriefing": null,
|
||||
"briefingGeneratedAt": "anchor+0d+12:00:00"
|
||||
},
|
||||
"snapshotHash": "4ac15bc271309c63b3b5d1e43a3367f7abdf952d3f4351bb1b22aa364bcb630a",
|
||||
"snapshotHash": "1869a4e79dfd3f71feee32a0ccbd4cfdbef7a531b73f1ec8c2de244b227aee27",
|
||||
"audit": [
|
||||
{
|
||||
"action": "insights.briefing-failure",
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@
|
||||
}
|
||||
},
|
||||
"promptChars": 34773,
|
||||
"promptSha256": "2197bdec8af3ff7034e7b533788ac94d36b64d4edf8d211bbacfac7e2298ad72"
|
||||
"promptSha256": "6f965f73e86093cb17311cf28689ad07736cb739b59e8912ff5e9bebe69078c6"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user