Skip to content

feat(sleep-stages): store modelset-v1 manifests with stage models and flag nights staged on other vitals - #930

Merged
ng merged 1 commit into
devfrom
feat/stage-model-set
Nov 16, 2026
Merged

ng merged 1 commit into
devfrom
feat/stage-model-set

Conversation

@ng

@ng ng commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Training now writes a modelset-v1 manifest next to each exported model, recording the version of every input the model was trained on. This PR handles the stage-model part of it in core.

  • POST /api/sleep-stages/models (and the tRPC uploadModel and MCP add_stage_model) accept an optional modelSet next to model. The pod validates it with zod and stores it with the library entry in a new stage_model_library.model_set column (migration 0036). Models uploaded without a set work as before.
    • nodes.stage is required and pinned. Its sha256 must equal the model's canonical hash, its version must equal the model's, and its optional contract must name the model's feature contract.
    • nodes.vitals is optional and expected: engine is the biometrics manifest hash and profile is the resolved config hash.
    • nodes.movementModel is refused with "Movement models are not supported on this pod yet". sleepypod-core-133 replaces that refusal with a check that the pinned movement model is installed.
    • training and evaluation are stored as given. The whole manifest is capped at 64 KB.
  • GET /api/sleep-stages/models?side= returns each entry's modelSet, or null.
  • The stage hash uses core's finite-binary64-json-v1 encoding through dataHash. That is the same encoding as configHash, with a budget large enough for a 1-2 MB forest; configHash stops at 20,000 values. The encoding is documented in docs/research/sleep-stage-calibration/README.md → "Model sets" so training can reproduce it in Python. A golden hash in src/lib/tests/stage-model-set.test.ts was computed with modules/common/biometrics/config.py's canonical_json.

Q6 decision (owner): stage normally, flag the mismatch

When the active model's set has nodes.vitals, getSleepStages compares it with the vitals that actually produced the night. The night is still staged by the model, never by the rules. A difference only adds a flag:

"stagedBy": { "engine": "model", "version": "…",
  "inputMismatch": { "expected": { "engine": "…", "profile": "…" },
                     "actual": { "engine": "…", "profile": "…" } | "mixed" | "unknown" } }

actual comes from each vitals row's own processing run (vitals.processing_run_id → biometric_processing_runs: bundle.manifestHash and config_hash, live runs on the same side). The repo's vitals-summary provenance already defines configuration identity this way (vital-summary-provenance.ts).

  • More than one engine/profile pair in the night gives "mixed": a profile change or update mid-night, or a night only partly recorded.
  • No recorded run at all gives "unknown".
  • A daemon restart under the same configuration starts a new run but is not a change.

The receipts table records which generation was applied and when, but not the running engine, and it has no row for the default profile, so it cannot answer the engine half on its own.

A night that matches, a set without a vitals node, a model without a set, and a night staged by the rules get no flag. GET /api/sleep-stages/model gains inputMismatch: the selected model's set compared with the side's latest live run. Settings → Sleep stages shows it as a note on the staging model card that does not block anything.

Test plan

  • vitest for src/lib/tests/stage-model-set.test.ts: golden hash matching Python, a 1000-tree forest past the configHash budget, schema bindings, refusal of a wrong sha, version or contract and of a movement node, and the mismatch rules
  • vitest for src/server/routers/tests/sleepStages.test.ts against migrated in-memory DBs:
    • a valid set is stored and listed
    • a sha mismatch is refused and nothing is stored
    • a movement node is refused
    • a mismatched night is staged by the model and flagged
    • a matched night has no flag
    • a mixed night is flagged, and a restart under the same config is not
    • an unrecorded night is unknown
    • no vitals node, no set, or rules staging gives no flag
  • PersonalModelCard test for the note; MCP test that modelSet passes through to the upload
  • pnpm tsc, pnpm lint, drizzle-kit check (both configs) and vitest related (3260 tests) pass in the pre-push hook
  • Full local vitest run: the only failures are in the Python/shell-environment suites (shadow build, python-installation, backtest coordinator/waveform, updateDeploy, telemetryBlocking, diagnosticCli). The same suites fail identically on origin/dev.
  • Manual: upload candidate.json with a set.json from a training run via jq -n --slurpfile m candidate.json --slurpfile s set.json '{side:"left", model:$m[0], modelSet:$s[0]}' | curl -X POST -H 'content-type: application/json' -d @- http://<pod>:3000/api/sleep-stages/models, then check GET /api/sleep-stages/models?side=left and a night's stagedBy

Migration note: this adds 0036. If another PR adds a 0036 first, regenerate this one with pnpm db:generate after rebasing; do not hand-edit the journal.

🤖 Generated with Claude Code

🛏️ Beam this PR onto a sleepypod ✨

Pick the snippet that matches your pod. Already-installed pods can't use the curl bootstraps below — sleepypod's egress firewall DROPs github.com, and the script that knows how to unblock WAN is the very file curl is trying to fetch. Use sp-update instead; it's on disk and opens WAN as its first step.

🔄 Already on a sleepypod (most common — review a PR on a running pod):

