Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions docs/production-incident-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -6227,6 +6227,57 @@ ClickHouse-precondition logs stop in production.
- Re-check Sentry for new Postgres connection-reset events after the next
deploy.

## 2026-05-20: Dashboard Sleep Stale Because Runtime Read Used Postgres v_sleep

### Symptoms

The dashboard sleep card was not up to date even though new raw sleep records
had synced. Production `fitness.sleep_session` contained sleep through
`2026-05-20` for WHOOP and Apple Health, while the Postgres materialized view
`fitness.v_sleep` only exposed stale sleep rows.

### User Impact

Dashboard and recovery surfaces that read `fitness.v_sleep` could display old
sleep duration, efficiency, sleep need, readiness, stress, anomaly, prediction,
and healthspan inputs.

### Evidence

Production raw sleep queries showed current rows for user
`f923fed7-d934-4cd9-8cb9-8e83020d0e69`, including WHOOP and Apple Health sleep
on `2026-05-20`. The corresponding `fitness.v_sleep` query was stale, with
latest Apple Health on `2026-05-06` and WHOOP on `2026-04-27`. ClickHouse
`analytics.v_sleep` was current, including WHOOP sleep ending
`2026-05-20 06:02:39.090000`.

### Root Cause

Runtime dashboard and recovery code still depended on the stale Postgres
materialized sleep view after ClickHouse had become the current deduped sleep
read model.

### Fix or Mitigation

This branch moves runtime sleep reads to ClickHouse `analytics.v_sleep`, keeps
Postgres only for raw `sleep_stage` interval lookups, removes the canonical
Postgres `v_sleep` view artifact, and adds migration `0025_drop_v_sleep.sql` to
drop both `clickhouse.v_sleep` and `fitness.v_sleep`.

### Remaining Risk

Some historical integration tests still contain explicit
`REFRESH MATERIALIZED VIEW fitness.v_sleep` setup and need to be converted to
ClickHouse test-store sync before those suites can pass against the dropped
view.

### Follow-Up Work

- Convert the remaining sleep-related integration tests to
`createClickHouseTestActivitySensorStore()` and
`syncClickHouseTestActivitySensorStore()`.
- Add a regression test that fails on new non-test runtime references to
`fitness.v_sleep`.
## 2026-05-20: Production DB Restart During IMU Sync

### Symptoms
Expand Down
110 changes: 110 additions & 0 deletions docs/superpowers/plans/2026-05-20-clickhouse-sleep-dashboard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# ClickHouse Sleep Dashboard Implementation Plan

> Follow the step-by-step checklist below and mark tasks complete using `- [ ]` syntax.

**Goal:** Remove dashboard/runtime dependence on stale `fitness.v_sleep` and read deduped sleep data from ClickHouse `analytics.v_sleep`.

**Architecture:** Keep raw sleep writes in Postgres. Treat ClickHouse `analytics.v_sleep` as the runtime deduped sleep read model and fail loudly when a route needs it without `ctx.sensorStore`. Keep Postgres only for raw `sleep_stage` rows where stage intervals are not mirrored yet.

**Tech Stack:** TypeScript, tRPC, Zod, Drizzle SQL for Postgres, `ActivitySensorStore.query()` for ClickHouse, Vitest.

---

## Task 1: Add Red Tests For ClickHouse Sleep Reads

**Files:**
- Modify: `packages/server/src/repositories/sleep-repository.test.ts`
- Modify: `packages/server/src/routers/sleep-need.test.ts`
- Modify: `packages/server/src/routers/mobile-dashboard.test.ts`

- [ ] **Step 1: Add repository tests proving list/latest sleep data comes from the sensor store**

Add tests that construct `SleepRepository` with `makeMockSensorStore()` and assert `analytics.v_sleep` appears in the ClickHouse query while `db.execute` is not called for `list()` and `getLatest()`.

- [ ] **Step 2: Add router tests proving sleep need and mobile dashboard use ClickHouse sleep rows**

Add tests that return sleep rows from `sensorStore.query()` and assert generated query strings include `analytics.v_sleep` and do not include `fitness.v_sleep`.

- [ ] **Step 3: Run red tests**

Run:

```bash
pnpm vitest packages/server/src/repositories/sleep-repository.test.ts packages/server/src/routers/sleep-need.test.ts packages/server/src/routers/mobile-dashboard.test.ts
```

Expected: FAIL because production code still queries `fitness.v_sleep`.

## Task 2: Add Shared ClickHouse Sleep Helpers

**Files:**
- Create: `packages/server/src/repositories/clickhouse-sleep-repository.ts`
- Modify: `packages/server/src/routers/test-helpers.ts`

