mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-08 20:42:43 +00:00
Resolve the canonical daily row deterministically: prefer the row already carrying the target stats: externalId before falling back to the row on the canonical local-noon instant, with a stable orderBy tiebreaker. Adopting a sibling and stamping the target externalId onto it could otherwise collide on the (userId, type, source, externalId) index with the real canonical row. Re-anchor the adopted row to local-noon only when that slot is free, so an externalId row at a tz/DST-shifted instant cannot collide on the measured_at composite during adopt. Guard the create against a concurrent insert on the same canonical composite: catch P2002 outside the transaction (a caught error inside leaves the tx in the aborted state) and retry the fold once, which then resolves and adopts the winning row instead of creating a duplicate. Add a real-Postgres case covering a row already on the canonical instant under the target stats: externalId plus a fresh out-of-window batch: the fold adopts in place, no P2002, one canonical row with the correctly folded mean.