sudo sp-update feat/stage-model-set

🚀 Fresh pod / first install — bootstraps from GitHub, rebuilds every push:

curl -fsSL https://raw.githubusercontent.com/sleepypod/core/feat/stage-model-set/scripts/install \
  | sudo bash -s -- --branch feat/stage-model-set

🎯 Pin to this exact build (run 43776866469 · 1fd2a78) — fresh-pod path, locked to one CI artifact for reproducible review:

curl -fsSL https://raw.githubusercontent.com/sleepypod/core/1fd2a7840a0f7c68a15898a45977320699126a4c/scripts/install \
  | sudo bash -s -- \
      --branch feat/stage-model-set \
      --artifact-url 'https://nightly.link/sleepypod/core/actions/runs/43776866469/sleepypod-core.zip'

🧊 Artifact: sleepypod-core · self-destructs in 30 days 💥

… flag nights staged on other vitals

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 15, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 27 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cb32f327-ed54-444f-b60f-8cbb565e4eba
Commits

Reviewing files that changed from the base of the PR and between 402859d and 1fd2a78.

Files ignored due to path filters: 1

  • src/db/tests/__snapshots__/schema.test.ts.snap is excluded by !**/*.snap
Files selected for processing: 19

  • docs/research/sleep-stage-calibration/README.md
  • src/biometrics/profiles/vital-summary-provenance.ts
  • src/biometrics/profiles/vitals-identity.ts
  • src/components/Settings/PersonalModelCard.tsx
  • src/components/Settings/tests/PersonalModelCard.test.tsx
  • src/db/migrations/0036_stage_model_library_model_set.sql
  • src/db/migrations/meta/0036_snapshot.json
  • src/db/migrations/meta/_journal.json
  • src/db/schema.ts
  • src/demo/handlers/sleepStages.ts
  • src/demo/tests/sleepStages.test.ts
  • src/lib/stage-model-set.ts
  • src/lib/tests/stage-model-set.test.ts
  • src/mcp/README.md
  • src/mcp/tests/server.test.ts
  • src/mcp/tools/stageModels.ts
  • src/server/routers/biometrics.ts
  • src/server/routers/sleepStages.ts
  • src/server/routers/tests/sleepStages.test.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.02985% with 4 lines in your changes missing coverage. Please review.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/components/Settings/PersonalModelCard.tsx 50.00% 0 Missing and 2 partials ⚠️
src/biometrics/profiles/vitals-identity.ts 88.88% 0 Missing and 1 partial ⚠️
src/lib/stage-model-set.ts 95.65% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@ng
ng added this pull request to the merge queue Nov 16, 2026
Merged via the queue into dev with commit 118ba42 Nov 16, 2026
8 of 9 checks passed
@ng
ng deleted the feat/stage-model-set branch November 16, 2026 01:49
ng added a commit that referenced this pull request Nov 23, 2026
…it stage models (#948)

Promotes `dev` to `main`.

## Changes
- **Pod 5 presence fixes (#944, #947):**
  - A Pod 5 hub with a J57 cover on NATS firmware no longer shows the cover as disconnected while its frames are streaming.
  - Presence scores Pod 3-dialect capSense against its own calibration.
  - The sleep-detector drops capSense frames that NATS firmware republishes one second later. Before, these made an empty side read as moving.
  - Pod 5's whole-second frame timestamps no longer stop a side from ever learning what an empty bed looks like, so the #768 empty-bed vitals veto now runs on Pod 5.
- **Alarms (#869, #923):** a single sleeper's alarm vibrates both sides, and each side's next alarm is published to Home Assistant over MQTT.
- **Biometrics charts (#919, #921, #926):**
  - Movement is charted in 15-minute buckets of larger movements.
  - Breathing is drawn as a 15-minute rolling floor.
  - Adds 3D flow, movement and schedule charts and per-side piezo lanes.
- **Local fit and stage models (#928, #929, #930, #927):**
  - Archived nights replay through local-fit with one pinned profile.
  - Fits rank by breathing error with REM/light separation.
  - Stage models are stored with modelset-v1 manifests (migration 0036 adds a nullable `stage_model_library.model_set` column).
  - Saved profiles rebase onto a new engine instead of falling back to defaults.
- **Scripts and tooling (#943, #925, #946, #924, #922):**
  - The other boot slot is neutralized so a U-Boot fallback stays reachable and offline.
  - Archive pulls gain a `--curl` transport.
  - Slash-named branches no longer create Vercel demo previews.
  - Fixes saved-profile title layout.

## Test plan
- [x] CI, Build & Package and Dev Release green on `dev` tip `3094a8c9`
- [x] `dev` @ `3094a8c` running on pod .88 (Pod 5 J55): all four services active with 0 restarts, occupancy API 200, both sides read empty with 0 zones lit, right-side capacitance `absence_ready` flipped 0 → 1
- [x] Required checks green on this PR
- [ ] After merge, wait for "Analyze & Release" on the `main` merge commit, then `sp-update main` on pod .88 and confirm `.git-info` matches the release
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant