Skip to content
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
cfef569
perf(analytics): bound power curve builds
Asherlc Jul 26, 2026
b69e412
test(analytics): update power eligibility fixture
Asherlc Jul 26, 2026
e81b6ed
docs(ops): record SAST registry outage
Asherlc Jul 26, 2026
c51911e
Merge remote-tracking branch 'origin/main' into Asherlc/use-subagents
Asherlc Jul 26, 2026
c6beae1
fix(analytics): preserve bounded power progress
Asherlc Jul 26, 2026
f86b76e
fix(analytics): order ClickHouse FINAL clause
Asherlc Jul 26, 2026
b59a46e
test(analytics): isolate power progress fixtures
Asherlc Jul 26, 2026
6c9446c
test(analytics): match power lifecycle schema
Asherlc Jul 26, 2026
33b6dc1
Merge remote-tracking branch 'origin/main' into Asherlc/use-subagents
Asherlc Jul 26, 2026
ea8efc6
fix(mobile): defer background WHOOP init
Asherlc Jul 26, 2026
d0d3d7f
fix(mobile): serialize initial WHOOP sync
Asherlc Jul 26, 2026
d13fe4f
fix(mobile): stop WHOOP sync on background
Asherlc Jul 26, 2026
8177587
test(mobile): await WHOOP stream startup
Asherlc Jul 26, 2026
de3ed01
Merge remote-tracking branch 'origin/main' into Asherlc/use-subagents
Asherlc Jul 26, 2026
c6fb426
fix(analytics): accept current dbt statuses
Asherlc Jul 26, 2026
6b14d54
Merge remote-tracking branch 'origin/main' into Asherlc/use-subagents
Asherlc Jul 26, 2026
a867312
perf(server): use monthly serving models
Asherlc Jul 26, 2026
3783b5e
refactor(server): drop report timezone input
Asherlc Jul 26, 2026
5aab1d4
test(server): cover report serving lifecycle
Asherlc Jul 26, 2026
f833747
docs(perf): record report query evidence
Asherlc Jul 26, 2026
fbdb8db
test(server): verify report query bindings
Asherlc Jul 26, 2026
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
39 changes: 39 additions & 0 deletions docs/production-incident-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -17961,3 +17961,42 @@ Drizzle schema and runtime Zod schemas. Findings and remediations:
- **Remaining risk / follow-up:** Merge through normal CI, deploy the corrected
parser, observe a complete analytics cycle, then resolve
`DOFEK-SERVER-5D` if it does not recur on the fixed release.

## 2026-07-26 — Monthly Report Timed Out on Recursive Analytics Views

