Molecular oxygen, O2, was recently detected in comet 67P by the ROSINA instrument on board the Rosetta spacecraft with a surprisingly high abundance of 4% relative to H2O, making O2 the fourth most abundant in comet 67P. Other volatile species with similar volatility, such as molecular nitrogen N2, were also detected by Rosetta, but with much lower abundances and much weaker correlations with water. Here, we investigate the chemical and physical origin of O2 and other volatile species using the new constraints provided by Rosetta. We follow the chemical evolution during star formation with state-of-the-art astrochemical models applied to dynamical physical models by considering three origins: i) in dark clouds, ii) during forming protostellar disks, and iii) during luminosity outbursts in disks. The models presented here favour a dark cloud (or “primordial”) grain surface chemistry origin for volatile species in comets, albeit for dark clouds which are slightly warmer and denser than those usually considered as solar system progenitors.