diff --git a/analytics/README.md b/analytics/README.md index 230ed9fcec..96e5e92b79 100644 --- a/analytics/README.md +++ b/analytics/README.md @@ -25,8 +25,14 @@ over `analytics.activity_summary_rows FINAL`; the expensive activity/sample joins belong in incremental dbt models, not in web/API requests. Complex offline ClickHouse models can set dbt `query_settings` locally and use `max_threads=1` so offline builds do not compete with request traffic. -`provider_stats` materializes provider record counts for the sync provider -inventory route so the API does not compute all-provider counts on request. +`recovery_read_model`, `strain_read_model`, and `healthspan_read_model` are +the named dashboard serving read models. They build on compact ingredient +models such as `daily_recovery_inputs`, `daily_activity_load`, and +`healthspan_activity_zone_minutes` so dashboard, recovery, stress, +sleep-need, and healthspan routes do not recompute broad windows at request +time. `provider_stats` materializes provider record counts for the sync +provider inventory route so the API does not compute all-provider counts on +request. `daily_recovery_inputs`, `daily_activity_load`, and `healthspan_activity_zone_minutes` are compact serving read models over daily metrics, sleep, activity summaries, and bounded activity samples for dashboard, @@ -36,12 +42,13 @@ Production `DBT_SAFE_MODELS` currently selects `sensor_scalar_sample`, `deduped_sensor`, `activity_source_records`, `activity_duplicate_matches`, `activity_duplicate_groups`, `deduped_activities`, `deduped_activity_members`, `sleep_heart_rate_sample`, `resting_heart_rate_sleep_window`, -`daily_recovery_inputs`, `activity_sensor_sample`, `activity_location_sample`, +`daily_recovery_inputs`, `recovery_read_model`, `activity_sensor_sample`, `activity_location_sample`, `activity_sensor_summary_rows`, `activity_location_summary_rows`, `activity_summary_rows`, `activity_vo2max_estimate`, `provider_stats`, -`daily_activity_load`, and `healthspan_activity_zone_minutes`. The sample-stage -and sample-intermediate models use dbt's `microbatch` incremental strategy with -`recorded_at` as the event time, daily batches, and short lookbacks so +`daily_activity_load`, `strain_read_model`, `healthspan_activity_zone_minutes`, +and `healthspan_read_model`. The sample-stage and sample-intermediate models +use dbt's `microbatch` incremental strategy with `recorded_at` as the event +time, daily batches, and short lookbacks so ClickHouse processes bounded sample-time windows instead of one large activity/window query. `deduped_activities` and `deduped_activity_members` materialize canonical activity identity once, but incremental runs only rebuild @@ -52,7 +59,8 @@ aggregate, and activity summary models use dirty keys from those intermediates and `max_threads=1` to keep the offline aggregate work out of web/API requests. `activity_vo2max_estimate` also uses dirty activity/user keys and `max_threads=1`; it materializes reusable per-activity VO2 max estimates, not -final API responses. `daily_recovery_inputs`, `daily_activity_load`, and -`healthspan_activity_zone_minutes` materialize serving inputs so request paths -do not recompute provider inventory, recovery baselines, training load, or zone -minutes from raw samples. +final API responses. `recovery_read_model`, `strain_read_model`, and +`healthspan_read_model` are the final route-facing dashboard models; the +lower-level recovery, activity-load, and zone-minute models remain internal +ingredients. `provider_stats` remains the route-facing provider inventory model +so request paths do not recompute provider counts from raw source tables. diff --git a/analytics/models/read_models/healthspan_read_model.sql b/analytics/models/read_models/healthspan_read_model.sql new file mode 100644 index 0000000000..570eb5ed79 --- /dev/null +++ b/analytics/models/read_models/healthspan_read_model.sql @@ -0,0 +1,202 @@ +{{ config( + materialized='incremental', + incremental_strategy='append', + engine='ReplacingMergeTree(refresh_version)', + order_by='(user_id, week_start)', + query_settings={ + 'max_threads': 1 + } +) }} + +WITH {% if is_incremental() %} +existing_weeks AS ( + SELECT + user_id, + max(week_start) AS latest_materialized_week_start + FROM {{ this }} + GROUP BY user_id +), +{% endif %} + +sleep_by_week AS ( + SELECT + user_id, + toMonday(toDate(started_at)) AS week_start, + avg(duration_minutes) AS avg_sleep_min, + stddevPop( + if( + toHour(started_at) < 12, + toHour(started_at) * 60 + toMinute(started_at) + 1440, + toHour(started_at) * 60 + toMinute(started_at) + ) + ) AS bedtime_stddev_min + FROM analytics.v_sleep + WHERE is_nap = false + GROUP BY user_id, toMonday(toDate(started_at)) +), + +resting_by_week AS ( + SELECT + user_id, + toMonday(toDate(ended_at)) AS week_start, + avg(resting_hr) AS avg_resting_hr + FROM {{ ref('resting_heart_rate_sleep_window') }} FINAL + WHERE is_deleted = 0 + AND ended_at IS NOT null + AND resting_hr IS NOT null + GROUP BY user_id, toMonday(toDate(ended_at)) +), + +daily_metrics_by_week AS ( + SELECT + user_id, + toMonday(date) AS week_start, + avg(steps) AS avg_steps, + CAST(coalesce(sum(exercise_minutes), 0), 'Float64') AS weekly_exercise_min + FROM analytics.v_daily_metrics + GROUP BY user_id, toMonday(date) +), + +zone_minutes_by_week AS ( + SELECT + user_id, + toMonday(toDate(started_at)) AS week_start, + CAST(sum(aerobic_minutes), 'Float64') AS weekly_aerobic_min, + CAST(sum(high_intensity_minutes), 'Float64') AS weekly_high_intensity_min + FROM {{ ref('healthspan_activity_zone_minutes') }} FINAL + WHERE is_deleted = 0 + AND started_at IS NOT null + GROUP BY user_id, toMonday(toDate(started_at)) +), + +strength_by_week AS ( + SELECT + user_id, + toMonday(toDate(started_at)) AS week_start, + countIf(activity_type = 'strength') AS strength_sessions + FROM {{ ref('deduped_activities') }} FINAL + WHERE is_deleted = 0 + AND started_at IS NOT null + GROUP BY user_id, toMonday(toDate(started_at)) +), + +vo2_by_week AS ( + SELECT + user_id, + toMonday(toDate(started_at)) AS week_start, + argMax(vo2max, started_at) AS latest_vo2max + FROM {{ ref('activity_vo2max_estimate') }} FINAL + WHERE is_deleted = 0 + GROUP BY user_id, toMonday(toDate(started_at)) +), + +body_by_week AS ( + SELECT + user_id, + toMonday(toDate(recorded_at)) AS week_start, + argMax(weight_kg, recorded_at) AS weight_kg, + argMax(body_fat_pct, recorded_at) AS body_fat_pct + FROM analytics.v_body_measurement + GROUP BY user_id, toMonday(toDate(recorded_at)) +), + +week_keys AS ( + SELECT + user_id, + week_start + FROM sleep_by_week + UNION DISTINCT + SELECT + user_id, + week_start + FROM resting_by_week + UNION DISTINCT + SELECT + user_id, + week_start + FROM daily_metrics_by_week + UNION DISTINCT + SELECT + user_id, + week_start + FROM zone_minutes_by_week + UNION DISTINCT + SELECT + user_id, + week_start + FROM strength_by_week + UNION DISTINCT + SELECT + user_id, + week_start + FROM vo2_by_week + UNION DISTINCT + SELECT + user_id, + week_start + FROM body_by_week +), + +week_keys_to_materialize AS ( + SELECT + week_keys.user_id AS user_id, + week_keys.week_start AS week_start + FROM week_keys + {% if is_incremental() %} + LEFT JOIN existing_weeks + ON existing_weeks.user_id = week_keys.user_id + WHERE existing_weeks.user_id IS null + OR week_keys.week_start >= existing_weeks.latest_materialized_week_start - INTERVAL 26 WEEK + {% endif %} +), + +refresh_clock AS ( + SELECT + toUInt64(toUnixTimestamp64Nano(now64(9))) AS refresh_version, + now64(9) AS refreshed_at +) + +SELECT + CAST(week_keys_to_materialize.user_id, 'UUID') AS user_id, + CAST(week_keys_to_materialize.week_start, 'Date') AS week_start, + sleep_by_week.avg_sleep_min AS avg_sleep_min, + sleep_by_week.bedtime_stddev_min AS bedtime_stddev_min, + resting_by_week.avg_resting_hr AS avg_resting_hr, + daily_metrics_by_week.avg_steps AS avg_steps, + vo2_by_week.latest_vo2max AS latest_vo2max, + greatest( + coalesce(zone_minutes_by_week.weekly_aerobic_min, toFloat64(0)), + coalesce(daily_metrics_by_week.weekly_exercise_min, toFloat64(0)) + ) AS weekly_aerobic_min, + coalesce( + zone_minutes_by_week.weekly_high_intensity_min, + toFloat64(0) + ) AS weekly_high_intensity_min, + CAST(strength_by_week.strength_sessions, 'Nullable(Float64)') AS sessions_per_week, + body_by_week.weight_kg AS weight_kg, + body_by_week.body_fat_pct AS body_fat_pct, + refresh_clock.refresh_version AS refresh_version, + refresh_clock.refreshed_at AS refreshed_at +FROM week_keys_to_materialize +LEFT JOIN sleep_by_week + ON sleep_by_week.user_id = week_keys_to_materialize.user_id + AND sleep_by_week.week_start = week_keys_to_materialize.week_start +LEFT JOIN resting_by_week + ON resting_by_week.user_id = week_keys_to_materialize.user_id + AND resting_by_week.week_start = week_keys_to_materialize.week_start +LEFT JOIN daily_metrics_by_week + ON daily_metrics_by_week.user_id = week_keys_to_materialize.user_id + AND daily_metrics_by_week.week_start = week_keys_to_materialize.week_start +LEFT JOIN zone_minutes_by_week + ON zone_minutes_by_week.user_id = week_keys_to_materialize.user_id + AND zone_minutes_by_week.week_start = week_keys_to_materialize.week_start +LEFT JOIN strength_by_week + ON strength_by_week.user_id = week_keys_to_materialize.user_id + AND strength_by_week.week_start = week_keys_to_materialize.week_start +LEFT JOIN vo2_by_week + ON vo2_by_week.user_id = week_keys_to_materialize.user_id + AND vo2_by_week.week_start = week_keys_to_materialize.week_start +LEFT JOIN body_by_week + ON body_by_week.user_id = week_keys_to_materialize.user_id + AND body_by_week.week_start = week_keys_to_materialize.week_start +CROSS JOIN refresh_clock diff --git a/analytics/models/read_models/read_model_microbatch.sql.test.ts b/analytics/models/read_models/read_model_microbatch.sql.test.ts index d1a598fc71..d14ea1478e 100644 --- a/analytics/models/read_models/read_model_microbatch.sql.test.ts +++ b/analytics/models/read_models/read_model_microbatch.sql.test.ts @@ -54,6 +54,7 @@ describe("production analytics read-model build", () => { "sleep_heart_rate_sample", "resting_heart_rate_sleep_window", "daily_recovery_inputs", + "recovery_read_model", "activity_sensor_sample", "activity_location_sample", "activity_sensor_summary_rows", @@ -62,7 +63,9 @@ describe("production analytics read-model build", () => { "activity_vo2max_estimate", "provider_stats", "daily_activity_load", + "strain_read_model", "healthspan_activity_zone_minutes", + "healthspan_read_model", ]); }); @@ -364,6 +367,42 @@ describe("production analytics read-model build", () => { expect(sql).not.toContain("ref('deduped_sensor')"); }); + it("materializes the recovery serving read model from daily recovery inputs", () => { + const sql = readModel("recovery_read_model"); + const normalizedSql = compactWhitespace(sql); + + expect(sql).toContain("materialized='incremental'"); + expect(sql).toContain("engine='ReplacingMergeTree(refresh_version)'"); + expect(sql).toContain("{% if is_incremental() %}"); + expect(sql).toContain("existing_dates AS"); + expect(sql).toContain("latest_materialized_refreshed_at"); + expect(normalizedSql).toContain("recovery_inputs.refreshed_at > existing_dates.latest_materialized_refreshed_at"); + expect(normalizedSql).toContain("existing_dates.latest_materialized_date - INTERVAL 60 DAY"); + expect(sql).toContain("ref('daily_recovery_inputs')"); + expect(sql).toContain("hrv_score"); + expect(sql).toContain("resting_hr_score"); + expect(sql).toContain("sleep_score"); + expect(sql).toContain("respiratory_rate_score"); + }); + + it("materializes the strain serving read model from activity load rows", () => { + const sql = readModel("strain_read_model"); + const normalizedSql = compactWhitespace(sql); + + expect(sql).toContain("materialized='incremental'"); + expect(sql).toContain("engine='ReplacingMergeTree(refresh_version)'"); + expect(sql).toContain("{% if is_incremental() %}"); + expect(sql).toContain("existing_dates AS"); + expect(normalizedSql).toContain("existing_dates.latest_materialized_date - INTERVAL 54 DAY"); + expect(normalizedSql).toContain("existing_dates.latest_materialized_date - INTERVAL 27 DAY"); + expect(sql).toContain("output_min_date"); + expect(sql).toContain("ref('daily_activity_load')"); + expect(sql).toContain("acute_load_7d"); + expect(sql).toContain("chronic_load_28d"); + expect(sql).toContain("workload_ratio"); + expect(sql).toContain("strain"); + }); + it("materializes healthspan zone minutes from bounded activity samples", () => { const sql = readModel("healthspan_activity_zone_minutes"); const normalizedSql = compactWhitespace(sql); @@ -382,4 +421,25 @@ describe("production analytics read-model build", () => { expect(normalizedSql).toContain("sensor_samples.activity_id = activity_metadata.activity_id"); expect(normalizedSql).toContain("sensor_samples.user_id = activity_metadata.user_id"); }); + + it("materializes the healthspan serving read model from compact inputs", () => { + const sql = readModel("healthspan_read_model"); + const normalizedSql = compactWhitespace(sql); + + expect(sql).toContain("materialized='incremental'"); + expect(sql).toContain("engine='ReplacingMergeTree(refresh_version)'"); + expect(sql).toContain("{% if is_incremental() %}"); + expect(sql).toContain("existing_weeks AS"); + expect(normalizedSql).toContain("existing_weeks.latest_materialized_week_start - INTERVAL 26 WEEK"); + expect(sql).toContain("ref('healthspan_activity_zone_minutes')"); + expect(sql).toContain("ref('resting_heart_rate_sleep_window')"); + expect(sql).toContain("ref('activity_vo2max_estimate')"); + expect(sql).toContain("toMonday(toDate(started_at)) AS week_start"); + expect(sql).not.toContain("activity_date"); + expect(sql).toContain("argMax(vo2max, started_at) AS latest_vo2max"); + expect(sql).toContain("avg_sleep_min"); + expect(sql).toContain("weekly_aerobic_min"); + expect(sql).toContain("weekly_high_intensity_min"); + expect(sql).toContain("latest_vo2max"); + }); }); diff --git a/analytics/models/read_models/recovery_read_model.sql b/analytics/models/read_models/recovery_read_model.sql new file mode 100644 index 0000000000..346053e72a --- /dev/null +++ b/analytics/models/read_models/recovery_read_model.sql @@ -0,0 +1,170 @@ +{{ config( + materialized='incremental', + incremental_strategy='append', + engine='ReplacingMergeTree(refresh_version)', + order_by='(user_id, date)', + query_settings={ + 'max_threads': 1 + } +) }} + +WITH {% if is_incremental() %} +existing_dates AS ( + SELECT + user_id, + max(date) AS latest_materialized_date, + max(refreshed_at) AS latest_materialized_refreshed_at + FROM {{ this }} + GROUP BY user_id +), +{% endif %} + +recovery_inputs AS ( + SELECT + user_id, + date, + hrv, + resting_hr, + respiratory_rate, + efficiency_pct, + hrv_mean_30d, + hrv_sd_30d, + rhr_mean_30d, + rhr_sd_30d, + rr_mean_30d, + rr_sd_30d, + hrv_mean_60d, + hrv_sd_60d, + rhr_mean_60d, + rhr_sd_60d, + refreshed_at + FROM {{ ref('daily_recovery_inputs') }} FINAL +), + +recovery_inputs_to_materialize AS ( + SELECT + recovery_inputs.user_id AS user_id, + recovery_inputs.date AS date, + recovery_inputs.hrv AS hrv, + recovery_inputs.resting_hr AS resting_hr, + recovery_inputs.respiratory_rate AS respiratory_rate, + recovery_inputs.efficiency_pct AS efficiency_pct, + recovery_inputs.hrv_mean_30d AS hrv_mean_30d, + recovery_inputs.hrv_sd_30d AS hrv_sd_30d, + recovery_inputs.rhr_mean_30d AS rhr_mean_30d, + recovery_inputs.rhr_sd_30d AS rhr_sd_30d, + recovery_inputs.rr_mean_30d AS rr_mean_30d, + recovery_inputs.rr_sd_30d AS rr_sd_30d, + recovery_inputs.hrv_mean_60d AS hrv_mean_60d, + recovery_inputs.hrv_sd_60d AS hrv_sd_60d, + recovery_inputs.rhr_mean_60d AS rhr_mean_60d, + recovery_inputs.rhr_sd_60d AS rhr_sd_60d + FROM recovery_inputs + {% if is_incremental() %} + LEFT JOIN existing_dates + ON existing_dates.user_id = recovery_inputs.user_id + WHERE existing_dates.user_id IS NULL + OR recovery_inputs.refreshed_at > existing_dates.latest_materialized_refreshed_at + OR recovery_inputs.date >= existing_dates.latest_materialized_date - INTERVAL 60 DAY + {% endif %} +), + +scored AS ( + SELECT + *, + if( + hrv IS NOT NULL AND hrv_mean_30d IS NOT NULL AND hrv_sd_30d IS NOT NULL AND hrv_sd_30d > 0, + (hrv - hrv_mean_30d) / hrv_sd_30d, + CAST(NULL, 'Nullable(Float64)') + ) AS hrv_z_score, + if( + resting_hr IS NOT NULL AND rhr_mean_30d IS NOT NULL AND rhr_sd_30d IS NOT NULL AND rhr_sd_30d > 0, + -1 * ((resting_hr - rhr_mean_30d) / rhr_sd_30d), + CAST(NULL, 'Nullable(Float64)') + ) AS resting_hr_z_score, + if( + respiratory_rate IS NOT NULL AND rr_mean_30d IS NOT NULL AND rr_sd_30d IS NOT NULL AND rr_sd_30d > 0, + -1 * ((respiratory_rate - rr_mean_30d) / rr_sd_30d), + CAST(NULL, 'Nullable(Float64)') + ) AS respiratory_rate_z_score, + if( + efficiency_pct IS NOT NULL, + least(100, greatest(0, round(efficiency_pct))), + 62 + ) AS sleep_score + FROM recovery_inputs_to_materialize +), + +sigmoid_inputs AS ( + SELECT + *, + if(hrv_z_score IS NULL, CAST(NULL, 'Nullable(Float64)'), 1 / (1 + exp(-hrv_z_score * 1.1))) AS hrv_sigmoid, + if(resting_hr_z_score IS NULL, CAST(NULL, 'Nullable(Float64)'), 1 / (1 + exp(-resting_hr_z_score * 1.1))) AS resting_hr_sigmoid, + if(respiratory_rate_z_score IS NULL, CAST(NULL, 'Nullable(Float64)'), 1 / (1 + exp(-respiratory_rate_z_score * 1.1))) AS respiratory_rate_sigmoid + FROM scored +), + +sigmoid_scores AS ( + SELECT + *, + if( + hrv_sigmoid IS NULL, + 62, + least(100, greatest(0, round(if( + hrv_sigmoid >= 0.5, + 62 + 38 * ((hrv_sigmoid - 0.5) / 0.5), + 62 - 62 * ((0.5 - hrv_sigmoid) / 0.5) + )))) + ) AS hrv_score, + if( + resting_hr_sigmoid IS NULL, + 62, + least(100, greatest(0, round(if( + resting_hr_sigmoid >= 0.5, + 62 + 38 * ((resting_hr_sigmoid - 0.5) / 0.5), + 62 - 62 * ((0.5 - resting_hr_sigmoid) / 0.5) + )))) + ) AS resting_hr_score, + if( + respiratory_rate_sigmoid IS NULL, + 62, + least(100, greatest(0, round(if( + respiratory_rate_sigmoid >= 0.5, + 62 + 38 * ((respiratory_rate_sigmoid - 0.5) / 0.5), + 62 - 62 * ((0.5 - respiratory_rate_sigmoid) / 0.5) + )))) + ) AS respiratory_rate_score + FROM sigmoid_inputs +), + +refresh_clock AS ( + SELECT + toUInt64(toUnixTimestamp64Nano(now64(9))) AS refresh_version, + now64(9) AS refreshed_at +) + +SELECT + CAST(user_id, 'UUID') AS user_id, + CAST(date, 'Date') AS date, + hrv, + resting_hr, + respiratory_rate, + efficiency_pct, + hrv_mean_30d, + hrv_sd_30d, + rhr_mean_30d, + rhr_sd_30d, + rr_mean_30d, + rr_sd_30d, + hrv_mean_60d, + hrv_sd_60d, + rhr_mean_60d, + rhr_sd_60d, + hrv_score, + resting_hr_score, + sleep_score, + respiratory_rate_score, + refresh_clock.refresh_version AS refresh_version, + refresh_clock.refreshed_at AS refreshed_at +FROM sigmoid_scores +CROSS JOIN refresh_clock diff --git a/analytics/models/read_models/strain_read_model.sql b/analytics/models/read_models/strain_read_model.sql new file mode 100644 index 0000000000..0d467fd1ca --- /dev/null +++ b/analytics/models/read_models/strain_read_model.sql @@ -0,0 +1,134 @@ +{{ config( + materialized='incremental', + incremental_strategy='append', + engine='ReplacingMergeTree(refresh_version)', + order_by='(user_id, date)', + query_settings={ + 'max_threads': 1 + } +) }} + +WITH {% if is_incremental() %} +existing_dates AS ( + SELECT + user_id, + max(date) AS latest_materialized_date + FROM {{ this }} + GROUP BY user_id +), +{% endif %} + +activity_load AS ( + SELECT + user_id, + toDate(started_at) AS date, + coalesce(sum(daily_load), 0) AS daily_load + FROM {{ ref('daily_activity_load') }} FINAL + WHERE started_at IS NOT NULL + GROUP BY user_id, toDate(started_at) +), + +activity_users AS ( + SELECT + user_id, + min(date) AS first_activity_date, + max(date) AS latest_activity_date + FROM activity_load + GROUP BY user_id +), + +date_bounds AS ( + SELECT + activity_users.user_id AS user_id, + {% if is_incremental() %} + if( + existing_dates.latest_materialized_date IS NULL, + activity_users.first_activity_date, + greatest( + activity_users.first_activity_date, + existing_dates.latest_materialized_date - INTERVAL 54 DAY + ) + ) AS calculation_min_date, + if( + existing_dates.latest_materialized_date IS NULL, + activity_users.first_activity_date, + greatest( + activity_users.first_activity_date, + existing_dates.latest_materialized_date - INTERVAL 27 DAY + ) + ) AS output_min_date, + {% else %} + activity_users.first_activity_date AS calculation_min_date, + activity_users.first_activity_date AS output_min_date, + {% endif %} + greatest(activity_users.latest_activity_date, today()) AS max_date + FROM activity_users + {% if is_incremental() %} + LEFT JOIN existing_dates + ON existing_dates.user_id = activity_users.user_id + {% endif %} +), + +date_series AS ( + SELECT + user_id, + calculation_min_date + INTERVAL date_offset DAY AS date + FROM date_bounds + ARRAY JOIN range( + toUInt32(dateDiff('day', calculation_min_date, max_date) + 1) + ) AS date_offset +), + +daily AS ( + SELECT + date_series.user_id AS user_id, + date_series.date AS date, + coalesce(activity_load.daily_load, 0) AS daily_load + FROM date_series + LEFT JOIN activity_load + ON activity_load.user_id = date_series.user_id + AND activity_load.date = date_series.date +), + +with_windows AS ( + SELECT + user_id, + date, + daily_load, + sum(daily_load) OVER ( + PARTITION BY user_id ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW + ) AS acute_load_7d, + avg(daily_load) OVER ( + PARTITION BY user_id ORDER BY date ROWS BETWEEN 27 PRECEDING AND CURRENT ROW + ) * 7 AS chronic_load_28d, + count() OVER ( + PARTITION BY user_id ORDER BY date ROWS BETWEEN 27 PRECEDING AND CURRENT ROW + ) AS chronic_count + FROM daily +), + +refresh_clock AS ( + SELECT + toUInt64(toUnixTimestamp64Nano(now64(9))) AS refresh_version, + now64(9) AS refreshed_at +) + +SELECT + CAST(with_windows.user_id, 'UUID') AS user_id, + CAST(with_windows.date, 'Date') AS date, + with_windows.daily_load AS daily_load, + least(21, round(2.775 * log(1 + greatest(with_windows.daily_load, 0)), 1)) AS strain, + with_windows.acute_load_7d AS acute_load_7d, + with_windows.chronic_load_28d AS chronic_load_28d, + if( + with_windows.chronic_load_28d > 0 AND with_windows.chronic_count = 28, + with_windows.acute_load_7d / with_windows.chronic_load_28d, + NULL + ) AS workload_ratio, + refresh_clock.refresh_version AS refresh_version, + refresh_clock.refreshed_at AS refreshed_at +FROM with_windows +INNER JOIN date_bounds + ON date_bounds.user_id = with_windows.user_id +CROSS JOIN refresh_clock +WHERE with_windows.date >= date_bounds.output_min_date diff --git a/deploy/README.md b/deploy/README.md index aaad6c6f5f..a72e946fcd 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -45,7 +45,7 @@ Dofek production is deployed as a **single-node Docker Swarm** stack on Oracle C - The `db` service has a 2 GiB container memory limit to prevent one PostgreSQL workload from exhausting the single-node host. If it hits that limit, treat it as a query/workload incident rather than increasing the cap by default. - PostgreSQL runs `timescale/timescaledb-ha:pg18.3-ts2.26.4-all` so TimescaleDB and PostGIS are both available. It is configured with `max_connections=40`, `work_mem=4MB`, `maintenance_work_mem=64MB`, `max_locks_per_transaction=4096` for large Timescale chunk scans, and logical replication settings needed by ClickHouse change-data capture. Production keeps six logical slots/senders and caps each slot at 16 GiB of retained WAL so PeerDB has recovery headroom without allowing an inactive slot to retain unbounded WAL. - ClickHouse has a 13 GiB container memory limit, a 1 CPU Swarm limit, and a checked-in `clickhouse_memory_limits_13g` profile with a 13 GiB `max_server_memory_usage` cap so large analytics queries fail or throttle inside ClickHouse instead of triggering host-level OOM kills or CPU-starving SSH/Docker on the single-node host. It also loads checked-in server profile settings from `deploy/clickhouse/users.d/` and server settings from `deploy/clickhouse/config.d/`; the production stack mounts these as Docker Swarm configs so app-managed geospatial `Nullable(Point)` columns, bounded memory, and seven-day system-log TTL retention work without manual server changes. Docker Swarm config contents are immutable, so changing a checked-in config file must also rotate the config key in `deploy/stack.yml` (for example `clickhouse_memory_limits_13g`) instead of reusing the same config name with new contents. -- All production entrypoint modes that run dbt use `--threads 1 --select $DBT_SAFE_MODELS` to avoid concurrent or unsafe ClickHouse model builds on the single-node host. `analytics-worker` also has a 0.5 CPU Swarm limit and currently runs the dbt-native microbatched `sensor_scalar_sample` and `deduped_sensor` models plus the dirty-keyed `activity_vo2max_estimate` model every 15 minutes. `analytics.activity_summary` is served from the incremental `analytics.activity_summary_rows` table through a thin view so dashboard workload routes do not recompute activity/sample joins on demand. Failed dbt runs sleep before retrying instead of exiting into an immediate Swarm restart loop. +- All production entrypoint modes that run dbt use `--threads 1 --select $DBT_SAFE_MODELS` to avoid concurrent or unsafe ClickHouse model builds on the single-node host. `analytics-worker` also has a 0.5 CPU Swarm limit and currently runs the dbt-native microbatched `sensor_scalar_sample` and `deduped_sensor` models plus the dirty-keyed dashboard read models every 15 minutes. `analytics.activity_summary` is served from the incremental `analytics.activity_summary_rows` table through a thin view, and `analytics.recovery_read_model`, `analytics.strain_read_model`, and `analytics.healthspan_read_model` are the named route-facing models for dashboard recovery, strain, and healthspan reads. Failed dbt runs sleep before retrying instead of exiting into an immediate Swarm restart loop. - Netdata has a 768 MiB container memory limit and a checked-in `deploy/netdata/netdata.conf` that bounds dbengine retention to two tiers: one day of per-second data capped at 96 MiB and seven days of per-minute data capped at 128 MiB. The stack mounts this file as a Docker Swarm config, so changing it must also rotate the config key in `deploy/stack.yml` (for example `netdata_db_limits_v2`). - PeerDB uses an internal catalog Postgres service, Temporal, worker services, and a private MinIO staging bucket. Its persistent catalog and staging data live under `/mnt/dofek-data/peerdb-catalog` and `/mnt/dofek-data/peerdb-minio`. The catalog uses the PostgreSQL 18 image layout: mount the host directory at `/var/lib/postgresql`, not `/var/lib/postgresql/data`, so the image can manage its versioned data directory. Production mirrors use 100,000-row CDC batches and single-worker 100,000-row initial snapshot partitions so PeerDB can stay inside its fixed memory limits at the cost of slower catch-up. - `metric_stream` storage controls (Timescale hypertable + compression) are managed via `docs/metric-stream-timescaledb-runbook.md` and `drizzle/0006_metric_stream_timescale_policies.sql`. diff --git a/docs/production-incident-baseline.md b/docs/production-incident-baseline.md index a487a08efa..9265bb40d8 100644 --- a/docs/production-incident-baseline.md +++ b/docs/production-incident-baseline.md @@ -10120,6 +10120,33 @@ new incremental tables are populated. or otherwise pre-aggregate the coverage buckets; simply increasing the database memory limit would leave the request-time scan pattern in place. +### 2026-06-04 dashboard metrics still slow without route-facing read models + +- Symptoms: Dashboard and related recovery, strain, and healthspan API calls + still did too much request-time aggregation after the first serving-model + rollout. +- User impact: Dashboard cards could load slowly or time out when routes fanned + out across ClickHouse ingredient models or PostgreSQL views instead of compact + route-facing tables. +- Evidence: Route code still queried ingredient models such as + `analytics.daily_recovery_inputs`, `analytics.daily_activity_load`, and + healthspan source views directly from API handlers. +- Root cause: The serving layer had intermediate dbt models, but no named + dashboard read models for the API contracts the UI actually needs. +- Fix / mitigation: Added dbt-owned incremental ClickHouse models + `analytics.recovery_read_model`, `analytics.strain_read_model`, and + `analytics.healthspan_read_model`, added deploy-time empty table creation, + and switched the affected server routes/repositories to read those compact + models. +- Remaining risk: Post-deploy Axiom/Sentry checks should confirm request + latency improves and that the UTC daily bucketing in the strain read model is + acceptable for route-facing workload displays. +- Follow-Up Work: Run post-deploy Axiom and Sentry checks for the affected + dashboard routes, verify `analytics.recovery_read_model` and + `analytics.healthspan_read_model` remain stable under scheduled dbt builds, + and add a short-term dashboard latency alert if route-facing latency remains + above the pre-read-model baseline. + ### 2026-06-04 Mobile WHOOP BLE tRPC non-JSON response - Symptoms: Sentry issue `DOFEK-MOBILE-B` reported production mobile diff --git a/entrypoint.sh b/entrypoint.sh index 9572d4c24e..69d2c15ae0 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -18,7 +18,7 @@ fi # Node 22+ natively handles TypeScript — transform-types also rewrites .ts imports NODE="node --experimental-transform-types --enable-source-maps --disable-warning=ExperimentalWarning --import ./src/opentelemetry-hook.mjs --import ./src/instrumentation.ts" -DBT_SAFE_MODELS="sensor_scalar_sample deduped_sensor activity_source_records activity_duplicate_matches activity_duplicate_groups deduped_activities deduped_activity_members sleep_heart_rate_sample resting_heart_rate_sleep_window daily_recovery_inputs activity_sensor_sample activity_location_sample activity_sensor_summary_rows activity_location_summary_rows activity_summary_rows activity_vo2max_estimate provider_stats daily_activity_load healthspan_activity_zone_minutes" +DBT_SAFE_MODELS="sensor_scalar_sample deduped_sensor activity_source_records activity_duplicate_matches activity_duplicate_groups deduped_activities deduped_activity_members sleep_heart_rate_sample resting_heart_rate_sleep_window daily_recovery_inputs recovery_read_model activity_sensor_sample activity_location_sample activity_sensor_summary_rows activity_location_summary_rows activity_summary_rows activity_vo2max_estimate provider_stats daily_activity_load strain_read_model healthspan_activity_zone_minutes healthspan_read_model" case "${1:-sync}" in web) diff --git a/packages/server/src/repositories/stress-repository.test.ts b/packages/server/src/repositories/stress-repository.test.ts index aa7219c8b9..87221975de 100644 --- a/packages/server/src/repositories/stress-repository.test.ts +++ b/packages/server/src/repositories/stress-repository.test.ts @@ -50,7 +50,7 @@ describe("StressRepository", () => { await repo.getStressScores(90, "2024-01-15"); const queryText = sensorStore.query.mock.calls[0]?.[1]; - expect(queryText).toContain("analytics.daily_recovery_inputs"); + expect(queryText).toContain("analytics.recovery_read_model AS recovery_inputs FINAL"); expect(queryText).not.toContain("fitness.v_daily_metrics"); expect(queryText).not.toContain("analytics.v_sleep"); }); diff --git a/packages/server/src/repositories/stress-repository.ts b/packages/server/src/repositories/stress-repository.ts index 5f8a6fd4a6..492dc441ff 100644 --- a/packages/server/src/repositories/stress-repository.ts +++ b/packages/server/src/repositories/stress-repository.ts @@ -123,7 +123,7 @@ export class StressRepository extends BaseRepository { rhr_mean_60d, rhr_sd_60d, efficiency_pct - FROM analytics.daily_recovery_inputs AS recovery_inputs + FROM analytics.recovery_read_model AS recovery_inputs FINAL WHERE recovery_inputs.user_id = {userId:UUID} AND recovery_inputs.date > toDate({windowStart:String}) AND recovery_inputs.date <= toDate({endDate:String}) diff --git a/packages/server/src/routers/clickhouse-integration-test-helpers.test.ts b/packages/server/src/routers/clickhouse-integration-test-helpers.test.ts index 7b087c0e72..75115cda1e 100644 --- a/packages/server/src/routers/clickhouse-integration-test-helpers.test.ts +++ b/packages/server/src/routers/clickhouse-integration-test-helpers.test.ts @@ -22,10 +22,13 @@ const testAnalyticsViewNames = [ "analytics.deduped_sensor", "analytics.resting_heart_rate_sleep_window", "analytics.daily_recovery_inputs", + "analytics.recovery_read_model", "analytics.deduped_location", "analytics.activity_summary", "analytics.daily_activity_load", + "analytics.strain_read_model", "analytics.healthspan_activity_zone_minutes", + "analytics.healthspan_read_model", "analytics.activity_trend_daily", ]; @@ -133,6 +136,13 @@ describe("clickhouse integration test helpers", () => { command.includes(".daily_recovery_inputs"), ), ).toBe(true); + expect( + setupCommands.some( + (command) => + command.includes("CREATE TABLE IF NOT EXISTS analytics_test_") && + command.includes(".recovery_read_model"), + ), + ).toBe(true); expect( setupCommands.some( (command) => @@ -140,6 +150,13 @@ describe("clickhouse integration test helpers", () => { command.includes(".daily_activity_load"), ), ).toBe(true); + expect( + setupCommands.some( + (command) => + command.includes("CREATE TABLE IF NOT EXISTS analytics_test_") && + command.includes(".strain_read_model"), + ), + ).toBe(true); expect( setupCommands.some( (command) => @@ -147,6 +164,13 @@ describe("clickhouse integration test helpers", () => { command.includes(".healthspan_activity_zone_minutes"), ), ).toBe(true); + expect( + setupCommands.some( + (command) => + command.includes("CREATE TABLE IF NOT EXISTS analytics_test_") && + command.includes(".healthspan_read_model"), + ), + ).toBe(true); clickHouseMocks.command.mockClear(); @@ -295,6 +319,14 @@ describe("clickhouse integration test helpers", () => { command.includes(".v_daily_metrics"), ), ).toBe(true); + expect( + commands.some( + (command) => + command.includes("INSERT INTO analytics_test_") && + command.includes(".recovery_read_model") && + command.includes(".daily_recovery_inputs"), + ), + ).toBe(true); expect( commands.some( (command) => @@ -309,6 +341,14 @@ describe("clickhouse integration test helpers", () => { command.includes(".activity_summary"), ), ).toBe(true); + expect( + commands.some( + (command) => + command.includes("INSERT INTO analytics_test_") && + command.includes(".strain_read_model") && + command.includes(".daily_activity_load"), + ), + ).toBe(true); expect( commands.some( (command) => @@ -317,5 +357,13 @@ describe("clickhouse integration test helpers", () => { command.includes(".activity_sensor_sample"), ), ).toBe(true); + expect( + commands.some( + (command) => + command.includes("INSERT INTO analytics_test_") && + command.includes(".healthspan_read_model") && + command.includes(".v_daily_metrics"), + ), + ).toBe(true); }); }); diff --git a/packages/server/src/routers/clickhouse-integration-test-helpers.ts b/packages/server/src/routers/clickhouse-integration-test-helpers.ts index f9aee92048..bb79e9dacd 100644 --- a/packages/server/src/routers/clickhouse-integration-test-helpers.ts +++ b/packages/server/src/routers/clickhouse-integration-test-helpers.ts @@ -296,11 +296,14 @@ const analyticsBuildOrder = [ "analytics.deduped_activities", "analytics.resting_heart_rate_sleep_window", "analytics.daily_recovery_inputs", + "analytics.recovery_read_model", "analytics.deduped_location", "analytics.activity_sensor_sample", "analytics.activity_summary", "analytics.daily_activity_load", + "analytics.strain_read_model", "analytics.healthspan_activity_zone_minutes", + "analytics.healthspan_read_model", "analytics.activity_trend_daily", ] as const; @@ -402,6 +405,28 @@ hrv_sd_60d Nullable(Float64), rhr_mean_60d Nullable(Float64), rhr_sd_60d Nullable(Float64), refresh_version UInt64, +refreshed_at DateTime64(9)`, + recovery_read_model: `user_id UUID, +date Date, +hrv Nullable(Float64), +resting_hr Nullable(Float64), +respiratory_rate Nullable(Float64), +efficiency_pct Nullable(Float64), +hrv_mean_30d Nullable(Float64), +hrv_sd_30d Nullable(Float64), +rhr_mean_30d Nullable(Float64), +rhr_sd_30d Nullable(Float64), +rr_mean_30d Nullable(Float64), +rr_sd_30d Nullable(Float64), +hrv_mean_60d Nullable(Float64), +hrv_sd_60d Nullable(Float64), +rhr_mean_60d Nullable(Float64), +rhr_sd_60d Nullable(Float64), +hrv_score Nullable(Float64), +resting_hr_score Nullable(Float64), +sleep_score Nullable(Float64), +respiratory_rate_score Nullable(Float64), +refresh_version UInt64, refreshed_at DateTime64(9)`, v_body_measurement: `id UUID, provider_id String, @@ -541,6 +566,15 @@ started_at DateTime64(6, 'UTC'), ended_at DateTime64(6, 'UTC'), daily_load Nullable(Float64), refresh_version UInt64, +refreshed_at DateTime64(9)`, + strain_read_model: `user_id UUID, +date Date, +daily_load Float64, +strain Float64, +acute_load_7d Float64, +chronic_load_28d Float64, +workload_ratio Nullable(Float64), +refresh_version UInt64, refreshed_at DateTime64(9)`, healthspan_activity_zone_minutes: `activity_id UUID, user_id UUID, @@ -550,6 +584,20 @@ aerobic_minutes Float64, high_intensity_minutes Float64, is_deleted UInt8, refresh_version UInt64, +refreshed_at DateTime64(9)`, + healthspan_read_model: `user_id UUID, +week_start Date, +avg_sleep_min Nullable(Float64), +bedtime_stddev_min Nullable(Float64), +avg_resting_hr Nullable(Float64), +avg_steps Nullable(Float64), +latest_vo2max Nullable(Float64), +weekly_aerobic_min Float64, +weekly_high_intensity_min Float64, +sessions_per_week Nullable(Float64), +weight_kg Nullable(Float64), +body_fat_pct Nullable(Float64), +refresh_version UInt64, refreshed_at DateTime64(9)`, activity_trend_daily: `user_id UUID, bucket_date Date, @@ -578,8 +626,11 @@ activity_count UInt64`, shortViewName === "deduped_activities" || shortViewName === "activity_sensor_sample" || shortViewName === "daily_recovery_inputs" || + shortViewName === "recovery_read_model" || shortViewName === "daily_activity_load" || + shortViewName === "strain_read_model" || shortViewName === "healthspan_activity_zone_minutes" || + shortViewName === "healthspan_read_model" || shortViewName === "provider_stats" ? "ReplacingMergeTree(refresh_version)" : "MergeTree"; @@ -590,12 +641,18 @@ activity_count UInt64`, ? "(user_id, activity_id, recorded_date, channel, recorded_at)" : shortViewName === "daily_recovery_inputs" ? "(user_id, date)" - : shortViewName === "daily_activity_load" || - shortViewName === "healthspan_activity_zone_minutes" - ? "(user_id, activity_id)" - : shortViewName === "provider_stats" - ? "(user_id, provider_id)" - : "tuple()"; + : shortViewName === "recovery_read_model" + ? "(user_id, date)" + : shortViewName === "daily_activity_load" || + shortViewName === "healthspan_activity_zone_minutes" + ? "(user_id, activity_id)" + : shortViewName === "strain_read_model" + ? "(user_id, date)" + : shortViewName === "healthspan_read_model" + ? "(user_id, week_start)" + : shortViewName === "provider_stats" + ? "(user_id, provider_id)" + : "tuple()"; return `CREATE TABLE IF NOT EXISTS ${viewName} ( ${columnDefinitions} ) @@ -924,6 +981,183 @@ FROM activity_load CROSS JOIN refresh_clock`; } +function buildTestRecoveryReadModelSelectSql(databases: IsolatedClickHouseDatabases): string { + return `SELECT + user_id, + date, + hrv, + resting_hr, + respiratory_rate, + efficiency_pct, + hrv_mean_30d, + hrv_sd_30d, + rhr_mean_30d, + rhr_sd_30d, + rr_mean_30d, + rr_sd_30d, + hrv_mean_60d, + hrv_sd_60d, + rhr_mean_60d, + rhr_sd_60d, + CAST(NULL, 'Nullable(Float64)') AS hrv_score, + CAST(NULL, 'Nullable(Float64)') AS resting_hr_score, + CAST(NULL, 'Nullable(Float64)') AS sleep_score, + CAST(NULL, 'Nullable(Float64)') AS respiratory_rate_score, + refresh_version, + refreshed_at +FROM ${databases.analytics}.daily_recovery_inputs`; +} + +function buildTestStrainReadModelSelectSql(databases: IsolatedClickHouseDatabases): string { + return `WITH activity_load AS ( + SELECT + user_id, + toDate(started_at) AS date, + coalesce(sum(daily_load), 0) AS daily_load + FROM ${databases.analytics}.daily_activity_load + GROUP BY user_id, toDate(started_at) +), +date_bounds AS ( + SELECT + user_id, + min(date) AS min_date, + greatest(max(date), today()) AS max_date + FROM activity_load + GROUP BY user_id +), +date_series AS ( + SELECT + date_bounds.user_id AS user_id, + date_bounds.min_date + INTERVAL number DAY AS date + FROM date_bounds + ARRAY JOIN range(toUInt32(dateDiff('day', min_date, max_date) + 1)) AS number +), +daily AS ( + SELECT + date_series.user_id AS user_id, + date_series.date AS date, + coalesce(activity_load.daily_load, 0) AS daily_load + FROM date_series + LEFT JOIN activity_load + ON activity_load.user_id = date_series.user_id + AND activity_load.date = date_series.date +), +with_windows AS ( + SELECT + user_id, + date, + daily_load, + sum(daily_load) OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS acute_load_7d, + avg(daily_load) OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN 27 PRECEDING AND CURRENT ROW) * 7 AS chronic_load_28d, + count() OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN 27 PRECEDING AND CURRENT ROW) AS chronic_count + FROM daily +), +refresh_clock AS ( + SELECT + toUInt64(toUnixTimestamp64Nano(now64(9))) AS refresh_version, + now64(9) AS refreshed_at +) +SELECT + user_id, + date, + daily_load, + least(21, round(2.775 * log(1 + greatest(daily_load, 0)), 1)) AS strain, + acute_load_7d, + chronic_load_28d, + if(chronic_load_28d > 0 AND chronic_count = 28, acute_load_7d / chronic_load_28d, NULL) AS workload_ratio, + refresh_clock.refresh_version AS refresh_version, + refresh_clock.refreshed_at AS refreshed_at +FROM with_windows +CROSS JOIN refresh_clock`; +} + +function buildTestHealthspanReadModelSelectSql(databases: IsolatedClickHouseDatabases): string { + return `WITH week_keys AS ( + SELECT + user_id, + toMonday(date) AS week_start + FROM ${databases.analytics}.v_daily_metrics + GROUP BY user_id, toMonday(date) + UNION DISTINCT + SELECT + user_id, + toMonday(toDate(started_at)) AS week_start + FROM ${databases.analytics}.healthspan_activity_zone_minutes FINAL + WHERE is_deleted = 0 + AND started_at IS NOT NULL + GROUP BY user_id, toMonday(toDate(started_at)) + UNION DISTINCT + SELECT + user_id, + toMonday(toDate(recorded_at)) AS week_start + FROM ${databases.analytics}.v_body_measurement + GROUP BY user_id, toMonday(toDate(recorded_at)) +), +metrics AS ( + SELECT + user_id, + toMonday(date) AS week_start, + avg(steps) AS avg_steps, + CAST(coalesce(sum(exercise_minutes), 0), 'Float64') AS weekly_aerobic_min + FROM ${databases.analytics}.v_daily_metrics + GROUP BY user_id, toMonday(date) +), +zone_minutes AS ( + SELECT + user_id, + toMonday(toDate(started_at)) AS week_start, + CAST(sum(aerobic_minutes), 'Float64') AS weekly_aerobic_min, + CAST(sum(high_intensity_minutes), 'Float64') AS weekly_high_intensity_min + FROM ${databases.analytics}.healthspan_activity_zone_minutes FINAL + WHERE is_deleted = 0 + AND started_at IS NOT NULL + GROUP BY user_id, toMonday(toDate(started_at)) +), +body_by_week AS ( + SELECT + user_id, + toMonday(toDate(recorded_at)) AS week_start, + argMax(weight_kg, recorded_at) AS weight_kg, + argMax(body_fat_pct, recorded_at) AS body_fat_pct + FROM ${databases.analytics}.v_body_measurement + GROUP BY user_id, toMonday(toDate(recorded_at)) +), +refresh_clock AS ( + SELECT + toUInt64(toUnixTimestamp64Nano(now64(9))) AS refresh_version, + now64(9) AS refreshed_at +) +SELECT + week_keys.user_id AS user_id, + week_keys.week_start AS week_start, + CAST(NULL, 'Nullable(Float64)') AS avg_sleep_min, + CAST(NULL, 'Nullable(Float64)') AS bedtime_stddev_min, + CAST(NULL, 'Nullable(Float64)') AS avg_resting_hr, + metrics.avg_steps AS avg_steps, + CAST(NULL, 'Nullable(Float64)') AS latest_vo2max, + greatest( + coalesce(metrics.weekly_aerobic_min, toFloat64(0)), + coalesce(zone_minutes.weekly_aerobic_min, toFloat64(0)) + ) AS weekly_aerobic_min, + coalesce(zone_minutes.weekly_high_intensity_min, toFloat64(0)) AS weekly_high_intensity_min, + CAST(NULL, 'Nullable(Float64)') AS sessions_per_week, + body_by_week.weight_kg AS weight_kg, + body_by_week.body_fat_pct AS body_fat_pct, + refresh_clock.refresh_version AS refresh_version, + refresh_clock.refreshed_at AS refreshed_at +FROM week_keys +LEFT JOIN metrics + ON metrics.user_id = week_keys.user_id + AND metrics.week_start = week_keys.week_start +LEFT JOIN zone_minutes + ON zone_minutes.user_id = week_keys.user_id + AND zone_minutes.week_start = week_keys.week_start +LEFT JOIN body_by_week + ON body_by_week.user_id = week_keys.user_id + AND body_by_week.week_start = week_keys.week_start +CROSS JOIN refresh_clock`; +} + function buildTestHealthspanActivityZoneMinutesSelectSql( databases: IsolatedClickHouseDatabases, ): string { @@ -1277,6 +1511,14 @@ AS ${buildTestDailyRecoveryInputsSelectSql({ analytics: "analytics", postgresFitness: "postgres_fitness", +})}`, + }); + await client.command({ + query: `CREATE VIEW IF NOT EXISTS analytics.recovery_read_model +AS +${buildTestRecoveryReadModelSelectSql({ + analytics: "analytics", + postgresFitness: "postgres_fitness", })}`, }); await client.command({ @@ -1285,6 +1527,14 @@ AS ${buildTestDailyActivityLoadSelectSql({ analytics: "analytics", postgresFitness: "postgres_fitness", +})}`, + }); + await client.command({ + query: `CREATE VIEW IF NOT EXISTS analytics.strain_read_model +AS +${buildTestStrainReadModelSelectSql({ + analytics: "analytics", + postgresFitness: "postgres_fitness", })}`, }); await client.command({ @@ -1293,6 +1543,14 @@ AS ${buildTestHealthspanActivityZoneMinutesSelectSql({ analytics: "analytics", postgresFitness: "postgres_fitness", +})}`, + }); + await client.command({ + query: `CREATE VIEW IF NOT EXISTS analytics.healthspan_read_model +AS +${buildTestHealthspanReadModelSelectSql({ + analytics: "analytics", + postgresFitness: "postgres_fitness", })}`, }); await client.command({ query: buildActivityVo2MaxEstimateTableSql() }); diff --git a/packages/server/src/routers/healthspan-query.test.ts b/packages/server/src/routers/healthspan-query.test.ts index 91d1b4f951..20df08a56e 100644 --- a/packages/server/src/routers/healthspan-query.test.ts +++ b/packages/server/src/routers/healthspan-query.test.ts @@ -41,12 +41,6 @@ function makeFetchContext( overrides: Partial[0]>, ): Parameters[0] { return { - db: { - execute: vi - .fn() - .mockResolvedValueOnce([{ weekly_exercise_min: null }]) - .mockResolvedValueOnce([makeRawHealthspanRow()]), - }, userId: "user-1", timezone: "UTC", accessWindow: fullAccessWindow, @@ -55,8 +49,13 @@ function makeFetchContext( } describe("fetchHealthspanRawData", () => { - it("reads precomputed zone minutes from the ClickHouse read model", async () => { - const query = vi.fn().mockResolvedValue([]); + it("reads healthspan inputs from the compact ClickHouse read model", async () => { + const query = vi.fn().mockResolvedValue([ + { + week_start: "2026-03-03", + ...makeRawHealthspanRow(), + }, + ]); const ctx = makeFetchContext({ sensorStore: makeSensorStore({ query, @@ -66,23 +65,121 @@ describe("fetchHealthspanRawData", () => { await fetchHealthspanRawData(ctx, "2026-03-15", 14); - const zoneQuery = query.mock.calls.find( - ([, queryText]) => - typeof queryText === "string" && - queryText.includes("analytics.healthspan_activity_zone_minutes"), - )?.[1]; - expect(zoneQuery).toEqual(expect.any(String)); - expect(query).toHaveBeenCalledWith( - expect.anything(), - expect.stringContaining("analytics.healthspan_activity_zone_minutes FINAL"), - expect.objectContaining({ - windowStart: "2026-03-01 00:00:00", - windowEndExclusive: "2026-03-16 00:00:00", + const queryText = query.mock.calls[0]?.[1]; + expect(queryText).toContain("analytics.healthspan_read_model"); + expect(queryText).not.toContain("analytics.healthspan_activity_zone_minutes"); + expect(queryText).not.toContain("analytics.v_sleep"); + expect(queryText).not.toContain("fitness.v_daily_metrics"); + }); + + it("aggregates weekly healthspan rows into the route raw shape", async () => { + const query = vi.fn().mockResolvedValue([ + { + week_start: "2026-03-03", + avg_sleep_min: 420, + bedtime_stddev_min: 20, + avg_resting_hr: 55, + avg_steps: 8000, + latest_vo2max: 42, + weekly_aerobic_min: 120, + weekly_high_intensity_min: 30, + sessions_per_week: 2, + weight_kg: 80, + body_fat_pct: 20, + }, + { + week_start: "2026-03-10", + avg_sleep_min: 480, + bedtime_stddev_min: 40, + avg_resting_hr: 53, + avg_steps: 10000, + latest_vo2max: 45, + weekly_aerobic_min: 180, + weekly_high_intensity_min: 60, + sessions_per_week: 3, + weight_kg: 79, + body_fat_pct: 19, + }, + ]); + const ctx = makeFetchContext({ + sensorStore: makeSensorStore({ + query, + getVo2MaxEstimates: vi.fn().mockResolvedValue([]), }), + }); + + const row = await fetchHealthspanRawData(ctx, "2026-03-15", 14); + + expect(row).toMatchObject({ + avg_sleep_min: 450, + bedtime_stddev_min: 30, + avg_resting_hr: 54, + avg_steps: 9000, + latest_vo2max: 45, + weekly_aerobic_min: 150, + weekly_high_intensity_min: 45, + sessions_per_week: 2.5, + weight_kg: 79, + body_fat_pct: 19, + weekly_history: [ + { week_start: "2026-03-03", avg_rhr: 55, avg_steps: 8000, avg_vo2max: 42 }, + { week_start: "2026-03-10", avg_rhr: 53, avg_steps: 10000, avg_vo2max: 45 }, + ], + }); + }); + + it("does not leak partial weeks for limited access windows", async () => { + const query = vi.fn().mockResolvedValue([]); + const ctx = makeFetchContext({ + accessWindow: { + kind: "limited", + paid: false, + reason: "free_signup_week", + startDate: "2026-03-05", + endDateExclusive: "2026-03-12", + }, + sensorStore: makeSensorStore({ query }), + }); + + await fetchHealthspanRawData(ctx, "2026-03-15", 14); + + const queryText = query.mock.calls[0]?.[1]; + expect(queryText).toContain("healthspan.week_start >= toDate({accessStartDate:String})"); + expect(queryText).toContain( + "healthspan.week_start + INTERVAL 7 DAY <= toDate({accessEndDateExclusive:String})", ); - expect(zoneQuery).toContain("is_deleted = 0"); - expect(zoneQuery).toContain("started_at < toDateTime({windowEndExclusive:String})"); - expect(zoneQuery).not.toContain("analytics.deduped_sensor"); - expect(zoneQuery).not.toContain("analytics.activity_summary"); + expect(queryText).not.toContain("toMonday(toDate({accessStartDate:String}))"); + expect(query.mock.calls[0]?.[2]).toMatchObject({ + accessStartDate: "2026-03-05", + accessEndDateExclusive: "2026-03-12", + }); + }); + + it("counts missing activity weeks as zero for weekly activity averages", async () => { + const query = vi.fn().mockResolvedValue([ + { + week_start: "2026-03-03", + ...makeRawHealthspanRow({ + weekly_aerobic_min: 120, + weekly_high_intensity_min: 30, + sessions_per_week: 3, + }), + }, + { + week_start: "2026-03-10", + ...makeRawHealthspanRow(), + }, + ]); + const ctx = makeFetchContext({ + sensorStore: makeSensorStore({ query }), + }); + + const row = await fetchHealthspanRawData(ctx, "2026-03-15", 14); + + expect(row).toMatchObject({ + weekly_aerobic_min: 60, + weekly_high_intensity_min: 15, + sessions_per_week: 1.5, + }); }); }); diff --git a/packages/server/src/routers/healthspan-query.ts b/packages/server/src/routers/healthspan-query.ts index f36b1474d7..046769f2ea 100644 --- a/packages/server/src/routers/healthspan-query.ts +++ b/packages/server/src/routers/healthspan-query.ts @@ -1,15 +1,6 @@ -import { averageVo2MaxEstimates } from "@dofek/training/derived-cardio"; -import { sql } from "drizzle-orm"; import { z } from "zod"; -import { dateAccessPredicate } from "../billing/entitlement.ts"; -import { dateWindowEnd, dateWindowStart, timestampWindowStart } from "../lib/date-window.ts"; -import { dateStringSchema, executeWithSchema } from "../lib/typed-sql.ts"; -import { fetchBodyCompRows } from "../repositories/body-clickhouse.ts"; -import { fetchSleepNights } from "../repositories/clickhouse-sleep-repository.ts"; -import { - fetchRestingHeartRateRows, - restingHeartRateValuesCte, -} from "../repositories/resting-heart-rate-query.ts"; +import { dateWindowStartString } from "../lib/date-window.ts"; +import { dateStringSchema } from "../lib/typed-sql.ts"; import type { AuthenticatedContext } from "../trpc.ts"; const historyRowSchema = z.object({ @@ -33,322 +24,129 @@ const rawRowSchema = z.object({ weekly_history: z.array(historyRowSchema).nullable(), }); -export type HealthspanRawRow = z.infer; - -const weeklyExerciseMinutesRowSchema = z.object({ - weekly_exercise_min: z.coerce.number().nullable(), +const healthspanReadModelRowSchema = z.object({ + week_start: dateStringSchema, + avg_sleep_min: z.coerce.number().nullable(), + bedtime_stddev_min: z.coerce.number().nullable(), + avg_resting_hr: z.coerce.number().nullable(), + avg_steps: z.coerce.number().nullable(), + latest_vo2max: z.coerce.number().nullable(), + weekly_aerobic_min: z.coerce.number().nullable(), + weekly_high_intensity_min: z.coerce.number().nullable(), + sessions_per_week: z.coerce.number().nullable(), + weight_kg: z.coerce.number().nullable(), + body_fat_pct: z.coerce.number().nullable(), }); -type WeeklyHistoryRow = z.infer; +export type HealthspanRawRow = z.infer; + +type HealthspanReadModelRow = z.infer; type HealthspanRawDataContext = Pick< AuthenticatedContext, "accessWindow" | "sensorStore" | "timezone" | "userId" -> & { - db: Parameters[0]; -}; - -function average(values: number[]): number | null { - if (values.length === 0) return null; - return values.reduce((sum, value) => sum + value, 0) / values.length; -} +>; -function populationStddev(values: number[]): number | null { - const mean = average(values); - if (mean == null) return null; - const variance = values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / values.length; - return Math.sqrt(variance); +function average(values: Array): number | null { + const presentValues = values.filter((value): value is number => value != null); + if (presentValues.length === 0) return null; + return presentValues.reduce((sum, value) => sum + value, 0) / presentValues.length; } -function bedtimeMinutes(timestamp: string, timezone: string): number | null { - const date = new Date(timestamp); - if (Number.isNaN(date.getTime())) return null; - const parts = new Intl.DateTimeFormat("en-US", { - timeZone: timezone, - hour: "2-digit", - minute: "2-digit", - hourCycle: "h23", - }).formatToParts(date); - const hour = Number(parts.find((part) => part.type === "hour")?.value); - const minute = Number(parts.find((part) => part.type === "minute")?.value); - if (!Number.isFinite(hour) || !Number.isFinite(minute)) return null; - const minutes = hour * 60 + minute; - return minutes < 720 ? minutes + 1440 : minutes; +function latestNonNullValue( + rows: HealthspanReadModelRow[], + key: TKey, +): number | null { + for (let rowIndex = rows.length - 1; rowIndex >= 0; rowIndex -= 1) { + const value = rows[rowIndex]?.[key]; + if (typeof value === "number") return value; + } + return null; } -function nextDateString(dateString: string): string { - const date = new Date(`${dateString}T00:00:00Z`); - date.setUTCDate(date.getUTCDate() + 1); - return date.toISOString().slice(0, 10); +function accessWindowClause(ctx: HealthspanRawDataContext): string { + if (ctx.accessWindow.kind === "full") return ""; + return ` + AND healthspan.week_start >= toDate({accessStartDate:String}) + AND healthspan.week_start + INTERVAL 7 DAY <= toDate({accessEndDateExclusive:String})`; } -async function fetchHrZoneTime( - ctx: HealthspanRawDataContext, - endDate: string, - totalDays: number, -): Promise<{ aerobic_minutes: number; high_intensity_minutes: number }> { - const sensorStore = ctx.sensorStore; - if (!sensorStore) return { aerobic_minutes: 0, high_intensity_minutes: 0 }; - - const windowStart = new Date(endDate); - windowStart.setUTCDate(windowStart.getUTCDate() - totalDays); - const windowStartTimestamp = windowStart - .toISOString() - .replace("T", " ") - .replace(/\.\d{3}Z$/, ""); - const windowEndExclusive = `${nextDateString(endDate)} 00:00:00`; - - const rows = await sensorStore.query( - z.object({ - aerobic_minutes: z.coerce.number(), - high_intensity_minutes: z.coerce.number(), - }), - `SELECT - coalesce(sum(aerobic_minutes), 0) AS aerobic_minutes, - coalesce(sum(high_intensity_minutes), 0) AS high_intensity_minutes - FROM analytics.healthspan_activity_zone_minutes FINAL - WHERE user_id = {userId:UUID} - AND is_deleted = 0 - AND started_at > toDateTime({windowStart:String}) - AND started_at < toDateTime({windowEndExclusive:String})`, - { - userId: ctx.userId, - windowStart: windowStartTimestamp, - windowEndExclusive, - }, - ); - - return rows[0] ?? { aerobic_minutes: 0, high_intensity_minutes: 0 }; +function accessWindowParams(ctx: HealthspanRawDataContext): Record { + if (ctx.accessWindow.kind === "full") return {}; + return { + accessStartDate: ctx.accessWindow.startDate, + accessEndDateExclusive: ctx.accessWindow.endDateExclusive, + }; } -async function fetchWeeklyExerciseMinutes( - ctx: HealthspanRawDataContext, - endDate: string, - totalDays: number, -): Promise { - const rows = await executeWithSchema( - ctx.db, - weeklyExerciseMinutesRowSchema, - sql`SELECT - (SUM(exercise_minutes)::real / GREATEST(${totalDays}::real / 7, 1)) AS weekly_exercise_min - FROM fitness.v_daily_metrics - WHERE user_id = ${ctx.userId} - AND date > ${dateWindowStart(endDate, totalDays)} - AND date <= ${dateWindowEnd(endDate)} - ${dateAccessPredicate(ctx.accessWindow, sql`date`)}`, - ); - - return rows[0]?.weekly_exercise_min ?? null; +function weeklyActivityAverage(rows: HealthspanReadModelRow[], key: keyof HealthspanReadModelRow) { + if (!rows.some((row) => typeof row[key] === "number")) return null; + const total = rows.reduce((sum, row) => { + const value = row[key]; + return sum + (typeof value === "number" ? value : 0); + }, 0); + return total / rows.length; } /** - * Fetch the raw aggregates and weekly history needed to compute a Healthspan score. - * - * Returns a single row with all nine metric inputs plus a JSON-aggregated - * weekly history for the trend subset (resting HR, steps, VO2 max). The query - * normalizes bedtime across midnight to avoid inflating the stddev for people - * whose bedtimes straddle 00:00. + * Fetch compact weekly Healthspan inputs and aggregate them for the requested window. */ export async function fetchHealthspanRawData( ctx: HealthspanRawDataContext, endDate: string, totalDays: number, ): Promise { - const restingHeartRateRows = ctx.sensorStore - ? await fetchRestingHeartRateRows({ - sensorStore: ctx.sensorStore, - userId: ctx.userId, - timezone: ctx.timezone, - endDate, - days: totalDays, - }) - : []; - const restingHeartRateCte = restingHeartRateValuesCte(restingHeartRateRows); - const hrZoneTime = await fetchHrZoneTime(ctx, endDate, totalDays); - const weeklyExerciseMin = await fetchWeeklyExerciseMinutes(ctx, endDate, totalDays); - const weeklyDivisor = Math.max(totalDays / 7, 1); - const weeklyAerobicMin = Math.max( - hrZoneTime.aerobic_minutes / weeklyDivisor, - weeklyExerciseMin ?? 0, - ); - const weeklyHighIntensityMin = hrZoneTime.high_intensity_minutes / weeklyDivisor; - const bodyMeasurements = ctx.sensorStore - ? await fetchBodyCompRows(ctx.sensorStore, ctx.userId, endDate, totalDays) - : []; - const latestWeightKg = latestNonNullValue(bodyMeasurements, "weight_kg"); - const latestBodyFatPct = latestNonNullValue(bodyMeasurements, "body_fat_pct"); - const sleepRows = ctx.sensorStore - ? await fetchSleepNights({ - sensorStore: ctx.sensorStore, - userId: ctx.userId, - timezone: ctx.timezone, - endDate, - days: totalDays, - accessWindow: ctx.accessWindow, - order: "asc", - }) - : []; - const sleepDurations = sleepRows - .map((row) => row.duration_minutes) - .filter((duration): duration is number => duration != null); - const bedtimes = sleepRows - .map((row) => bedtimeMinutes(row.started_at, ctx.timezone)) - .filter((minutes): minutes is number => minutes != null); - const avgSleepMin = average(sleepDurations); - const bedtimeStddevMin = populationStddev(bedtimes); + if (!ctx.sensorStore) return null; - const rows = await executeWithSchema( - ctx.db, - rawRowSchema, - sql`WITH ${restingHeartRateCte}, - metrics_agg AS ( - SELECT - (SELECT AVG(resting_hr) - FROM resting_heart_rate - WHERE date > ${dateWindowStart(endDate, totalDays)} - AND date <= ${dateWindowEnd(endDate)} - ${dateAccessPredicate(ctx.accessWindow, sql`date`)}) AS avg_resting_hr, - (SELECT AVG(steps) - FROM fitness.v_daily_metrics - WHERE user_id = ${ctx.userId} - AND date > ${dateWindowStart(endDate, totalDays)} - AND date <= ${dateWindowEnd(endDate)} - ${dateAccessPredicate(ctx.accessWindow, sql`date`)}) AS avg_steps, - NULL::real AS latest_vo2max - ), - strength_freq AS ( - SELECT NULLIF(COUNT(*), 0)::real / GREATEST(${totalDays}::real / 7, 1) AS sessions_per_week - FROM fitness.activity - WHERE user_id = ${ctx.userId} - AND activity_type = 'strength' - AND started_at > ${timestampWindowStart(endDate, totalDays)} - AND started_at < (${dateWindowEnd(endDate)} + INTERVAL '1 day')::timestamp - ${dateAccessPredicate(ctx.accessWindow, sql`started_at::date`)} - ), - weekly_rhr AS ( - SELECT - date_trunc('week', date)::date AS week_start, - AVG(resting_hr) AS avg_rhr - FROM resting_heart_rate - WHERE date > ${dateWindowStart(endDate, totalDays)} - AND date <= ${dateWindowEnd(endDate)} - ${dateAccessPredicate(ctx.accessWindow, sql`date`)} - GROUP BY date_trunc('week', date) - ), - weekly_steps AS ( - SELECT - date_trunc('week', date)::date AS week_start, - AVG(steps) AS avg_steps - FROM fitness.v_daily_metrics - WHERE user_id = ${ctx.userId} - AND date > ${dateWindowStart(endDate, totalDays)} - AND date <= ${dateWindowEnd(endDate)} - ${dateAccessPredicate(ctx.accessWindow, sql`date`)} - GROUP BY date_trunc('week', date) - ), - weekly_dates AS ( - SELECT week_start FROM weekly_rhr - UNION - SELECT week_start FROM weekly_steps - ), - weekly_metrics AS ( - SELECT - wd.week_start, - wr.avg_rhr, - ws.avg_steps, - NULL::real AS avg_vo2max - FROM weekly_dates wd - LEFT JOIN weekly_rhr wr ON wr.week_start = wd.week_start - LEFT JOIN weekly_steps ws ON ws.week_start = wd.week_start - ORDER BY week_start ASC - ) - SELECT - ${avgSleepMin}::real AS avg_sleep_min, - ${bedtimeStddevMin}::real AS bedtime_stddev_min, - ma.avg_resting_hr, - ma.avg_steps, - ma.latest_vo2max, - ${weeklyAerobicMin}::real AS weekly_aerobic_min, - ${weeklyHighIntensityMin}::real AS weekly_high_intensity_min, - sf.sessions_per_week, - ${latestWeightKg}::real AS weight_kg, - ${latestBodyFatPct}::real AS body_fat_pct, - (SELECT json_agg(json_build_object( - 'week_start', wm.week_start::text, - 'avg_rhr', wm.avg_rhr, - 'avg_steps', wm.avg_steps, - 'avg_vo2max', wm.avg_vo2max - ) ORDER BY wm.week_start ASC) FROM weekly_metrics wm) AS weekly_history - FROM metrics_agg ma - CROSS JOIN strength_freq sf`, + const rows = await ctx.sensorStore.query( + healthspanReadModelRowSchema, + `SELECT + toString(healthspan.week_start) AS week_start, + avg_sleep_min, + bedtime_stddev_min, + avg_resting_hr, + avg_steps, + latest_vo2max, + weekly_aerobic_min, + weekly_high_intensity_min, + sessions_per_week, + weight_kg, + body_fat_pct + FROM analytics.healthspan_read_model AS healthspan FINAL + WHERE healthspan.user_id = {userId:UUID} + AND healthspan.week_start > toMonday(toDate({windowStart:String})) + AND healthspan.week_start <= toMonday(toDate({endDate:String})) + ${accessWindowClause(ctx)} + ORDER BY healthspan.week_start ASC`, + { + userId: ctx.userId, + windowStart: dateWindowStartString(endDate, totalDays), + endDate, + ...accessWindowParams(ctx), + }, ); - const row = rows[0] ?? null; - if (!row || !ctx.sensorStore) { - return row; - } + if (rows.length === 0) return null; - const vo2MaxEstimates = await ctx.sensorStore.getVo2MaxEstimates( - endDate, - totalDays, - ctx.userId, - ctx.timezone, + const sortedRows = [...rows].sort((firstRow, secondRow) => + firstRow.week_start.localeCompare(secondRow.week_start), ); - return { - ...row, - latest_vo2max: averageVo2MaxEstimates(vo2MaxEstimates.map((estimate) => estimate.vo2max)), - weekly_history: mergeWeeklyVo2Max(row.weekly_history, vo2MaxEstimates), - }; -} - -function latestNonNullValue, TKey extends string>( - rows: TRow[], - key: TKey, -): number | null { - for (let rowIndex = rows.length - 1; rowIndex >= 0; rowIndex -= 1) { - const value = rows[rowIndex]?.[key]; - if (value != null) { - return Number(value); - } - } - return null; -} - -function mergeWeeklyVo2Max( - history: WeeklyHistoryRow[] | null, - estimates: Array<{ activity_date: string; vo2max: number }>, -): WeeklyHistoryRow[] | null { - const weeklyRows = new Map(); - for (const row of history ?? []) { - weeklyRows.set(row.week_start, row); - } - - const estimatesByWeek = new Map(); - for (const estimate of estimates) { - const weekStart = getIsoWeekStart(estimate.activity_date); - const weekEstimates = estimatesByWeek.get(weekStart) ?? []; - weekEstimates.push(estimate.vo2max); - estimatesByWeek.set(weekStart, weekEstimates); - } - - for (const [weekStart, weekEstimates] of estimatesByWeek) { - const existing = weeklyRows.get(weekStart); - weeklyRows.set(weekStart, { - week_start: weekStart, - avg_rhr: existing?.avg_rhr ?? null, - avg_steps: existing?.avg_steps ?? null, - avg_vo2max: averageVo2MaxEstimates(weekEstimates), - }); - } - - const mergedRows = [...weeklyRows.values()].sort((left, right) => - left.week_start.localeCompare(right.week_start), - ); - return mergedRows.length > 0 ? mergedRows : history; -} -function getIsoWeekStart(dateString: string): string { - const date = new Date(`${dateString}T00:00:00.000Z`); - const daysSinceMonday = (date.getUTCDay() + 6) % 7; - date.setUTCDate(date.getUTCDate() - daysSinceMonday); - return date.toISOString().slice(0, 10); + return rawRowSchema.parse({ + avg_sleep_min: average(sortedRows.map((row) => row.avg_sleep_min)), + bedtime_stddev_min: average(sortedRows.map((row) => row.bedtime_stddev_min)), + avg_resting_hr: average(sortedRows.map((row) => row.avg_resting_hr)), + avg_steps: average(sortedRows.map((row) => row.avg_steps)), + latest_vo2max: latestNonNullValue(sortedRows, "latest_vo2max"), + weekly_aerobic_min: weeklyActivityAverage(sortedRows, "weekly_aerobic_min"), + weekly_high_intensity_min: weeklyActivityAverage(sortedRows, "weekly_high_intensity_min"), + sessions_per_week: weeklyActivityAverage(sortedRows, "sessions_per_week"), + weight_kg: latestNonNullValue(sortedRows, "weight_kg"), + body_fat_pct: latestNonNullValue(sortedRows, "body_fat_pct"), + weekly_history: sortedRows.map((row) => ({ + week_start: row.week_start, + avg_rhr: row.avg_resting_hr, + avg_steps: row.avg_steps, + avg_vo2max: row.latest_vo2max, + })), + }); } diff --git a/packages/server/src/routers/healthspan.test.ts b/packages/server/src/routers/healthspan.test.ts index a2d09f351b..8777afd4e3 100644 --- a/packages/server/src/routers/healthspan.test.ts +++ b/packages/server/src/routers/healthspan.test.ts @@ -5,7 +5,13 @@ import { createTestCallerFactory } from "./test-helpers.ts"; vi.mock("../trpc.ts", async () => { const { initTRPC } = await import("@trpc/server"); const trpc = initTRPC - .context<{ db: unknown; userId: string | null; timezone: string; sensorStore?: unknown }>() + .context<{ + accessWindow: typeof fullAccessWindow; + db: unknown; + userId: string | null; + timezone: string; + sensorStore?: unknown; + }>() .create(); return { router: trpc.router, @@ -384,97 +390,52 @@ function makeSensorStore(overrides: Partial): ActivitySenso }; } -function makeRawHealthspanRow(overrides: Partial = {}): HealthspanRawRow { - return { - avg_sleep_min: null, - bedtime_stddev_min: null, - avg_resting_hr: null, - avg_steps: null, - latest_vo2max: null, - weekly_aerobic_min: null, - weekly_high_intensity_min: null, - sessions_per_week: null, - weight_kg: null, - body_fat_pct: null, - weekly_history: null, - ...overrides, - }; -} - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null; -} - -function collectSqlParameterValues(value: unknown): unknown[] { - if (Array.isArray(value)) { - return value.flatMap(collectSqlParameterValues); - } - if (!isRecord(value)) { - return [value]; - } - - if ("value" in value) { - return []; - } - - const queryChunks = value.queryChunks; - if (Array.isArray(queryChunks)) { - return queryChunks.flatMap(collectSqlParameterValues); - } - - return []; -} - -function collectSqlText(value: unknown): string { - if (Array.isArray(value)) { - return value.map(collectSqlText).join(""); - } - if (!isRecord(value)) { - return ""; - } - - if ("value" in value) { - const chunkValue = value.value; - if (typeof chunkValue === "string") { - return chunkValue; - } - if (Array.isArray(chunkValue)) { - return chunkValue.filter((item): item is string => typeof item === "string").join(""); - } - return ""; - } - - const queryChunks = value.queryChunks; - if (Array.isArray(queryChunks)) { - return queryChunks.map(collectSqlText).join(""); - } - - return ""; -} - -function findSqlCall(calls: unknown[][], text: string): unknown { - return calls.map(([query]) => query).find((query) => collectSqlText(query).includes(text)); -} - -function expectSqlParamsToContainNumber(values: unknown[], expected: number): void { - expect( - values.some( - (value) => typeof value === "number" && Math.abs(value - expected) < Number.EPSILON, - ), - ).toBe(true); +function makeHealthspanReadModelRows(rows: HealthspanRawRow[]) { + return rows.flatMap((row, rowIndex) => { + const historyRows = + row.weekly_history && row.weekly_history.length > 0 + ? row.weekly_history + : [ + { + week_start: `2026-03-${String(rowIndex + 2).padStart(2, "0")}`, + avg_rhr: row.avg_resting_hr, + avg_steps: row.avg_steps, + avg_vo2max: row.latest_vo2max, + }, + ]; + + return historyRows.map((historyRow) => ({ + week_start: historyRow.week_start, + avg_sleep_min: row.avg_sleep_min, + bedtime_stddev_min: row.bedtime_stddev_min, + avg_resting_hr: historyRow.avg_rhr, + avg_steps: historyRow.avg_steps, + latest_vo2max: historyRow.avg_vo2max, + weekly_aerobic_min: row.weekly_aerobic_min, + weekly_high_intensity_min: row.weekly_high_intensity_min, + sessions_per_week: row.sessions_per_week, + weight_kg: row.weight_kg, + body_fat_pct: row.body_fat_pct, + })); + }); } -function countSqlNumberParams(values: unknown[], expected: number): number { - return values.filter( - (value) => typeof value === "number" && Math.abs(value - expected) < Number.EPSILON, - ).length; +function makeHealthspanCallerContext(rows: HealthspanRawRow[]) { + return { + accessWindow: fullAccessWindow, + db: { execute: vi.fn() }, + userId: "user-1", + timezone: "UTC", + sensorStore: makeSensorStore({ + query: vi.fn().mockResolvedValue(makeHealthspanReadModelRows(rows)), + }), + }; } function makeFetchContext( overrides: Partial[0]>, ): Parameters[0] { return { - db: { execute: vi.fn().mockResolvedValue([makeRawHealthspanRow()]) }, userId: "user-1", timezone: "UTC", accessWindow: fullAccessWindow, @@ -483,133 +444,40 @@ function makeFetchContext( } describe("fetchHealthspanRawData", () => { - it("passes derived sleep, body, and zone metrics into the aggregate query", async () => { - const execute = vi - .fn() - .mockResolvedValueOnce([{ weekly_exercise_min: null }]) - .mockResolvedValueOnce([makeRawHealthspanRow()]); - const query = vi.fn(async (_schema: unknown, queryText: string) => { - if (queryText.includes("analytics.resting_heart_rate_sleep_window")) { - return [{ date: "2026-03-02", resting_hr: 48 }]; - } - if (queryText.includes("analytics.healthspan_activity_zone_minutes")) { - return [{ aerobic_minutes: 140, high_intensity_minutes: 70 }]; - } - if (queryText.includes("analytics.v_body_measurement")) { - return [ - { recorded_at: "2026-03-01 08:00:00", weight_kg: null, body_fat_pct: 21 }, - { recorded_at: "2026-03-02 08:00:00", weight_kg: 80, body_fat_pct: null }, - { recorded_at: "2026-03-03 08:00:00", weight_kg: 77, body_fat_pct: null }, - ]; - } - if (queryText.includes("analytics.v_sleep")) { - return [ - { - date: "2026-03-01", - started_at: "2026-03-01T12:00:00.000Z", - duration_minutes: 420, - deep_minutes: null, - rem_minutes: null, - light_minutes: null, - awake_minutes: null, - efficiency_pct: null, - }, - { - date: "2026-03-02", - started_at: "2026-03-02T13:00:00.000Z", - duration_minutes: null, - deep_minutes: null, - rem_minutes: null, - light_minutes: null, - awake_minutes: null, - efficiency_pct: null, - }, - { - date: "2026-03-03", - started_at: "2026-03-03T00:30:00.000Z", - duration_minutes: 480, - deep_minutes: null, - rem_minutes: null, - light_minutes: null, - awake_minutes: null, - efficiency_pct: null, - }, - { - date: "2026-03-04", - started_at: "not-a-date", - duration_minutes: 600, - deep_minutes: null, - rem_minutes: null, - light_minutes: null, - awake_minutes: null, - efficiency_pct: null, - }, - ]; - } - return []; - }); - const sensorStore = makeSensorStore({ - query, - getVo2MaxEstimates: vi.fn().mockResolvedValue([]), - }); + it("reads compact weekly rows from the Healthspan read model", async () => { + const query = vi.fn().mockResolvedValue([ + { + week_start: "2026-03-03", + avg_sleep_min: 420, + bedtime_stddev_min: 20, + avg_resting_hr: 55, + avg_steps: 8000, + latest_vo2max: 42, + weekly_aerobic_min: 120, + weekly_high_intensity_min: 30, + sessions_per_week: 2, + weight_kg: 80, + body_fat_pct: 20, + }, + ]); const ctx = makeFetchContext({ - db: { execute }, - sensorStore, + sensorStore: makeSensorStore({ query }), }); - await fetchHealthspanRawData(ctx, "2026-03-15", 14); + const result = await fetchHealthspanRawData(ctx, "2026-03-15", 14); - expect(query).toHaveBeenCalledWith( - expect.anything(), - expect.stringContaining("analytics.healthspan_activity_zone_minutes"), - expect.objectContaining({ - windowStart: "2026-03-01 00:00:00", - windowEndExclusive: "2026-03-16 00:00:00", - }), + expect(query.mock.calls[0]?.[1]).toContain( + "analytics.healthspan_read_model AS healthspan FINAL", ); - const aggregateSql = findSqlCall(execute.mock.calls, "metrics_agg"); - const sqlValues = collectSqlParameterValues(aggregateSql); - expectSqlParamsToContainNumber(sqlValues, 500); - expectSqlParamsToContainNumber(sqlValues, Math.sqrt(115_800)); - expectSqlParamsToContainNumber(sqlValues, 70); - expectSqlParamsToContainNumber(sqlValues, 35); - expectSqlParamsToContainNumber(sqlValues, 77); - expectSqlParamsToContainNumber(sqlValues, 21); - }); - - it("uses device-reported exercise minutes as the aerobic activity floor", async () => { - const execute = vi - .fn() - .mockResolvedValueOnce([{ weekly_exercise_min: 112 }]) - .mockResolvedValueOnce([makeRawHealthspanRow()]); - const query = vi.fn(async (_schema: unknown, queryText: string) => { - if (queryText.includes("analytics.healthspan_activity_zone_minutes")) { - return [{ aerobic_minutes: 0, high_intensity_minutes: 0 }]; - } - return []; - }); - const ctx = makeFetchContext({ - db: { execute }, - sensorStore: makeSensorStore({ - query, - getVo2MaxEstimates: vi.fn().mockResolvedValue([]), - }), - }); - - await fetchHealthspanRawData(ctx, "2026-03-15", 14); - - const aggregateSql = findSqlCall(execute.mock.calls, "metrics_agg"); - const sqlValues = collectSqlParameterValues(aggregateSql); - expectSqlParamsToContainNumber(sqlValues, 112); + expect(query.mock.calls[0]?.[1]).not.toContain("analytics.healthspan_activity_zone_minutes"); + expect(result?.weekly_history).toEqual([ + { week_start: "2026-03-03", avg_rhr: 55, avg_steps: 8000, avg_vo2max: 42 }, + ]); }); - it("bounds Healthspan SQL reads by end date and access window", async () => { - const execute = vi - .fn() - .mockResolvedValueOnce([{ weekly_exercise_min: null }]) - .mockResolvedValueOnce([makeRawHealthspanRow()]); + it("bounds the Healthspan read model by end date and access window", async () => { + const query = vi.fn().mockResolvedValue([]); const ctx = makeFetchContext({ - db: { execute }, accessWindow: { kind: "limited", paid: false, @@ -617,118 +485,30 @@ describe("fetchHealthspanRawData", () => { startDate: "2026-03-05", endDateExclusive: "2026-03-12", }, + sensorStore: makeSensorStore({ query }), }); await fetchHealthspanRawData(ctx, "2026-03-15", 14); - const weeklyExerciseSql = findSqlCall(execute.mock.calls, "weekly_exercise_min"); - expect(collectSqlText(weeklyExerciseSql)).toContain("AND date <= "); - expect(collectSqlText(weeklyExerciseSql)).toContain("AND date >= "); - expect(collectSqlText(weeklyExerciseSql)).toContain("AND date < "); - - const aggregateSqlText = collectSqlText(findSqlCall(execute.mock.calls, "metrics_agg")); - expect(aggregateSqlText).toContain("AND date <= "); - expect(aggregateSqlText).toContain("AND date >= "); - expect(aggregateSqlText).toContain("AND date < "); - expect(aggregateSqlText).toContain("AND started_at < "); - expect(aggregateSqlText).toContain("AND started_at::date >= "); - expect(aggregateSqlText).toContain("AND started_at::date < "); - }); - - it("keeps activity zone read-model bounds in the ClickHouse query", async () => { - const query = vi.fn().mockResolvedValue([]); - const ctx = makeFetchContext({ - sensorStore: makeSensorStore({ - query, - getVo2MaxEstimates: vi.fn().mockResolvedValue([]), - }), - }); - - await fetchHealthspanRawData(ctx, "2026-03-15", 14); - - const zoneQuery = query.mock.calls.find( - ([, queryText]) => - typeof queryText === "string" && - queryText.includes("analytics.healthspan_activity_zone_minutes"), - )?.[1]; - expect(zoneQuery).toEqual(expect.any(String)); - expect(query).toHaveBeenCalledWith( - expect.anything(), - expect.stringContaining("analytics.healthspan_activity_zone_minutes"), - expect.objectContaining({ - windowStart: "2026-03-01 00:00:00", - windowEndExclusive: "2026-03-16 00:00:00", - }), + const queryText = query.mock.calls[0]?.[1]; + expect(queryText).toContain("healthspan.week_start > toMonday(toDate({windowStart:String}))"); + expect(queryText).toContain("healthspan.week_start <= toMonday(toDate({endDate:String}))"); + expect(queryText).toContain("healthspan.week_start >= toDate({accessStartDate:String})"); + expect(queryText).toContain( + "healthspan.week_start + INTERVAL 7 DAY <= toDate({accessEndDateExclusive:String})", ); - expect(zoneQuery).toMatch(/AND\s+started_at\s*>\s*toDateTime\(\{windowStart:String\}\)/); - expect(zoneQuery).toMatch(/AND\s+started_at\s*<\s*toDateTime\(\{windowEndExclusive:String\}\)/); - }); - - it("merges VO2 max estimates into sorted weekly history", async () => { - const execute = vi.fn().mockResolvedValue([ - makeRawHealthspanRow({ - weekly_history: [ - { week_start: "2026-03-16", avg_rhr: 55, avg_steps: 10_000, avg_vo2max: null }, - ], - }), - ]); - const getVo2MaxEstimates = vi.fn().mockResolvedValue([ - { - activity_id: "activity-1", - activity_date: "2026-03-03", - method: "cycling_power", - vo2max: 40, - }, - { - activity_id: "activity-2", - activity_date: "2026-03-05", - method: "submaximal_acsm", - vo2max: 50, - }, - { - activity_id: "activity-3", - activity_date: "2026-03-17", - method: "submaximal_acsm", - vo2max: 60, - }, - ]); - const ctx = makeFetchContext({ - db: { execute }, - sensorStore: makeSensorStore({ getVo2MaxEstimates }), - }); - - const result = await fetchHealthspanRawData(ctx, "2026-03-20", 21); - - expect(result?.latest_vo2max).toBe(50); - expect(result?.weekly_history).toEqual([ - { week_start: "2026-03-02", avg_rhr: null, avg_steps: null, avg_vo2max: 45 }, - { week_start: "2026-03-16", avg_rhr: 55, avg_steps: 10_000, avg_vo2max: 60 }, - ]); - }); - - it("keeps missing weekly history as null when no VO2 max estimates exist", async () => { - const execute = vi.fn().mockResolvedValue([makeRawHealthspanRow({ weekly_history: null })]); - const ctx = makeFetchContext({ - db: { execute }, - sensorStore: makeSensorStore({ getVo2MaxEstimates: vi.fn().mockResolvedValue([]) }), + expect(query.mock.calls[0]?.[2]).toMatchObject({ + windowStart: "2026-03-01", + endDate: "2026-03-15", + accessStartDate: "2026-03-05", + accessEndDateExclusive: "2026-03-12", }); - - const result = await fetchHealthspanRawData(ctx, "2026-03-20", 21); - - expect(result?.weekly_history).toBeNull(); }); - it("uses null sensor metrics and zero zone minutes without a sensor store", async () => { - const execute = vi.fn().mockResolvedValue([makeRawHealthspanRow()]); - const ctx = makeFetchContext({ - db: { execute }, - }); - - await fetchHealthspanRawData(ctx, "2026-03-15", 14); + it("returns null without a sensor store", async () => { + const result = await fetchHealthspanRawData(makeFetchContext({}), "2026-03-15", 14); - const sqlValues = collectSqlParameterValues(execute.mock.calls[1]?.[0]); - expect(sqlValues).not.toContain(undefined); - expect(countSqlNumberParams(sqlValues, 0)).toBeGreaterThanOrEqual(2); + expect(result).toBeNull(); }); }); @@ -736,9 +516,11 @@ describe("healthspanRouter", () => { describe("score", () => { it("returns null score when no data", async () => { const caller = createCaller({ + accessWindow: fullAccessWindow, db: { execute: vi.fn().mockResolvedValue([]) }, userId: "user-1", timezone: "UTC", + sensorStore: makeSensorStore({ query: vi.fn().mockResolvedValue([]) }), }); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); @@ -764,11 +546,7 @@ describe("healthspanRouter", () => { weekly_history: [], }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); expect(result.metrics).toHaveLength(9); @@ -809,21 +587,21 @@ describe("healthspanRouter", () => { expect(result.healthspanScore).toBe(Math.round(totalScore / metricsWithData.length)); }); - it("uses sensor-store VO2 max estimates for the current value and weekly history", async () => { + it("uses read-model VO2 max estimates for the current value and weekly history", async () => { const rows = [ { avg_sleep_min: 480, bedtime_stddev_min: 20, avg_resting_hr: 55, avg_steps: 10000, - latest_vo2max: null, + latest_vo2max: 45, weekly_aerobic_min: 200, weekly_high_intensity_min: 80, sessions_per_week: 3, weight_kg: 75, body_fat_pct: 15, weekly_history: [ - { week_start: "2026-03-09", avg_rhr: 55, avg_steps: 10000, avg_vo2max: null }, + { week_start: "2026-03-09", avg_rhr: 55, avg_steps: 10000, avg_vo2max: 45 }, ], }, ]; @@ -841,21 +619,23 @@ describe("healthspanRouter", () => { vo2max: 50, }, ]); - const execute = vi.fn().mockResolvedValue(rows); + const query = vi.fn().mockResolvedValue(makeHealthspanReadModelRows(rows)); const caller = createCaller({ - db: { execute }, + accessWindow: fullAccessWindow, + db: { execute: vi.fn() }, userId: "user-1", timezone: "UTC", - sensorStore: makeSensorStore({ getVo2MaxEstimates }), + sensorStore: makeSensorStore({ getVo2MaxEstimates, query }), }); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); const vo2 = result.metrics.find((metric) => metric.name === "VO2 Max"); - const queryJson = JSON.stringify(execute.mock.calls[0]?.[0]); - expect(queryJson).not.toContain("derived_vo2max_estimates"); + const queryText = query.mock.calls[0]?.[1]; + expect(queryText).not.toContain("derived_vo2max_estimates"); expect(vo2?.value).toBe(45); - expect(getVo2MaxEstimates).toHaveBeenCalledWith("2026-03-15", 84, "user-1", "UTC"); + expect(queryText).toContain("analytics.healthspan_read_model"); + expect(getVo2MaxEstimates).not.toHaveBeenCalled(); expect(result.history[0]?.score).toBe( Math.round((scoreRestingHr(55) + scoreSteps(10000) + scoreVo2Max(45)) / 3), ); @@ -877,11 +657,7 @@ describe("healthspanRouter", () => { weekly_history: null, }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); expect(result.healthspanScore).toBeNull(); @@ -908,11 +684,7 @@ describe("healthspanRouter", () => { weekly_history: null, }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); // Only 2 metrics have real data — below minimum threshold @@ -937,11 +709,7 @@ describe("healthspanRouter", () => { weekly_history: null, }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); // 3 metrics with real data: sleep duration (100), sleep consistency (78), resting HR (90) @@ -965,11 +733,7 @@ describe("healthspanRouter", () => { weekly_history: null, }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); const sleepDur = result.metrics.find((m) => m.name === "Sleep Duration"); @@ -1006,11 +770,7 @@ describe("healthspanRouter", () => { ], }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); expect(result.trend).toBe("improving"); }); @@ -1036,11 +796,7 @@ describe("healthspanRouter", () => { ], }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); expect(result.trend).toBe("declining"); }); @@ -1066,11 +822,7 @@ describe("healthspanRouter", () => { ], }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); expect(result.trend).toBe("stable"); }); @@ -1095,11 +847,7 @@ describe("healthspanRouter", () => { ], }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); expect(result.trend).toBeNull(); }); @@ -1122,11 +870,7 @@ describe("healthspanRouter", () => { ], }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); expect(result.history).toHaveLength(1); @@ -1153,11 +897,7 @@ describe("healthspanRouter", () => { weekly_history: null, }, ]; - const caller = createCaller({ - db: { execute: vi.fn().mockResolvedValue(rows) }, - userId: "user-1", - timezone: "UTC", - }); + const caller = createCaller(makeHealthspanCallerContext(rows)); const result = await caller.score({ weeks: 12, endDate: "2026-03-15" }); const lean = result.metrics.find((m) => m.name === "Lean Body Mass"); diff --git a/packages/server/src/routers/mobile-dashboard.test.ts b/packages/server/src/routers/mobile-dashboard.test.ts index d542fe844b..15ecd6c280 100644 --- a/packages/server/src/routers/mobile-dashboard.test.ts +++ b/packages/server/src/routers/mobile-dashboard.test.ts @@ -252,7 +252,7 @@ describe("mobileDashboard.dashboard", () => { expect(result.strain.dailyStrain).toBe(0); const queryText = vi.mocked(sensorStore.query).mock.calls[0]?.[1]; - expect(queryText).toContain("analytics.daily_activity_load"); + expect(queryText).toContain("analytics.strain_read_model FINAL"); expect(queryText).not.toContain("analytics.activity_summary"); }); diff --git a/packages/server/src/routers/mobile-dashboard.ts b/packages/server/src/routers/mobile-dashboard.ts index a675819e63..2036e31ec1 100644 --- a/packages/server/src/routers/mobile-dashboard.ts +++ b/packages/server/src/routers/mobile-dashboard.ts @@ -168,22 +168,21 @@ export const mobileDashboardRouter = router({ daily_load: z.coerce.number(), }), `SELECT - toString(toDate(toTimeZone(ended_at, {timezone:String}))) AS metric_date, - sum(daily_load) AS daily_load - FROM analytics.daily_activity_load + toString(date) AS metric_date, + daily_load + FROM analytics.strain_read_model FINAL WHERE user_id = {userId:UUID} - AND toDate(toTimeZone(ended_at, {timezone:String})) > toDate({endDate:String}) - 60 - AND toDate(toTimeZone(ended_at, {timezone:String})) <= toDate({endDate:String}) - GROUP BY metric_date`, - { userId: ctx.userId, timezone: tz, endDate }, + AND date > toDate({endDate:String}) - 60 + AND date <= toDate({endDate:String})`, + { userId: ctx.userId, endDate }, ), sensorStore.query( z.object({ load: z.coerce.number() }), - `SELECT coalesce(sum(daily_load), 0) AS load - FROM analytics.daily_activity_load + `SELECT coalesce(daily_load, 0) AS load + FROM analytics.strain_read_model FINAL WHERE user_id = {userId:UUID} - AND toDate(toTimeZone(started_at, {timezone:String})) = toDate({endDate:String}) - 1`, - { userId: ctx.userId, timezone: tz, endDate }, + AND date = toDate({endDate:String}) - 1`, + { userId: ctx.userId, endDate }, ), fetchRestingHeartRateRows({ sensorStore, diff --git a/packages/server/src/routers/recovery-settings-sleep-need-sport-settings.test.ts b/packages/server/src/routers/recovery-settings-sleep-need-sport-settings.test.ts index b3667a74fb..d5fca386b3 100644 --- a/packages/server/src/routers/recovery-settings-sleep-need-sport-settings.test.ts +++ b/packages/server/src/routers/recovery-settings-sleep-need-sport-settings.test.ts @@ -122,11 +122,11 @@ describe("recoveryRouter", () => { ...makeMockSensorStore([]), query: vi.fn(async (_schema: unknown, query: string) => { if (query.includes("analytics.v_sleep")) return toSleepRows(rows); - if (query.includes("analytics.daily_activity_load")) { + if (query.includes("analytics.strain_read_model")) { if (rows.some((row) => "daily_load" in row || "acute_load" in row)) return rows; return [{ load: rows[0]?.yesterday_load ?? 0 }]; } - if (query.includes("analytics.daily_recovery_inputs")) return rows; + if (query.includes("analytics.recovery_read_model")) return rows; return []; }), }; diff --git a/packages/server/src/routers/recovery.test.ts b/packages/server/src/routers/recovery.test.ts index cb22d0f8e8..c3a855680f 100644 --- a/packages/server/src/routers/recovery.test.ts +++ b/packages/server/src/routers/recovery.test.ts @@ -414,10 +414,27 @@ describe("recoveryRouter.workloadRatio", () => { expect(result.displayedStrain).toBe(0); expect(result.displayedDate).toBeNull(); const queryText = vi.mocked(sensorStore.query).mock.calls[0]?.[1]; - expect(queryText).toContain("analytics.daily_activity_load"); + expect(queryText).toContain("analytics.strain_read_model AS strain FINAL"); + expect(queryText).toContain("toDate(toTimeZone(toDateTime(strain.date), {timezone:String}))"); expect(queryText).not.toContain("analytics.activity_summary"); }); + it("passes the user timezone when reading strain read-model dates", async () => { + const sensorStore = makeSensorStore([]); + const caller = createCaller({ + db: { execute: vi.fn() }, + userId: "user-1", + timezone: "America/Los_Angeles", + sensorStore, + }); + + await caller.workloadRatio({ endDate: "2026-03-15" }); + + expect(vi.mocked(sensorStore.query).mock.calls[0]?.[2]).toMatchObject({ + timezone: "America/Los_Angeles", + }); + }); + it("maps SQL rows to WorkloadRatioRow format with rounding", async () => { const rows = [ { @@ -717,7 +734,7 @@ describe("recoveryRouter.readinessScore", () => { expect(result).toEqual([]); const queryText = vi.mocked(sensorStore.query).mock.calls[0]?.[1]; const queryParams = vi.mocked(sensorStore.query).mock.calls[0]?.[2]; - expect(queryText).toContain("analytics.daily_recovery_inputs"); + expect(queryText).toContain("analytics.recovery_read_model AS recovery_inputs FINAL"); expect(queryText).not.toContain("fitness.v_daily_metrics"); expect(queryText).not.toContain("analytics.v_sleep"); expect(queryText).not.toContain("accessStartDate"); @@ -1308,7 +1325,7 @@ describe("recoveryRouter.readinessScore", () => { describe("recoveryRouter.strainTarget", () => { // Sets up a strainTarget caller. PG mocks: readinessRows, then optional sleepRows. - // CH mock: loads from analytics.daily_activity_load. + // CH mock: loads from analytics.strain_read_model. function setup({ readinessRows = [], sleepRows, @@ -1355,7 +1372,9 @@ describe("recoveryRouter.strainTarget", () => { await caller.strainTarget({ endDate: "2026-03-28" }); const queryText = vi.mocked(sensorStore.query).mock.calls[1]?.[1]; - expect(queryText).toContain("analytics.daily_activity_load"); + expect(queryText).toContain("analytics.strain_read_model AS strain FINAL"); + expect(queryText).toContain("toString(strain.date) AS date"); + expect(queryText).toContain("strain.date >= toDate({windowStart:String})"); expect(queryText).not.toContain("analytics.activity_summary"); }); diff --git a/packages/server/src/routers/recovery.ts b/packages/server/src/routers/recovery.ts index b75a9fc122..3c139bacf8 100644 --- a/packages/server/src/routers/recovery.ts +++ b/packages/server/src/routers/recovery.ts @@ -263,7 +263,6 @@ export const recoveryRouter = router({ .input(z.object({ days: z.number().default(90), endDate: endDateSchema })) .query(async ({ ctx, input }): Promise => { const sensorStore = requireSensorStore(ctx.sensorStore, "recovery.workloadRatio"); - const queryDays = input.days + 28; const workloadRowSchema = z.object({ date: z.string(), daily_load: z.coerce.number(), @@ -273,51 +272,21 @@ export const recoveryRouter = router({ }); const rows = await sensorStore.query( workloadRowSchema, - `WITH activity_load AS ( - SELECT - toDate(toTimeZone(started_at, {timezone:String})) AS date, - sum(daily_load) AS daily_load - FROM analytics.daily_activity_load - WHERE user_id = {userId:UUID} - AND toDate(toTimeZone(started_at, {timezone:String})) >= toDate({windowStart:String}) - GROUP BY toDate(toTimeZone(started_at, {timezone:String})) - ), - date_series AS ( - SELECT toDate({windowStart:String}) + INTERVAL number DAY AS date - FROM numbers(toUInt64({totalDays:Int32}) + 1) - ), - daily AS ( - SELECT - ds.date AS date, - coalesce(al.daily_load, 0) AS daily_load - FROM date_series ds - LEFT JOIN activity_load al ON al.date = ds.date - ), - with_windows AS ( - SELECT - date, - daily_load, - sum(daily_load) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS acute_load, - avg(daily_load) OVER (ORDER BY date ROWS BETWEEN 27 PRECEDING AND CURRENT ROW) AS chronic_load_avg, - count() OVER (ORDER BY date ROWS BETWEEN 27 PRECEDING AND CURRENT ROW) AS chronic_count - FROM daily - ) - SELECT - toString(with_windows.date) AS date, - with_windows.daily_load AS daily_load, - with_windows.acute_load AS acute_load, - with_windows.chronic_load_avg * 7 AS chronic_load, - if(with_windows.chronic_load_avg > 0 AND with_windows.chronic_count = 28, - with_windows.acute_load / (with_windows.chronic_load_avg * 7), - NULL) AS workload_ratio - FROM with_windows - WHERE with_windows.date > toDate({outputWindowStart:String}) + `SELECT + toString(toDate(toTimeZone(toDateTime(strain.date), {timezone:String}))) AS date, + strain.daily_load AS daily_load, + strain.acute_load_7d AS acute_load, + strain.chronic_load_28d AS chronic_load, + strain.workload_ratio AS workload_ratio + FROM analytics.strain_read_model AS strain FINAL + WHERE strain.user_id = {userId:UUID} + AND strain.date > toDate({outputWindowStart:String}) + AND strain.date <= toDate({endDate:String}) ORDER BY date ASC`, { userId: ctx.userId, timezone: ctx.timezone, - windowStart: dateWindowStartString(input.endDate, queryDays), - totalDays: queryDays, + endDate: input.endDate, outputWindowStart: dateWindowStartString(input.endDate, input.days), }, ); @@ -473,7 +442,7 @@ export const recoveryRouter = router({ rr_mean_30d, rr_sd_30d, efficiency_pct - FROM analytics.daily_recovery_inputs AS recovery_inputs + FROM analytics.recovery_read_model AS recovery_inputs FINAL WHERE recovery_inputs.user_id = {userId:UUID} AND recovery_inputs.date > toDate({windowStart:String}) AND recovery_inputs.date <= toDate({endDate:String}) @@ -620,24 +589,24 @@ export const recoveryRouter = router({ `, ); - // Get daily loads for ACWR from the compact ClickHouse activity-load read model. + // Get daily loads for ACWR from the compact ClickHouse strain read model. const loads = await sensorStore.query( z.object({ date: z.string(), daily_load: z.coerce.number(), }), `SELECT - toString(toDate(toTimeZone(started_at, {timezone:String}))) AS date, - sum(daily_load) AS daily_load - FROM analytics.daily_activity_load - WHERE user_id = {userId:UUID} - AND toDate(toTimeZone(started_at, {timezone:String})) >= toDate({windowStart:String}) - GROUP BY toDate(toTimeZone(started_at, {timezone:String})) + toString(strain.date) AS date, + strain.daily_load AS daily_load + FROM analytics.strain_read_model AS strain FINAL + WHERE strain.user_id = {userId:UUID} + AND strain.date >= toDate({windowStart:String}) + AND strain.date <= toDate({endDate:String}) ORDER BY date ASC`, { userId: ctx.userId, - timezone: ctx.timezone, windowStart: dateWindowStartString(input.endDate, input.days), + endDate: input.endDate, }, ); diff --git a/packages/server/src/routers/sleep-need.test.ts b/packages/server/src/routers/sleep-need.test.ts index 4f47730b8a..74cf186cf5 100644 --- a/packages/server/src/routers/sleep-need.test.ts +++ b/packages/server/src/routers/sleep-need.test.ts @@ -157,10 +157,27 @@ describe("sleepNeedRouter", () => { } expect(result.canRecommend).toBe(false); const queryText = vi.mocked(sensorStore.query).mock.calls[0]?.[1]; - expect(queryText).toContain("analytics.daily_activity_load"); + expect(queryText).toContain("analytics.strain_read_model FINAL"); + expect(queryText).toContain("toDate(toTimeZone(toDateTime(date), {timezone:String}))"); expect(queryText).not.toContain("analytics.activity_summary"); }); + it("passes the user timezone when selecting yesterday's strain load", async () => { + const sensorStore = makeMockSensorStore([[{ load: 0 }], []]); + const caller = createCaller({ + db: { execute: vi.fn().mockResolvedValue([]) }, + userId: "user-1", + timezone: "America/Los_Angeles", + sensorStore, + }); + + await caller.calculate({ endDate: "2026-03-15" }); + + expect(vi.mocked(sensorStore.query).mock.calls[0]?.[2]).toMatchObject({ + timezone: "America/Los_Angeles", + }); + }); + it("computes baseline from good recovery nights when >= 7 good nights", async () => { // Create nights where good_recovery is true and duration varies const rows = Array.from({ length: 10 }, (_, i) => ({ diff --git a/packages/server/src/routers/sleep-need.ts b/packages/server/src/routers/sleep-need.ts index efddeb93d7..52f23206b3 100644 --- a/packages/server/src/routers/sleep-need.ts +++ b/packages/server/src/routers/sleep-need.ts @@ -167,9 +167,10 @@ export const sleepNeedRouter = router({ z.object({ load: z.coerce.number() }), `SELECT coalesce(sum(daily_load), 0) AS load - FROM analytics.daily_activity_load + FROM analytics.strain_read_model FINAL WHERE user_id = {userId:UUID} - AND toDate(toTimeZone(started_at, {timezone:String})) = toDate({endDate:String}) - INTERVAL 1 DAY + AND toDate(toTimeZone(toDateTime(date), {timezone:String})) = + toDate({endDate:String}) - INTERVAL 1 DAY `, { userId: ctx.userId, timezone: ctx.timezone, endDate: input.endDate }, ); diff --git a/packages/server/src/routers/strength-stress.test.ts b/packages/server/src/routers/strength-stress.test.ts index 1a43698c5f..6414ff6590 100644 --- a/packages/server/src/routers/strength-stress.test.ts +++ b/packages/server/src/routers/strength-stress.test.ts @@ -176,7 +176,7 @@ describe("stressRouter", () => { sensorStore: { ...makeMockSensorStore([]), query: vi.fn(async (_schema: unknown, query: string) => { - if (query.includes("analytics.daily_recovery_inputs")) return rows; + if (query.includes("analytics.recovery_read_model")) return rows; return []; }), }, diff --git a/packages/server/src/routers/stress.test.ts b/packages/server/src/routers/stress.test.ts index c9dd304597..278ae895f9 100644 --- a/packages/server/src/routers/stress.test.ts +++ b/packages/server/src/routers/stress.test.ts @@ -118,7 +118,7 @@ describe("Router transformation logic", () => { const queryText = query.mock.calls.find( ([, sqlText]) => - typeof sqlText === "string" && sqlText.includes("analytics.daily_recovery_inputs"), + typeof sqlText === "string" && sqlText.includes("analytics.recovery_read_model"), )?.[1]; expect(queryText).toEqual(expect.any(String)); expect(queryText).not.toContain("fitness.v_daily_metrics"); diff --git a/src/db/clickhouse-migrations.test.ts b/src/db/clickhouse-migrations.test.ts index 1ccc14e2c5..1beefa2d7a 100644 --- a/src/db/clickhouse-migrations.test.ts +++ b/src/db/clickhouse-migrations.test.ts @@ -22,6 +22,7 @@ import * as incrementalRestingHeartRateMigration from "./clickhouse-migrations/0 import * as incrementalActivitySummaryMigration from "./clickhouse-migrations/0022_incremental_activity_summary.ts"; import * as incrementalActivityVo2MaxEstimateMigration from "./clickhouse-migrations/0023_incremental_activity_vo2max_estimate.ts"; import * as recreateProviderStatsDbtTableMigration from "./clickhouse-migrations/0025_recreate_provider_stats_dbt_table.ts"; +import * as createNamedDashboardReadModelTablesMigration from "./clickhouse-migrations/0026_create_named_dashboard_read_model_tables.ts"; import { clickHouseMigrationFileNames } from "./clickhouse-migrations/registry.ts"; import { runClickHouseMigrationStatement } from "./clickhouse-migrations/statement-runner.ts"; import { @@ -58,6 +59,7 @@ describe("buildClickHouseMigrationStatements", () => { "0023_incremental_activity_vo2max_estimate.ts", "0024_create_dbt_serving_read_model_tables.ts", "0025_recreate_provider_stats_dbt_table.ts", + "0026_create_named_dashboard_read_model_tables.ts", ]); }); @@ -166,6 +168,17 @@ describe("buildClickHouseMigrationStatements", () => { expect(statements[2]).toContain("ORDER BY (user_id, provider_id)"); }); + it("keeps named dashboard read model table creation in its migration file", () => { + const statements = createNamedDashboardReadModelTablesMigration.createMigration().statements; + const statementSql = statements.join("\n"); + + expect(statements).toHaveLength(3); + expect(statementSql).toContain("CREATE TABLE IF NOT EXISTS analytics.recovery_read_model"); + expect(statementSql).toContain("CREATE TABLE IF NOT EXISTS analytics.strain_read_model"); + expect(statementSql).toContain("CREATE TABLE IF NOT EXISTS analytics.healthspan_read_model"); + expect(statementSql).toContain("ENGINE = ReplacingMergeTree(refresh_version)"); + }); + it("renders the shared ReplacingMergeTree table engine helper", () => { expect( replacingMergeTreeTable("(user_id, recorded_at)"), @@ -379,7 +392,7 @@ describe("runClickHouseMigrations", () => { const count = await runClickHouseMigrations(client, "postgres://health:fixture@db:5432/health"); - expect(count).toBe(25); + expect(count).toBe(26); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS fitness" }); expect(command).toHaveBeenCalledWith({ query: "CREATE DATABASE IF NOT EXISTS analytics" }); expect(command).toHaveBeenCalledWith( diff --git a/src/db/clickhouse-migrations/0026_create_named_dashboard_read_model_tables.ts b/src/db/clickhouse-migrations/0026_create_named_dashboard_read_model_tables.ts new file mode 100644 index 0000000000..639df3d9f2 --- /dev/null +++ b/src/db/clickhouse-migrations/0026_create_named_dashboard_read_model_tables.ts @@ -0,0 +1,68 @@ +import type { ClickHouseMigration } from "./types.ts"; + +const recoveryReadModelTableSql = `CREATE TABLE IF NOT EXISTS analytics.recovery_read_model ( + user_id UUID, + date Date, + hrv Nullable(Float64), + resting_hr Nullable(Float64), + respiratory_rate Nullable(Float64), + efficiency_pct Nullable(Float64), + hrv_mean_30d Nullable(Float64), + hrv_sd_30d Nullable(Float64), + rhr_mean_30d Nullable(Float64), + rhr_sd_30d Nullable(Float64), + rr_mean_30d Nullable(Float64), + rr_sd_30d Nullable(Float64), + hrv_mean_60d Nullable(Float64), + hrv_sd_60d Nullable(Float64), + rhr_mean_60d Nullable(Float64), + rhr_sd_60d Nullable(Float64), + hrv_score Nullable(Float64), + resting_hr_score Nullable(Float64), + sleep_score Nullable(Float64), + respiratory_rate_score Nullable(Float64), + refresh_version UInt64, + refreshed_at DateTime64(9, 'UTC') +) +ENGINE = ReplacingMergeTree(refresh_version) +ORDER BY (user_id, date)`; + +const strainReadModelTableSql = `CREATE TABLE IF NOT EXISTS analytics.strain_read_model ( + user_id UUID, + date Date, + daily_load Float64, + strain Float64, + acute_load_7d Float64, + chronic_load_28d Float64, + workload_ratio Nullable(Float64), + refresh_version UInt64, + refreshed_at DateTime64(9, 'UTC') +) +ENGINE = ReplacingMergeTree(refresh_version) +ORDER BY (user_id, date)`; + +const healthspanReadModelTableSql = `CREATE TABLE IF NOT EXISTS analytics.healthspan_read_model ( + user_id UUID, + week_start Date, + avg_sleep_min Nullable(Float64), + bedtime_stddev_min Nullable(Float64), + avg_resting_hr Nullable(Float64), + avg_steps Nullable(Float64), + latest_vo2max Nullable(Float64), + weekly_aerobic_min Float64, + weekly_high_intensity_min Float64, + sessions_per_week Nullable(Float64), + weight_kg Nullable(Float64), + body_fat_pct Nullable(Float64), + refresh_version UInt64, + refreshed_at DateTime64(9, 'UTC') +) +ENGINE = ReplacingMergeTree(refresh_version) +ORDER BY (user_id, week_start)`; + +export function createMigration(): ClickHouseMigration { + return { + id: "0026_create_named_dashboard_read_model_tables", + statements: [recoveryReadModelTableSql, strainReadModelTableSql, healthspanReadModelTableSql], + }; +} diff --git a/src/db/clickhouse-migrations/registry.test.ts b/src/db/clickhouse-migrations/registry.test.ts index b394dcd542..dd8798bba1 100644 --- a/src/db/clickhouse-migrations/registry.test.ts +++ b/src/db/clickhouse-migrations/registry.test.ts @@ -18,8 +18,20 @@ describe("clickHouseMigrations", () => { "CREATE TABLE IF NOT EXISTS analytics.healthspan_activity_zone_minutes", ), ); + expect(clickHouseMigrationFileNames).toContain( + "0026_create_named_dashboard_read_model_tables.ts", + ); expect(statements).toContainEqual( expect.stringContaining("CREATE TABLE IF NOT EXISTS analytics.provider_stats"), ); + expect(statements).toContainEqual( + expect.stringContaining("CREATE TABLE IF NOT EXISTS analytics.recovery_read_model"), + ); + expect(statements).toContainEqual( + expect.stringContaining("CREATE TABLE IF NOT EXISTS analytics.strain_read_model"), + ); + expect(statements).toContainEqual( + expect.stringContaining("CREATE TABLE IF NOT EXISTS analytics.healthspan_read_model"), + ); }); }); diff --git a/src/db/clickhouse-migrations/registry.ts b/src/db/clickhouse-migrations/registry.ts index fa9117fd4b..09436903da 100644 --- a/src/db/clickhouse-migrations/registry.ts +++ b/src/db/clickhouse-migrations/registry.ts @@ -23,6 +23,7 @@ import { createMigration as createMigration0022 } from "./0022_incremental_activ import { createMigration as createMigration0023 } from "./0023_incremental_activity_vo2max_estimate.ts"; import { createMigration as createMigration0024 } from "./0024_create_dbt_serving_read_model_tables.ts"; import { createMigration as createMigration0025 } from "./0025_recreate_provider_stats_dbt_table.ts"; +import { createMigration as createMigration0026 } from "./0026_create_named_dashboard_read_model_tables.ts"; import type { ClickHouseMigration, ClickHouseMigrationFactory } from "./types.ts"; const migrationFactories: ClickHouseMigrationFactory[] = [ @@ -51,6 +52,7 @@ const migrationFactories: ClickHouseMigrationFactory[] = [ createMigration0023, createMigration0024, createMigration0025, + createMigration0026, ]; export const clickHouseMigrationFileNames = [ @@ -79,6 +81,7 @@ export const clickHouseMigrationFileNames = [ "0023_incremental_activity_vo2max_estimate.ts", "0024_create_dbt_serving_read_model_tables.ts", "0025_recreate_provider_stats_dbt_table.ts", + "0026_create_named_dashboard_read_model_tables.ts", ] as const; export function clickHouseMigrations(postgresConnectionString: string): ClickHouseMigration[] {