- **Status:** Direct fix validated locally and against production data; merge
and production deployment pending.
- **Symptoms:** Monthly report requests repeatedly raised ClickHouse client
timeouts in
[Sentry issue DOFEK-SERVER-5C](https://east-bay-software.sentry.io/issues/DOFEK-SERVER-5C).
- **User impact:** The monthly report could not load before the request's
120-second execution deadline.
- **Evidence:** The exact parameterized production repository query timed out
after 120.012 seconds while reading 3,777,652 rows and 995.16 MiB, with a
1.04 GiB peak. The equivalent aggregation over the compact
`activity_summary`, `daily_sleep`, and `daily_recovery` serving models
completed against the same production data in 0.101 seconds. The physical
serving tables contained only 3,653 activity-summary rows, 330 daily-sleep
rows, and 119 daily-recovery rows.
- **Root cause:** The request path joined `analytics.v_activity` and read
`analytics.v_sleep`, `analytics.v_daily_metrics`, and the resting-heart-rate
view, forcing global recursive deduplication and sensor aggregation for a
small user-and-month result that already existed in compact dbt-owned
serving models.
- **Fix / mitigation:** Read current activities from
`analytics.activity_summary`, daily sleep from `analytics.daily_sleep FINAL`,
and daily vitals from `analytics.daily_recovery FINAL`. Preserve the
monthly response shape and calculations without adding a timeout, retry, or
cache fallback. ClickHouse documents `FINAL` as the query modifier that
applies an engine's merge logic to the selected data:
<https://clickhouse.com/docs/sql-reference/statements/select/from#final-modifier>.
- **Validation:** A real-ClickHouse regression test first failed after its
recursive test views were removed, reproducing the old repository's hard
dependency on `v_activity`. It now seeds only the three compact serving
models and verifies the complete monthly report result with those recursive
views absent. The focused integration test passes.
- **Remaining risk / follow-up:** Merge through normal CI, deploy the query,
invoke the production monthly report, confirm sub-second completion in
ClickHouse query history, and resolve `DOFEK-SERVER-5C` if no fixed-release
event recurs. The weekly report contains a similar recursive query and should
be investigated separately rather than silently expanded into this fix.
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { setupTestDatabase, type TestContext } from "../../../../src/db/test-helpers.ts";
import {
createClickHouseTestActivitySensorStore,
executeClickHouseTestCommand,
} from "../routers/clickhouse-integration-test-helpers.ts";
import type { ActivitySensorStore } from "./activity-repository.ts";
import { MonthlyReportRepository } from "./monthly-report-repository.ts";

const userId = "77777777-7777-4777-8777-777777777777";
const activityId = "88888888-8888-4888-8888-888888888888";

describe("MonthlyReportRepository ClickHouse read models", () => {
let testContext: TestContext;
let sensorStore: ActivitySensorStore;

beforeAll(async () => {
testContext = await setupTestDatabase();
sensorStore = await createClickHouseTestActivitySensorStore(testContext);

await executeClickHouseTestCommand(
testContext,
`INSERT INTO analytics.activity_summary (
activity_id,
user_id,
activity_type,
started_at,
ended_at,
avg_hr,
max_hr
) VALUES (
toUUID('${activityId}'),
toUUID('${userId}'),
'cycling',
toDateTime64(toStartOfMonth(today()) + INTERVAL 5 DAY, 6, 'UTC'),
toDateTime64(toStartOfMonth(today()) + INTERVAL 5 DAY + INTERVAL 1 HOUR, 6, 'UTC'),
100,
200
)`,
);
await executeClickHouseTestCommand(
testContext,
`INSERT INTO analytics.daily_sleep (
user_id,
date,
provider_id,
started_at,
duration_minutes,
refresh_version,
is_deleted,
refreshed_at
) VALUES (
toUUID('${userId}'),
toDate(toStartOfMonth(today()) + INTERVAL 5 DAY),
'test-provider',
toDateTime64(toStartOfMonth(today()) + INTERVAL 5 DAY, 6, 'UTC'),
300,
1,
0,
now64(9)
), (
toUUID('${userId}'),
toDate(toStartOfMonth(today()) + INTERVAL 5 DAY),
'test-provider',
toDateTime64(toStartOfMonth(today()) + INTERVAL 5 DAY, 6, 'UTC'),
480,
2,
0,
now64(9)
), (
toUUID('${userId}'),
toDate(toStartOfMonth(today()) + INTERVAL 6 DAY),
'test-provider',
toDateTime64(toStartOfMonth(today()) + INTERVAL 6 DAY, 6, 'UTC'),
600,
1,
0,
now64(9)
), (
toUUID('${userId}'),
toDate(toStartOfMonth(today()) + INTERVAL 6 DAY),
'test-provider',
toDateTime64(toStartOfMonth(today()) + INTERVAL 6 DAY, 6, 'UTC'),
600,
2,
1,
now64(9)
)`,
);
await executeClickHouseTestCommand(
testContext,
`INSERT INTO analytics.daily_recovery (
user_id,
date,
hrv,
resting_hr,
is_deleted,
refresh_version,
refreshed_at
) VALUES (
toUUID('${userId}'),
toDate(toStartOfMonth(today()) + INTERVAL 5 DAY),
40,
60,
0,
1,
now64(9)
), (
toUUID('${userId}'),
toDate(toStartOfMonth(today()) + INTERVAL 5 DAY),
60,
50,
0,
2,
now64(9)
), (
toUUID('${userId}'),
toDate(toStartOfMonth(today()) + INTERVAL 6 DAY),
80,
45,
0,
1,
now64(9)
), (
toUUID('${userId}'),
toDate(toStartOfMonth(today()) + INTERVAL 6 DAY),
80,
45,
1,
2,
now64(9)
)`,
);

for (const recursiveView of ["v_activity", "v_sleep", "v_daily_metrics"]) {
await executeClickHouseTestCommand(testContext, `DROP TABLE analytics.${recursiveView} SYNC`);
}
}, 120_000);

afterAll(async () => {
await testContext?.cleanup();
});

it("builds the report from compact serving models without recursive views", async () => {
const report = await new MonthlyReportRepository(userId, sensorStore).getReport(12);

expect(report.current).toEqual({
monthStart: `${new Date().toISOString().slice(0, 7)}-01`,
trainingHours: 1,
activityCount: 1,
avgDailyStrain: 30,
avgSleepMinutes: 480,
avgRestingHr: 50,
avgHrv: 60,
trainingHoursTrend: null,
avgSleepTrend: null,
});
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved
expect(report.history).toHaveLength(12);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ describe("MonthlyReportRepository", () => {
getHeartRateCurveRows: vi.fn(),
getPaceCurveRows: vi.fn(),
};
const repo = new MonthlyReportRepository("user-1", sensorStore, "America/Los_Angeles");
const repo = new MonthlyReportRepository("user-1", sensorStore);
return { repo, execute: query };
}

Expand Down Expand Up @@ -169,17 +169,6 @@ describe("MonthlyReportRepository", () => {
expect(result.current?.avgHrv).toBeNull();
});

it("uses the configured timezone for resting heart rate dates", async () => {
const { repo, execute } = makeRepository([]);
await repo.getReport(6);

expect(execute).toHaveBeenCalledWith(
expect.anything(),
expect.any(String),
expect.objectContaining({ timezone: "America/Los_Angeles" }),
);
});

it("returns null trend when previous training hours is zero", async () => {
const { repo } = makeRepository([
makeDbRow({ month_start: "2025-01-01", training_hours: 0, avg_sleep_minutes: 0 }),
Expand Down
39 changes: 14 additions & 25 deletions packages/server/src/repositories/monthly-report-repository.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { z } from "zod";
import { dateWindowStartString } from "../lib/date-window.ts";
import { dateStringSchema } from "../lib/typed-sql.ts";
import type { ActivitySensorStore } from "./activity-repository.ts";
import { restingHeartRateClickHouseCte } from "./resting-heart-rate-query.ts";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -116,30 +114,22 @@ export class MonthRow {
export class MonthlyReportRepository {
readonly #userId: string;
readonly #sensorStore: ActivitySensorStore;
readonly #timezone: string;

constructor(userId: string, sensorStore: ActivitySensorStore, timezone = "UTC") {
constructor(userId: string, sensorStore: ActivitySensorStore) {
this.#userId = userId;
this.#sensorStore = sensorStore;
this.#timezone = timezone;
}

async getReport(months: number): Promise<MonthlyReportResult> {
const today = new Date().toISOString().slice(0, 10);
const rhrWindowStart = dateWindowStartString(today, months * 31 + 31);
const rows = await this.#sensorStore.query(
monthRowSchema,
`WITH ${restingHeartRateClickHouseCte()},
per_activity AS (
`WITH per_activity AS (
SELECT
toDate(asum.started_at) AS date,
dateDiff('second', asum.started_at, asum.ended_at) / 3600.0 AS hours,
dateDiff('second', asum.started_at, asum.ended_at) / 60.0
* asum.avg_hr / nullIf(toFloat64(asum.max_hr), 0) AS load
FROM analytics.activity_summary asum
INNER JOIN analytics.v_activity va
ON va.id = asum.activity_id
AND va.user_id = asum.user_id
WHERE asum.user_id = {userId:UUID}
AND asum.started_at >= toStartOfMonth(today()) - INTERVAL {months:Int32} MONTH
AND asum.ended_at IS NOT NULL
Expand All @@ -151,11 +141,11 @@ export class MonthlyReportRepository {
GROUP BY date
),
sleep_raw AS (
SELECT toDate(started_at) AS date, duration_minutes
FROM analytics.v_sleep
SELECT date, duration_minutes
FROM analytics.daily_sleep FINAL
WHERE user_id = {userId:UUID}
AND is_nap = false
AND started_at >= toStartOfMonth(today()) - INTERVAL {months:Int32} MONTH
AND is_deleted = 0
AND date >= toStartOfMonth(today()) - INTERVAL {months:Int32} MONTH
),
sleep_daily AS (
SELECT date, max(duration_minutes) AS duration_minutes
Expand All @@ -164,14 +154,13 @@ export class MonthlyReportRepository {
),
metrics_daily AS (
SELECT
dm.date AS date,
drhr.resting_hr AS resting_hr,
dm.hrv AS hrv
FROM analytics.v_daily_metrics AS dm
LEFT JOIN resting_heart_rate AS drhr
ON drhr.date = toString(dm.date)
WHERE dm.user_id = {userId:UUID}
AND dm.date >= toStartOfMonth(today()) - INTERVAL {months:Int32} MONTH
recovery.date AS date,
recovery.resting_hr AS resting_hr,
recovery.hrv AS hrv
FROM analytics.daily_recovery AS recovery FINAL
WHERE recovery.user_id = {userId:UUID}
AND recovery.is_deleted = 0
AND recovery.date >= toStartOfMonth(today()) - INTERVAL {months:Int32} MONTH
),
date_series AS (
SELECT toStartOfMonth(today()) - INTERVAL {months:Int32} MONTH + INTERVAL number DAY AS date
Expand All @@ -191,7 +180,7 @@ export class MonthlyReportRepository {
LEFT JOIN metrics_daily m ON m.date = d.date
GROUP BY toStartOfMonth(d.date)
ORDER BY month_start ASC`,
{ userId: this.#userId, timezone: this.#timezone, months, rhrEndDate: today, rhrWindowStart },
{ userId: this.#userId, months },
);

const monthRows = rows.map((row) => new MonthRow(row));
Expand Down
4 changes: 1 addition & 3 deletions packages/server/src/routers/health-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ export const healthReportRouter = router({
input.weeks,
input.endDate,
)
: await new MonthlyReportRepository(ctx.userId, ctx.sensorStore, ctx.timezone).getReport(
input.months,
);
: await new MonthlyReportRepository(ctx.userId, ctx.sensorStore).getReport(input.months);

if (!reportData.current) {
throw new TRPCError({
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/routers/monthly-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const monthlyReportRouter = router({
.input(z.object({ months: z.number().min(1).max(24).default(6) }))
.query(async ({ ctx, input }): Promise<MonthlyReportResult> => {
const sensorStore = requireSensorStore(ctx.sensorStore, "monthlyReport.report");
const repo = new MonthlyReportRepository(ctx.userId, sensorStore, ctx.timezone);
const repo = new MonthlyReportRepository(ctx.userId, sensorStore);
return repo.getReport(input.months);
}),
});
Loading