Skip to content

hrv: refuse RMSSD when the RR stream banks more beat-time than elapsed - #88

Merged
abdulsaheel merged 2 commits into
OpenStrap:mainfrom
DropTabl:fix/rr-overcount-gate-solo
Oct 9, 2026
Merged

abdulsaheel merged 2 commits into
OpenStrap:mainfrom
DropTabl:fix/rr-overcount-gate-solo

Conversation

@DropTabl

@DropTabl DropTabl commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Why: nothing checks that the stored beats can physically fit in the time they span. A double-ingested or two-device-interleaved RR stream reads Σ RR ÷ wall span ≈ 2.0 and passes every existing gate. Duplicated beats add zero differences and deflate RMSSD by ~1/√2, and interleaved streams inflate it. Neither looks like jitter to the ACF1 screen or the spectral checks.

What changed:

  • rrCoverage(rrMs, rrTsMs) → RrCoverage (coverage, sum, span, implausible and duplicate counts).
    • Plausible intervals are 300–2400 ms; the rest are counted, never summed.
    • The span runs from the earliest to the latest beat, so input order doesn't matter.
    • The first interval stretches the span only if it is itself plausible.
    • Null under 10 min of span.
    • Ceiling 1.10: contiguous runs measure 0.963 (gen4), 0.999 (W5) and 1.001 (MG), so it has margin. Gaps only push coverage below 1 and are never refused.
  • The sleep-session headline:
    • checks its own beats and is absent above the ceiling, with the note rr_overcount:coverage=…;
    • also drops any 5-min window that banks more than 1.10 × its length (overcounted_windows), because a strap-off gap elsewhere can dilute the night-wide ratio.
  • New sleepSessionRmssdDetail → SessionRmssd (rmssd, windows, diff_acf1, rr_coverage, overcounted_windows). sleepSessionWindowedRmssd stays as a thin wrapper.
  • hrvTime, nocturnalRmssd and nightHrvShape take an optional coverage and refuse when it is over-counted. In hrvTime an over-counted stream also skips the breathing-line fallback. SDNN keeps publishing. Callers that pass no coverage are unchanged.

User-visible before → after: a night whose RR was stored twice used to show an RMSSD about 30 % low as if it were real. Now it shows HRV "—" with the reason.

Tests:

  • rrCoverage: 1.0, 2.0, the null cases, implausible intervals, the implausible first interval, order independence, a gappy night.
  • The headline refuses an over-counted session; a duplicated stretch is caught per window even when a gap dilutes the night.
  • The over-count guard blocks hrvTime's breathing-line fallback; the test uses the slow-drift fixture and fails without the guard.
  • nightHrvShape is absent on an over-counted stream; an honest coverage changes nothing.

Output changes: an over-counted night loses its RMSSD headline; new rr_coverage / overcounted_windows keys.
Requires kAlgoVersion bump (batched).

🤖 Generated with Claude Code

Summary by Sourcery

Reject RMSSD results derived from RR streams that contain more beat-time than elapsed time and surface the integrity diagnostics to callers.

New Features:

  • Add RR stream coverage diagnostics to detect duplicated or interleaved beat data and expose session HRV details.
  • Report coverage and over-counted-window diagnostics in sleep-session RMSSD output.

Bug Fixes:

  • Refuse RMSSD-family metrics for physically inconsistent RR streams instead of publishing misleading values.
  • Prevent over-counted data from being rescued by the breathing-line fallback and exclude affected sleep-session windows.

Enhancements:

  • Propagate optional RR coverage checks through hrvTime, nocturnalRmssd, and nightHrvShape while preserving SDNN output and existing behavior when coverage is omitted.
  • Keep the existing sleep-session RMSSD API as a wrapper around the detailed result and document the new integrity check.

Documentation:

  • Document RR coverage validation and its effect on HRV metrics in the algorithm reference.

Tests:

  • Add coverage, ordering, gap, implausible-interval, session-level, per-window, fallback, and HRV-shape regression tests.

Summary by CodeRabbit

  • Bug Fixes

    • HRV results now detect over-counted beat data and withhold affected RMSSD and pNN50 metrics. SDNN and SDANN remain available.
    • Sleep-session RMSSD excludes over-counted sessions and invalid windows, with results noting how many windows were skipped.
    • Nighttime HRV shape and nocturnal RMSSD are marked unavailable when beat data is over-counted.
  • New Features

    • Sleep-session RMSSD results now include the number of contributing and skipped windows, autocorrelation, and session coverage.

…lapsed

Nothing checked that the stored beats can physically fit in the time they
span. A double-ingested or two-device-interleaved RR stream reads Σ RR /
wall span ≈ 2.0 and passes every existing gate: duplicated beats add zero
differences and deflate RMSSD by ~1/√2, interleaved streams inflate it,
and neither looks like jitter to the ACF1 screen or the spectral checks.

