How does the Health app reconcile overlapping sleep samples written to HealthKit?

I'm trying to understand the exact rules the Health app uses to reconcile (deduplicate/merge/discard) overlapping sleep samples, and I'm hoping an Apple engineer can clarify the behavior. Background: My Apple Watch wrote sleep samples to HealthKit twice within the same day, and the two writes overlap substantially: Same stage, overlapping in time — e.g., two "Core" sleep samples that overlap each other in time. Different stages, overlapping in time — e.g., Deep and Core overlap, and Core and REM (Rapid Eye Movement) also overlap. Observation: Even though the raw samples contain these overlaps, the Health app ultimately displays non-overlapping data (i.e., it has reconciled the overlaps somehow). I'm confused about the exact reconciliation rules the Health app applies to such overlapping data. To make the problem clearer, I've visualized the raw HealthKit samples. In the attached chart, you can see the same stage was written multiple times at different timestamps, shown in chronological order. However, the data ultimately displayed by the Health app differs significantly from the raw data — samples appear to have been reconciled, dropped, and merged in various ways. Question: What are the detailed rules the Health app uses to reconcile overlapping sleep samples? Specifically:

When samples of the same stage overlap in time, how is the overlap resolved? When samples of different stages overlap in time, which stage takes precedence, and how are the boundaries adjusted? Are samples merged, truncated, or discarded entirely? Under what conditions? Any clarification from the HealthKit team would be greatly appreciated.

Appendix 1 — Raw data visualization. All sleep samples as shown in the Health app (source: the complete sleep dataset in the Health app).

Appendix 2 — Final presentation. How the Health app presents the data after reconciling the raw samples.

Note — Comparing Appendix 2 with Appendix 1, the following differences are clearly visible:

1.A portion of Deep sleep was discarded. 2.Four awake segments were discarded. 3.Multiple REM segments were also discarded. 4.Core sleep was partially merged.

How does the Health app reconcile overlapping sleep samples written to HealthKit?
 
 
Q