From 4e6847593d6917efa21f1f334081e216686bf851 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 00:29:33 +0100 Subject: [PATCH 1/9] fix(backup): check the client major against the server before dump and restore The image's pg_dump major is the highest server major HealthLog can run against, and nothing compared the two before running the tool. A server newer than the client stopped the boot at the dump before migrating with pg_dump's own mismatch line, the container restarted into the same error every few seconds, and the nightly dump failed the same way (#1431). Every path that runs pg_dump or pg_restore against a server now reads server_version_num and the tool's --version first and, when the server is newer, refuses with one message that names both majors and the way out: createDatabaseDump (the nightly dump and the dump before migrating) and db-restore. The dump before migrating exits 3 for this case; the entrypoint says why once and waits ten minutes before it exits, so a restart policy does not loop, and docker stop ends the wait. A boot with nothing to migrate starts and logs the same line as a warning. The recovery readiness model reads the stored failure back and calls the database dump failing from the first run (client_too_old), so admins get it as a backup alert instead of "the last dump failed". The upgrade guide and the self-hosting pages state the ceiling and how to check it. --- CHANGELOG.md | 5 + docker-entrypoint.sh | 20 +- docs/ops/postgres-major-upgrade.md | 45 ++++- docs/self-hosting/getting-started.md | 4 + docs/self-hosting/truenas.md | 18 +- docs/self-hosting/unraid.md | 6 +- messages/de.json | 1 + messages/en.json | 1 + messages/es.json | 1 + messages/fr.json | 1 + messages/it.json | 1 + messages/ko.json | 1 + messages/nl.json | 1 + messages/pl.json | 1 + messages/pt-BR.json | 1 + messages/ru.json | 1 + scripts/__tests__/db-dump.test.ts | 64 ++++++- scripts/__tests__/db-restore.test.ts | 56 +++++- scripts/__tests__/docker-entrypoint.test.ts | 136 +++++++++++++ scripts/db-dump.mjs | 44 ++++- scripts/db-restore.mjs | 22 ++- .../__tests__/client-server-major.test.ts | 180 ++++++++++++++++++ src/lib/database-backup/dump-core.mjs | 112 ++++++++++- src/lib/database-backup/dump-problems.ts | 18 ++ .../__tests__/readiness-model.test.ts | 42 ++++ src/lib/recovery/readiness-model.ts | 19 +- tests/integration/database-backup.test.ts | 178 +++++++++++++++++ 27 files changed, 949 insertions(+), 30 deletions(-) create mode 100644 scripts/__tests__/docker-entrypoint.test.ts create mode 100644 src/lib/database-backup/__tests__/client-server-major.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 040bacbe86..6e6a9ea4da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,7 @@ - A snooze stays with the dose it was set on. It was dated by the medication's last change, so a later write to the medication, such as the low-stock notice or an edit, carried a morning snooze over to the afternoon dose: the today list showed it snoozed and its reminder stayed silent. The snooze now keeps its own time. - Readiness counts a reading on the day it was taken in the time zone of the person's profile. The dashboard, the score pages, the API, the iPhone app, the Coach and the nightly scores grouped the day in Berlin time, so for someone in another zone a late-evening resting pulse or HRV landed in the next day's readiness. - A high stress or strain score reads as high. A stress of 80 was described as "on the low side" in the score's assessment and labelled "low" under its ring, and the ring on the score page announced it as good. Stress and strain now read low, moderate or high, the way their bands already run. +- A database server on a newer PostgreSQL major than the client tools in the image is now named as the problem, with both version numbers and the way out. Before, the dump the app takes before migrating failed with a one-line version mismatch, the boot stopped there and the container restarted into the same error every few seconds, while the nightly dumps failed with the same line and `db-restore` would have too. Every path that dumps or restores now compares the two majors first. At boot the app still refuses to migrate without its dump, but says why once and waits ten minutes before it exits; with nothing to migrate it starts and logs a warning. A nightly dump that fails this way shows as failing on the backups page from the first night and reaches admins as a backup alert, and `db-restore` refuses before it writes anything. The upgrade guide now states the ceiling: the highest server major HealthLog supports is the client major in the image, 19 today. Thanks to @aw23edfr4 for tracing it. (Refs [#1431](https://github.com/MBombeck/HealthLog/issues/1431)) ### Security @@ -86,6 +87,10 @@ - Mental-health questionnaire results no longer reach the AI Coach or a connected AI assistant. The Mental wellbeing page says they never do, but the day read both use (`get_day`) carried every PHQ-9, GAD-7, WHO-5 and Sleep Condition Indicator result with its score and severity, and the AI general overview read the totals each result also files as a reading. Results and their scores are now left out of every read that goes to a model or an MCP client, and those reads are filtered once more on the way out, so a read added later cannot hand them over either. The page now says exactly that, in every language, and a test seeds a record with each questionnaire and checks every Coach and MCP read for them. - A request signed in with a token is answered as the account the token belongs to, whatever cookie rides along with it. The native app keeps every cookie it is sent, and three sign-in routes (the password change, registration and the passkey sign-in) handed it a web session cookie as well as its token. The server read that cookie first, so a session from an earlier sign-in could outlive the app's own sign-out and decide which account a later request ran as. The token now always decides: a cookie of the same account is ignored, a cookie of another account is refused with 401 and that session is ended, and an admin page never opens for a request that carries a token. Only the app's own tokens (`hlk_…`, what the iPhone app and the API tokens under Settings send) count: an `Authorization` header with anything else, such as the credential an authenticating reverse proxy forwards in front of the app, is ignored and the cookie decides, so the web app keeps its session behind such a proxy. No route hands a token client a session cookie or one of its hint cookies any more. A password change made with a token answers with a fresh token pair in place of the cookie, since the change ends every sign-in on the account, the caller's own included. +### Updating + +- If you run HealthLog against your own PostgreSQL server, keep its major at or below the client major in the image (`docker run --rm --entrypoint pg_dump ghcr.io/mbombeck/healthlog:latest --version`). See `docs/ops/postgres-major-upgrade.md`. + ## [1.49.0] — 2026-11-23 ### Added diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 246a20b2f3..c4070d062c 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -94,7 +94,25 @@ node scripts/pending-migrations.mjs || true # without the backups volume): a warning, and the boot goes on. A kept # directory and a failed dump: the boot stops here, before anything is # migrated. -if ! node scripts/db-dump.mjs pre-migration; then +# +# Exit 3 is the dump that cannot be taken at all: the database server's major +# is newer than this image's pg_dump (#1431). A restart does not change that, +# and with `restart: unless-stopped` an immediate exit came straight back into +# the same error every few seconds. So the reason is said once, and the +# entrypoint waits ten minutes (inside the healthcheck's start period) before +# it exits; `docker stop` ends the wait at once. +dump_status=0 +node scripts/db-dump.mjs pre-migration || dump_status=$? +if [ "$dump_status" -eq 3 ]; then + echo "HealthLog: ERROR — not migrating: this image's PostgreSQL client cannot dump this database server (see above). Nothing was changed." >&2 + echo "HealthLog: to migrate without a dump this once, set DB_BACKUP_BEFORE_MIGRATE=false; the nightly dumps fail until the client and the server match." >&2 + echo "HealthLog: waiting 10 minutes before exiting, so a restart policy does not restart into the same error. docker stop ends the wait." >&2 + trap 'kill "$wait_pid" 2>/dev/null; exit 1' TERM INT + sleep 600 & + wait_pid=$! + wait "$wait_pid" || true + exit 1 +elif [ "$dump_status" -ne 0 ]; then echo "HealthLog: ERROR — not migrating without the dump. Free disk space or fix the error above and start again." >&2 echo "HealthLog: to migrate without a dump this once, set DB_BACKUP_BEFORE_MIGRATE=false." >&2 exit 1 diff --git a/docs/ops/postgres-major-upgrade.md b/docs/ops/postgres-major-upgrade.md index 49cbc32558..fa92335799 100644 --- a/docs/ops/postgres-major-upgrade.md +++ b/docs/ops/postgres-major-upgrade.md @@ -7,21 +7,48 @@ on the first start after the update. Nothing needs doing by hand on a stack that runs the project's `docker-compose.yml`. Installs that bring their own Postgres (Unraid, an existing database server) -are not touched: HealthLog runs on 16, 18 and 19 alike, and the move there is -yours to schedule with the steps under [By hand](#by-hand). +are not touched, and the move there is yours to schedule with the steps under +[By hand](#by-hand), within one ceiling. -One limit holds in the other direction, though. The image carries `pg_dump` -and `pg_restore` of major 19, and a PostgreSQL client reads servers of its own -major and older but refuses a newer one. A server above the client's major -fails the dump the app takes before every migration, and the app then stops -rather than migrate without one — by which time its nightly dumps have been -failing for as long as the server has been newer. So keep your own server at -or below the major the image carries; this names it for the release you run: +## The highest server major this image supports + +The image carries `pg_dump` and `pg_restore` of one major, and a PostgreSQL +client works with servers of its own major and older, never a newer one. So +**the highest server major HealthLog supports is the client major in the +image you run**: 19 for the current releases, with 16, 18 and 19 all +supported. Check it for the release you run: ```bash docker run --rm --entrypoint pg_dump ghcr.io/mbombeck/healthlog:latest --version ``` +and the server's major with `SHOW server_version;` in `psql`. Keep the server +at or below the client's major; move it past only once a HealthLog release +ships the newer client. + +Every path that runs one of the tools checks the pair first: the dump before +migrating, the nightly dump, and `db-restore`. A server newer than the client +is refused before anything is written, with one line that names both majors: + +``` +HealthLog: ERROR — This image's PostgreSQL client (pg_dump) is 19; your server is 20. ... +``` + +- **At boot, with migrations pending**, the app does not migrate without the + dump. It says why once, waits ten minutes and then exits, so a restart + policy does not restart it into the same error every few seconds; + `docker stop` ends the wait. Bring the server back to the client's major + (restore a dump into a server of that major), or migrate this once without + a dump with `DB_BACKUP_BEFORE_MIGRATE=false`, knowing the nightly dumps + keep failing until the two match. +- **At boot, with nothing to migrate**, the app starts and logs the same line + as a warning. +- **The nightly dump** fails the run with that line. The recovery readiness + check under Admin, Backups calls it failing from the first run, and every + admin gets it as a backup alert on the channels they enabled. +- **`db-restore`** refuses before `pg_restore` runs. Restore into a server of + the client's major or older. + ## What happens on the first start `db-upgrade` is a short-lived container next to `db`. It starts after the new diff --git a/docs/self-hosting/getting-started.md b/docs/self-hosting/getting-started.md index d6b73934a1..1b12fa8b17 100644 --- a/docs/self-hosting/getting-started.md +++ b/docs/self-hosting/getting-started.md @@ -121,6 +121,10 @@ Compose starts two services and one short-lived step: - `db-upgrade` — moves a Postgres 16 database from v1.45 or earlier into the new one, once, and exits; on a new install it has nothing to do. See [Moving to a newer Postgres major](../ops/postgres-major-upgrade.md). + Pointing `DATABASE_URL` at your own server instead works for any major up + to the PostgreSQL client major in the image (19 today); the app refuses a + newer one, see + [the highest supported major](../ops/postgres-major-upgrade.md#the-highest-server-major-this-image-supports). - `app` — HealthLog itself, listening on `localhost:3000`. The image runs `prisma migrate deploy` on boot so the schema lands automatically; subsequent restarts no-op when the database is diff --git a/docs/self-hosting/truenas.md b/docs/self-hosting/truenas.md index 61b1e64473..8eb90239eb 100644 --- a/docs/self-hosting/truenas.md +++ b/docs/self-hosting/truenas.md @@ -221,15 +221,15 @@ before you touch it. Until the catalog app is listed, install HealthLog with Apps, Discover Apps, the menu next to Custom App, Install via YAML, using these values: -| Setting | Value | -| ------------ | -------------------------------------------------------------------------------------- | -| Image | `ghcr.io/mbombeck/healthlog`, tag `X.Y.Z` (amd64 and arm64) | -| Port | `3000` (HTTP) | -| User | runs as uid `1001` by default; no extra capabilities, `no-new-privileges` is fine | -| Health check | `GET /api/health`, `200` when ready | -| Start period | 10 min, like the image: migrations run at every boot and wait out a held lock | -| Database | PostgreSQL 18 (16 works too), no extensions, in its own container with its own dataset | -| Volumes | `/var/lib/healthlog/backups` for the database dumps (uid `1001`); the database its own | +| Setting | Value | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Image | `ghcr.io/mbombeck/healthlog`, tag `X.Y.Z` (amd64 and arm64) | +| Port | `3000` (HTTP) | +| User | runs as uid `1001` by default; no extra capabilities, `no-new-privileges` is fine | +| Health check | `GET /api/health`, `200` when ready | +| Start period | 10 min, like the image: migrations run at every boot and wait out a held lock | +| Database | PostgreSQL 18 (16 and 19 work too, nothing newer than the image's client major, see `docs/ops/postgres-major-upgrade.md`), no extensions, in its own container with its own dataset | +| Volumes | `/var/lib/healthlog/backups` for the database dumps (uid `1001`); the database its own | | Variable | Required | Notes | | ----------------------- | -------- | ---------------------------------------------------------------------------------------- | diff --git a/docs/self-hosting/unraid.md b/docs/self-hosting/unraid.md index fe10923e12..f02dcc72a5 100644 --- a/docs/self-hosting/unraid.md +++ b/docs/self-hosting/unraid.md @@ -76,8 +76,10 @@ then add HealthLog pointed at it. 1. In **Apps** (Community Applications), search for a **PostgreSQL** container (for example jj9987's `postgresql`). Install version 18; an existing 16 - works too. Moving a 16 to 18 later is a dump and restore, see - [Moving to a newer Postgres major](../ops/postgres-major-upgrade.md#by-hand). + works too, and so does 19. Do not go past the PostgreSQL client major in + the HealthLog image (19 today): the app cannot dump a newer server, and + then refuses to migrate. Moving a 16 to 18 later is a dump and restore, see + [Moving to a newer Postgres major](../ops/postgres-major-upgrade.md#the-highest-server-major-this-image-supports). 2. Set: - `POSTGRES_USER` = `healthlog` - `POSTGRES_PASSWORD` = your generated password diff --git a/messages/de.json b/messages/de.json index 48abaae3a2..b8bd5c9a5d 100644 --- a/messages/de.json +++ b/messages/de.json @@ -9497,6 +9497,7 @@ "first_pending": "Der erste Datenbank-Dump ist noch nicht gelaufen.", "stale": "Der neueste Datenbank-Dump ist {hours, plural, one {# Stunde} other {# Stunden}} alt.", "last_failed": "Der letzte Datenbank-Dump ist fehlgeschlagen. Der davor ist noch aktuell.", + "client_too_old": "Der PostgreSQL-Client dieses Images hat Version {client}, der Datenbankserver läuft aber auf {server}, daher kann kein Datenbank-Dump erstellt werden. Nutze ein HealthLog-Image mit Client {server} oder neuer, oder lass den Server auf {client} oder älter.", "fresh": "Der neueste Datenbank-Dump ist aktuell.", "nowhere_to_write": "Das Dump-Verzeichnis {directory} ist nicht beschreibbar und es ist kein externer Bucket eingerichtet, daher kann kein Dump aufbewahrt werden.", "not_persistent": "Das Dump-Verzeichnis {directory} liegt nicht auf dauerhaftem Speicher, und es ist kein externer Bucket eingerichtet. Jeder Dump wäre beim nächsten Update verloren. Binde das Backup-Volume ein.", diff --git a/messages/en.json b/messages/en.json index 1ec024839b..30956d7bfc 100644 --- a/messages/en.json +++ b/messages/en.json @@ -9497,6 +9497,7 @@ "first_pending": "The first database dump has not run yet.", "stale": "The newest database dump is {hours, plural, one {# hour} other {# hours}} old.", "last_failed": "The last database dump failed. The one before it is still recent.", + "client_too_old": "This image's PostgreSQL client is {client}, but the database server runs {server}, so no database dump can be taken. Use a HealthLog image whose client is {server} or newer, or keep the server on {client} or older.", "fresh": "The newest database dump is recent.", "nowhere_to_write": "The dump directory {directory} cannot be written to and no off-host bucket is set up, so no dump can be kept.", "not_persistent": "The dump directory {directory} is not on persistent storage and no off-host bucket is set up, so every dump would be lost at the next update. Mount the backups volume.", diff --git a/messages/es.json b/messages/es.json index 2d6b23e4d3..fb2403d8b7 100644 --- a/messages/es.json +++ b/messages/es.json @@ -9497,6 +9497,7 @@ "first_pending": "El primer volcado de la base de datos aún no se ha ejecutado.", "stale": "El volcado de la base de datos más reciente tiene {hours, plural, one {# hora} other {# horas}}.", "last_failed": "El último volcado de la base de datos falló. El anterior sigue siendo reciente.", + "client_too_old": "El cliente de PostgreSQL de esta imagen es la versión {client}, pero el servidor de base de datos usa la {server}, así que no se puede hacer ningún volcado. Usa una imagen de HealthLog cuyo cliente sea {server} o posterior, o mantén el servidor en {client} o anterior.", "fresh": "El último volcado de la base de datos es reciente.", "nowhere_to_write": "No se puede escribir en el directorio de volcados {directory} y no hay ningún bucket externo configurado, así que no se puede guardar ningún volcado.", "not_persistent": "El directorio de volcados {directory} no está en almacenamiento persistente y no hay un bucket externo configurado, así que cada volcado se perdería en la próxima actualización. Monta el volumen de copias.", diff --git a/messages/fr.json b/messages/fr.json index 6f7cfd3474..7e77cf4be8 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -9497,6 +9497,7 @@ "first_pending": "Le premier dump de la base de données n'a pas encore été lancé.", "stale": "Le dump de la base de données le plus récent date de {hours, plural, one {# heure} other {# heures}}.", "last_failed": "Le dernier dump de la base de données a échoué. Le précédent est encore récent.", + "client_too_old": "Le client PostgreSQL de cette image est en version {client}, mais le serveur de base de données est en {server} : aucun dump ne peut être réalisé. Utilisez une image HealthLog dont le client est en {server} ou plus récent, ou gardez le serveur en {client} ou plus ancien.", "fresh": "Le dernier dump de la base de données est récent.", "nowhere_to_write": "Le dossier des dumps {directory} n'est pas accessible en écriture et aucun bucket externe n'est configuré, donc aucun dump ne peut être conservé.", "not_persistent": "Le répertoire des dumps {directory} n'est pas sur un stockage persistant et aucun bucket hors site n'est configuré : chaque dump serait perdu à la prochaine mise à jour. Montez le volume de sauvegarde.", diff --git a/messages/it.json b/messages/it.json index ce10f18c6a..cc4821ee17 100644 --- a/messages/it.json +++ b/messages/it.json @@ -9497,6 +9497,7 @@ "first_pending": "Il primo dump del database non è ancora stato eseguito.", "stale": "Il dump del database più recente ha {hours, plural, one {# ora} other {# ore}}.", "last_failed": "L'ultimo dump del database non è riuscito. Quello precedente è ancora recente.", + "client_too_old": "Il client PostgreSQL di questa immagine è la versione {client}, ma il server del database usa la {server}, quindi non si può fare nessun dump. Usa un'immagine HealthLog con client {server} o più recente, oppure tieni il server su {client} o precedente.", "fresh": "L'ultimo dump del database è recente.", "nowhere_to_write": "La cartella dei dump {directory} non è scrivibile e non è configurato nessun bucket esterno, quindi non si può conservare alcun dump.", "not_persistent": "La cartella dei dump {directory} non è su uno spazio persistente e non è configurato alcun bucket esterno, quindi ogni dump andrebbe perso al prossimo aggiornamento. Monta il volume dei backup.", diff --git a/messages/ko.json b/messages/ko.json index 960b0baa91..b22a0c63c7 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -9497,6 +9497,7 @@ "first_pending": "첫 데이터베이스 덤프가 아직 실행되지 않았습니다.", "stale": "최신 데이터베이스 덤프가 {hours, plural, other {#시간}} 전 것입니다.", "last_failed": "마지막 데이터베이스 덤프가 실패했습니다. 그 전 덤프는 아직 최근 것입니다.", + "client_too_old": "이 이미지의 PostgreSQL 클라이언트는 {client} 버전인데 데이터베이스 서버는 {server} 버전이라 데이터베이스 덤프를 만들 수 없습니다. 클라이언트가 {server} 이상인 HealthLog 이미지를 쓰거나, 서버를 {client} 이하로 유지하세요.", "fresh": "최신 데이터베이스 덤프가 최근 것입니다.", "nowhere_to_write": "덤프 디렉터리 {directory}에 쓸 수 없고 외부 버킷도 설정되어 있지 않아 덤프를 보관할 수 없습니다.", "not_persistent": "덤프 디렉터리 {directory}이(가) 영구 저장소에 있지 않고 외부 버킷도 설정되지 않아, 모든 덤프가 다음 업데이트 때 사라집니다. 백업 볼륨을 마운트하세요.", diff --git a/messages/nl.json b/messages/nl.json index a10f55c08a..e6441e1738 100644 --- a/messages/nl.json +++ b/messages/nl.json @@ -9497,6 +9497,7 @@ "first_pending": "De eerste databasedump is nog niet uitgevoerd.", "stale": "De nieuwste databasedump is {hours, plural, one {# uur} other {# uur}} oud.", "last_failed": "De laatste databasedump is mislukt. De dump daarvoor is nog recent.", + "client_too_old": "De PostgreSQL-client van dit image is versie {client}, maar de databaseserver draait {server}, dus er kan geen databasedump worden gemaakt. Gebruik een HealthLog-image met client {server} of nieuwer, of houd de server op {client} of ouder.", "fresh": "De nieuwste databasedump is recent.", "nowhere_to_write": "De dumpmap {directory} is niet beschrijfbaar en er is geen externe bucket ingesteld, dus er kan geen dump worden bewaard.", "not_persistent": "De dumpmap {directory} staat niet op blijvende opslag en er is geen externe bucket ingesteld, dus elke dump gaat bij de volgende update verloren. Koppel het back-upvolume.", diff --git a/messages/pl.json b/messages/pl.json index 5cb7b1e84a..f5a26e4f5b 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -9497,6 +9497,7 @@ "first_pending": "Pierwszy zrzut bazy danych jeszcze się nie odbył.", "stale": "Najnowszy zrzut bazy danych ma {hours, plural, one {# godzinę} few {# godziny} many {# godzin} other {# godziny}}.", "last_failed": "Ostatni zrzut bazy danych nie powiódł się. Poprzedni jest jeszcze aktualny.", + "client_too_old": "Klient PostgreSQL w tym obrazie ma wersję {client}, a serwer bazy danych działa na {server}, więc nie da się wykonać zrzutu bazy. Użyj obrazu HealthLog z klientem {server} lub nowszym albo zostaw serwer na {client} lub starszym.", "fresh": "Najnowszy zrzut bazy danych jest aktualny.", "nowhere_to_write": "Katalog zrzutów {directory} nie jest zapisywalny i nie skonfigurowano zewnętrznego bucketu, więc żaden zrzut nie może zostać zachowany.", "not_persistent": "Katalog zrzutów {directory} nie leży na trwałym nośniku, a zewnętrzny bucket nie jest ustawiony, więc każdy zrzut przepadnie przy następnej aktualizacji. Podłącz wolumin kopii.", diff --git a/messages/pt-BR.json b/messages/pt-BR.json index 63d9e49d98..a12201da99 100644 --- a/messages/pt-BR.json +++ b/messages/pt-BR.json @@ -9497,6 +9497,7 @@ "first_pending": "O primeiro dump do banco de dados ainda não foi executado.", "stale": "O dump do banco de dados mais recente tem {hours, plural, one {# hora} other {# horas}}.", "last_failed": "O último dump do banco de dados falhou. O anterior ainda é recente.", + "client_too_old": "O cliente PostgreSQL desta imagem é a versão {client}, mas o servidor do banco de dados roda a {server}, então nenhum dump pode ser feito. Use uma imagem do HealthLog com cliente {server} ou mais novo, ou mantenha o servidor na {client} ou anterior.", "fresh": "O dump do banco de dados mais recente está em dia.", "nowhere_to_write": "Não é possível gravar no diretório de dumps {directory} e nenhum bucket externo está configurado, então nenhum dump pode ser guardado.", "not_persistent": "A pasta de dumps {directory} não está em armazenamento persistente e nenhum bucket externo está configurado, então cada dump se perde na próxima atualização. Monte o volume de backups.", diff --git a/messages/ru.json b/messages/ru.json index 415df552f4..cb381346ed 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -9497,6 +9497,7 @@ "first_pending": "Первый дамп базы данных ещё не выполнялся.", "stale": "Самому новому дампу базы данных {hours, plural, one {# час} few {# часа} many {# часов} other {# часа}}.", "last_failed": "Последний дамп базы данных не удался. Предыдущий всё ещё свежий.", + "client_too_old": "Клиент PostgreSQL в этом образе версии {client}, а сервер базы данных работает на {server}, поэтому дамп базы сделать нельзя. Используйте образ HealthLog с клиентом {server} или новее либо оставьте сервер на {client} или старше.", "fresh": "Новейший дамп базы данных свежий.", "nowhere_to_write": "В каталог дампов {directory} нельзя писать, и внешний бакет не настроен, поэтому ни один дамп нельзя сохранить.", "not_persistent": "Каталог дампов {directory} не на постоянном хранилище, и внешний бакет не настроен, поэтому каждый дамп был бы потерян при следующем обновлении. Смонтируйте том резервных копий.", diff --git a/scripts/__tests__/db-dump.test.ts b/scripts/__tests__/db-dump.test.ts index bad66da72d..f876b86a8e 100644 --- a/scripts/__tests__/db-dump.test.ts +++ b/scripts/__tests__/db-dump.test.ts @@ -11,10 +11,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const pendingMigrations = vi.fn<() => Promise>(); -const createDatabaseDump = vi.fn(async () => ({ +const createDatabaseDump = vi.fn<() => Promise>(async () => ({ dumpPath: "/b/healthlog-20261025T013000Z-pre-migration.dump", manifest: { dump: { bytes: 1024 }, rowCounts: { "public.users": 1 } }, })); +const assertClientServesServer = vi.fn<() => Promise>(async () => ({ + clientMajor: 19, + serverMajor: 18, +})); vi.mock("../pending-migrations.mjs", () => ({ pendingMigrations: () => pendingMigrations(), @@ -28,9 +32,14 @@ vi.mock("../../src/lib/database-backup/dump-core.mjs", async (original) => ({ latestMigration: async () => "0488_account_deletion_grace", listUserTables: async () => ["public.users"], createDatabaseDump: () => createDatabaseDump(), + assertClientServesServer: () => assertClientServesServer(), applyRetention: async () => [], })); +import { + ClientTooOldError, + clientServerMismatch, +} from "../../src/lib/database-backup/dump-core.mjs"; import { preMigrationDump } from "../db-dump.mjs"; const env = { @@ -44,7 +53,21 @@ beforeEach(() => { vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); createDatabaseDump.mockClear(); + assertClientServesServer.mockClear(); }); + +/** What `pg_dump` 19 against a server on 20 is refused with. */ +function tooOld() { + const pair = { tool: "pg_dump", clientMajor: 19, serverMajor: 20 }; + return new ClientTooOldError(clientServerMismatch(pair) ?? "", pair); +} + +function errorLines(): string { + return vi + .mocked(console.error) + .mock.calls.map((c) => String(c[0])) + .join("\n"); +} afterEach(() => vi.restoreAllMocks()); describe("the dump before migrating", () => { @@ -67,4 +90,43 @@ describe("the dump before migrating", () => { expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(0); expect(createDatabaseDump).toHaveBeenCalledTimes(1); }); + + // #1431: a server newer than the image's client stopped the boot with + // pg_dump's own mismatch line. It stops the boot still, with its own exit + // code, so the entrypoint does not restart it in a hot loop, and with one + // message that names both majors. + it("stops with its own exit code and one clear message when the server is newer than the client", async () => { + pendingMigrations.mockResolvedValue(["0489_database_backup_run_key"]); + createDatabaseDump.mockRejectedValueOnce(tooOld()); + expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(3); + const errors = errorLines(); + expect(errors).toMatch( + /This image's PostgreSQL client \(pg_dump\) is 19; your server is 20\./, + ); + expect(errors.match(/your server is 20/g)).toHaveLength(1); + expect(errors).not.toContain("the database dump before migrating failed"); + }); + + it("keeps exit 1 for any other failed dump", async () => { + pendingMigrations.mockResolvedValue(["0489_database_backup_run_key"]); + createDatabaseDump.mockRejectedValueOnce(new Error("No space left")); + expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(1); + }); + + it("warns at a boot with nothing to migrate that the nightly dump cannot work", async () => { + pendingMigrations.mockResolvedValue([]); + assertClientServesServer.mockRejectedValueOnce(tooOld()); + expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(0); + expect(createDatabaseDump).not.toHaveBeenCalled(); + expect(errorLines()).toMatch( + /WARNING .*client \(pg_dump\) is 19; your server is 20\..*nightly database dump/, + ); + }); + + it("says nothing at such a boot when the client serves the server", async () => { + pendingMigrations.mockResolvedValue([]); + expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(0); + expect(assertClientServesServer).toHaveBeenCalledTimes(1); + expect(errorLines()).toBe(""); + }); }); diff --git a/scripts/__tests__/db-restore.test.ts b/scripts/__tests__/db-restore.test.ts index 3479d2566f..fe5eece966 100644 --- a/scripts/__tests__/db-restore.test.ts +++ b/scripts/__tests__/db-restore.test.ts @@ -16,7 +16,9 @@ import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const tablesInTarget = vi.fn(async (): Promise => []); -const runTool = vi.fn(async () => ""); +const runTool = vi.fn(async (..._args: unknown[]) => ""); +/** What the target answers for `server_version_num`; null answers nothing. */ +let serverVersionNum: number | null = null; const end = vi.fn(async () => {}); /** What the stand-in bucket lists under `database/`; downloads are refused. */ const bucketKeys = vi.fn(async (): Promise => []); @@ -26,7 +28,15 @@ const downloads = vi.fn(async (key: string) => { vi.mock("../../src/lib/database-backup/dump-core.mjs", async (original) => ({ ...(await original>()), - connect: async () => ({ query: async () => ({ rows: [] }), end }), + connect: async () => ({ + query: async (sql: string) => + serverVersionNum !== null && /server_version_num/.test(sql) + ? { + rows: [{ v: `${serverVersionNum / 10000}.0`, n: serverVersionNum }], + } + : { rows: [] }, + end, + }), listUserTables: () => tablesInTarget(), runTool: (...args: unknown[]) => runTool(...(args as [])), openBucket: async () => ({ @@ -93,7 +103,9 @@ beforeEach(() => { lines.push(String(line)); }); tablesInTarget.mockResolvedValue([]); - runTool.mockClear(); + runTool.mockReset(); + runTool.mockResolvedValue(""); + serverVersionNum = null; }); afterEach(() => { rmSync(dir, { recursive: true, force: true }); @@ -150,6 +162,44 @@ describe("db-restore refuses before it writes", () => { expect(runTool).not.toHaveBeenCalled(); }); + // #1431: the same ceiling as the dump's. `pg_restore` is not run against a + // server newer than its own major; the refusal names both and the way out. + it("refuses a server newer than this image's pg_restore, before it restores", async () => { + writeDump(); + serverVersionNum = 200000; + runTool.mockImplementation(async (...args: unknown[]) => + (args[1] as string[]).includes("--version") + ? "pg_restore (PostgreSQL) 19.1\n" + : "", + ); + expect(await main(["latest"], env())).toBe(1); + expect(errors.join("\n")).toMatch( + /This image's PostgreSQL client \(pg_restore\) is 19; your server is 20\./, + ); + const restored = runTool.mock.calls.filter( + (c) => !(c[1] as string[]).includes("--version"), + ); + expect(restored).toEqual([]); + }); + + it("restores into a server of the client's own major", async () => { + writeDump(); + serverVersionNum = 190001; + runTool.mockImplementation(async (...args: unknown[]) => + (args[1] as string[]).includes("--version") + ? "pg_restore (PostgreSQL) 19.1\n" + : "", + ); + await main(["latest"], env()); + expect( + runTool.mock.calls.some( + (c) => + c[0] === "pg_restore" && + (c[1] as string[]).includes("--single-transaction"), + ), + ).toBe(true); + }); + it("says when there is nothing to restore, and how it is used", async () => { expect(await main(["latest"], env())).toBe(1); expect(errors.join("\n")).toMatch(/no restorable dump/); diff --git a/scripts/__tests__/docker-entrypoint.test.ts b/scripts/__tests__/docker-entrypoint.test.ts new file mode 100644 index 0000000000..0053e1a074 --- /dev/null +++ b/scripts/__tests__/docker-entrypoint.test.ts @@ -0,0 +1,136 @@ +/** + * How `docker-entrypoint.sh` ends when the dump before migrating fails. + * + * `node` is a stand-in on PATH: every check the entrypoint runs with it + * passes, `scripts/db-dump.mjs` exits with the code a case asks for, and + * `scripts/migrate-deploy.mjs` leaves a mark, so a case can tell whether the + * boot went on to migrate. The real dump step and its exit codes are in + * `db-dump.test.ts` and `tests/integration/database-backup.test.ts`. + * + * A server newer than the image's `pg_dump` (#1431) is the failure a restart + * cannot fix. With `restart: unless-stopped` an immediate exit restarted into + * the same error every few seconds; the entrypoint now says why once and + * waits before it exits, and `docker stop` still ends it at once. + */ +import { spawn } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +const ENTRYPOINT = join(process.cwd(), "docker-entrypoint.sh"); +const work = mkdtempSync(join(tmpdir(), "hl-entrypoint-")); +const bin = join(work, "bin"); + +mkdirSync(bin, { recursive: true }); +writeFileSync( + join(bin, "node"), + `#!/bin/sh +case "$*" in + *scripts/db-dump.mjs*) + [ "$DUMP_EXIT" = 3 ] && echo "HealthLog: ERROR — This image's PostgreSQL client (pg_dump) is 19; your server is 20." >&2 + exit "$DUMP_EXIT" ;; + *scripts/migrate-deploy.mjs*) : > "$MIGRATED_MARK"; exit 0 ;; + *) exit 0 ;; +esac +`, +); +chmodSync(join(bin, "node"), 0o755); + +afterAll(() => rmSync(work, { recursive: true, force: true })); + +interface Run { + code: number | null; + signal: NodeJS.Signals | null; + stderr: string; + stdout: string; + migrated: boolean; + ms: number; +} + +/** + * Run the entrypoint with the dump step exiting `dumpExit`. With `stopAfter`, + * SIGTERM is sent that many ms after the wait message appears, as + * `docker stop` would. + */ +function boot(dumpExit: number, stopAfter?: number): Promise { + const mark = join(work, `migrated-${dumpExit}-${Date.now()}`); + return new Promise((resolve, reject) => { + const started = Date.now(); + const child = spawn("sh", [ENTRYPOINT, "true"], { + env: { + PATH: `${bin}:${process.env.PATH}`, + DATABASE_URL: "postgresql://u:p@127.0.0.1:5432/healthlog", + API_TOKEN_HMAC_KEY: "hmac", + ENCRYPTION_KEY: "a".repeat(64), + DUMP_EXIT: String(dumpExit), + MIGRATED_MARK: mark, + }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stderr = ""; + let stdout = ""; + let stopping = false; + child.stdout.on("data", (c) => (stdout += String(c))); + child.stderr.on("data", (c) => { + stderr += String(c); + if (stopAfter !== undefined && !stopping && /waiting/i.test(stderr)) { + stopping = true; + setTimeout(() => child.kill("SIGTERM"), stopAfter); + } + }); + const guard = setTimeout(() => { + child.kill("SIGKILL"); + reject(new Error(`the entrypoint did not end: ${stderr}`)); + }, 15_000); + child.on("close", (code, signal) => { + clearTimeout(guard); + resolve({ + code, + signal, + stderr, + stdout, + migrated: existsSync(mark), + ms: Date.now() - started, + }); + }); + }); +} + +describe("the entrypoint when the dump before migrating fails", () => { + it("migrates and starts after a dump that worked", async () => { + const run = await boot(0); + expect(run.code, run.stderr).toBe(0); + expect(run.migrated).toBe(true); + }); + + it("stops at once, without migrating, after a dump that failed", async () => { + const run = await boot(1); + expect(run.code).toBe(1); + expect(run.migrated).toBe(false); + expect(run.stderr).toContain("not migrating without the dump"); + expect(run.stderr).not.toMatch(/waiting/i); + }); + + it("does not migrate, says why once, and waits instead of restarting into the same error, when the server is newer than the client", async () => { + const run = await boot(3, 1500); + // It was still waiting when it was stopped, and the stop ended it with + // the entrypoint's own failure code rather than a kill. + expect(run.ms).toBeGreaterThanOrEqual(1500); + expect(run.signal).toBeNull(); + expect(run.code).toBe(1); + expect(run.migrated).toBe(false); + expect(run.stderr.match(/your server is 20/g)).toHaveLength(1); + expect(run.stderr).toContain("cannot dump this database server"); + expect(run.stderr).toContain("DB_BACKUP_BEFORE_MIGRATE=false"); + expect(run.stderr).not.toContain("Free disk space"); + }); +}); diff --git a/scripts/db-dump.mjs b/scripts/db-dump.mjs index 6337658f65..83312522e4 100644 --- a/scripts/db-dump.mjs +++ b/scripts/db-dump.mjs @@ -21,7 +21,11 @@ * not a reason to keep the app down. Exit 1: the directory is kept and the * dump failed. The entrypoint then stops the boot and names the switch that skips * the dump, because migrating without the way back the operator was promised - * is the one thing this step exists to prevent. + * is the one thing this step exists to prevent. Exit 3: the dump cannot be + * taken at all, because the server's major is newer than this image's + * `pg_dump` (#1431). That does not pass with a restart, so the entrypoint + * says so once and does not restart in a hot loop. At a boot with nothing to + * migrate the same pair is a warning, since the nightly dump fails on it. * * Fast on purpose: one snapshot, `pg_dump`, a count per table for the * manifest, `pg_restore --list` to prove the file reads. Nothing else. @@ -32,7 +36,9 @@ import { pathToFileURL } from "node:url"; import { applyRetention, + assertClientServesServer, backupDirectoryStatus, + ClientTooOldError, connect, createDatabaseDump, latestMigration, @@ -59,6 +65,32 @@ function imageVersion(env) { } } +/** The exit code for a server newer than this image's `pg_dump`. */ +export const CLIENT_TOO_OLD_EXIT = 3; + +/** + * Warn, and only warn, when this image's `pg_dump` cannot dump the server: + * nothing is migrated at this boot, but the nightly dump fails until the + * pair is fixed. Any other error here is not this step's to report. + * + * @param {string} databaseUrl + */ +async function warnIfClientTooOld(databaseUrl) { + let client; + try { + client = await connect(databaseUrl); + await assertClientServesServer(client, "pg_dump"); + } catch (error) { + if (error instanceof ClientTooOldError) { + warn( + `${error.message} The nightly database dump fails until the two match; the app starts.`, + ); + } + } finally { + await client?.end().catch(() => {}); + } +} + /** Megabytes as an operator reads them. */ function mb(bytes) { return `${(bytes / 1024 / 1024).toFixed(1)} MB`; @@ -93,7 +125,10 @@ export async function preMigrationDump(env = process.env, options = {}) { ); pending = null; } - if (pending !== null && pending.length === 0) return 0; + if (pending !== null && pending.length === 0) { + await warnIfClientTooOld(databaseUrl); + return 0; + } const migrations = pending === null ? "any pending migrations" @@ -129,6 +164,7 @@ export async function preMigrationDump(env = process.env, options = {}) { `${dir} ${why}, so no dump is taken before ${pending === null ? migrations : `the ${migrations}`}. ` + "Mount the backups volume (docker-compose.yml) to keep a way back; continuing.", ); + await warnIfClientTooOld(databaseUrl); return 0; } @@ -148,6 +184,10 @@ export async function preMigrationDump(env = process.env, options = {}) { `${Object.keys(manifest.rowCounts).length} tables, ${Math.round((Date.now() - started) / 1000)} s).`, ); } catch (error) { + if (error instanceof ClientTooOldError) { + console.error(`HealthLog: ERROR — ${error.message}`); + return CLIENT_TOO_OLD_EXIT; + } console.error( `HealthLog: ERROR — the database dump before migrating failed: ${error instanceof Error ? error.message : String(error)}`, ); diff --git a/scripts/db-restore.mjs b/scripts/db-restore.mjs index fd9908a327..1f76259e48 100644 --- a/scripts/db-restore.mjs +++ b/scripts/db-restore.mjs @@ -34,7 +34,9 @@ * fingerprints; each one missing or different is named, and a mismatch * of the active encryption key refuses (`--ignore-key-mismatch` restores * anyway, for an operator who knows the key is lost); - * 4. the target database must hold no table at all. This never overwrites. + * 4. the target database must hold no table at all. This never overwrites; + * 5. the target server's major must not be newer than this image's + * `pg_restore` (#1431): the refusal names both majors and the way out. * Then `pg_restore` in one transaction, `ANALYZE`, and a count of every table * against the manifest. A count that differs empties the database again and * fails, so the app is never started on a restore that does not match. @@ -48,6 +50,8 @@ import { basename, dirname, isAbsolute, join } from "node:path"; import { pathToFileURL } from "node:url"; import { + assertClientServesServer, + ClientTooOldError, compareKeyFingerprints, compareRowCounts, connect, @@ -433,6 +437,22 @@ async function restoreCommand(arg, flags, env) { ); } + // 5. The image's client can work with this server. + try { + await assertClientServesServer(client, "pg_restore", { + versionLine: () => + runTool("pg_restore", ["--version"], { capture: true }).then( + (line) => line.trim(), + () => null, + ), + }); + } catch (error) { + if (error instanceof ClientTooOldError) { + throw new Refusal(error.message); + } + throw error; + } + say("restoring (one transaction)..."); const started = Date.now(); await runTool( diff --git a/src/lib/database-backup/__tests__/client-server-major.test.ts b/src/lib/database-backup/__tests__/client-server-major.test.ts new file mode 100644 index 0000000000..cf733bf1cd --- /dev/null +++ b/src/lib/database-backup/__tests__/client-server-major.test.ts @@ -0,0 +1,180 @@ +/** + * The client tools' major caps the server major (#1431). `pg_dump` refuses a + * server newer than its own major, and it says so in a line that, inside a + * boot abort, did not point at the cause. These are the rules of the check + * that runs before any client tool touches the server: how a `--version` + * line and `server_version_num` are read, when the pair is refused, and the + * one message an operator gets for it. + */ +import { describe, expect, it } from "vitest"; + +import { + ClientTooOldError, + assertClientServesServer, + clientMajorFromVersionLine, + clientServerMismatch, + serverMajorFromVersionNum, +} from "../dump-core.mjs"; +import { clientTooOldIn } from "../dump-problems"; + +describe("reading the client's major", () => { + it.each([ + ["pg_dump (PostgreSQL) 16.4", 16], + ["pg_dump (PostgreSQL) 18.6 (Debian 18.6-1.pgdg13+1)", 18], + ["pg_restore (PostgreSQL) 19.0", 19], + ["pg_dump (PostgreSQL) 20.1", 20], + ["pg_dump (PostgreSQL) 19devel", 19], + ["pg_dump (PostgreSQL) 19beta2", 19], + ["pg_dump (PostgreSQL) 20rc1", 20], + ["pg_dump (PostgreSQL) 9.6.24", 9], + ["pg_dump (PostgreSQL) 18.6\n", 18], + ])("%s is %i", (line, major) => { + expect(clientMajorFromVersionLine(line)).toBe(major); + }); + + it.each([[null], [""], ["command not found"], ["pg_dump (PostgreSQL)"]])( + "%j names no major", + (line) => { + expect(clientMajorFromVersionLine(line)).toBeNull(); + }, + ); +}); + +describe("reading the server's major", () => { + it.each([ + [160004, 16], + [180006, 18], + [190000, 19], // 19devel and 19beta report the .0 + [190001, 19], + [200000, 20], + [90624, 9], + ])("%i is %i", (num, major) => { + expect(serverMajorFromVersionNum(num)).toBe(major); + }); + + it.each([[null], [0], [-1], [Number.NaN], [1.5]])("%s is unknown", (num) => { + expect(serverMajorFromVersionNum(num)).toBeNull(); + }); +}); + +describe("which pairs are refused", () => { + it.each([ + [19, 16], + [19, 18], + [19, 19], + [20, 19], + ])("client %i serves server %i", (client, server) => { + expect( + clientServerMismatch({ + tool: "pg_dump", + clientMajor: client, + serverMajor: server, + }), + ).toBeNull(); + }); + + it.each([ + [18, 19], + [19, 20], + [16, 18], + ])("client %i refuses server %i", (client, server) => { + expect( + clientServerMismatch({ + tool: "pg_dump", + clientMajor: client, + serverMajor: server, + }), + ).not.toBeNull(); + }); + + // An unknown side is not a reason to refuse: the tool runs and says what + // is wrong in its own words, as before the check existed. + it.each([ + [null, 20], + [19, null], + [null, null], + ])("client %s and server %s are not refused", (client, server) => { + expect( + clientServerMismatch({ + tool: "pg_dump", + clientMajor: client, + serverMajor: server, + }), + ).toBeNull(); + }); + + it("names both majors and the way out, in one message that reads back", () => { + const message = clientServerMismatch({ + tool: "pg_dump", + clientMajor: 19, + serverMajor: 20, + }); + expect(message).toMatch( + /^This image's PostgreSQL client \(pg_dump\) is 19; your server is 20\./, + ); + expect(message).toContain("PostgreSQL 19 and older"); + expect(message).toContain("client is 20 or newer"); + expect(message).toContain("keep the server on 19 or older"); + expect(message).toContain("docs/ops/postgres-major-upgrade.md"); + // The ledger keeps 500 characters of a failure. + expect(message!.length).toBeLessThanOrEqual(500); + expect(clientTooOldIn(message)).toEqual({ + tool: "pg_dump", + client: 19, + server: 20, + }); + }); + + it("reads no mismatch out of any other failure", () => { + expect(clientTooOldIn(null)).toBeNull(); + expect( + clientTooOldIn( + "pg_dump exited 1: pg_dump: error: aborting because of server version mismatch", + ), + ).toBeNull(); + }); +}); + +describe("the check before a tool runs", () => { + const server = (n: number | null) => ({ + query: async () => + n === null + ? { rows: [] } + : { rows: [{ v: `${Math.floor(n / 10000)}.0`, n }] }, + }); + + it("refuses a server newer than the client, before the tool is run", async () => { + const error = await assertClientServesServer(server(200000), "pg_dump", { + versionLine: async () => "pg_dump (PostgreSQL) 19.1", + }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(ClientTooOldError); + expect((error as ClientTooOldError).clientMajor).toBe(19); + expect((error as ClientTooOldError).serverMajor).toBe(20); + expect((error as Error).message).toMatch( + /client \(pg_dump\) is 19; your server is 20/, + ); + }); + + it("lets an older or equal server through", async () => { + for (const n of [160004, 180006, 190001]) { + await expect( + assertClientServesServer(server(n), "pg_restore", { + versionLine: async () => "pg_restore (PostgreSQL) 19.1", + }), + ).resolves.toMatchObject({ clientMajor: 19 }); + } + }); + + it("lets the tool run when either major cannot be read", async () => { + await expect( + assertClientServesServer(server(null), "pg_dump", { + versionLine: async () => "pg_dump (PostgreSQL) 19.1", + }), + ).resolves.toEqual({ clientMajor: 19, serverMajor: null }); + await expect( + assertClientServesServer(server(200000), "pg_dump", { + versionLine: async () => null, + }), + ).resolves.toEqual({ clientMajor: null, serverMajor: 20 }); + }); +}); diff --git a/src/lib/database-backup/dump-core.mjs b/src/lib/database-backup/dump-core.mjs index 565e408621..77068874bb 100644 --- a/src/lib/database-backup/dump-core.mjs +++ b/src/lib/database-backup/dump-core.mjs @@ -920,13 +920,119 @@ async function createPrivateFile(path) { /** `pg_dump (PostgreSQL) 18.6`, or null when it cannot be asked. */ export async function pgDumpVersion() { + return toolVersion("pg_dump"); +} + +/** + * A client tool's `--version` line, or null when it cannot be asked. + * @param {string} tool + */ +export async function toolVersion(tool) { try { - return (await runTool("pg_dump", ["--version"], { capture: true })).trim(); + return (await runTool(tool, ["--version"], { capture: true })).trim(); } catch { return null; } } +// ── The client's major caps the server's ─────────────────────────────────── +// +// `pg_dump` reads servers of its own major and older, and refuses a newer one +// with a version-mismatch line. So the client major in the image is the +// highest server major HealthLog can dump, and the dump before migrating +// gates the boot: a server moved past it took the app down at the next +// release with a migration, and the nightly dump failed with the same line +// (#1431). `pg_restore` is held to the same rule. Every path that runs either +// tool against a server checks the pair first and refuses with one message +// that names both majors and the way out. + +/** + * The major in a `--version` line: `pg_dump (PostgreSQL) 19.1` is 19, and so + * are `19devel`, `19beta2` and `19rc1`. Null when the line names none. + * + * @param {string | null | undefined} line + * @returns {number | null} + */ +export function clientMajorFromVersionLine(line) { + const match = /\(PostgreSQL\)\s+(\d+)/.exec(line ?? ""); + return match ? Number(match[1]) : null; +} + +/** + * The major in `server_version_num`: 190001 is 19. A development or beta + * build reports its major's `.0` (190000). Null for anything else. + * + * @param {number | null | undefined} num + * @returns {number | null} + */ +export function serverMajorFromVersionNum(num) { + return typeof num === "number" && Number.isSafeInteger(num) && num > 0 + ? Math.floor(num / 10000) + : null; +} + +/** + * The operator message for a client older than the server, or null when the + * pair works. A side that cannot be read is not refused: the tool runs and + * says what is wrong in its own words. + * + * The message opens with a fixed sentence `clientTooOldIn` (dump-problems.ts) + * reads back from a stored failure, and stays under the ledger's 500 + * characters. + * + * @param {{ tool: string; clientMajor: number | null; serverMajor: number | null }} pair + * @returns {string | null} + */ +export function clientServerMismatch({ tool, clientMajor, serverMajor }) { + if (clientMajor === null || serverMajor === null) return null; + if (serverMajor <= clientMajor) return null; + return ( + `This image's PostgreSQL client (${tool}) is ${clientMajor}; your server is ${serverMajor}. ` + + `${tool} cannot work with a server newer than its own major, so this image supports PostgreSQL ${clientMajor} and older. ` + + `Use a HealthLog image whose client is ${serverMajor} or newer, or keep the server on ${clientMajor} or older ` + + `(docs/ops/postgres-major-upgrade.md).` + ); +} + +/** A client tool older than the server it was about to run against. */ +export class ClientTooOldError extends Error { + /** + * @param {string} message + * @param {{ tool: string; clientMajor: number; serverMajor: number }} pair + */ + constructor(message, pair) { + super(message); + this.name = "ClientTooOldError"; + this.tool = pair.tool; + this.clientMajor = pair.clientMajor; + this.serverMajor = pair.serverMajor; + } +} + +/** + * The check before `tool` runs against the server `client` is connected to: + * throws `ClientTooOldError` when the server's major is newer than the + * tool's. Answers both majors, either null when it could not be read. + * + * @param {Queryable} client + * @param {string} tool + * @param {{ versionLine?: () => Promise }} [options] + * @returns {Promise<{ clientMajor: number | null; serverMajor: number | null }>} + */ +export async function assertClientServesServer(client, tool, options = {}) { + const [line, server] = await Promise.all([ + (options.versionLine ?? (() => toolVersion(tool)))(), + serverVersion(client).catch(() => null), + ]); + const clientMajor = clientMajorFromVersionLine(line); + const serverMajor = serverMajorFromVersionNum(server?.versionNum ?? null); + const message = clientServerMismatch({ tool, clientMajor, serverMajor }); + if (message !== null && clientMajor !== null && serverMajor !== null) { + throw new ClientTooOldError(message, { tool, clientMajor, serverMajor }); + } + return { clientMajor, serverMajor }; +} + /** * Read an archive's table of contents back. A file `pg_restore` cannot list * is not a dump, whatever its name. Answers the number of entries. @@ -1090,6 +1196,10 @@ export async function createDatabaseDump(options) { /** The files this call created, and only those, go on a failure. */ const created = []; try { + // Before anything is written: a server newer than this image's + // `pg_dump` is refused with the majors and the way out, not with the + // tool's own mismatch line. + await assertClientServesServer(client, "pg_dump"); await client.query("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY"); const { rows } = await client.query( "SELECT pg_export_snapshot() AS snapshot", diff --git a/src/lib/database-backup/dump-problems.ts b/src/lib/database-backup/dump-problems.ts index e044625501..74da0db187 100644 --- a/src/lib/database-backup/dump-problems.ts +++ b/src/lib/database-backup/dump-problems.ts @@ -42,3 +42,21 @@ export function databaseDumpProblems( const isTheUpload = offhost !== null && failure?.at === offhost.at; return { failure: sinceGood && !isTheUpload ? failure : null, offhost }; } + +/** + * The majors in a failure `clientServerMismatch` (dump-core.mjs) wrote: the + * server is newer than this image's `pg_dump` or `pg_restore` (#1431). Null + * for any other failure. Read here rather than in the dump module, which + * runs client tools and cannot be bundled for the browser. + */ +export function clientTooOldIn( + text: string | null | undefined, +): { tool: string; client: number; server: number } | null { + const match = + /This image's PostgreSQL client \((pg_dump|pg_restore)\) is (\d+); your server is (\d+)\./.exec( + text ?? "", + ); + return match + ? { tool: match[1], client: Number(match[2]), server: Number(match[3]) } + : null; +} diff --git a/src/lib/recovery/__tests__/readiness-model.test.ts b/src/lib/recovery/__tests__/readiness-model.test.ts index 35f0153e36..25e73908b7 100644 --- a/src/lib/recovery/__tests__/readiness-model.test.ts +++ b/src/lib/recovery/__tests__/readiness-model.test.ts @@ -8,6 +8,7 @@ */ import { describe, expect, it } from "vitest"; +import { clientServerMismatch } from "@/lib/database-backup/dump-core.mjs"; import type { DatabaseBackupHealth } from "@/lib/recovery/database-dump-health"; import { DUMP_FAILING_AFTER_HOURS, @@ -167,6 +168,47 @@ describe("database dump", () => { }); }); + // #1431: a server newer than the image's pg_dump fails every run until the + // client or the server changes. That is not "the last one failed, the one + // before is recent": it is failing from the first run, with both majors. + it("fails at once, naming both majors, when the server is newer than the client", () => { + const tooOld = clientServerMismatch({ + tool: "pg_dump", + clientMajor: 19, + serverMajor: 20, + }); + expect( + evalDump( + dump({ lastFailureAt: ago(HOUR), lastFailureReason: tooOld ?? "" }), + ), + ).toMatchObject({ + state: "failing", + reason: "client_too_old", + params: { client: 19, server: 20 }, + detail: tooOld, + }); + expect( + evalDump( + dump({ + lastGoodAt: null, + lastFailureAt: ago(HOUR), + lastFailureReason: tooOld ?? "", + }), + ), + ).toMatchObject({ state: "failing", reason: "client_too_old" }); + // A dump that worked after it (the image or the server was changed) is + // no longer this problem. + expect( + evalDump( + dump({ + lastGoodAt: ago(HOUR), + lastFailureAt: ago(2 * HOUR), + lastFailureReason: tooOld ?? "", + }), + ), + ).toMatchObject({ state: "ok", reason: "fresh" }); + }); + // The run that kept its dump here and failed its upload is the newest good // dump and the newest failure at the same instant; read as only those two, // it looked fresh while nothing reached the bucket. diff --git a/src/lib/recovery/readiness-model.ts b/src/lib/recovery/readiness-model.ts index 7293923dee..ec2d82517e 100644 --- a/src/lib/recovery/readiness-model.ts +++ b/src/lib/recovery/readiness-model.ts @@ -30,7 +30,10 @@ import { type OffhostBackupFreshness, } from "@/lib/jobs/offhost-backup-freshness"; import type { LifecycleVerdict } from "@/lib/jobs/offhost-lifecycle"; -import { databaseDumpProblems } from "@/lib/database-backup/dump-problems"; +import { + clientTooOldIn, + databaseDumpProblems, +} from "@/lib/database-backup/dump-problems"; import type { DatabaseBackupHealth } from "@/lib/recovery/database-dump-health"; import type { KitEntry } from "@/lib/recovery/kit-rules"; @@ -218,6 +221,20 @@ export function evaluateDatabaseDump( { directory: dump.directory }, ); } + // A server newer than the image's `pg_dump` fails every run until the + // image or the server changes (#1431): failing from the first run, not + // "the last one failed", and the sentence names both majors. + const tooOld = clientTooOldIn(failureReason); + if (tooOld) { + return signal( + id, + "failing", + "client_too_old", + lastGoodAt, + { client: tooOld.client, server: tooOld.server }, + failureReason, + ); + } const limitMs = DUMP_FAILING_AFTER_HOURS * HOUR_MS; const failedSinceGood = lastFailureAt !== null; if (lastGoodAt === null) { diff --git a/tests/integration/database-backup.test.ts b/tests/integration/database-backup.test.ts index e451b9dcff..ea53cfcca0 100644 --- a/tests/integration/database-backup.test.ts +++ b/tests/integration/database-backup.test.ts @@ -15,6 +15,7 @@ import { execFileSync } from "node:child_process"; import { chmodSync, existsSync, + mkdirSync, mkdtempSync, readFileSync, readdirSync, @@ -46,8 +47,45 @@ const OFFHOST_KEY = "e".repeat(64); const work = mkdtempSync(join(tmpdir(), "hl-db-backup-")); const backups = join(work, "backups"); const shims = join(work, "bin"); +const tooOldBin = join(work, "too-old-bin"); +const tooOldRan = join(work, "too-old-ran"); const originalPath = process.env.PATH; +/** The test server's major, from `server_version_num`. */ +async function testServerMajor(): Promise { + const client = await connect(process.env.DATABASE_URL ?? ""); + try { + const { rows } = await client.query( + "SELECT current_setting('server_version_num')::int AS n", + ); + return Math.floor(Number(rows[0].n) / 10000); + } finally { + await client.end(); + } +} + +/** + * `pg_dump` / `pg_restore` one major older than the test server (#1431). + * They answer `--version` and nothing else: any other call is written to + * `tooOldRan` and fails, so a case can prove the tool was never run. + */ +function writeTooOldClient(major: number): void { + mkdirSync(tooOldBin, { recursive: true }); + for (const tool of ["pg_dump", "pg_restore"]) { + const path = join(tooOldBin, tool); + writeFileSync( + path, + `#!/bin/sh +if [ "$1" = "--version" ]; then echo "${tool} (PostgreSQL) ${major}.4"; exit 0; fi +echo "${tool} $*" >> ${JSON.stringify(tooOldRan)} +echo "${tool}: error: aborting because of server version mismatch" >&2 +exit 1 +`, + ); + chmodSync(path, 0o755); + } +} + /** The id of the container that serves DATABASE_URL. */ function containerId(): string { const port = new URL(process.env.DATABASE_URL ?? "").port; @@ -170,6 +208,7 @@ beforeAll(async () => { mkdirSync(shims, { recursive: true }); mkdirSync(backups, { recursive: true }); writeShims(containerId()); + writeTooOldClient((await testServerMajor()) - 1); process.env.PATH = `${shims}:${originalPath}`; for (const name of ["dump-a", "dump-b", "dump-c"]) { await prisma.user.create({ @@ -716,6 +755,22 @@ describe("the dump before migrating", () => { ); expect(readdirSync(preDir).sort()).toEqual(before); }); + + it("stops the boot with its own code and both majors when the server is newer than the client", async () => { + await new Promise((r) => setTimeout(r, 1100)); + const before = readdirSync(preDir).sort(); + const major = await testServerMajor(); + process.env.PATH = `${tooOldBin}:${originalPath}`; + const { code, errors } = await preMigration({ DB_BACKUP_DIR: preDir }); + process.env.PATH = `${shims}:${originalPath}`; + expect(code, errors).toBe(3); + expect(errors).toContain( + `This image's PostgreSQL client (pg_dump) is ${major - 1}; your server is ${major}.`, + ); + expect(errors).not.toContain("version mismatch"); + expect(existsSync(tooOldRan)).toBe(false); + expect(readdirSync(preDir).sort()).toEqual(before); + }); }); describe("two dumps in the same second", () => { @@ -744,3 +799,126 @@ describe("two dumps in the same second", () => { ).toEqual(before); }); }); + +// #1431: the image's client major caps the server major. Against a real +// server, with a client one major older that answers only `--version`. +describe("a server newer than this image's client", () => { + const dir = join(work, "too-old"); + const target = `too_old_${process.pid}_${Date.now()}`; + let targetUrl = ""; + + beforeAll(async () => { + const { mkdirSync } = await import("node:fs"); + mkdirSync(dir, { recursive: true }); + // A good dump to restore, written with the real client first. + const { createDatabaseDump } = + await import("@/lib/database-backup/dump-core.mjs"); + await createDatabaseDump({ + databaseUrl: process.env.DATABASE_URL ?? "", + dir, + kind: "daily", + now: new Date("2026-12-30T01:30:00Z"), + }); + const admin = await connect(process.env.DATABASE_URL ?? ""); + await admin.query(`CREATE DATABASE ${target}`); + await admin.end(); + const url = new URL(process.env.DATABASE_URL ?? ""); + url.pathname = `/${target}`; + targetUrl = url.toString(); + process.env.PATH = `${tooOldBin}:${originalPath}`; + }); + + afterAll(async () => { + process.env.PATH = `${shims}:${originalPath}`; + const admin = await connect(process.env.DATABASE_URL ?? ""); + await admin.query(`DROP DATABASE IF EXISTS ${target} WITH (FORCE)`); + await admin.end(); + }); + + it("fails the nightly dump with both majors, writes nothing, and the readiness signal fails at once", async () => { + const major = await testServerMajor(); + const before = readdirSync(dir).sort(); + const now = new Date("2027-01-01T01:30:00Z"); + const report = await runDatabaseBackup(prisma, { + now, + env: { ...process.env, DB_BACKUP_DIR: dir }, + }); + expect(report.status).toBe("failed"); + expect(report.error).toMatch( + new RegExp( + `^This image's PostgreSQL client \\(pg_dump\\) is ${major - 1}; your server is ${major}\\.`, + ), + ); + expect(existsSync(tooOldRan)).toBe(false); + expect(readdirSync(dir).sort()).toEqual(before); + + const health = await getDatabaseBackupHealth( + new Date("2027-01-01T02:00:00Z"), + { ...process.env, DB_BACKUP_DIR: dir }, + ); + expect( + evaluateDatabaseDump({ + now: new Date("2027-01-01T02:00:00Z"), + dump: health, + dumpWatchedSince: null, + }), + ).toMatchObject({ + state: "failing", + reason: "client_too_old", + params: { client: major - 1, server: major }, + }); + }); + + it("refuses the restore into an empty database before pg_restore runs", async () => { + const major = await testServerMajor(); + const errors: string[] = []; + const spyErr = vi + .spyOn(console, "error") + .mockImplementation((l: string) => void errors.push(String(l))); + const spyLog = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + const code = await restoreMain(["latest"], { + ...process.env, + DB_BACKUP_DIR: dir, + DATABASE_URL: targetUrl, + }); + expect(code, errors.join("\n")).toBe(1); + } finally { + spyErr.mockRestore(); + spyLog.mockRestore(); + } + expect(errors.join("\n")).toContain( + `This image's PostgreSQL client (pg_restore) is ${major - 1}; your server is ${major}.`, + ); + expect(existsSync(tooOldRan)).toBe(false); + const client = await connect(targetUrl); + try { + const { rows } = await client.query( + "SELECT count(*)::int AS n FROM pg_tables WHERE schemaname = 'public'", + ); + expect(rows[0].n).toBe(0); + } finally { + await client.end(); + } + }); + + it("warns at a boot with nothing to migrate, and lets it go on", async () => { + const { preMigrationDump } = await import("../../scripts/db-dump.mjs"); + const errors: string[] = []; + const spyErr = vi + .spyOn(console, "error") + .mockImplementation((l: string) => void errors.push(String(l))); + const spyLog = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + expect( + await preMigrationDump({ ...process.env, DB_BACKUP_DIR: dir }), + ).toBe(0); + } finally { + spyErr.mockRestore(); + spyLog.mockRestore(); + } + expect(errors.join("\n")).toMatch( + /WARNING .*client \(pg_dump\) is \d+; your server is \d+\..*nightly database dump fails/, + ); + }); +}); From 36880caed8f317b61efbcc3a47638c8d038d68b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 00:55:44 +0100 Subject: [PATCH 2/9] fix(insights): read every day value of a ranked metric from one source The stress score, the intraday resting baseline, the overview's resting series, the pulse and BMI status snapshots, the GLP-1 plateau check, the same-hours comparison, the graded series' recent weeks, medication effect segments, plan progress and the tiered context each chose a source for themselves: a mean across sources, or the row that synced last. They now go through the ladder and the day picker. A structural guard freezes the rule: every readDayAggregates call passes the ladder, and every file under insights, daily, analytics and dashboard that reads measurement rows applies it or is listed with its reason. (cherry picked from commit c8462b9d699d0b8089467b4161fc7464eb172b66) --- CHANGELOG.md | 1 + .../day-value-source-rule-guard.test.ts | 250 ++++++++++++++++++ .../pulse-day-mean-reader-guard.test.ts | 4 - src/lib/ai/coach/memory/plan-progress.ts | 2 + .../__tests__/intraday-pulse-io.test.ts | 3 + src/lib/analytics/intraday-pulse-io.ts | 30 ++- .../insights/__tests__/glp1-plateau.test.ts | 30 +++ .../insights/__tests__/stress-score.test.ts | 53 +++- src/lib/insights/bmi-status.ts | 48 ++-- .../resting-pulse-daily.ts | 28 +- .../insights/derived/coincident-deviation.ts | 3 + src/lib/insights/glp1-plateau.ts | 37 ++- src/lib/insights/graded-series.ts | 2 + src/lib/insights/pulse-status.ts | 41 ++- src/lib/insights/stress-score.ts | 32 ++- .../efficacy/load-segmented-effects.ts | 3 + .../__tests__/tiered-context-envelope.test.ts | 1 + .../rollups/__tests__/tiered-context.test.ts | 1 + src/lib/rollups/tiered-context.ts | 14 +- 19 files changed, 511 insertions(+), 72 deletions(-) create mode 100644 src/__tests__/day-value-source-rule-guard.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 040bacbe86..41c889a9cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Fixed +- Daily values from several devices now follow your source order everywhere, not only on the metric page. The stress score, the intraday pulse page's resting baseline, the overview's resting-pulse series, the status summaries for pulse, BMI and every other metric, the resting pulse estimated from all-day heart rate, the GLP-1 plateau check, the comparison of today against earlier days at the same hours, medication effect segments, Coach plan progress and the context the Coach reads each took a day from two devices as the mean of both, or as whichever synced last. They now keep the device you ranked first for that day. - A task bound to a chain with no provider set up now says so in Settings, AI. Such a task does not run, and its action disappears from where it would appear, such as "Read with AI" on a document or the Coach, with no word about why. The task's row under "Chains per task" now says that nothing in its chain is set up and that the action comes back once a provider is set up or another chain is picked. Thanks to @ch3funio for trying the empty chain on purpose. (Refs [#1404](https://github.com/MBombeck/HealthLog/issues/1404)) - Readiness, the "vitals out of range" flag and the briefing's signals of the day read each day from the source you ranked first, as the metric page does. With two devices reporting the same date, such as a ring worn at night and a watch worn in the day, readiness used the mean of both resting heart rates and moved whenever the lower-ranked device revised its estimate, and the briefing could quote whichever reading happened to sort last. Thanks to @sdrburgess for the report and the numbers that pinned it down. (Refs [#1514](https://github.com/MBombeck/HealthLog/issues/1514)) - The sleep figures on the Insights overview count nights, not the pieces a night is stored in. A watch writes a night as dozens of short stages, and the overview averaged those, so a 7-hour night read as an average of 16 minutes, the shortest "night" was a half-minute awake spell, and the latest value was the last stage of the night. The overview now takes each night's time asleep, from one source per night as the sleep pages do, before it works out the average, the range, the trend and the count. The dashboard and the analytics figures already counted nights. diff --git a/src/__tests__/day-value-source-rule-guard.test.ts b/src/__tests__/day-value-source-rule-guard.test.ts new file mode 100644 index 0000000000..972ddafea0 --- /dev/null +++ b/src/__tests__/day-value-source-rule-guard.test.ts @@ -0,0 +1,250 @@ +/** + * Structural guard: a reader of a day's value for a metric that several + * sources report goes through the one source-priority rule. + * + * The rule is the person's ladder (`loadUserSourcePriority`) and the day + * picker that applies it: `pickCanonicalSourceRows` over rows or per-source + * groups, `readDayAggregates` with `sourcePriority`, the rank CASE + * (`buildSourceRankCase`, `canonicalMeasurementsCte`) in SQL, and the rollup + * collapse. Two devices reporting the same day's resting heart rate are two + * estimates of one value: their mean is neither, and the newest row is + * whichever synced last. The today readings averaged across sources (#1514), + * the sleep reader that took segments for nights (#1565) and the day totals + * read as hours (#1459) each slipped past a different reader, because every + * reader chose for itself. + * + * Two arms, both frozen both ways (a new unlisted match fails, a listed entry + * that no longer matches fails): + * + * 1. Every `readDayAggregates(...)` call in `src/lib` and `src/app` passes + * `sourcePriority`. Without it the helper folds every source's readings + * into one day. The one call listed folds the worst reading of any + * source on purpose. + * + * 2. Every file under `lib/{insights,daily,analytics,dashboard}` that reads + * measurement rows itself (Prisma `measurement.findMany` / `findFirst` / + * `aggregate` / `groupBy` / `count`, or SQL `FROM measurements`) applies + * the rule somewhere in its code, or is listed with the reason its read + * is not a day value of a multi-source metric: a presence probe, a + * single producer, a reader that keeps the source on every row for its + * consumer, a latest-reading lookup of a sparse type. + * + * Comments are stripped before matching, the matchers are whitespace-tolerant, + * and floors fail the guard if either arm stops finding anything. The planted + * cases run each matcher over an offender. It is a tripwire, not a proof: arm + * 2 judges a file, not each read inside it, so a second read added to a file + * that already applies the rule slips it. + */ +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + readSourceText, + stripComments, + walkSourceFiles, +} from "./helpers/source-files"; + +const SRC = join(process.cwd(), "src"); + +type Reason = + | "probe" + | "single-producer" + | "per-source" + | "latest-reading" + | "window" + | "worst-of-any-source" + | "open"; + +/** Arm 1: `readDayAggregates` calls that fold every source, by file. */ +const POOLED_DAY_AGGREGATES: Record< + string, + { count: number; reason: Reason; why: string } +> = { + "lib/illness/safety-floor-check.ts": { + count: 1, + reason: "worst-of-any-source", + why: "the sustained-low safety floor takes each day's worst reading of any device, so a dip one device saw is never hidden behind another device's ladder rank", + }, +}; + +/** Arm 2: files that read measurement rows without the rule, and why. */ +const READERS_WITHOUT_RULE: Record = { + "lib/insights/feature-cache.ts": { + reason: "probe", + why: "the newest updatedAt of any row, a cache fingerprint; no value is read", + }, + "lib/insights/recovery-empty-read.ts": { + reason: "probe", + why: "whether any device recovery row exists, to explain an empty card", + }, + "lib/dashboard/widgets/unavailable-widgets.ts": { + reason: "probe", + why: "whether a type has any row at all, to hide a widget without data", + }, + "lib/insights/derived/readiness.ts": { + reason: "single-producer", + why: "reads RECOVERY_SCORE filtered to source COMPUTED, HealthLog's own readiness rows", + }, + "lib/daily/morning-load.ts": { + reason: "per-source", + why: "device scores of the last nights with their source on every row; the card names each device's own score", + }, + "lib/insights/recent-readings.ts": { + reason: "open", + why: "the status snapshots' newest readings (rows, or hour cells beyond the cap) pool every source, and metric-status and pulse-status fold them into days; the pick has to reach readNewestRowsPerType and readHourCells", + }, + "lib/insights/derived/bmi.ts": { + reason: "latest-reading", + why: "the newest weight in the window as the BMI input", + }, + "lib/insights/derived/fitness-age.ts": { + reason: "latest-reading", + why: "the newest VO2 max reading, a sparse type a device writes every few days", + }, + "lib/insights/derived/six-minute-walk.ts": { + reason: "latest-reading", + why: "the newest six-minute-walk distance and weight, sparse types", + }, + "lib/insights/derived/vascular-age.ts": { + reason: "latest-reading", + why: "the newest vascular-age and pulse-wave-velocity readings, written by one scale", + }, + "lib/dashboard/summary-reads.ts": { + reason: "latest-reading", + why: "the newest reading per type ever, the reading counts, and which local days hold any reading; no day value", + }, + "lib/dashboard/snapshot.ts": { + reason: "window", + why: "the same 30-day glucose panel as lib/analytics/response/glucose.ts, read for the snapshot; its other reads go through the ladder helpers", + }, + "lib/analytics/response/glucose.ts": { + reason: "window", + why: "the 30-day glucose panel over every reading at its own instant, grouped by meal context; spot checks and a sensor are readings of one blood, not two estimates of one day", + }, + "lib/analytics/resting-pulse-read.ts": { + reason: "open", + why: "the low-percentile resting proxy pools every source's PULSE readings per day; the pick belongs in the fold and the closed-block cache key, and the pinned single-statement read in dense-day-readers.test.ts moves with it", + }, +}; + +/** A file applies the rule when its code names one of these. */ +const RULE = + /\b(?:loadUserSourcePriority|pickCanonicalSourceRows|canonicalMeasurements(?:Cte|From)|collapseRollupRowsBySource|buildSourceRankCase|sourcePriority|priorityJson|rankPerSource|rankUnqualified|resolveCanonicalRecovery|describeRecoveryDivergence|canonicalRowsOfDay|pickCumulativeDaySum|canonicalCumulativeDayTotalsSql)\b/; + +/** A measurement read of the file's own. */ +const RAW_READ = + /\.measurement\s*\.\s*(?:findMany|findFirst|aggregate|groupBy|count)\s*\(|\bFROM\s+"?measurements"?\s+[a-z]/g; + +/** The argument text of every `readDayAggregates(` call in `code`. */ +function readDayAggregatesCalls(code: string): string[] { + const out: string[] = []; + const re = /\breadDayAggregates\s*\(/g; + for (const m of code.matchAll(re)) { + const start = m.index + m[0].length; + let depth = 1; + let i = start; + while (i < code.length && depth > 0) { + const ch = code[i]; + if (ch === "(") depth += 1; + else if (ch === ")") depth -= 1; + i += 1; + } + out.push(code.slice(start, i - 1)); + } + return out; +} + +/** Whether a call's argument text passes the ladder. */ +function passesSourcePriority(args: string): boolean { + return /\bsourcePriority\b/.test(args); +} + +const files = walkSourceFiles(SRC, { floor: 1000 }).filter( + (rel) => + (rel.startsWith("lib/") || rel.startsWith("app/")) && + !rel.includes("__tests__") && + !/\.test\.tsx?$/.test(rel), +); +const code = new Map( + files.map((rel) => [rel, stripComments(readSourceText(join(SRC, rel)), rel)]), +); + +describe("readDayAggregates calls pass the ladder", () => { + const calls = files.flatMap((rel) => + rel === "lib/measurements/day-aggregates.ts" + ? [] + : readDayAggregatesCalls(code.get(rel)!) + .filter((a) => a.trim().length > 0) + .map((args) => ({ file: rel, args })), + ); + + it("finds the calls at all", () => { + expect(calls.length).toBeGreaterThanOrEqual(8); + }); + + it("folds every source only where it is listed, as often as it is listed", () => { + const pooled = new Map(); + for (const c of calls) { + if (passesSourcePriority(c.args)) continue; + pooled.set(c.file, (pooled.get(c.file) ?? 0) + 1); + } + expect(Object.fromEntries(pooled)).toEqual( + Object.fromEntries( + Object.entries(POOLED_DAY_AGGREGATES).map(([f, a]) => [f, a.count]), + ), + ); + }); + + it("the matcher catches a planted call without the ladder", () => { + const planted = `const d = await readDayAggregates({ + userId, type, since, + timeZone: tz, + }); + const e = await readDayAggregates({ userId, type, since, timeZone: tz, sourcePriority: p });`; + const found = readDayAggregatesCalls(planted); + expect(found).toHaveLength(2); + expect(found.map(passesSourcePriority)).toEqual([false, true]); + }); +}); + +describe("day readers in insights, daily, analytics and dashboard apply the rule", () => { + const scoped = files.filter((rel) => + /^lib\/(?:insights|daily|analytics|dashboard)\//.test(rel), + ); + const readers = scoped.filter((rel) => { + RAW_READ.lastIndex = 0; + return RAW_READ.test(code.get(rel)!); + }); + + it("walks the folders and finds their readers", () => { + expect(scoped.length).toBeGreaterThanOrEqual(250); + expect(readers.length).toBeGreaterThanOrEqual(30); + }); + + it("every reader applies the rule or is listed with its reason", () => { + const without = readers.filter((rel) => !RULE.test(code.get(rel)!)); + expect(without.sort()).toEqual(Object.keys(READERS_WITHOUT_RULE).sort()); + }); + + it("gives every listed reader a reason", () => { + for (const [file, { why }] of Object.entries({ + ...READERS_WITHOUT_RULE, + ...POOLED_DAY_AGGREGATES, + })) { + expect(why.length, file).toBeGreaterThan(30); + } + }); + + it("the matchers catch a planted reader that averages across sources", () => { + const planted = stripComments( + `// loadUserSourcePriority is mentioned only in a comment + const agg = await prisma.measurement + .aggregate({ where: { userId, type: "HEART_RATE_VARIABILITY" }, _avg: { value: true } }); + const rows = await prisma.$queryRaw\`SELECT AVG(value) FROM measurements m WHERE m."type" = 'PULSE'\`;`, + "planted.ts", + ); + RAW_READ.lastIndex = 0; + expect([...planted.matchAll(RAW_READ)]).toHaveLength(2); + expect(RULE.test(planted)).toBe(false); + }); +}); diff --git a/src/__tests__/pulse-day-mean-reader-guard.test.ts b/src/__tests__/pulse-day-mean-reader-guard.test.ts index e98e0f5265..85a1719757 100644 --- a/src/__tests__/pulse-day-mean-reader-guard.test.ts +++ b/src/__tests__/pulse-day-mean-reader-guard.test.ts @@ -100,10 +100,6 @@ const SQL_READERS: Record = { "lib/measurements/dense-series-read.ts": HELPER, "lib/rollups/measurement-rollups.ts": HELPER, "lib/rollups/tiered-context.ts": HELPER, - "lib/insights/stress-score.ts": { - exempt: - "the scored day's mean SDNN over HEART_RATE_VARIABILITY rows only; pulse never enters", - }, "lib/insights/correlation-channel-series.ts": { exempt: "the one SQL mean is the room-climate hour mean, over INDOOR_CO2 / INDOOR_TEMPERATURE / INDOOR_HUMIDITY only; pulse reaches the correlation channels through `dayValueRows` and the rollup compose", diff --git a/src/lib/ai/coach/memory/plan-progress.ts b/src/lib/ai/coach/memory/plan-progress.ts index b295ca6718..f83bb18e94 100644 --- a/src/lib/ai/coach/memory/plan-progress.ts +++ b/src/lib/ai/coach/memory/plan-progress.ts @@ -19,6 +19,7 @@ import { prisma } from "@/lib/db"; import { planDayValue } from "@/lib/jobs/coach-plan-review"; import { resolvePlanMetric } from "@/lib/ai/coach/plan-metric"; import { readDayAggregates } from "@/lib/measurements/day-aggregates"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; import { applyDisplayTransform, applyDisplayTransformDelta, @@ -124,6 +125,7 @@ export async function computePlanProgress( since: new Date(plan.startedAt.getTime() - (BEFORE_DAYS + 1) * MS_PER_DAY), until: ctx.now, timeZone: ctx.timeZone, + sourcePriority: await loadUserSourcePriority(ctx.userId), ...(ctx.db ? { db: ctx.db } : {}), }); const beforeFromKey = shiftDateKey(startKey, -BEFORE_DAYS); diff --git a/src/lib/analytics/__tests__/intraday-pulse-io.test.ts b/src/lib/analytics/__tests__/intraday-pulse-io.test.ts index 0f5c0f0128..9cf27880e5 100644 --- a/src/lib/analytics/__tests__/intraday-pulse-io.test.ts +++ b/src/lib/analytics/__tests__/intraday-pulse-io.test.ts @@ -26,6 +26,9 @@ vi.mock("@/lib/db", () => ({ })); vi.mock("@/lib/logging/context", () => ({ annotate: annotateMock })); +vi.mock("@/lib/rollups/measurement-read", () => ({ + loadUserSourcePriority: async () => null, +})); vi.mock("@/lib/measurements/dense-bucket-read", async () => { const { makeFakeDenseBucketRead } = await import("@/lib/measurements/__tests__/fake-dense-bucket-read"); diff --git a/src/lib/analytics/intraday-pulse-io.ts b/src/lib/analytics/intraday-pulse-io.ts index f578bec7ab..6d75934395 100644 --- a/src/lib/analytics/intraday-pulse-io.ts +++ b/src/lib/analytics/intraday-pulse-io.ts @@ -19,6 +19,8 @@ import { prisma } from "@/lib/db"; import { annotate } from "@/lib/logging/context"; import { mergeRestingWithProxy } from "@/lib/analytics/resting-pulse"; import { readRestingPulseProxy } from "@/lib/analytics/resting-pulse-read"; +import { pickCanonicalSourceRows } from "@/lib/analytics/source-priority"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; import { readLocalDayMinuteBuckets } from "@/lib/measurements/dense-bucket-read"; import { CUMULATIVE_SAMPLE_SOURCES } from "@/lib/measurements/intraday-cumulative-profile"; import { localDayWindow } from "@/lib/tz/local-day"; @@ -104,12 +106,26 @@ async function resolveBaseline( mature: boolean; source: "resting" | "proxy" | "none"; }> { - const restingRows = await prisma.measurement.findMany({ - where: { userId, type: "RESTING_HEART_RATE", deletedAt: null }, - orderBy: { measuredAt: "desc" }, - take: 90, - select: { value: true, measuredAt: true }, - }); + const dayKeyOf = (d: Date) => userDayKey(d, timezone); + // A day with resting rows from two sources keeps the one the person's + // ladder puts first, so the median weighs each day once. + const restingRows = pickCanonicalSourceRows( + await prisma.measurement.findMany({ + where: { userId, type: "RESTING_HEART_RATE", deletedAt: null }, + orderBy: [{ measuredAt: "desc" }, { id: "desc" }], + take: 90, + select: { + value: true, + measuredAt: true, + source: true, + deviceType: true, + type: true, + }, + }), + "restingHeartRate", + await loadUserSourcePriority(userId), + dayKeyOf, + ).canonicalRows; // Only reach for the heavier PULSE-proxy read when the resting rows // cannot carry the baseline on their own: too few of them, OR the newest @@ -144,7 +160,7 @@ async function resolveBaseline( value: r.value, })), proxySamples, - dayKeyOf: (d) => userDayKey(d, timezone), + dayKeyOf, }); const recentMedian = median(resolved.series.slice(-30).map((p) => p.value)); diff --git a/src/lib/insights/__tests__/glp1-plateau.test.ts b/src/lib/insights/__tests__/glp1-plateau.test.ts index 9434f9dc5c..746553b853 100644 --- a/src/lib/insights/__tests__/glp1-plateau.test.ts +++ b/src/lib/insights/__tests__/glp1-plateau.test.ts @@ -4,6 +4,7 @@ vi.mock("@/lib/db", () => ({ prisma: { medication: { findMany: vi.fn() }, measurement: { findMany: vi.fn() }, + user: { findUnique: vi.fn() }, }, })); @@ -15,6 +16,9 @@ import { const dayMs = 24 * 60 * 60 * 1000; +type MedicationRows = Awaited>; +type MeasurementRows = Awaited>; + beforeEach(() => { vi.resetAllMocks(); }); @@ -107,6 +111,32 @@ describe("glp1-plateau", () => { expect(result?.weightDeltaKg).toBeCloseTo(-0.2, 5); }); + it("reads one source per day when two report weight on the same day", async () => { + const now = new Date("2026-05-14T00:00:00Z"); + vi.mocked(prisma.medication.findMany).mockResolvedValue([ + makeMed(30, now), + ] as unknown as MedicationRows); + // The last day carries the scale (ladder first) and a later relayed + // reading from another source. The scale's reading ends the window. + const lastDay = now.getTime() - 1 * dayMs; + vi.mocked(prisma.measurement.findMany).mockResolvedValue([ + { + value: 90.0, + measuredAt: new Date(now.getTime() - 20 * dayMs), + source: "WITHINGS", + }, + { value: 89.8, measuredAt: new Date(lastDay), source: "WITHINGS" }, + { + value: 88.0, + measuredAt: new Date(lastDay + 60_000), + source: "APPLE_HEALTH", + }, + ] as unknown as MeasurementRows); + const result = await detectGlp1Plateau("user-1", now); + expect(result?.readingsCount).toBe(2); + expect(result?.weightDeltaKg).toBeCloseTo(-0.2, 5); + }); + it("returns a plateau context when weight stays flat", async () => { const now = new Date("2026-05-14T00:00:00Z"); vi.mocked(prisma.medication.findMany).mockResolvedValue([ diff --git a/src/lib/insights/__tests__/stress-score.test.ts b/src/lib/insights/__tests__/stress-score.test.ts index 3cd5ee4306..5685fb99ad 100644 --- a/src/lib/insights/__tests__/stress-score.test.ts +++ b/src/lib/insights/__tests__/stress-score.test.ts @@ -31,6 +31,10 @@ vi.mock("@/lib/insights/derived/baseline", () => ({ .mockResolvedValue({ ageYears: null, sex: "MALE", heightCm: 180 }), })); +vi.mock("@/lib/rollups/measurement-read", () => ({ + loadUserSourcePriority: vi.fn(async () => null), +})); + import { stressExternalId, stressMeasuredAt, @@ -49,28 +53,32 @@ function okBaseline(center: number, spread: number) { }; } -function makePrisma(sdnnValues: number[]) { - // The day's intra-day SDNN is counted and averaged in SQL; the fake - // aggregates the fixture values the same way. - const aggregate = vi.fn().mockResolvedValue({ - _count: { _all: sdnnValues.length }, - _avg: { - value: - sdnnValues.length === 0 - ? null - : sdnnValues.reduce((s, v) => s + v, 0) / sdnnValues.length, - }, - }); +function makePrisma( + sdnnValues: number[], + bySource: Record = { APPLE_HEALTH: sdnnValues }, +) { + // The day's intra-day SDNN is counted and summed in SQL per source and + // device; the fake groups the fixture values the same way. + const groupBy = vi.fn().mockResolvedValue( + Object.entries(bySource).map(([source, values]) => ({ + source, + deviceType: null, + _count: { _all: values.length }, + _sum: { + value: values.length === 0 ? null : values.reduce((s, v) => s + v, 0), + }, + })), + ); const upsert = vi.fn().mockResolvedValue({}); const findUnique = vi .fn() .mockResolvedValue({ dateOfBirth: null, gender: "MALE", heightCm: 180 }); return { prisma: { - measurement: { aggregate, upsert }, + measurement: { groupBy, upsert }, user: { findUnique }, } as unknown as Parameters[0], - aggregate, + groupBy, upsert, }; } @@ -141,6 +149,23 @@ describe("persistStressScore", () => { }); }); + it("scores the ladder's source when two sources report SDNN for the day", async () => { + // WHOOP outranks Apple Health on the default `hrv` ladder. Mixed, the + // mean would be 50 and score lower; the picked source alone sits at + // baseline and scores no stress. + const { prisma, upsert } = makePrisma([], { + APPLE_HEALTH: [40, 40, 40, 40], + WHOOP: [60, 60, 60, 60], + }); + computeVitalsBaselineMock.mockResolvedValue(okBaseline(60, 10)); + + const result = await persistStressScore(prisma, "user-1", NOW); + + expect(result.outcome).toBe("stored"); + expect(result.score).toBe(0); + expect(upsert).toHaveBeenCalledTimes(1); + }); + it("writes NOTHING when there are too few intra-day samples", async () => { const { prisma, upsert } = makePrisma( Array(STRESS_MIN_INTRADAY_SAMPLES - 1).fill(50), diff --git a/src/lib/insights/bmi-status.ts b/src/lib/insights/bmi-status.ts index c488004cdd..ebdec4b3dc 100644 --- a/src/lib/insights/bmi-status.ts +++ b/src/lib/insights/bmi-status.ts @@ -29,6 +29,9 @@ import { type StatusTextResult, } from "@/lib/insights/status-pipeline"; import { heightSquaredM2 } from "@/lib/analytics/classifications"; +import { pickCanonicalSourceRows } from "@/lib/analytics/source-priority"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; +import { userDayKey } from "@/lib/tz/resolver"; /** * Public entry — unchanged signature. Prepares the card (cache-read, @@ -120,23 +123,7 @@ async function buildBmiSnapshot( // v1.4.28 — cap the snapshot input (weight runs at most once // per day for typical users; 365 covers a full year while the // downstream payload budget trims further). - const measurements = await prisma.measurement - .findMany({ - where: { - userId, - type: "WEIGHT", - // Soft-deleted rows must never reach the prompt snapshot. - deletedAt: null, - }, - orderBy: { measuredAt: "desc" }, - take: 365, - select: { - value: true, - measuredAt: true, - timeZone: true, - }, - }) - .then((rows) => rows.reverse()); + const measurements = await readWeightRows(userId, userTz); const now = new Date(); // v1.2.5 — bucket day windows on the user's own calendar so a @@ -262,3 +249,30 @@ const BMI_STATUS_CARD: StatusCardPlugin = { emptyMessage: "Bmi-status summary was empty after normalization", build: buildBmiSnapshot, }; + +/** + * The newest 365 weight readings, oldest first; soft-deleted rows never + * reach the prompt snapshot. A day weighed by two sources keeps the one the + * person's ladder puts first, as the weight chart does. + */ +async function readWeightRows(userId: string, userTz: string) { + const rows = await prisma.measurement.findMany({ + where: { userId, type: "WEIGHT", deletedAt: null }, + orderBy: [{ measuredAt: "desc" }, { id: "desc" }], + take: 365, + select: { + value: true, + measuredAt: true, + timeZone: true, + source: true, + deviceType: true, + type: true, + }, + }); + return pickCanonicalSourceRows( + rows.reverse(), + "weight", + await loadUserSourcePriority(userId), + (d) => userDayKey(d, userTz), + ).canonicalRows; +} diff --git a/src/lib/insights/comprehensive-overview/resting-pulse-daily.ts b/src/lib/insights/comprehensive-overview/resting-pulse-daily.ts index acb54fc0d2..e382409968 100644 --- a/src/lib/insights/comprehensive-overview/resting-pulse-daily.ts +++ b/src/lib/insights/comprehensive-overview/resting-pulse-daily.ts @@ -16,10 +16,16 @@ * evening logger west of UTC by one day and sell a lag-1 correlation as * same-day. Unlike the mood side, this series builds from raw rows, so it * re-keys directly with no rollup-tier change. + * + * A day with resting rows from two sources (a watch and a ring) reads the + * one source the person's ladder puts first, as every other day reader does, + * instead of the mean of both. */ import { prisma } from "@/lib/db"; import { resolveRestingPulseSeries } from "@/lib/analytics/resting-pulse"; import { readRestingPulseProxy } from "@/lib/analytics/resting-pulse-read"; +import { pickCanonicalSourceRows } from "@/lib/analytics/source-priority"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; import { userDayKey } from "@/lib/tz/format"; import type { DailyValue } from "./daily-series"; @@ -36,13 +42,29 @@ export async function readRestingPulseDaily( deletedAt: null, measuredAt: { gte: since }, }, - select: { measuredAt: true, value: true }, + orderBy: [{ measuredAt: "asc" }, { id: "asc" }], + select: { + measuredAt: true, + value: true, + source: true, + deviceType: true, + type: true, + }, }); const localDayKey = (d: Date) => userDayKey(d, userTz); - const restingPulseSeries = + const restingRows = restingPulseRows.length > 0 + ? pickCanonicalSourceRows( + restingPulseRows, + "restingHeartRate", + await loadUserSourcePriority(userId), + localDayKey, + ).canonicalRows + : restingPulseRows; + const restingPulseSeries = + restingRows.length > 0 ? resolveRestingPulseSeries({ - restingSamples: restingPulseRows, + restingSamples: restingRows, pulseSamples: [], dayKeyOf: localDayKey, }).series diff --git a/src/lib/insights/derived/coincident-deviation.ts b/src/lib/insights/derived/coincident-deviation.ts index 8e8792dec2..5629698d43 100644 --- a/src/lib/insights/derived/coincident-deviation.ts +++ b/src/lib/insights/derived/coincident-deviation.ts @@ -144,6 +144,9 @@ async function readSameHoursDays( timeZone: tz, valueRange: plausibleMetricRange(type), upToLocalTime: localClockOf(cutAt, tz), + sourcePriority: isSourceRankedType(type) + ? await loadUserSourcePriority(userId) + : undefined, }); } diff --git a/src/lib/insights/glp1-plateau.ts b/src/lib/insights/glp1-plateau.ts index 6e1307e990..da5d4a9618 100644 --- a/src/lib/insights/glp1-plateau.ts +++ b/src/lib/insights/glp1-plateau.ts @@ -18,6 +18,8 @@ */ import { prisma } from "@/lib/db"; import type { Locale } from "@/lib/i18n/config"; +import { pickCanonicalSourceRows } from "@/lib/analytics/source-priority"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; import { sanitizeForPrompt } from "@/lib/insights/sanitize"; import { applyDisplayTransformDelta, @@ -83,16 +85,31 @@ export async function detectGlp1Plateau( const windowStart = new Date(now.getTime()); windowStart.setDate(windowStart.getDate() - PLATEAU_WINDOW_DAYS); - const weightRows = await prisma.measurement.findMany({ - where: { - userId, - type: "WEIGHT", - measuredAt: { gte: windowStart }, - deletedAt: null, - }, - orderBy: { measuredAt: "asc" }, - select: { value: true, measuredAt: true }, - }); + // A day weighed on two scales (or a scale and a hand entry) keeps the one + // source the person's ladder puts first, so the window's ends are the + // same readings the weight chart shows for those days. + const { canonicalRows: weightRows } = pickCanonicalSourceRows( + await prisma.measurement.findMany({ + where: { + userId, + type: "WEIGHT", + measuredAt: { gte: windowStart }, + deletedAt: null, + }, + orderBy: [{ measuredAt: "asc" }, { id: "asc" }], + select: { + value: true, + measuredAt: true, + source: true, + deviceType: true, + type: true, + }, + }), + "weight", + await loadUserSourcePriority(userId), + // eslint-disable-next-line healthlog/no-utc-day-key -- baseline: this builder has no zone yet (see doseSince below) + (d) => d.toISOString().slice(0, 10), + ); if (weightRows.length < 2) return null; const first = weightRows[0].value; diff --git a/src/lib/insights/graded-series.ts b/src/lib/insights/graded-series.ts index 616745700c..fb60906da7 100644 --- a/src/lib/insights/graded-series.ts +++ b/src/lib/insights/graded-series.ts @@ -386,6 +386,8 @@ async function readGradedDayAggregates( // Future-dated readings were skipped by the in-memory fold. until: now, timeZone, + // One source per day, as the monthly and yearly slices from the tier. + sourcePriority: await loadUserSourcePriority(userId), // `readDayAggregates` puts a row at segment k when it is older than k // starts (`measured_at < start`). The in-memory fold treats an age of // exactly the window as the older bucket, so shift each start by 1 ms. diff --git a/src/lib/insights/pulse-status.ts b/src/lib/insights/pulse-status.ts index bd1a3c3eac..07ce040c2b 100644 --- a/src/lib/insights/pulse-status.ts +++ b/src/lib/insights/pulse-status.ts @@ -38,6 +38,8 @@ import { import { binaryReferenceSex } from "@/lib/profile/sex"; import { ageInYears } from "@/lib/tz/date-only"; import { userDayKey } from "@/lib/tz/resolver"; +import { pickCanonicalSourceRows } from "@/lib/analytics/source-priority"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; /** * Public entry — unchanged signature. Prepares the card (cache-read, @@ -99,18 +101,7 @@ async function buildPulseSnapshot( // not the raw PULSE stream (Apple fills PULSE with workout HR). Pull // RESTING_HEART_RATE rows; the resolver falls back to a low-percentile // PULSE proxy when the user has none. - const restingMeasurements = await prisma.measurement - .findMany({ - where: { - userId, - type: "RESTING_HEART_RATE", - deletedAt: null, - }, - orderBy: { measuredAt: "desc" }, - take: 365, - select: { value: true, measuredAt: true }, - }) - .then((rows) => rows.reverse()); + const restingMeasurements = await readRestingRows(userId, userTz); const now = new Date(); @@ -323,3 +314,29 @@ const PULSE_STATUS_CARD: StatusCardPlugin = { emptyMessage: "Pulse-status summary was empty after normalization", build: buildPulseSnapshot, }; + +/** + * The newest 365 resting-pulse rows, oldest first. A day with resting rows + * from two sources keeps the one the person's ladder puts first, as the + * resting-pulse chart does. + */ +async function readRestingRows(userId: string, userTz: string) { + const rows = await prisma.measurement.findMany({ + where: { userId, type: "RESTING_HEART_RATE", deletedAt: null }, + orderBy: [{ measuredAt: "desc" }, { id: "desc" }], + take: 365, + select: { + value: true, + measuredAt: true, + source: true, + deviceType: true, + type: true, + }, + }); + return pickCanonicalSourceRows( + rows.reverse(), + "restingHeartRate", + await loadUserSourcePriority(userId), + (d) => userDayKey(d, userTz), + ).canonicalRows; +} diff --git a/src/lib/insights/stress-score.ts b/src/lib/insights/stress-score.ts index dcf62586ab..2e2d802856 100644 --- a/src/lib/insights/stress-score.ts +++ b/src/lib/insights/stress-score.ts @@ -53,6 +53,8 @@ import { loadBaselineProfile, } from "@/lib/insights/derived/baseline"; import { scoreDeviation } from "@/lib/insights/derived/readiness"; +import { pickCanonicalSourceRows } from "@/lib/analytics/source-priority"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; import type { BaselineProfile } from "@/lib/insights/derived/baseline"; import { scoreDayKey, @@ -113,7 +115,8 @@ export function stressProxyFromSdnn( /** * The scored day's intra-day SDNN: how many raw `HEART_RATE_VARIABILITY` - * rows the scored UTC day holds, and their mean, aggregated in Postgres. The + * rows the scored UTC day holds, and their mean, aggregated in Postgres per + * source and device, of the source the ladder picks for the day. The * dense intra-day retention tier keeps these raw within its window, so for a * recently-synced day the engine sees the full intra-day set; the aggregate * counts every one of them, where a row read used to stop at 2 000. @@ -127,7 +130,8 @@ async function readIntradaySdnn( // eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: UTC day window of the UTC-day score engines (scoreDayKey) const dayStart = new Date(`${dayKey}T00:00:00.000Z`); const dayEnd = new Date(dayStart.getTime() + MS_PER_DAY); - const agg = await prisma.measurement.aggregate({ + const groups = await prisma.measurement.groupBy({ + by: ["source", "deviceType"], where: { userId, type: "HEART_RATE_VARIABILITY" as MeasurementType, @@ -137,10 +141,30 @@ async function readIntradaySdnn( // already-folded `stats:` daily-mean row is one point, not a shape. NOT: { externalId: { startsWith: "stats:" } }, }, + orderBy: [{ source: "asc" }, { deviceType: "asc" }], _count: { _all: true }, - _avg: { value: true }, + _sum: { value: true }, }); - return { count: agg._count._all, mean: agg._avg.value }; + // A day with SDNN from two sources scores the one the person's ladder puts + // first. The picker decides from which sources and device types are + // present, never from the values, so it picks the same over these groups + // as over the raw rows. + const { canonicalRows } = pickCanonicalSourceRows( + groups.map((g) => ({ + measuredAt: dayStart, + source: g.source, + deviceType: g.deviceType, + type: "HEART_RATE_VARIABILITY" as MeasurementType, + n: g._count._all, + sum: g._sum.value ?? 0, + })), + "hrv", + await loadUserSourcePriority(userId), + () => dayKey, + ); + const count = canonicalRows.reduce((acc, g) => acc + g.n, 0); + const total = canonicalRows.reduce((acc, g) => acc + g.sum, 0); + return { count, mean: count === 0 ? null : total / count }; } export interface StressComputeResult { diff --git a/src/lib/medications/efficacy/load-segmented-effects.ts b/src/lib/medications/efficacy/load-segmented-effects.ts index 75ae92b4ac..b5e23abfc0 100644 --- a/src/lib/medications/efficacy/load-segmented-effects.ts +++ b/src/lib/medications/efficacy/load-segmented-effects.ts @@ -15,6 +15,7 @@ import { import { dueSchedules } from "@/lib/medications/intake-tracking"; import { dayKeyOfDate } from "@/lib/medications/course-window"; import { readDayAggregates } from "@/lib/measurements/day-aggregates"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; import { plausibleMetricRange } from "@/lib/measurements/value-domain"; import { userDayKey } from "@/lib/tz/format"; import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only"; @@ -219,6 +220,7 @@ export async function loadSegmentedEffects(params: { userDayKey(dc.effectiveFrom, timezone), ); + const sourcePriority = await loadUserSourcePriority(userId); for (const target of targets) { const rows = await readDayAggregates({ userId, @@ -227,6 +229,7 @@ export async function loadSegmentedEffects(params: { until, timeZone: timezone, valueRange: plausibleMetricRange(target), + sourcePriority, }); out.set( target, diff --git a/src/lib/rollups/__tests__/tiered-context-envelope.test.ts b/src/lib/rollups/__tests__/tiered-context-envelope.test.ts index 8c81fbfc9d..1cc39c2981 100644 --- a/src/lib/rollups/__tests__/tiered-context-envelope.test.ts +++ b/src/lib/rollups/__tests__/tiered-context-envelope.test.ts @@ -28,6 +28,7 @@ vi.mock("../measurement-rollups", () => ({ vi.mock("@/lib/db", () => ({ prisma: { measurement: { findMany: mocks.measurementFindMany }, + user: { findUnique: async () => null }, $queryRaw: mocks.queryRaw, }, })); diff --git a/src/lib/rollups/__tests__/tiered-context.test.ts b/src/lib/rollups/__tests__/tiered-context.test.ts index 60fb1f0ab5..93eda11f58 100644 --- a/src/lib/rollups/__tests__/tiered-context.test.ts +++ b/src/lib/rollups/__tests__/tiered-context.test.ts @@ -43,6 +43,7 @@ vi.mock("../measurement-coverage", () => ({ vi.mock("@/lib/db", () => ({ prisma: { measurement: { findMany: mocks.measurementFindMany }, + user: { findUnique: async () => null }, // v1.37.19 — the live band fallback. $queryRaw: mocks.queryRaw, }, diff --git a/src/lib/rollups/tiered-context.ts b/src/lib/rollups/tiered-context.ts index 0972589ceb..ddda5bc191 100644 --- a/src/lib/rollups/tiered-context.ts +++ b/src/lib/rollups/tiered-context.ts @@ -39,6 +39,7 @@ import { readRollupBuckets, } from "./measurement-rollups"; import { readDayAggregates } from "@/lib/measurements/day-aggregates"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; import { dayWeightedRowsSql, windowMeanSql } from "@/lib/measurements/day-mean"; import { usesHourlyMeanDay } from "@/lib/measurements/day-statistic"; import { Prisma } from "@/generated/prisma/client"; @@ -262,6 +263,7 @@ async function readRecentDaily( type: MeasurementType, now: number, tz: string, + userPriorityJson: unknown, ): Promise { const since = new Date(now - TIERED_BANDS.rawDays * DAY_MS); // Folded per local day in SQL: one row per day however densely the type @@ -271,6 +273,10 @@ async function readRecentDaily( type, since, timeZone: tz, + sourcePriority: + userPriorityJson !== undefined + ? userPriorityJson + : await loadUserSourcePriority(userId), }); // A pulse day is the mean of its local hours' means (`dayMean`, see // `day-mean.ts`); every other type's day is the mean of its readings. @@ -547,7 +553,13 @@ export async function buildTieredSeries( await Promise.all([ options.skipRecentDaily || coarseOnly ? Promise.resolve([]) - : readRecentDaily(userId, type, now, options.tz), + : readRecentDaily( + userId, + type, + now, + options.tz, + options.userPriorityJson, + ), coarseOnly ? emptyBand : readBand( From 1fce458b4c704e8c35cf0d487bb3af20e82d9f24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 00:58:59 +0100 Subject: [PATCH 3/9] fix(insights): take the status snapshots and the resting proxy from one source a day The status snapshots' recent readings (rows, or hour cells beyond the cap) and the low-percentile resting proxy pooled every source's readings into a day. The recent readings now keep each local day to its first source on the person's ladder through the day picker, with hour cells read per source so the pick can still choose. The proxy folds each (day, source) and keeps the day's first source in ladder order, with the ladder in the closed block's cache key. The ladder rank of one type is one helper in source-rank-sql, shared with readDayAggregates. The day-value guard lists no open reader any more, and its reason type has no open arm. (cherry picked from commit 5d3e005f832cc9131707469274c7a3274f22898d) --- .../day-value-source-rule-guard.test.ts | 11 +- src/lib/analytics/resting-pulse-read.ts | 74 +++++++++-- src/lib/analytics/source-rank-sql.ts | 39 +++++- .../__tests__/recent-readings.test.ts | 121 ++++++++++++++++-- src/lib/insights/recent-readings.ts | 113 +++++++++++++--- src/lib/measurements/day-aggregates.ts | 35 ++--- tests/integration/dense-day-readers.test.ts | 98 ++++++++++---- 7 files changed, 391 insertions(+), 100 deletions(-) diff --git a/src/__tests__/day-value-source-rule-guard.test.ts b/src/__tests__/day-value-source-rule-guard.test.ts index 972ddafea0..3c718fd3a5 100644 --- a/src/__tests__/day-value-source-rule-guard.test.ts +++ b/src/__tests__/day-value-source-rule-guard.test.ts @@ -52,8 +52,7 @@ type Reason = | "per-source" | "latest-reading" | "window" - | "worst-of-any-source" - | "open"; + | "worst-of-any-source"; /** Arm 1: `readDayAggregates` calls that fold every source, by file. */ const POOLED_DAY_AGGREGATES: Record< @@ -89,10 +88,6 @@ const READERS_WITHOUT_RULE: Record = { reason: "per-source", why: "device scores of the last nights with their source on every row; the card names each device's own score", }, - "lib/insights/recent-readings.ts": { - reason: "open", - why: "the status snapshots' newest readings (rows, or hour cells beyond the cap) pool every source, and metric-status and pulse-status fold them into days; the pick has to reach readNewestRowsPerType and readHourCells", - }, "lib/insights/derived/bmi.ts": { reason: "latest-reading", why: "the newest weight in the window as the BMI input", @@ -121,10 +116,6 @@ const READERS_WITHOUT_RULE: Record = { reason: "window", why: "the 30-day glucose panel over every reading at its own instant, grouped by meal context; spot checks and a sensor are readings of one blood, not two estimates of one day", }, - "lib/analytics/resting-pulse-read.ts": { - reason: "open", - why: "the low-percentile resting proxy pools every source's PULSE readings per day; the pick belongs in the fold and the closed-block cache key, and the pinned single-statement read in dense-day-readers.test.ts moves with it", - }, }; /** A file applies the rule when its code names one of these. */ diff --git a/src/lib/analytics/resting-pulse-read.ts b/src/lib/analytics/resting-pulse-read.ts index 7ccf2bdf7e..777bf6428b 100644 --- a/src/lib/analytics/resting-pulse-read.ts +++ b/src/lib/analytics/resting-pulse-read.ts @@ -18,6 +18,14 @@ * profile zone the caller passes, as `readDayAggregates` cuts a pulse day; * a reading's own zone is not read (`reading-zone-reader-ratchet.test.ts`). * + * A day folds the readings of one source: the first source of the day on the + * person's `pulse` ladder (rank, then source name, as `readDayAggregates` + * picks a day). A watch and a phone app reporting the same day's pulse are + * two streams of one heart; pooling them took the 20th percentile of a + * mixture, which neither device measured. The day's sample floor applies to + * the picked source's readings, so a better-ranked source with too few + * readings leaves the day out rather than handing it to a lower-ranked one. + * * The fold is cached as a closed block. A day's proxy depends only on that * day's readings, so the whole local days between the window's first * (partial) day and the start of today fold once and are kept in the @@ -33,10 +41,15 @@ * all read it, so they share the block and pay for the two live days only. */ import { Prisma, type PrismaClient } from "@/generated/prisma/client"; +import { + sourceLadderOfType, + sourceRankOfTypeSql, +} from "@/lib/analytics/source-rank-sql"; import { closedBlockKeyPart } from "@/lib/cache/closed-block"; import { PROCESS_CACHE_MAX_TTL_MS } from "@/lib/cache/ttl-ceiling"; import { caches, type ServerCache } from "@/lib/cache/server-cache"; import { prisma } from "@/lib/db"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; import { isValidTimezone, userDayKey } from "@/lib/tz/format"; import { localDayWindow } from "@/lib/tz/local-day"; @@ -59,16 +72,20 @@ import { const CLOSED_PROXY_TTL_MS = PROCESS_CACHE_MAX_TTL_MS; /** - * The cache key of the closed proxy days `[blockFrom, blockTo)`. Exported so - * a test can tell whether a write left the block in place. + * The cache key of the closed proxy days `[blockFrom, blockTo)` under the + * pulse ladder of `sourcePriority`, so a reordered ladder never serves days + * picked by the old one. Exported so a test can tell whether a write left + * the block in place. */ export function restingPulseProxyBlockKey( userId: string, timeZone: string, blockFrom: Date, blockTo: Date, + sourcePriority: unknown, ): string { - return `${userId}|resting-pulse-proxy|${timeZone}|from:${blockFrom.getTime()}|${closedBlockKeyPart(blockTo)}`; + const ladder = sourceLadderOfType("PULSE", sourcePriority).join(">"); + return `${userId}|resting-pulse-proxy|${timeZone}|ladder:${ladder}|from:${blockFrom.getTime()}|${closedBlockKeyPart(blockTo)}`; } /** A `[from, to)` window of `measured_at`; open-ended without `to`. */ @@ -82,6 +99,7 @@ async function foldProxy( db: Pick, userId: string, timeZone: string, + sourcePriority: unknown, windows: readonly Window[], ): Promise { const fraction = RESTING_PROXY_DAILY_PERCENTILE / 100; @@ -93,11 +111,18 @@ async function foldProxy( ), " OR ", ); + // Each (day, source) folds on its own and the day keeps its first source + // in ladder order: one row per source and day is ranked, never a window + // over the raw stream. + const rank = Prisma.raw( + sourceRankOfTypeSql("PULSE", sourcePriority, "f.source") ?? "90", + ); const rows = await db.$queryRaw>( Prisma.sql` WITH src AS ( SELECT to_char((m."measured_at" AT TIME ZONE 'UTC') AT TIME ZONE ${timeZone}, 'YYYY-MM-DD') AS day, + m."source" AS source, m."measured_at" AS measured_at, m."value" AS value FROM measurements m @@ -105,13 +130,25 @@ async function foldProxy( AND m."type" = 'PULSE'::measurement_type AND m."deleted_at" IS NULL AND (${inWindows}) + ), + folded AS ( + SELECT + day, + source, + COUNT(*) AS n, + MIN(measured_at) AS first_at, + (percentile_cont(${fraction}::double precision) WITHIN GROUP (ORDER BY value))::double precision AS p + FROM src + GROUP BY day, source + ), + picked AS ( + SELECT DISTINCT ON (f.day) f.n, f.first_at, f.p + FROM folded f + ORDER BY f.day, (${rank}), f.source::text ) - SELECT - MIN(measured_at) AS first_at, - (percentile_cont(${fraction}::double precision) WITHIN GROUP (ORDER BY value))::double precision AS p - FROM src - GROUP BY day - HAVING COUNT(*) >= ${RESTING_PROXY_MIN_DAILY_SAMPLES} + SELECT first_at, p + FROM picked + WHERE n >= ${RESTING_PROXY_MIN_DAILY_SAMPLES} ORDER BY first_at ASC `, ); @@ -133,6 +170,7 @@ export async function readRestingPulseProxy(opts: { const timeZone = isValidTimezone(opts.timeZone) ? opts.timeZone : "UTC"; const { userId, since } = opts; const now = opts.now ?? new Date(); + const sourcePriority = await loadUserSourcePriority(userId); // The whole local days between the partial first day and today. const blockFrom = localDayWindow( userDayKey(since, timeZone), @@ -140,10 +178,18 @@ export async function readRestingPulseProxy(opts: { ).dayEnd; const blockTo = localDayWindow(userDayKey(now, timeZone), timeZone).dayStart; if (blockFrom >= blockTo) { - return foldProxy(prisma, userId, timeZone, [{ from: since }]); + return foldProxy(prisma, userId, timeZone, sourcePriority, [ + { from: since }, + ]); } const cache = caches.analytics as ServerCache; - const key = restingPulseProxyBlockKey(userId, timeZone, blockFrom, blockTo); + const key = restingPulseProxyBlockKey( + userId, + timeZone, + blockFrom, + blockTo, + sourcePriority, + ); // On a miss the whole window folds in one statement, exactly as an // uncached read does, and the closed days are kept from it; on a hit only // the partial first day and today fold. @@ -151,7 +197,9 @@ export async function readRestingPulseProxy(opts: { const closed = await cache.wrap( key, async () => { - whole = await foldProxy(prisma, userId, timeZone, [{ from: since }]); + whole = await foldProxy(prisma, userId, timeZone, sourcePriority, [ + { from: since }, + ]); return whole.filter( (p) => p.measuredAt >= blockFrom && p.measuredAt < blockTo, ); @@ -160,7 +208,7 @@ export async function readRestingPulseProxy(opts: { ); const days: PulseSample[] = whole ?? [ ...closed.value, - ...(await foldProxy(prisma, userId, timeZone, [ + ...(await foldProxy(prisma, userId, timeZone, sourcePriority, [ { from: since, to: blockFrom }, { from: blockTo }, ])), diff --git a/src/lib/analytics/source-rank-sql.ts b/src/lib/analytics/source-rank-sql.ts index d138bbf7c7..b3d10b2f9c 100644 --- a/src/lib/analytics/source-rank-sql.ts +++ b/src/lib/analytics/source-rank-sql.ts @@ -18,7 +18,10 @@ * convention the rollup writer uses for its date-trunc + type-list splices. * The user id is always passed as a bound parameter, never spliced. */ -import type { MeasurementType } from "@/generated/prisma/client"; +import type { + MeasurementSource, + MeasurementType, +} from "@/generated/prisma/client"; import { assertInstantSql } from "@/lib/analytics/request-clock-sql"; import { metricKeyForType } from "@/lib/measurements/cumulative-day-sum"; import { @@ -111,6 +114,40 @@ export function buildSourceRankCase( return `CASE ${branches.join(" ")} ELSE 90 END`; } +/** + * The source ladder a day read of `type` picks by, best first, from the + * user's `sourcePriorityJson` (`null` for the default ladders). Empty for a + * type without a ladder: its days have one producer and nothing to pick. + */ +export function sourceLadderOfType( + type: MeasurementType, + priorityJson: unknown, +): readonly MeasurementSource[] { + const metricKey = metricKeyForType(type); + if (metricKey === null || !RANKED_TYPES.includes(type)) return []; + return getSourceLadder(parseSourcePriority(priorityJson), metricKey); +} + +/** + * A SQL rank of `sourceCol` on `type`'s ladder: 0 for the best source, 90 for + * a source off the ladder, so the source name breaks the tie as it does in + * `canonicalMeasurementsCte`. `null` for a type without a ladder. The + * literals are closed-enum values asserted against a fixed pattern before + * they are spliced; `sourceCol` is the caller's own column reference. + */ +export function sourceRankOfTypeSql( + type: MeasurementType, + priorityJson: unknown, + sourceCol: string, +): string | null { + const ladder = sourceLadderOfType(type, priorityJson); + if (ladder.length === 0) return null; + const whens = ladder + .map((source, i) => `WHEN '${assertEnumLiteral(source)}' THEN ${i}`) + .join(" "); + return `CASE ${sourceCol}::text ${whens} ELSE 90 END`; +} + const INTERVAL_RE = /^\d+ (day|days|month|months|year|years)$/; function assertInterval(value: string): string { if (!INTERVAL_RE.test(value)) { diff --git a/src/lib/insights/__tests__/recent-readings.test.ts b/src/lib/insights/__tests__/recent-readings.test.ts index 259794e87d..ffc22c599d 100644 --- a/src/lib/insights/__tests__/recent-readings.test.ts +++ b/src/lib/insights/__tests__/recent-readings.test.ts @@ -1,14 +1,20 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -const { findMany, annotate, countReadingsUpTo, readHourCells } = vi.hoisted( - () => ({ - findMany: vi.fn(), - annotate: vi.fn(), - countReadingsUpTo: vi.fn(), - readHourCells: vi.fn(), - }), -); +const { + findMany, + annotate, + countReadingsUpTo, + readHourCells, + loadUserSourcePriority, +} = vi.hoisted(() => ({ + findMany: vi.fn(), + annotate: vi.fn(), + countReadingsUpTo: vi.fn(), + readHourCells: vi.fn(), + loadUserSourcePriority: vi.fn(), +})); vi.mock("@/lib/db", () => ({ prisma: { measurement: { findMany } } })); +vi.mock("@/lib/rollups/measurement-read", () => ({ loadUserSourcePriority })); vi.mock("@/lib/logging/context", () => ({ annotate })); vi.mock("@/lib/measurements/dense-bucket-read", () => ({ countReadingsUpTo, @@ -30,6 +36,8 @@ beforeEach(() => { annotate.mockReset(); countReadingsUpTo.mockReset(); readHourCells.mockReset(); + loadUserSourcePriority.mockReset(); + loadUserSourcePriority.mockResolvedValue(null); }); describe("readRecentReadings", () => { @@ -85,8 +93,20 @@ describe("readRecentReadings", () => { findMany.mockResolvedValueOnce(dense); countReadingsUpTo.mockResolvedValueOnce(DENSE_READ_CAP + 1); readHourCells.mockResolvedValueOnce([ - { measuredAt: minutesAgo(120), value: 61.5, n: 1400, source: null }, - { measuredAt: minutesAgo(60), value: 64, n: 1450, source: null }, + { + measuredAt: minutesAgo(120), + value: 61.5, + n: 1400, + source: "APPLE_HEALTH", + deviceType: null, + }, + { + measuredAt: minutesAgo(60), + value: 64, + n: 1450, + source: "APPLE_HEALTH", + deviceType: null, + }, ]); const out = await readRecentReadings("u1", "PULSE", TZ, now); // No raw window read: the newest 365 and then the cells. @@ -96,6 +116,8 @@ describe("readRecentReadings", () => { type: "PULSE", timeZone: TZ, summed: false, + // Per source, so the day pick can still choose between them. + bySource: true, }); expect(out).toEqual([ { measuredAt: minutesAgo(120), value: 61.5 }, @@ -122,4 +144,83 @@ describe("readRecentReadings", () => { expect(await readRecentReadings("u1", "PULSE", TZ, now)).toHaveLength(1); expect(findMany).toHaveBeenCalledTimes(1); }); + + it("keeps each day to the source the ladder puts first", async () => { + // Withings ranks above a hand-typed reading on the default pulse ladder. + findMany.mockResolvedValueOnce([ + { + value: 90, + measuredAt: minutesAgo(30), + source: "MANUAL", + deviceType: null, + }, + { + value: 60, + measuredAt: minutesAgo(20), + source: "WITHINGS", + deviceType: null, + }, + { + value: 62, + measuredAt: minutesAgo(10), + source: "WITHINGS", + deviceType: null, + }, + // The day before holds only the hand-typed reading, and keeps it. + { + value: 88, + measuredAt: minutesAgo(1440), + source: "MANUAL", + deviceType: null, + }, + ]); + const out = await readRecentReadings("u1", "PULSE", TZ, now); + expect(out).toEqual([ + { value: 88, measuredAt: minutesAgo(1440) }, + { value: 60, measuredAt: minutesAgo(20) }, + { value: 62, measuredAt: minutesAgo(10) }, + ]); + }); + + it("follows the person's own ladder", async () => { + loadUserSourcePriority.mockResolvedValue({ + metricPriority: { pulse: ["MANUAL", "WITHINGS"] }, + }); + findMany.mockResolvedValueOnce([ + { + value: 90, + measuredAt: minutesAgo(30), + source: "MANUAL", + deviceType: null, + }, + { + value: 60, + measuredAt: minutesAgo(20), + source: "WITHINGS", + deviceType: null, + }, + ]); + const out = await readRecentReadings("u1", "PULSE", TZ, now); + expect(out).toEqual([{ value: 90, measuredAt: minutesAgo(30) }]); + }); + + it("passes a type without a ladder through, every source kept", async () => { + findMany.mockResolvedValueOnce([ + { + value: 5.1, + measuredAt: minutesAgo(30), + source: "MANUAL", + deviceType: null, + }, + { + value: 5.4, + measuredAt: minutesAgo(20), + source: "APPLE_HEALTH", + deviceType: null, + }, + ]); + const out = await readRecentReadings("u1", "BLOOD_GLUCOSE", TZ, now); + expect(out).toHaveLength(2); + expect(loadUserSourcePriority).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/insights/recent-readings.ts b/src/lib/insights/recent-readings.ts index f9785ece36..1e58ae682a 100644 --- a/src/lib/insights/recent-readings.ts +++ b/src/lib/insights/recent-readings.ts @@ -18,8 +18,23 @@ * a stream just over the cap can move against the same stream just under it. * The longer tail of every snapshot comes from the rollup tier, not from * here. + * + * Every read keeps, per local day, the readings of the day's first source on + * the person's ladder (`pickCanonicalSourceRows`, the pick the metric page + * makes). The snapshots fold these readings into days, and a day that holds + * a watch's and a phone app's readings of one metric is two estimates of one + * value, not one estimate weighed by whichever wrote more often. A type + * without a ladder has one producer per day and passes through. The cut that + * decides between the latest readings and the 30-day window is taken on + * every source's readings, before the pick, so it does not move with the + * ladder. */ -import type { MeasurementType } from "@/generated/prisma/client"; +import type { + MeasurementSource, + MeasurementType, +} from "@/generated/prisma/client"; +import { pickCanonicalSourceRows } from "@/lib/analytics/source-priority"; +import { isSourceRankedType } from "@/lib/analytics/source-rank-sql"; import { prisma } from "@/lib/db"; import { annotate } from "@/lib/logging/context"; import { isCumulativeDaySumType } from "@/lib/measurements/cumulative-day-sum"; @@ -27,7 +42,10 @@ import { countReadingsUpTo, readHourCells, } from "@/lib/measurements/dense-bucket-read"; +import { metricKeyForType } from "@/lib/measurements/cumulative-day-sum"; import { readNewestRowsPerType } from "@/lib/measurements/newest-per-type"; +import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; +import { userDayKey } from "@/lib/tz/format"; export const RECENT_READINGS = 365; export const RECENT_MIN_DAYS = 30; @@ -41,6 +59,45 @@ export interface RecentReading { measuredAt: Date; } +/** A reading as read, with what the source pick needs. */ +interface SourcedReading extends RecentReading { + source: MeasurementSource; + deviceType: string | null; +} + +const SOURCED_SELECT = { + value: true, + measuredAt: true, + source: true, + deviceType: true, +} as const; + +/** + * `rows` (oldest first) narrowed to each local day's canonical source, as + * plain readings. A type without a ladder passes through. + */ +async function pickDaySource( + userId: string, + type: MeasurementType, + timeZone: string, + rows: readonly SourcedReading[], +): Promise { + const metricKey = metricKeyForType(type); + const kept = + metricKey === null || !isSourceRankedType(type) || rows.length === 0 + ? rows + : pickCanonicalSourceRows( + rows.map((r) => ({ ...r, type })), + metricKey, + await loadUserSourcePriority(userId), + (d) => userDayKey(d, timeZone), + ).canonicalRows; + // The picker keeps a day's rows together; the readings stay oldest first. + return kept + .map((r) => ({ value: r.value, measuredAt: r.measuredAt })) + .sort((a, b) => a.measuredAt.getTime() - b.measuredAt.getTime()); +} + /** Oldest first. */ export async function readRecentReadings( userId: string, @@ -51,9 +108,9 @@ export async function readRecentReadings( // dense-take: the newest 365 only; when they span under 30 days the 30-day window is read by time below. const latest = await prisma.measurement.findMany({ where: { userId, type, deletedAt: null }, - orderBy: { measuredAt: "desc" }, + orderBy: [{ measuredAt: "desc" }, { id: "desc" }], take: RECENT_READINGS, - select: { value: true, measuredAt: true }, + select: SOURCED_SELECT, }); const since = new Date(now.getTime() - RECENT_MIN_DAYS * DAY_MS); const oldest = latest.at(-1); @@ -62,21 +119,27 @@ export async function readRecentReadings( !oldest || oldest.measuredAt <= since ) { - return latest.reverse(); + return pickDaySource(userId, type, timeZone, latest.reverse()); } - return readWindowReadings(userId, type, since, timeZone); + return pickDaySource( + userId, + type, + timeZone, + await readWindowReadings(userId, type, since, timeZone), + ); } /** - * Every reading of the window, oldest first: the rows themselves while they - * fit under {@link DENSE_READ_CAP}, one reading per local hour beyond it. + * Every reading of the window, oldest first, with its source: the rows + * themselves while they fit under {@link DENSE_READ_CAP}, one reading per + * local hour, source and device type beyond it. */ async function readWindowReadings( userId: string, type: MeasurementType, since: Date, timeZone: string, -): Promise { +): Promise { const count = await countReadingsUpTo({ userId, type, @@ -86,8 +149,8 @@ async function readWindowReadings( if (count <= DENSE_READ_CAP) { return prisma.measurement.findMany({ where: { userId, type, deletedAt: null, measuredAt: { gte: since } }, - orderBy: { measuredAt: "asc" }, - select: { value: true, measuredAt: true }, + orderBy: [{ measuredAt: "asc" }, { id: "asc" }], + select: SOURCED_SELECT, }); } annotate({ @@ -100,9 +163,15 @@ async function readWindowReadings( since, timeZone, summed: isCumulativeDaySumType(type), - bySource: false, + bySource: true, }); - return cells.map((c) => ({ value: c.value, measuredAt: c.measuredAt })); + return cells.map((c) => ({ + value: c.value, + measuredAt: c.measuredAt, + // `bySource` names every cell's source. + source: c.source!, + deviceType: c.deviceType, + })); } /** @@ -129,10 +198,15 @@ export async function readLatestReadingsPerType( perTypeCap: perType, }); const since = new Date(now.getTime() - RECENT_MIN_DAYS * DAY_MS); - const byType = new Map(); + const byType = new Map(); for (const r of rows) { const list = byType.get(r.type) ?? []; - list.push({ value: r.value, measuredAt: r.measuredAt }); + list.push({ + value: r.value, + measuredAt: r.measuredAt, + source: r.source, + deviceType: r.deviceType, + }); byType.set(r.type, list); } const out: Array = []; @@ -141,9 +215,14 @@ export async function readLatestReadingsPerType( if (!list) continue; // Oldest first, so the first row is the oldest of the newest `perType`. const shortWindow = list.length >= perType && list[0].measuredAt > since; - const readings = shortWindow - ? await readWindowReadings(userId, type, since, timeZone) - : list; + const readings = await pickDaySource( + userId, + type, + timeZone, + shortWindow + ? await readWindowReadings(userId, type, since, timeZone) + : list, + ); for (const r of readings) out.push({ type, ...r }); } return out.sort((a, b) => a.measuredAt.getTime() - b.measuredAt.getTime()); diff --git a/src/lib/measurements/day-aggregates.ts b/src/lib/measurements/day-aggregates.ts index b7f0eac833..fd045b5663 100644 --- a/src/lib/measurements/day-aggregates.ts +++ b/src/lib/measurements/day-aggregates.ts @@ -32,12 +32,7 @@ import { READING_ZONE_SLACK_MS } from "@/lib/tz/reading-zone"; import { MS_PER_DAY } from "@/lib/time-constants"; import { dayWeightedRowsSql } from "@/lib/measurements/day-mean"; import { usesHourlyMeanDay } from "@/lib/measurements/day-statistic"; -import { RANKED_TYPES } from "@/lib/analytics/source-rank-sql"; -import { metricKeyForType } from "@/lib/measurements/cumulative-day-sum"; -import { - getSourceLadder, - parseSourcePriority, -} from "@/lib/validations/source-priority"; +import { sourceRankOfTypeSql } from "@/lib/analytics/source-rank-sql"; export interface DayAggregateRow { /** Calendar day in the requested zone, `YYYY-MM-DD`. */ @@ -123,29 +118,15 @@ function canonicalSourceKeep( alias: string, day: Prisma.Sql, ): Prisma.Sql { - const metricKey = metricKeyForType(opts.type); - if ( - opts.sourcePriority === undefined || - metricKey === null || - !RANKED_TYPES.includes(opts.type) - ) { - return Prisma.sql`TRUE`; - } - const ladder = getSourceLadder( - parseSourcePriority(opts.sourcePriority), - metricKey, + if (opts.sourcePriority === undefined) return Prisma.sql`TRUE`; + const rankSql = sourceRankOfTypeSql( + opts.type, + opts.sourcePriority, + `${alias}."source"`, ); - if (ladder.length === 0) return Prisma.sql`TRUE`; + if (rankSql === null) return Prisma.sql`TRUE`; const a = Prisma.raw(alias); - const whens = ladder - .map((source, i) => { - if (!/^[A-Z0-9_]+$/.test(source)) { - throw new Error(`unsafe source literal for SQL splice: ${source}`); - } - return `WHEN '${source}' THEN ${i}`; - }) - .join(" "); - const rank = Prisma.raw(`CASE ${alias}."source"::text ${whens} ELSE 90 END`); + const rank = Prisma.raw(rankSql); return Prisma.sql`(${a}."source" = FIRST_VALUE(${a}."source") OVER ( PARTITION BY ${day} ORDER BY (${rank}), ${a}."source"::text diff --git a/tests/integration/dense-day-readers.test.ts b/tests/integration/dense-day-readers.test.ts index 66ced4ba9f..919d909d03 100644 --- a/tests/integration/dense-day-readers.test.ts +++ b/tests/integration/dense-day-readers.test.ts @@ -43,6 +43,7 @@ import { restingPulseProxyBlockKey, } from "@/lib/analytics/resting-pulse-read"; import { caches } from "@/lib/cache/server-cache"; +import { sourceLadderOfType } from "@/lib/analytics/source-rank-sql"; import { readCumulativeDayProfiles } from "@/lib/measurements/intraday-cumulative-profile"; import { buildWorkoutHrSeries, foldHrBuckets } from "@/lib/workouts/hr-series"; import { shiftDateKey, userDayKey } from "@/lib/tz/format"; @@ -593,15 +594,20 @@ describe("the other dense-day readers", () => { }); /** - * The 30-day fold as it ran before the closed block: one statement over the - * whole window. The reference the cached read must equal. + * The 30-day fold as one plain statement over the whole window, each local + * day kept to its first source on the default pulse ladder. The reference + * the cached read must equal. */ async function referenceProxy(userId: string, since: Date) { - const rows = await prisma.$queryRaw>( + const ladder = sourceLadderOfType("PULSE", null); + const rows = await prisma.$queryRaw< + Array<{ day: string; source: string; first_at: Date; p: number; n: number }> + >( Prisma.sql` WITH src AS ( SELECT to_char((m."measured_at" AT TIME ZONE 'UTC') AT TIME ZONE ${TZ}, 'YYYY-MM-DD') AS day, + m."source"::text AS source, m."measured_at" AS measured_at, m."value" AS value FROM measurements m @@ -611,34 +617,70 @@ async function referenceProxy(userId: string, since: Date) { AND m."measured_at" >= ${since} ) SELECT + day, + source, + COUNT(*)::int AS n, MIN(measured_at) AS first_at, (percentile_cont(0.2::double precision) WITHIN GROUP (ORDER BY value))::double precision AS p FROM src - GROUP BY day - HAVING COUNT(*) >= 3 - ORDER BY first_at ASC + GROUP BY day, source `, ); - return rows.map((r) => ({ - measuredAt: r.first_at, - value: Math.round(Number(r.p)), - })); + const rank = (s: string) => { + const i = ladder.indexOf(s as (typeof ladder)[number]); + return i === -1 ? 90 : i; + }; + const best = new Map(); + for (const r of rows) { + const held = best.get(r.day); + if ( + !held || + rank(r.source) < rank(held.source) || + (rank(r.source) === rank(held.source) && r.source < held.source) + ) { + best.set(r.day, r); + } + } + return [...best.values()] + .filter((r) => Number(r.n) >= 3) + .sort((a, b) => a.first_at.getTime() - b.first_at.getTime()) + .map((r) => ({ + measuredAt: r.first_at, + value: Math.round(Number(r.p)), + })); } -/** The proxy fold's statements, by the start the counter keeps of them. */ +/** + * The proxy fold's statements, by the start the counter keeps of them (its + * first 160 characters). + */ const PROXY_STATEMENT = - /^WITH src AS \( SELECT to_char\(\(m\."measured_at" AT TIME ZONE 'UTC'\) AT TIME ZONE \$\d+, 'YYYY-MM-DD'\) AS day, m\."measured_at" AS measured_at, m\."value" AS value/; + /^WITH src AS \( SELECT to_char\(\(m\."measured_at" AT TIME ZONE 'UTC'\) AT TIME ZONE \$\d+, 'YYYY-MM-DD'\) AS day, m\."source" AS source/; -/** Three pulse readings at `at`, a minute apart, and the write tail's eviction. */ -async function writePulse(at: Date, value: number, tag: string) { +/** How many proxy folds a counted read sent. */ +const proxyFolds = (m: { statements: string[] }) => + m.statements.filter((t) => PROXY_STATEMENT.test(t)).length; + +/** + * Three pulse readings at `at`, a minute apart, and the write tail's + * eviction. From the seeded stream's own source unless `source` says + * otherwise, so the day's pick keeps them. + */ +async function writePulse( + at: Date, + value: number, + tag: string, + source: "GOOGLE_HEALTH" | "MANUAL" = "GOOGLE_HEALTH", +) { const rows = [0, 1, 2].map((i) => ({ id: `${tag}-${i}`, userId: DENSE, type: "PULSE" as const, value, unit: "bpm", - // Manual readings at odd milliseconds: no seeded row shares the key. - source: "MANUAL" as const, + // Odd milliseconds: the seeded stream's instants fall on sevenths of a + // millisecond, so no seeded row shares the key. + source, measuredAt: new Date(at.getTime() + i * 60_000 + 777), })); await prisma.measurement.createMany({ data: rows }); @@ -657,6 +699,7 @@ describe("the 30-day resting-pulse proxy, folded once and shared", () => { TZ, localDayWindow(userDayKey(since, TZ), TZ).dayEnd, localDayWindow(userDayKey(NOW, TZ), TZ).dayStart, + null, ), ) !== null; @@ -668,8 +711,8 @@ describe("the 30-day resting-pulse proxy, folded once and shared", () => { const coldMs = performance.now() - started; expect(cold.result).toEqual(await referenceProxy(DENSE, since)); expect(cold.result.length).toBeGreaterThanOrEqual(26); - // A miss is the old single statement, and it keeps the closed days. - expect(cold.count).toBe(1); + // A miss is one fold over the whole window, and it keeps the closed days. + expect(proxyFolds(cold)).toBe(1); expect(blockCached()).toBe(true); const warmStarted = performance.now(); @@ -677,7 +720,7 @@ describe("the 30-day resting-pulse proxy, folded once and shared", () => { const warmMs = performance.now() - warmStarted; expect(warm.result).toEqual(cold.result); // Only the partial first day and today are folded again. - expect(warm.count).toBe(1); + expect(proxyFolds(warm)).toBe(1); report( `resting proxy, 30 days: cold ${coldMs.toFixed(0)} ms, warm ${warmMs.toFixed(0)} ms`, ); @@ -686,10 +729,22 @@ describe("the 30-day resting-pulse proxy, folded once and shared", () => { await writePulse(new Date(NOW.getTime() - 10 * 60_000), 41, "today"); expect(blockCached()).toBe(true); const synced = await countStatements(read); - expect(synced.count).toBe(1); + expect(proxyFolds(synced)).toBe(1); expect(synced.result).toEqual(await referenceProxy(DENSE, since)); expect(synced.result.at(-1)!.value).toBe(41); + // A hand-typed reading on the same day ranks below the stream's source + // on the pulse ladder: the day stays the stream's, not a pooled mixture. + await writePulse( + new Date(NOW.getTime() - 8 * 60_000), + 20, + "typed", + "MANUAL", + ); + const typed = await countStatements(read); + expect(typed.result).toEqual(synced.result); + expect(typed.result).toEqual(await referenceProxy(DENSE, since)); + // A backfill that reaches into the closed days drops the block. const { dayStart } = localDayWindow(shiftDateKey(DAY, -5), TZ); await writePulse(new Date(dayStart.getTime() + 3 * 3_600_000), 20, "old"); @@ -737,8 +792,7 @@ describe("the 30-day resting-pulse proxy, folded once and shared", () => { const after = await sync(true, "launch"); const afterMs = after.ms; const unshared = await sync(false, "launch-unshared"); - const folds = (m: { statements: string[] }) => - m.statements.filter((t) => PROXY_STATEMENT.test(t)).length; + const folds = proxyFolds; report( `daily digest: cold ${coldMs.toFixed(0)} ms / ${cold.count} statements / ${folds(cold)} proxy folds, ` + `after a sync ${afterMs.toFixed(0)} ms / ${after.count} statements / ${folds(after)} proxy folds, ` + From ca656101330fab728d9aa2fc972ce0157c6cf0d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 01:08:29 +0100 Subject: [PATCH 4/9] test(insights): list main's own readers in the day-value guard The guard was written against the 1.50 tree. On main the morning load reader does not exist, the recovery empty-state reader applies no raw read the matcher sees, and the same-time baseline reads only the newest row's unit; its hourly profiles come from the per-sample source alone. --- src/__tests__/day-value-source-rule-guard.test.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/__tests__/day-value-source-rule-guard.test.ts b/src/__tests__/day-value-source-rule-guard.test.ts index 3c718fd3a5..59b0ab0006 100644 --- a/src/__tests__/day-value-source-rule-guard.test.ts +++ b/src/__tests__/day-value-source-rule-guard.test.ts @@ -72,22 +72,18 @@ const READERS_WITHOUT_RULE: Record = { reason: "probe", why: "the newest updatedAt of any row, a cache fingerprint; no value is read", }, - "lib/insights/recovery-empty-read.ts": { - reason: "probe", - why: "whether any device recovery row exists, to explain an empty card", - }, "lib/dashboard/widgets/unavailable-widgets.ts": { reason: "probe", why: "whether a type has any row at all, to hide a widget without data", }, + "lib/insights/derived/same-time-baseline.ts": { + reason: "probe", + why: "the unit of the newest row as the display unit; the hourly profiles come from readCumulativeDayProfiles, which reads the per-sample source alone", + }, "lib/insights/derived/readiness.ts": { reason: "single-producer", why: "reads RECOVERY_SCORE filtered to source COMPUTED, HealthLog's own readiness rows", }, - "lib/daily/morning-load.ts": { - reason: "per-source", - why: "device scores of the last nights with their source on every row; the card names each device's own score", - }, "lib/insights/derived/bmi.ts": { reason: "latest-reading", why: "the newest weight in the window as the BMI input", From 02198c45a5b2c3cf798fa921a6943d4aaea16fc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 01:26:07 +0100 Subject: [PATCH 5/9] fix(backup): tell a refused off-host copy by where it failed, not OpenSSL's text decryptOffhostFile recognised a failed GCM tag by matching the error message against /auth|unable to authenticate/. Node 22 words it that way; Node 26 on OpenSSL 4 says "bad decrypt", so a restore on a newer Node showed the raw OpenSSL error instead of the explanation, and the dump-core test failed there. The decipher now runs inside a Transform whose flush calls final(); a throw there is the tag refusal and surfaces as OffhostTagRefusedError (code OFFHOST_TAG_REFUSED) with the original error as its cause. Other failures keep their reason and carry it as the cause as well. The test asserts on the class and code. The health-record route test loads the route graph once in a beforeAll, so the first test no longer spends its 5 s budget on a cold import on a loaded machine. --- CHANGELOG.md | 1 + .../health-record/__tests__/route.test.ts | 9 ++- .../__tests__/dump-core.test.ts | 6 +- src/lib/database-backup/dump-core.mjs | 59 +++++++++++++++++-- 4 files changed, 67 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e6a9ea4da..0ee8f2d095 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ - A damaged Gadgetbridge or Health Connect database is refused as a broken file, also when the damage sits behind a sound header and only shows once a table is read. The import used to fail with SQLite's own message as an internal error. - A FHIR Bundle, or a health record inside an Apple Health export, that nests deeper than 64 levels is refused as an unreadable file. A few hundred kilobytes nested deep enough made the import fail with an internal error instead. - An Apple Health export no longer stops as a whole at one cycle sample with a date that does not read. That sample is skipped and counted, and the rest of the export is imported. +- Restoring an off-host database copy that was renamed or altered says so on any Node and OpenSSL version. The restore recognised a failed integrity check by the wording of OpenSSL's error, which Node 22 gives as "unable to authenticate data" and Node 26 on OpenSSL 4 as "bad decrypt", so a restore run on a newer Node showed the raw OpenSSL error instead of the explanation. The check now goes by where the failure arose, not by its text. - A measurement CSV or a dose-history CSV with more than 100 000 rows, or a row wider than 1000 columns, is refused straight away. Blank lines are no longer held as rows while the file is read. Sixteen megabytes of line breaks used to hold several gigabytes of server memory for most of a minute, and a file of short junk lines answered with a status line for each of millions of rows. - The sleep page's night timeline is drawn only for a night whose stages were recorded in order. A Garmin night arrives as one total per stage, all stamped on the wake time, and the page drew those totals as a timeline of bars stacked against the morning. Whether a night holds an order is now decided once on the server, from the shape of its stages rather than from a list of services, so Garmin, Oura's stage totals and any later service that sends totals get the same note WHOOP and Polar already had, and the iPhone app reads the same answer. Such a night no longer counts awakenings it cannot know. When two services describe the same night, the copy with a recorded order wins: a Garmin night that also reaches HealthLog through Apple Health shows the Apple Health timeline, and so now does a WHOOP or Polar night, which used to win on the source order and hide the recorded one. Thanks to @kruemelro for the report and the side-by-side screenshots. (Refs [#1419](https://github.com/MBombeck/HealthLog/issues/1419)) - A PDF read by an AI provider that takes page images is now rendered sharp enough for small print. Pages were rendered at 72 dpi, so an A4 lab report reached the model 842 px tall and decimal commas or units like `mmol/l` could get lost. Pages now render at 200 dpi, held to 2000 px on the long edge so every provider reads them without downscaling them first; an A4 page arrives at about 171 dpi. Document reads, lab scans, supplement labels and previews all render through this one path. diff --git a/src/app/api/export/health-record/__tests__/route.test.ts b/src/app/api/export/health-record/__tests__/route.test.ts index db98bbcdd5..4b20773751 100644 --- a/src/app/api/export/health-record/__tests__/route.test.ts +++ b/src/app/api/export/health-record/__tests__/route.test.ts @@ -12,7 +12,7 @@ * reads what comes out, with a positive control beside each exclusion so * nothing can pass on an empty fixture. */ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { NextRequest } from "next/server"; import { unzipSync } from "fflate"; @@ -175,6 +175,13 @@ function pdfBytesText(bytes: Uint8Array): Promise { return readPdfText(bytes); } +// The route pulls in the PDF, FHIR and zip writers. Loading that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../route"); +}, 60_000); + beforeEach(() => { vi.clearAllMocks(); vi.mocked(resolveModuleMap).mockResolvedValue({} as never); diff --git a/src/lib/database-backup/__tests__/dump-core.test.ts b/src/lib/database-backup/__tests__/dump-core.test.ts index f0fae08eb9..40625b486f 100644 --- a/src/lib/database-backup/__tests__/dump-core.test.ts +++ b/src/lib/database-backup/__tests__/dump-core.test.ts @@ -804,7 +804,11 @@ describe("an off-host copy read back by the restore", () => { ), keys: [key], }), - ).rejects.toThrow(/does not open/); + ).rejects.toMatchObject({ + name: "OffhostTagRefusedError", + code: "OFFHOST_TAG_REFUSED", + message: expect.stringMatching(/does not open/), + }); expect(await readdir(dir)).toEqual([name]); // Altered. diff --git a/src/lib/database-backup/dump-core.mjs b/src/lib/database-backup/dump-core.mjs index 77068874bb..99b8df87a7 100644 --- a/src/lib/database-backup/dump-core.mjs +++ b/src/lib/database-backup/dump-core.mjs @@ -44,6 +44,7 @@ import { } from "node:fs"; import { readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import { basename, dirname, join, resolve } from "node:path"; +import { Transform } from "node:stream"; import { pipeline } from "node:stream/promises"; import { createGunzip } from "node:zlib"; @@ -1606,24 +1607,70 @@ export async function decryptOffhostFile(options) { const decipher = createDecipheriv("aes-256-gcm", key, header.iv); decipher.setAAD(Buffer.from(`${AAD_PREFIX}${options.objectKey}`, "utf8")); decipher.setAuthTag(tag); + // The tag is checked in `final()`. Its failure is told apart by where it + // was thrown, never by OpenSSL's wording, which differs between Node and + // OpenSSL versions ("unable to authenticate data", "bad decrypt", ...). + let tagRefused = false; + const opener = new Transform({ + transform(chunk, _encoding, callback) { + let out; + try { + out = decipher.update(chunk); + } catch (err) { + callback(err instanceof Error ? err : new Error(String(err))); + return; + } + callback(null, out); + }, + flush(callback) { + let last; + try { + last = decipher.final(); + } catch (cause) { + tagRefused = true; + callback( + cause instanceof Error ? cause : new Error(String(cause), { cause }), + ); + return; + } + callback(null, last); + }, + }); try { await pipeline( createReadStream(options.inPath, { start: header.length, end: size - TAG_LENGTH - 1, }), - decipher, + opener, createGunzip(), createWriteStream(options.outPath, { flags: "wx", mode: 0o600 }), ); } catch (err) { await rm(options.outPath, { force: true }); + if (tagRefused) { + throw new OffhostTagRefusedError( + "the off-host copy does not open with this key under this name (altered, renamed, or written with another key)", + { cause: err }, + ); + } const reason = err instanceof Error ? err.message : String(err); - throw new Error( - /auth|unable to authenticate/i.test(reason) - ? "the off-host copy does not open with this key under this name (altered, renamed, or written with another key)" - : `could not open the off-host copy: ${reason}`, - ); + throw new Error(`could not open the off-host copy: ${reason}`, { + cause: err, + }); + } +} + +/** An off-host copy whose GCM tag does not verify under the key and name given. */ +export class OffhostTagRefusedError extends Error { + /** + * @param {string} message + * @param {ErrorOptions} [options] + */ + constructor(message, options) { + super(message, options); + this.name = "OffhostTagRefusedError"; + this.code = "OFFHOST_TAG_REFUSED"; } } From 314087f4b0a6eb24c5a20f03c277292b9f21a8dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 01:27:59 +0100 Subject: [PATCH 6/9] fix(auth): bound the password strength estimator zxcvbn ran on the whole submitted password on the request thread, and its work grows with the square of the length times the l33t substitutions it tries. Registration with open sign-ups and the profile claim are anonymous, so a crafted password of a few hundred characters cost seconds of CPU per request and held up every other request. checkPasswordStrength now scores passwordEstimateInput(password): at most PASSWORD_STRENGTH_MAX_LENGTH (32) characters, cut before the seventh distinct l33t character. New passwords are capped at 1024 characters on registration, the profile claim and password change; sign-in and the current-password check stay uncapped, so an existing longer password still verifies. password-estimate-cost.test.ts pins the bound, measures the worst shapes under 50 ms a call, keeps the server's zxcvbn call in src/lib/auth/password.ts alone and pins the length cap. --- CHANGELOG.md | 2 + docs/api/openapi.yaml | 2 + .../api/auth/password/__tests__/route.test.ts | 10 +- .../__tests__/password-estimate-cost.test.ts | 160 ++++++++++++++++++ src/lib/auth/password.ts | 37 +++- src/lib/validations/auth.ts | 15 +- .../validations/managed-profile-handover.ts | 2 +- src/lib/zxcvbn-i18n.ts | 12 ++ 8 files changed, 234 insertions(+), 6 deletions(-) create mode 100644 src/lib/auth/__tests__/password-estimate-cost.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e6a9ea4da..518c569699 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,6 +75,7 @@ ### Security +- A long, crafted password can no longer stall the server. The strength check that runs when you register, claim a profile, change your password or an admin resets one read the whole password on the one request thread, and a few hundred characters of the right mix cost seconds of work each time; registration and the profile claim need no sign-in, so anyone could repeat it. The check now reads at most the first 32 characters and stops before an unusual mix of symbols, which keeps it to a few milliseconds. A new password may be at most 1024 characters long. A password of more than 32 characters is judged by its first 32. - A FIT import keeps its memory ceiling on a server whose heap was raised through `NODE_OPTIONS`, as the scaling guide describes. The process-wide heap limit replaced the decoder's own 192 MB ceiling, so a crafted file could take as much memory as the whole server was allowed before it was refused. The decoder now runs in a process of its own that sets its ceiling itself and starts without `NODE_OPTIONS`. - A Live Activity started over the push relay no longer tells the relay or Apple when it was started. Its id, which the relay writes into the Activity in the clear, began with a timestamp; it is now random and holds nothing else. - Names read from outside (codes, units and column names in an import, the parts of a backup, form fields, keys in a request or a stored setting) are no longer looked up in, or written into, an ordinary object. A name that every object already answers to made a FHIR Bundle, Apple Health or backup import, a profile update or a settings read fail with an internal error, and in a Health Connect import it changed a value shared by every object in the server process until the next restart. Such a name is now an ordinary entry or an unknown one, and a test fails on a new lookup of this kind in the code that reads outside input. @@ -89,6 +90,7 @@ ### Updating +- A new password longer than 1024 characters is refused when you register, claim a profile or change your password. A password you already have keeps working whatever its length: signing in and confirming your current password are not capped. - If you run HealthLog against your own PostgreSQL server, keep its major at or below the client major in the image (`docker run --rm --entrypoint pg_dump ghcr.io/mbombeck/healthlog:latest --version`). See `docs/ops/postgres-major-upgrade.md`. ## [1.49.0] — 2026-11-23 diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index 236953510a..63ab0226ac 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -32425,6 +32425,7 @@ components: password: type: string minLength: 12 + maxLength: 1024 timezone: type: string maxLength: 64 @@ -32447,6 +32448,7 @@ components: newPassword: type: string minLength: 12 + maxLength: 1024 confirmPassword: type: string minLength: 1 diff --git a/src/app/api/auth/password/__tests__/route.test.ts b/src/app/api/auth/password/__tests__/route.test.ts index cec1c277fe..46ad773f01 100644 --- a/src/app/api/auth/password/__tests__/route.test.ts +++ b/src/app/api/auth/password/__tests__/route.test.ts @@ -173,7 +173,15 @@ describe("POST /api/auth/password — 422 multi-issue (v1.4.43 W6)", () => { // The declared bounds of a size issue come from the schema. Object.keys(issue) .filter( - (k) => !["minimum", "maximum", "inclusive", "origin"].includes(k), + (k) => + ![ + "minimum", + "maximum", + "inclusive", + "origin", + "minimumInclusive", + "maximumInclusive", + ].includes(k), ) .sort(), ).toEqual(["code", "message", "path"]); diff --git a/src/lib/auth/__tests__/password-estimate-cost.test.ts b/src/lib/auth/__tests__/password-estimate-cost.test.ts new file mode 100644 index 0000000000..3a09c53a68 --- /dev/null +++ b/src/lib/auth/__tests__/password-estimate-cost.test.ts @@ -0,0 +1,160 @@ +/** + * The password strength check runs zxcvbn on the request thread, and + * registration (with sign-ups open) and the profile claim are anonymous. + * zxcvbn's work grows with the square of the length times the number of l33t + * substitutions it tries: unbounded, a long crafted password cost seconds per + * call and one address could hold the event loop. These tests pin the bound + * (`passwordEstimateInput`), measure the worst shapes found, freeze the + * server's zxcvbn call to the one file that applies the bound, and pin the + * length cap on new passwords without capping sign-in. + */ +import { describe, it, expect, vi } from "vitest"; + +vi.mock("@node-rs/argon2", () => ({ hash: vi.fn(), verify: vi.fn() })); + +import { + checkPasswordStrength, + passwordEstimateInput, +} from "@/lib/auth/password"; +import { + changePasswordSchema, + loginPasswordSchema, + newAccountPasswordSchema, +} from "@/lib/validations/auth"; +import { PASSWORD_STRENGTH_MAX_LENGTH } from "@/lib/zxcvbn-i18n"; +import { readSourceFolder } from "@/__tests__/helpers/source-files"; + +const LONG = 1024; +const fill = (unit: string) => + unit.repeat(Math.ceil(LONG / unit.length)).slice(0, LONG); + +/** + * The slowest shapes found by fuzzing the bounded estimator: l33t characters + * that each stand for two letters, interleaved with letters so that every + * substitution spells dictionary words, plus the repeat, sequence, date and + * symbol shapes zxcvbn treats specially. + */ +const WORST_SHAPES = [ + fill("a4b@c1d|e7f+"), + fill("a@@@a+|ea11+1a4+++4aaeaaeae117a4"), + fill("4@1|7+"), + fill("1|7+!4@8({[<3690$5%2"), + fill("|o"), + fill("ab"), + fill("a"), + fill("0123456789"), + fill("19901231"), + fill("p@55w0rd"), + fill("monkeydragon"), + fill("ä€😀"), + fill("!@#$%^&*()"), +]; + +/** The fastest of a few runs: the cost of the input, not of the scheduler. */ +function cheapestRunMs(fn: () => void): number { + let best = Infinity; + for (let i = 0; i < 3; i++) { + const start = performance.now(); + fn(); + best = Math.min(best, performance.now() - start); + } + return best; +} + +describe("passwordEstimateInput", () => { + it("leaves an ordinary password whole", () => { + for (const pw of [ + "Tr0ub4dor&3", + "correct horse battery staple", + "P@ssw0rd!2024", + ]) { + expect(passwordEstimateInput(pw)).toBe(pw); + } + }); + + it("reads at most PASSWORD_STRENGTH_MAX_LENGTH characters", () => { + const long = "abcdefghij".repeat(10); + expect(passwordEstimateInput(long)).toBe( + long.slice(0, PASSWORD_STRENGTH_MAX_LENGTH), + ); + }); + + it("cuts before the seventh distinct l33t character", () => { + expect(passwordEstimateInput("x4@1|7+yy8zz")).toBe("x4@1|7+yy"); + // Repeating the six already seen does not count again. + expect(passwordEstimateInput("4@1|7+4@1|7+")).toBe("4@1|7+4@1|7+"); + }); +}); + +describe("estimator cost on hostile input", () => { + it("scores the worst shapes within 50 ms a call", () => { + // Warm the dictionaries and the JIT so the first shape is not charged + // for loading. + checkPasswordStrength("warm up the estimator"); + const slow: string[] = []; + for (const shape of WORST_SHAPES) { + const worst = cheapestRunMs(() => + checkPasswordStrength(shape, ["someusername", "someone@example.com"]), + ); + if (worst >= 50) + slow.push( + `${JSON.stringify(shape.slice(0, 12))}…: ${worst.toFixed(1)} ms`, + ); + } + expect(slow).toEqual([]); + }); +}); + +describe("zxcvbn has one server caller", () => { + // The strength meter component loads zxcvbn with a dynamic import and + // scores in the browser, on the person's own CPU; the matcher below does + // not see that form, and it is not a server path. + it("is imported and called only in src/lib/auth/password.ts", () => { + const files = readSourceFolder("src", { + floor: 3000, + include: (rel) => + !rel.startsWith("generated/") && + !rel.includes("__tests__") && + !/\.test\.tsx?$/.test(rel), + }); + const call = /from\s+["']zxcvbn|require\(\s*["']zxcvbn|\bzxcvbn\s*\(/; + const callers = files + .filter(([, text]) => call.test(text)) + .map(([rel]) => rel); + // A non-empty match set: the matcher still finds the one real caller. + expect(callers).toEqual(["lib/auth/password.ts"]); + }); +}); + +describe("new password length cap", () => { + const ok = "Xq7#vLp2!mRt".padEnd(1024, "z"); + const tooLong = ok + "z"; + + it("accepts 1024 characters and refuses 1025 on every new-password schema", () => { + expect(newAccountPasswordSchema.safeParse(ok).success).toBe(true); + expect(newAccountPasswordSchema.safeParse(tooLong).success).toBe(false); + const change = (pw: string) => + changePasswordSchema.safeParse({ + currentPassword: "current", + newPassword: pw, + confirmPassword: pw, + }).success; + expect(change(ok)).toBe(true); + expect(change(tooLong)).toBe(false); + }); + + it("leaves sign-in and the current password uncapped", () => { + const existing = "y".repeat(4096); + expect( + loginPasswordSchema.safeParse({ email: "someone", password: existing }) + .success, + ).toBe(true); + expect( + changePasswordSchema.safeParse({ + currentPassword: existing, + newPassword: ok, + confirmPassword: ok, + }).success, + ).toBe(true); + }); +}); diff --git a/src/lib/auth/password.ts b/src/lib/auth/password.ts index eb3f4ae8e2..84b9bf33b1 100644 --- a/src/lib/auth/password.ts +++ b/src/lib/auth/password.ts @@ -1,6 +1,9 @@ import { hash, verify } from "@node-rs/argon2"; import zxcvbn from "zxcvbn-typescript"; -import { getZxcvbnTranslations } from "@/lib/zxcvbn-i18n"; +import { + getZxcvbnTranslations, + PASSWORD_STRENGTH_MAX_LENGTH, +} from "@/lib/zxcvbn-i18n"; import { getServerTranslator } from "@/lib/i18n/server-translator"; import { defaultLocale, type Locale } from "@/lib/i18n/config"; // The Argon2id params live in a plain `.mjs` module so the operator @@ -112,6 +115,35 @@ export interface PasswordStrength { const MIN_PASSWORD_LENGTH = 12; +/** + * The characters zxcvbn's l33t matcher reads as substituted letters. It tries + * every combination of the substitutions present, so its work multiplies with + * each distinct one: twenty of them make 800 combinations, each a full + * dictionary pass over the password. + */ +const L33T_CHARACTERS = new Set("4@8({[<369!|170$5+%2"); +const MAX_DISTINCT_L33T_CHARACTERS = 6; + +/** + * The part of a password the estimator scores: at most + * `PASSWORD_STRENGTH_MAX_LENGTH` characters, cut before the seventh distinct + * l33t character. Both bounds keep one call in the low milliseconds on any + * input (`password-estimate-cost.test.ts` measures the worst shapes found). + * A password that reaches either bound with a strong prefix is strong; one + * that is cut early reads weaker than it is, which errs on the safe side. + */ +export function passwordEstimateInput(password: string): string { + const seen = new Set(); + const limit = Math.min(password.length, PASSWORD_STRENGTH_MAX_LENGTH); + for (let i = 0; i < limit; i++) { + const ch = password[i]; + if (!L33T_CHARACTERS.has(ch) || seen.has(ch)) continue; + if (seen.size === MAX_DISTINCT_L33T_CHARACTERS) return password.slice(0, i); + seen.add(ch); + } + return password.slice(0, limit); +} + export function checkPasswordStrength( password: string, userInputs: string[] = [], @@ -130,7 +162,8 @@ export function checkPasswordStrength( }; } - const result = zxcvbn(password, userInputs); + // The one call into zxcvbn; every estimate goes through the bound above. + const result = zxcvbn(passwordEstimateInput(password), userInputs); const feedback: string[] = []; if (result.feedback.warning) { diff --git a/src/lib/validations/auth.ts b/src/lib/validations/auth.ts index cd480768e5..f59bf6f47c 100644 --- a/src/lib/validations/auth.ts +++ b/src/lib/validations/auth.ts @@ -6,6 +6,15 @@ import { clientTransportSchema } from "@/lib/validations/client-transport"; /** Minimum password length — must match checkPasswordStrength() in @/lib/auth/password.ts */ const PASSWORD_MIN_LENGTH = 12; +/** + * The longest new password a form accepts. Far past anything a person or a + * password manager produces; the strength estimator reads only the first + * `PASSWORD_STRENGTH_MAX_LENGTH` characters of it either way. Sign-in and the + * current-password check carry no such cap, so a longer password set before + * the cap still verifies. + */ +const PASSWORD_MAX_LENGTH = 1024; + /** * v1.42 (#959) — the prefix a managed profile's generated username carries * (`managed-`, `src/lib/managed-profiles/create.ts`). An account a person @@ -43,7 +52,8 @@ export const newAccountPasswordSchema = z .min( PASSWORD_MIN_LENGTH, `Password must be at least ${PASSWORD_MIN_LENGTH} characters`, - ); + ) + .max(PASSWORD_MAX_LENGTH); export const registerSchema = z.object({ email: z.email("Invalid email address"), @@ -151,7 +161,8 @@ export const changePasswordSchema = z .min( PASSWORD_MIN_LENGTH, `New password must be at least ${PASSWORD_MIN_LENGTH} characters`, - ), + ) + .max(PASSWORD_MAX_LENGTH), confirmPassword: z.string().min(1, "Password confirmation is required"), }) .refine((data) => data.newPassword === data.confirmPassword, { diff --git a/src/lib/validations/managed-profile-handover.ts b/src/lib/validations/managed-profile-handover.ts index f60b0d28c3..46e47830ba 100644 --- a/src/lib/validations/managed-profile-handover.ts +++ b/src/lib/validations/managed-profile-handover.ts @@ -72,7 +72,7 @@ export const claimSchema = z token: claimTokenSchema, username: accountUsernameSchema, email: z.email("Invalid email address").max(254), - password: newAccountPasswordSchema.max(1024), + password: newAccountPasswordSchema, }) .strict(); diff --git a/src/lib/zxcvbn-i18n.ts b/src/lib/zxcvbn-i18n.ts index c0a87aa9dd..b8e26d9868 100644 --- a/src/lib/zxcvbn-i18n.ts +++ b/src/lib/zxcvbn-i18n.ts @@ -7,6 +7,18 @@ */ import type { Locale } from "@/lib/i18n/config"; +/** + * How much of a password the server-side strength estimator reads, on every + * path that scores one (`src/lib/auth/password.ts`). + * + * zxcvbn's matching grows with the square of the length times the number of + * l33t substitutions it tries, and it runs on the request thread: 256 + * characters cost seconds of CPU per call. A password whose first 32 + * characters are hard to guess is strong whatever follows; a long one whose + * first 32 are easy reads weaker than it is, which errs on the safe side. + */ +export const PASSWORD_STRENGTH_MAX_LENGTH = 32; + const warningsDe: Record = { "Straight rows of keys are easy to guess": "Gerade Tastenreihen sind leicht zu erraten", From ab5c5ea89ff4a5965f64a180eda6cae26cfedd6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 01:40:01 +0100 Subject: [PATCH 7/9] test(sleep): seed the per-night summary's nights before the run's day A night starting yesterday at 22:00 UTC is still running until about 05:30 UTC, so a run in the first hours of a UTC day read only the part already behind it and the summary came out short. --- tests/integration/sleep-stats-per-night.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/integration/sleep-stats-per-night.test.ts b/tests/integration/sleep-stats-per-night.test.ts index 573df6f9d8..e7d7b1763a 100644 --- a/tests/integration/sleep-stats-per-night.test.ts +++ b/tests/integration/sleep-stats-per-night.test.ts @@ -102,7 +102,11 @@ async function seed() { }> = []; for (let n = 1; n <= NIGHTS; n++) { // Bedtime 22:00 UTC the evening before day `today - n + 1`. - let cursor = today.getTime() - n * DAY_MS + 22 * 60 * MIN_MS; + // Each night starts at 22:00 UTC two or more days back and ends near + // 05:30 UTC the next morning: a night starting yesterday evening would + // still be running for the first hours of a UTC day, and a run then saw + // only its finished half. + let cursor = today.getTime() - (n + 1) * DAY_MS + 22 * 60 * MIN_MS; const bedStart = cursor; for (const seg of NIGHT) { cursor += seg.minutes * MIN_MS; From f0daa4251cfa1b81125a31eb53e14841f86e5bf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 02:26:01 +0100 Subject: [PATCH 8/9] test(sleep): seed the per-night summary's nights a day back The latest seeded night started at 22:00 UTC the evening before the run's day and ended about 05:30 UTC on it. A run between midnight and then saw that night only in part, and the summary read 140 to 175 minutes instead of 420. Anchoring the seed a day earlier keeps every segment before the run's clock. --- tests/integration/sleep-stats-per-night.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/integration/sleep-stats-per-night.test.ts b/tests/integration/sleep-stats-per-night.test.ts index 573df6f9d8..adcacfb188 100644 --- a/tests/integration/sleep-stats-per-night.test.ts +++ b/tests/integration/sleep-stats-per-night.test.ts @@ -88,7 +88,11 @@ async function seed() { }); cookieJar.set("healthlog_session", session.id); - const today = new Date(); + // Anchored a day back: the latest night then ends yesterday morning, so + // no segment lies after the run's clock, whatever hour the suite runs at. + // Anchored on today, the latest night ran until about 05:30 UTC and a run + // between midnight and then saw it only in part. + const today = new Date(Date.now() - DAY_MS); today.setUTCHours(0, 0, 0, 0); const rows: Array<{ userId: string; From 23f579b70ee4297ab86f414ff368593bf990403b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 27 Nov 2026 03:32:13 +0100 Subject: [PATCH 9/9] test: keep cold chart imports and PDF rendering off the 5 s test budget The chart tests imported Recharts and the chart kit inside their first test, and the PDF tests render real pages through pdf.js and Skia. On a loaded machine either took past the default 5 s and failed a test that had nothing wrong with it. The chart files now load their graph once in a beforeAll on a 60 s hook budget, and the two render files carry a budget sized for rendering. --- .../charts/__tests__/health-chart-comparison.test.tsx | 9 ++++++++- .../charts/__tests__/health-chart-data-table.test.tsx | 9 ++++++++- .../charts/__tests__/health-chart-heading-level.test.tsx | 9 ++++++++- .../charts/__tests__/health-chart-type-label.test.tsx | 9 ++++++++- ...medication-compliance-chart-empty-state-gate.test.tsx | 9 ++++++++- .../__tests__/mood-chart-empty-state-gate.test.tsx | 9 ++++++++- .../documents/__tests__/rasterize-pdf-font-data.test.ts | 5 +++++ src/lib/documents/__tests__/rasterize-pdf.test.ts | 5 +++++ 8 files changed, 58 insertions(+), 6 deletions(-) diff --git a/src/components/charts/__tests__/health-chart-comparison.test.tsx b/src/components/charts/__tests__/health-chart-comparison.test.tsx index 6b2d61ccad..936abb5303 100644 --- a/src/components/charts/__tests__/health-chart-comparison.test.tsx +++ b/src/components/charts/__tests__/health-chart-comparison.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi } from "vitest"; +import { describe, it, beforeAll, expect, vi } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; /** @@ -62,6 +62,13 @@ vi.mock("@/hooks/use-auth", () => ({ }), })); +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../health-chart"); +}, 60_000); + describe("", () => { it("renders no comparison caption when baseline is 'none' (regression guard)", async () => { const { I18nProvider } = await import("@/lib/i18n/context"); diff --git a/src/components/charts/__tests__/health-chart-data-table.test.tsx b/src/components/charts/__tests__/health-chart-data-table.test.tsx index 1b98d2849b..3b25cf91a5 100644 --- a/src/components/charts/__tests__/health-chart-data-table.test.tsx +++ b/src/components/charts/__tests__/health-chart-data-table.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import enMessages from "../../../../messages/en.json"; @@ -65,6 +65,13 @@ function rowCount(html: string): number { return (html.match(/data-slot="chart-data-table-row"/g) ?? []).length; } +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../health-chart"); +}, 60_000); + describe(" — data table", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/components/charts/__tests__/health-chart-heading-level.test.tsx b/src/components/charts/__tests__/health-chart-heading-level.test.tsx index 5343a6b0a3..3b68f4cc36 100644 --- a/src/components/charts/__tests__/health-chart-heading-level.test.tsx +++ b/src/components/charts/__tests__/health-chart-heading-level.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import deMessages from "../../../../messages/de.json"; @@ -41,6 +41,13 @@ vi.mock("@/hooks/use-auth", () => ({ }), })); +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../health-chart"); +}, 60_000); + describe(" — card heading level", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/components/charts/__tests__/health-chart-type-label.test.tsx b/src/components/charts/__tests__/health-chart-type-label.test.tsx index aaefdf00dd..75b472457e 100644 --- a/src/components/charts/__tests__/health-chart-type-label.test.tsx +++ b/src/components/charts/__tests__/health-chart-type-label.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import de from "../../../../messages/de.json"; @@ -55,6 +55,13 @@ vi.mock("@/hooks/use-chart-overlay-prefs", () => ({ }), })); +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../health-chart"); +}, 60_000); + describe(" — series names", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx b/src/components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx index d2ab37256b..b12c7f2da6 100644 --- a/src/components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx +++ b/src/components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; // vi.doMock below invalidates the module registry, so the re-imported // provider gets a fresh (unprimed) locale cache — pass the DE bundle @@ -24,6 +24,13 @@ vi.mock("@/hooks/use-auth", () => ({ }), })); +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../medication-compliance-chart"); +}, 60_000); + describe(" — empty-state gate by raw count", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/components/charts/__tests__/mood-chart-empty-state-gate.test.tsx b/src/components/charts/__tests__/mood-chart-empty-state-gate.test.tsx index 48a3c552a5..b8519cc21c 100644 --- a/src/components/charts/__tests__/mood-chart-empty-state-gate.test.tsx +++ b/src/components/charts/__tests__/mood-chart-empty-state-gate.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; // vi.doMock below invalidates the module registry, so the re-imported // provider gets a fresh (unprimed) locale cache — pass the DE bundle @@ -32,6 +32,13 @@ function dayKeyAgo(agoDays: number): string { return new Date(Date.now() - agoDays * 86_400_000).toISOString().slice(0, 10); } +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../mood-chart"); +}, 60_000); + describe(" — empty-state gate by raw count", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/lib/documents/__tests__/rasterize-pdf-font-data.test.ts b/src/lib/documents/__tests__/rasterize-pdf-font-data.test.ts index d8a92fd1dd..cddeccf3c9 100644 --- a/src/lib/documents/__tests__/rasterize-pdf-font-data.test.ts +++ b/src/lib/documents/__tests__/rasterize-pdf-font-data.test.ts @@ -110,6 +110,11 @@ const renderHere = (data: Buffer) => minInkRatio: raster.RASTER_MIN_INK_RATIO, }); +// Every test here renders real pages through pdf.js and Skia: CPU work that +// takes well under a second alone and several on a loaded machine. The +// budget is sized for that work rather than for a unit test. +vi.setConfig({ testTimeout: 30_000 }); + describe("rasterizePdf font and decoder data (#1124)", () => { it("gives pdfjs its font, CMap and wasm directories and no system fonts", async () => { const result = await renderHere(fixture("fallback-fonts.pdf")); diff --git a/src/lib/documents/__tests__/rasterize-pdf.test.ts b/src/lib/documents/__tests__/rasterize-pdf.test.ts index 87ad875ae4..00866559e0 100644 --- a/src/lib/documents/__tests__/rasterize-pdf.test.ts +++ b/src/lib/documents/__tests__/rasterize-pdf.test.ts @@ -116,6 +116,11 @@ function sizedPdf(mediaBox: string): Buffer { ); } +// Every test here renders real pages through pdf.js and Skia: CPU work that +// takes well under a second alone and several on a loaded machine. The +// budget is sized for that work rather than for a unit test. +vi.setConfig({ testTimeout: 30_000 }); + describe("page resolution", () => { // The provider bound the edge cap answers to: OpenAI fits every image into // 2048 x 2048 before it reads it.