rrCoverage(rrMs, rrTsMs) measures Σ plausible RR ([300, 2400] ms; the rest
are counted, so one 65 535 ms glitch cannot fake an over-count) over the
wall span (last − first + the first beat's own interval, when that
interval is itself plausible: an implausible one is never summed, so it
must not stretch the denominator either), null under 10 minutes where
whole-second stamps make the span meaningless. Contiguous runs measure
0.963 (gen4), 0.999 (W5) and 1.001 (MG), so the ceiling of 1.10 has
margin; gaps only push coverage below 1 and are never refused.
duplicate_beats is reported as a diagnostic only (equal beats in one
whole-second record repeat legitimately).

The sleep-session headline computes it over the session's own beats and
is absent above the ceiling (note rr_overcount:coverage=…), before any
window or breathing-line logic runs. It now also has a detail form,
sleepSessionRmssdDetail → SessionRmssd (rmssd, windows, diff_acf1,
rr_coverage), with sleepSessionWindowedRmssd as a thin wrapper, so
callers can store what the headline rests on. A night-wide ratio can be
diluted below the ceiling by a strap-off gap elsewhere while one stretch
holds every beat twice, so the headline also judges each 5-min window on
its own: a window whose beats bank more than 1.10 × its length is
dropped (counted in overcounted_windows) rather than averaged in. hrvTime and nocturnalRmssd
take an optional coverage and refuse RMSSD/pNN50 (SDNN survives) or the
whole metric; in hrvTime an over-counted stream also skips the
breathing-line fallback, since a line in a stream that is not one
heart's beats proves nothing. nightHrvShape takes the same coverage
and is absent on an over-counted stream, since each of its bins is an
RMSSD of it. The span uses the earliest and latest beat, so the result
does not depend on the order beats arrive in. Callers that pass no coverage are
unchanged.

Output changes: an over-counted night loses its RMSSD headline; new
rr_coverage key on the headline detail.
Requires kAlgoVersion bump (batched).
@sourcery-ai

sourcery-ai Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR adds a coverage-based integrity gate that compares plausible RR beat-time with elapsed span, then threads it through sleep-session, nocturnal, time-domain, and nightly-shape RMSSD paths to prevent duplicated or interleaved streams from producing misleading HRV while preserving SDNN and backward compatibility when no over-count is detected.

Sequence diagram for sleep-session RMSSD over-count protection

sequenceDiagram
    participant Caller
    participant Session as sleepSessionRmssdDetail
    participant Coverage as rrCoverage
    participant Windows as 5-minute windows

    Caller->>Session: sleepSessionRmssdDetail(rrMs, rrTsMs)
    Session->>Coverage: rrCoverage(session beats)
    Coverage-->>Session: RrCoverage
    alt coverage > 1.10
        Session-->>Caller: absent(rr_overcount:coverage=...)
    else coverage acceptable
        loop each 5-minute window
            Session->>Session: sum plausible RR beat-time
            alt banked beat-time > 1.10 × window length
                Session->>Windows: drop window
            else window acceptable
                Session->>Windows: compute RMSSD
            end
        end
        Session-->>Caller: SessionRmssd(rmssd, windows, rrCoverage, overcountedWindows)
    end
Loading

Flow diagram for RR coverage integrity gating

flowchart TD
    A[Raw RR intervals and beat timestamps] --> B[rrCoverage]
    B --> C{coverage > 1.10?}
    C -->|No| D[RMSSD metrics continue]
    C -->|Yes| E[Refuse RMSSD with rr_overcount note]
    E --> F[SDNN continues publishing]
    D --> G[Backward-compatible behavior]
Loading

File-Level Changes

Change Details Files
Add a raw RR stream coverage integrity metric to detect duplicated or interleaved beats.
  • Compute plausible RR sum versus order-independent wall-clock span with a 1.10 refusal ceiling.
  • Ignore implausible intervals for coverage while exposing diagnostic counts and duplicate counts.
  • Return null for invalid, mismatched, or sub-10-minute inputs and serialize coverage diagnostics.
lib/src/onehz/clinical/hrv_time.dart
ALGORITHMS.md
Propagate over-count refusals through HRV estimators while preserving non-RMSSD metrics.
  • Add optional coverage inputs to hrvTime, nocturnalRmssd, and nightHrvShape.
  • Suppress RMSSD-family outputs and hrvTime breathing fallback for over-counted streams.
  • Keep SDNN available and emit a consistent rr_overcount diagnostic note.
