Repository navigation
[16.0][FIX] ni_observation: pick the latest observation deterministically - #163
Merged
Merged
Conversation
The latest-observation views keep one row per patient (or encounter) and type with DISTINCT ON, ordered by occurrence only. When two observations of a type share an occurrence (created in the same transaction, for example by two questionnaires mapped to the same type), PostgreSQL may return either row. The patient and encounter forms then read a row that the next query no longer returns, and fail with "records ... cannot be found". Break the tie by id. Found by the Phase 1 data migration pilot (nirun-life#141); 16.0 has the same views.
This was referenced Oct 14, 2026
piruin
approved these changes
Oct 15, 2026
4 tasks done
6 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
ni.patient.observationandni.encounter.observation(latest observation per patient/encounter and type):ORDER BY … occurrence DESC, id DESC.tests/test_latest_observation.py.ni_observation16.0.0.6.0 → 16.0.0.6.1, so-urecreates the views.Why
The views use
DISTINCT ON (…, type_id)ordered byoccurrenceonly. When two observations of a type share an occurrence (for example two questionnaires mapped to the same type, completed in one transaction), PostgreSQL may return either row. The patient and encounter forms then read a row that the next query no longer returns, and fail with "records … cannot be found".Found by the Phase 1 data migration pilot (#141, findings comment). The same fix is in the 17.0/18.0/19.0 migration PRs (#156, #157, #158); this is the 16.0 backport for production. Part of P0-4 (#135), epic #131.
How tested
--test-tags /ni_observationon a fresh 16.0 DB: 27 tests, 0 failed.test_same_occurrence_picks_the_last_recordfails.pre-commitclean.Notes for reviewer
-u ni_observation.