- [ ] **Step 1: Implement helper functions**

Create helpers for one-row-per-night sleep queries over `analytics.v_sleep`, including `fetchSleepNights()`, `fetchLatestSleepNight()`, and `fetchSleepEfficiencyByDate()`.

- [ ] **Step 2: Parse query results with Zod**

Use schemas with nullable numeric fields and string dates/timestamps, matching the existing route output contracts.

## Task 3: Switch Dashboard Sleep Routes

**Files:**
- Modify: `packages/server/src/repositories/sleep-repository.ts`
- Modify: `packages/server/src/routers/sleep.ts`
- Modify: `packages/server/src/routers/sleep-need.ts`
- Modify: `packages/server/src/routers/mobile-dashboard.ts`
- Modify: `packages/server/src/routers/recovery.ts`
- Modify: `packages/server/src/routers/stress.ts`

- [ ] **Step 1: Pass `ctx.sensorStore` into `SleepRepository`**

Routes that expose sleep list/latest data should require ClickHouse for deduped sleep data.

- [ ] **Step 2: Replace `fitness.v_sleep` dashboard joins with ClickHouse helper output**

Keep daily metrics in Postgres where they already live, but fetch sleep rows from ClickHouse and combine in TypeScript or via small values CTEs.

- [ ] **Step 3: Keep stage interval reads on raw Postgres tables**

`getStages()` and `getLatestStages()` can still read `fitness.sleep_stage`, but the selected/latest sleep session should come from ClickHouse.

## Task 4: Remove Postgres Materialized View Ownership

**Files:**
- Add: `drizzle/0025_drop_v_sleep.sql`
- Delete: `drizzle/_views/02_v_sleep.sql`
- Modify docs mentioning the old Postgres materialized view.

- [ ] **Step 1: Add a forward migration that drops `fitness.v_sleep`**

Use `DROP MATERIALIZED VIEW IF EXISTS fitness.v_sleep;` with no replacement compatibility view.

- [ ] **Step 2: Remove the canonical Postgres view file**

Delete `drizzle/_views/02_v_sleep.sql` so future deploy tooling cannot recreate the materialized view.

## Task 5: Verify

**Files:**
- Modify: tests touched by the route/repository changes.

- [ ] **Step 1: Run targeted tests**

Run:

```bash
pnpm vitest packages/server/src/repositories/sleep-repository.test.ts packages/server/src/routers/sleep-need.test.ts packages/server/src/routers/mobile-dashboard.test.ts packages/server/src/routers/recovery.test.ts packages/server/src/routers/stress.test.ts
```

- [ ] **Step 2: Search for remaining runtime references**

Run:

```bash
rg -n "fitness\\.v_sleep|REFRESH MATERIALIZED VIEW.*v_sleep" packages/server/src src drizzle docs
```

Expected: no production runtime references to `fitness.v_sleep`; historical docs/tests may mention it only when describing removal.
2 changes: 2 additions & 0 deletions drizzle/0025_drop_v_sleep.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DROP VIEW IF EXISTS clickhouse.v_sleep;
DROP MATERIALIZED VIEW IF EXISTS fitness.v_sleep;
117 changes: 0 additions & 117 deletions drizzle/_views/02_v_sleep.sql

This file was deleted.

10 changes: 0 additions & 10 deletions packages/server/src/billing/entitlement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,6 @@ export function dateAccessPredicate(window: AccessWindow | undefined, column: SQ
AND ${column} < ${window.endDateExclusive}::date`;
}

/**
* Returns a SQL predicate fragment that restricts a timestamp column to the
* billing access window. Returns an empty fragment for full-access or absent windows.
*/
export function timestampAccessPredicate(window: AccessWindow | undefined, column: SQL): SQL {
if (!window || window.kind === "full") return sql``;
return sql`AND ${column} >= ${window.startDate}::date
AND ${column} < ${window.endDateExclusive}::date`;
}

export function resolveAccessWindow(input: ResolveAccessWindowInput): AccessWindow {
if (input.paidGrantReason) {
return { kind: "full", paid: true, reason: "paid_grant" };
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/insights/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const dailyRowSchema = z.object({
skin_temp_c: z.number().nullable(),
});

/** Zod schema for rows from fitness.v_sleep used by insights/correlation queries. */
/** Zod schema for sleep rows used by insights/correlation queries. */
export const sleepRowSchema = z.object({
started_at: timestampStringSchema,
duration_minutes: z.number().nullable(),
Expand Down
29 changes: 0 additions & 29 deletions packages/server/src/lib/sql-fragments.test.ts

This file was deleted.

Loading
Loading