mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
feat(rollups): schema scaffolding for mood + medication-compliance + cumulative-sum tiers
Three additive Prisma additions land in one commit so the v1.4.39 wave agents (W-MOOD, W-MED, W-SUM) build against a stable generated client: - `mood_entry_rollups`: per-(user, granularity, bucket) mood stats (count / mean / min / max / sd). Reuses the existing `measurement_rollup_granularity` enum. - `medication_compliance_rollups`: per-(user, medication, day) scheduled / taken / skipped triple. `day` is the user-tz-anchored YYYY-MM-DD string so multi-instance reads do not re-derive boundaries. - `measurement_rollups.sum_value`: nullable column. Cumulative-metric read paths consume it directly; boot backfill folds NULLs on first reach. Migrations 0070 / 0071 / 0072 use IF NOT EXISTS + DO $$ EXCEPTION WHEN duplicate_object guards (mirror 0061 / 0067 / 0069). No ALTER on existing tables that downgrade row contracts, no DROP. Backward-safe read paths land in the wave agents that follow. Includes `.planning/round-v1438-perf-analysis.md` — the read-only audit that anchors the wave plan.
This commit is contained in:
1 parent
2fd344ed2d
commit
0d33f91d01
5 files changed
+767
No files matched your search
@@ -0,0 +1,41 @@
|
||||
-- v1.4.39 W-MOOD — persistent mood rollup table.
|
||||
--
|
||||
-- Second cache tier behind the 60-s LRU on /api/mood/analytics. Per-
|
||||
-- (userId, granularity, bucketStart) stats so the read path skips the
|
||||
-- unbounded MoodEntry.findMany walk that drove the 12.7 s cold mount on
|
||||
-- power-user accounts.
|
||||
--
|
||||
-- Granularity reuses the existing `measurement_rollup_granularity` enum
|
||||
-- so the worker / cross-granularity readers share a single type.
|
||||
--
|
||||
-- Additive only — no ALTER on existing tables, no DROP. The primary key
|
||||
-- `(user_id, granularity, bucket_start)` guarantees idempotent upserts
|
||||
-- under re-run; the IF NOT EXISTS guard makes the migration replay-safe
|
||||
-- on partially-applied environments (mirrors 0061 / 0067 / 0068 / 0069).
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "mood_entry_rollups" (
|
||||
"user_id" TEXT NOT NULL,
|
||||
"granularity" "measurement_rollup_granularity" NOT NULL,
|
||||
"bucket_start" TIMESTAMPTZ(3) NOT NULL,
|
||||
"count" INTEGER NOT NULL,
|
||||
"mean" DOUBLE PRECISION NOT NULL,
|
||||
"min_score" INTEGER NOT NULL,
|
||||
"max_score" INTEGER NOT NULL,
|
||||
"sd" DOUBLE PRECISION,
|
||||
"computed_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "mood_entry_rollups_pkey"
|
||||
PRIMARY KEY ("user_id", "granularity", "bucket_start")
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "mood_entry_rollups_user_granularity_bucket_desc_idx"
|
||||
ON "mood_entry_rollups" ("user_id", "granularity", "bucket_start" DESC);
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "mood_entry_rollups"
|
||||
ADD CONSTRAINT "mood_entry_rollups_user_id_fkey"
|
||||
FOREIGN KEY ("user_id") REFERENCES "users"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
@@ -0,0 +1,49 @@
|
||||
-- v1.4.39 W-MED — persistent medication compliance rollup table.
|
||||
--
|
||||
-- Replaces the unbounded MedicationIntakeEvent.findMany walk on
|
||||
-- `/api/medications/intake?scope=compliance` and the equivalent fan-out
|
||||
-- inside `computeUserHealthScoreFastPath`. Per-(userId, medicationId,
|
||||
-- day) stats with scheduled / taken / skipped counts.
|
||||
--
|
||||
-- `day` is a TEXT column (YYYY-MM-DD anchored to the user's timezone)
|
||||
-- rather than a DATE because the day-key has to survive a
|
||||
-- multi-instance read that may pick a different node than the writer.
|
||||
-- Storing the user-tz-anchored string removes the per-row tz round-trip
|
||||
-- the writer would otherwise have to perform.
|
||||
--
|
||||
-- Additive only. PK + FK + descending index for the "last N days" read
|
||||
-- path. IF NOT EXISTS / EXCEPTION guards mirror 0067 / 0069 / 0070.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "medication_compliance_rollups" (
|
||||
"user_id" TEXT NOT NULL,
|
||||
"medication_id" TEXT NOT NULL,
|
||||
"day" TEXT NOT NULL,
|
||||
"scheduled" INTEGER NOT NULL,
|
||||
"taken" INTEGER NOT NULL,
|
||||
"skipped" INTEGER NOT NULL,
|
||||
"computed_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "medication_compliance_rollups_pkey"
|
||||
PRIMARY KEY ("user_id", "medication_id", "day")
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "medication_compliance_rollups_user_day_desc_idx"
|
||||
ON "medication_compliance_rollups" ("user_id", "day" DESC);
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "medication_compliance_rollups"
|
||||
ADD CONSTRAINT "medication_compliance_rollups_user_id_fkey"
|
||||
FOREIGN KEY ("user_id") REFERENCES "users"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "medication_compliance_rollups"
|
||||
ADD CONSTRAINT "medication_compliance_rollups_medication_id_fkey"
|
||||
FOREIGN KEY ("medication_id") REFERENCES "medications"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- v1.4.39 W-SUM — cumulative-metric sumValue column on measurement_rollups.
|
||||
--
|
||||
-- Cumulative measurement types (ACTIVITY_STEPS, FLIGHTS_CLIMBED,
|
||||
-- WALKING_RUNNING_DISTANCE, TIME_IN_DAYLIGHT, ACTIVE_ENERGY) report
|
||||
-- per-event slices; the analytics + dashboard hot paths need the
|
||||
-- per-day SUM, not the per-day MEAN. Today those paths fall through to
|
||||
-- `pickCumulativeDaySum` in JS over the chunked per-type series.
|
||||
--
|
||||
-- Adding `sum_value` directly on the rollup row lets the read path
|
||||
-- consume it via a single bounded findMany. Nullable because existing
|
||||
-- rows pre-date the writer change; the boot-time backfill folds NULLs
|
||||
-- into populated values on first reach (deterministic upsert with the
|
||||
-- same composite PK).
|
||||
--
|
||||
-- Additive only — IF NOT EXISTS guard mirrors 0068.
|
||||
|
||||
ALTER TABLE "measurement_rollups"
|
||||
ADD COLUMN IF NOT EXISTS "sum_value" DOUBLE PRECISION;
|
||||
@@ -284,6 +284,17 @@ model User {
|
||||
// 22:00 window (the cron fires every 15 min — without the ledger
|
||||
// a user could see three pushes back-to-back).
|
||||
moodReminderDispatches MoodReminderDispatch[]
|
||||
// v1.4.39 W-MOOD — per-(user, granularity, bucket) mood rollup. New
|
||||
// tier behind the mood-analytics read path; per-write hooks fold
|
||||
// MoodEntry mutations into the DAY granularity inline so the next
|
||||
// read serves from this table instead of the unbounded
|
||||
// MoodEntry.findMany walk.
|
||||
moodEntryRollups MoodEntryRollup[]
|
||||
// v1.4.39 W-MED — per-(user, medication, day) compliance rollup.
|
||||
// Per-write hook on MedicationIntakeEvent mutations + the scheduler
|
||||
// keep the row in sync so `/api/medications/intake?scope=compliance`
|
||||
// and `computeUserHealthScoreFastPath` skip the per-event findMany.
|
||||
medicationComplianceRollups MedicationComplianceRollup[]
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
@@ -522,6 +533,13 @@ model MeasurementRollup {
|
||||
sd Float?
|
||||
slope Float?
|
||||
r2 Float?
|
||||
/// v1.4.39 W-SUM — cumulative-metric sum for the bucket. Populated
|
||||
/// alongside `mean / count` for every type; cumulative read paths
|
||||
/// (steps, flights, distance, daylight, active-energy) consume this
|
||||
/// directly instead of re-deriving from raw measurements. Nullable
|
||||
/// to keep the migration additive — the boot backfill fills NULLs
|
||||
/// for existing rows; new rows always carry the sum.
|
||||
sumValue Float? @map("sum_value")
|
||||
computedAt DateTime @default(now()) @map("computed_at") @db.Timestamptz(3)
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
@@ -723,6 +741,10 @@ model Medication {
|
||||
/// roll-up (GI / METABOLIC / INJECTION_SITE / COGNITIVE /
|
||||
/// GLP1_SPECIFIC) and 1-5 Likert severity per entry.
|
||||
sideEffects MedicationSideEffect[]
|
||||
/// v1.4.39 W-MED — per-(medication, day) compliance rollup. Mutations
|
||||
/// on the linked MedicationIntakeEvent rows refresh the row inline;
|
||||
/// the read paths consume this instead of the per-event findMany.
|
||||
complianceRollups MedicationComplianceRollup[]
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@ -1211,6 +1233,79 @@ model MoodReminderDispatch {
|
||||
@@map("mood_reminder_dispatches")
|
||||
}
|
||||
|
||||
// ─── Mood Entry Rollup (v1.4.39 W-MOOD) ───────────────────────
|
||||
//
|
||||
// Second cache tier behind the 60-s LRU on `/api/mood/analytics`.
|
||||
// One row per `(userId, granularity, bucketStart)` carrying the
|
||||
// `count` + `mean` + min/max + population SD over the bucket window.
|
||||
// `RollupGranularity` from the measurement rollup tier is reused so
|
||||
// the worker / future cross-granularity readers share a single enum.
|
||||
//
|
||||
// Write path: every MoodEntry create/update/delete fires
|
||||
// `recomputeMoodBucketsForEntry` which upserts the DAY bucket for
|
||||
// the entry's `(userId, dayKey)` inline. WEEK / MONTH / YEAR are
|
||||
// enqueued through pg-boss for the worker to fold so the write path
|
||||
// stays sub-ms.
|
||||
//
|
||||
// Read path: `/api/mood/analytics` reads `prisma.moodEntryRollup.
|
||||
// findMany({ where: { userId, granularity: 'DAY' } })` and runs the
|
||||
// existing summarize() logic against the rollup instead of pulling
|
||||
// every MoodEntry into Node.
|
||||
//
|
||||
// Stats semantics (population, not sample): `sd = STDDEV_POP(score)`
|
||||
// over the bucket window so two-tier cached / live reads agree
|
||||
// byte-for-byte the same way the MeasurementRollup tier does.
|
||||
model MoodEntryRollup {
|
||||
userId String @map("user_id")
|
||||
granularity RollupGranularity
|
||||
bucketStart DateTime @map("bucket_start") @db.Timestamptz(3)
|
||||
count Int
|
||||
mean Float
|
||||
minScore Int @map("min_score")
|
||||
maxScore Int @map("max_score")
|
||||
sd Float?
|
||||
computedAt DateTime @default(now()) @map("computed_at") @db.Timestamptz(3)
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([userId, granularity, bucketStart])
|
||||
@@index([userId, granularity, bucketStart(sort: Desc)])
|
||||
@@map("mood_entry_rollups")
|
||||
}
|
||||
|
||||
// ─── Medication Compliance Rollup (v1.4.39 W-MED) ─────────────
|
||||
//
|
||||
// Per-(userId, medicationId, day) compliance ledger. Replaces the
|
||||
// unbounded MedicationIntakeEvent findMany on
|
||||
// `/api/medications/intake?scope=compliance` and the equivalent
|
||||
// fan-out inside `computeUserHealthScoreFastPath`.
|
||||
//
|
||||
// Day-key is anchored to the user's IANA timezone (TEXT, encoded as
|
||||
// `YYYY-MM-DD`) so the read path can collapse a date range into a
|
||||
// straight WHERE clause without re-deriving the boundary per row.
|
||||
//
|
||||
// Write path: every MedicationIntakeEvent create / update / delete
|
||||
// (and the scheduler that mints fresh `scheduledFor` rows) fires
|
||||
// `recomputeMedicationComplianceForDay` which upserts the
|
||||
// `(user, medication, day)` row. Worker handles weekly / monthly
|
||||
// re-fold off the hot path.
|
||||
model MedicationComplianceRollup {
|
||||
userId String @map("user_id")
|
||||
medicationId String @map("medication_id")
|
||||
day String // YYYY-MM-DD anchored to user.timezone
|
||||
scheduled Int
|
||||
taken Int
|
||||
skipped Int
|
||||
computedAt DateTime @default(now()) @map("computed_at") @db.Timestamptz(3)
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
medication Medication @relation(fields: [medicationId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([userId, medicationId, day])
|
||||
@@index([userId, day(sort: Desc)])
|
||||
@@map("medication_compliance_rollups")
|
||||
}
|
||||
|
||||
// ─── Integration Status (v1.4.15) ─────────────────────────
|
||||
//
|
||||
// Per-(user, integration) row that captures the most recent sync attempt
|
||||
|
||||
Reference in new issue
Block a user