lib/src/onehz/clinical/hrv_time.dart
lib/src/onehz/sleep/night_hrv_shape.dart
Refactor sleep-session RMSSD calculation to expose diagnostics and reject duplicated windows.
  • Introduce SessionRmssd detail output while retaining the existing API as a wrapper.
  • Refuse sessions over the coverage ceiling and drop individual 5-minute windows exceeding the per-window beat-time limit.
  • Expose rr_coverage and overcounted_windows in serialized results.
lib/src/onehz/clinical/hrv_time.dart
Add comprehensive coverage and refusal-path regression tests.
  • Cover normal, duplicated, invalid, implausible, gappy, and order-independent streams.
  • Verify session-wide and per-window refusal behavior, including gap dilution.
  • Verify breathing fallback blocking, night-shape refusal, diagnostics, and unchanged behavior without or below the coverage ceiling.
test/onehz/clinical_test.dart

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 2b27141f-fb4c-4de7-a96d-0b00d18acf0c
📥 Commits

Reviewing files that changed from the base of the PR and between 27b0ba4 and f130a28.

📒 Files selected for processing (4)
  • ALGORITHMS.md
  • lib/src/onehz/clinical/hrv_time.dart
  • lib/src/onehz/sleep/night_hrv_shape.dart
  • test/onehz/clinical_test.dart

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The change adds RR-stream coverage diagnostics and applies over-count checks to HRV and sleep-session RMSSD calculations. It adds detailed sleep-session results with contributing and skipped window counts, updates the algorithms table, and adds tests for coverage, duplicated beats, gaps, and consumer behavior.

Changes

RR Coverage and RMSSD

Layer / File(s) Summary
RR coverage diagnostic
lib/src/onehz/clinical/hrv_time.dart, test/onehz/clinical_test.dart
Adds RrCoverage and coverage calculation for plausible RR intervals. Coverage is unavailable for invalid or short inputs. Tests cover ordinary, duplicated, shuffled, and invalid inputs.
HRV coverage gates
lib/src/onehz/clinical/hrv_time.dart, lib/src/onehz/sleep/night_hrv_shape.dart, test/onehz/clinical_test.dart
When supplied coverage is over-counted, hrvTime, nocturnalRmssd, and nightHrvShape return absent RMSSD-related results. hrvTime retains SDNN and SDANN. Tests compare over-counted and honest coverage.
Sleep-session RMSSD detail
lib/src/onehz/clinical/hrv_time.dart, test/onehz/clinical_test.dart, ALGORITHMS.md
Adds SessionRmssd results and per-window over-count checks. Over-counted windows are skipped, and the session result includes contributing and skipped window counts. Tests cover duplicated beats and windows. The algorithms table documents the diagnostic and detail function.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: abdulsaheel

Merge Risk: ⚪ Minimal · up to f130a

The window rule behaves as documented; no identified issue needs to be fixed before merging.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: blocking RMSSD when the RR stream contains more plausible beat-time than elapsed time.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 0…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Autopilot · 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

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="lib/src/onehz/clinical/hrv_time.dart" line_range="1052" />
<code_context>
+    for (final v in buckets[idx]!) {
+      if (_rrCoverageCounts(v)) bankedMs += v;
+    }
+    if (bankedMs > kRrCoverageCeiling * windowSec * 1000) {
+      overCountedWindows++;
+      continue;
</code_context>
<issue_to_address>
**Partial-window duplicates enter headline**

When the session ends partway through a 5-minute bucket and a gap elsewhere keeps session-wide coverage below the ceiling, `sleepSessionRmssdDetail` compares `bankedMs` with 1.10 times the full `windowSec`, so duplicated beat-time in the shorter bucket passes the local gate and its corrupted RMSSD remains in the headline.

Compare `bankedMs` with 1.10 times the bucket’s actual elapsed span, accounting for beat overhang.

Also at `lib/src/onehz/clinical/hrv_time.dart:1053`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the coverage calculation or 1.10 threshold is wrong, valid RR streams could have RMSSD or sleep-session windows refused, producing incorrect persisted or downstream readiness metrics. Reverting restores the prior behavior, and affected metrics are bounded and can be recomputed.

Blocking findings: lib/src/onehz/clinical/hrv_time.dart:1052


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread lib/src/onehz/clinical/hrv_time.dart Outdated
The per-window over-count check compared a window's banked beat-time with
110 % of the full window length. The session's last window can be cut
short by its end, so a duplicated tail there (e.g. 2 min of beats stored
twice, ~240 s banked) stayed under 330 s and its corrupted RMSSD entered
the headline whenever a gap elsewhere kept the night-wide ratio below the
ceiling. Each window is now judged against its own span, clipped to the
session end, plus its earliest beat's interval (that beat began before
its end stamp), the same overhang rrCoverage allows.
@abdulsaheel
abdulsaheel merged commit 11e2b70 into OpenStrap:main Oct 9, 2026
4 checks passed
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.

2 participants