From ac6b42f32e5886b6bbfbea96fd830a44480e1079 Mon Sep 17 00:00:00 2001 From: Steffen Date: Mon, 5 Oct 2026 12:01:35 +0200 Subject: [PATCH] Implement US-06 latest observation recording-time ties --- .../Persistence/SqlObservationRepository.cs | 3 +- src/README.md | 4 +- .../LatestObservationTests.cs | 97 ++++++++++++++++++- 3 files changed, 100 insertions(+), 4 deletions(-) diff --git a/src/ObservationService/Persistence/SqlObservationRepository.cs b/src/ObservationService/Persistence/SqlObservationRepository.cs index 625c2dc..849d86b 100644 --- a/src/ObservationService/Persistence/SqlObservationRepository.cs +++ b/src/ObservationService/Persistence/SqlObservationRepository.cs @@ -38,7 +38,8 @@ public sealed class SqlObservationRepository(ObservationDbContext db) : Observat public Task FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken) => db.Observations.AsNoTracking().Where(o => o.PatientId == patientId) - .OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.ObservationId) + .OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.CreatedAt) + .ThenByDescending(o => o.ObservationId) .FirstOrDefaultAsync(cancellationToken); public Task> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to, diff --git a/src/README.md b/src/README.md index 1d144ed..75d75ed 100644 --- a/src/README.md +++ b/src/README.md @@ -118,9 +118,9 @@ with US-04; no further production code or migration is needed for US-05. The Observation Service checks patient existence by calling the gateway's patient retrieval API over HTTP before saving. It has no reference to Patient/Profile implementation code and no access to that service's database. Missing patients return `404`; validation failures return `400`. Patient lookup failures return `502` or `504` and do not save an observation. Measurement timestamps without an offset represent UTC clock values and are stored as supplied, independently of the host time zone; timestamps with an offset are normalized to UTC. PostgreSQL uses the diagram's `timestamp` columns without a time-zone component. -`GET /api/patients/{patientId}/observations/latest` returns `200` with that patient's observation having the greatest measurement timestamp, regardless of recording order. It returns `404` when no observation is available. Equal measurement timestamps are resolved consistently by observation identifier; US-06 does not prescribe which tied observation to return. Selection happens in the Observation Service's own database through the documented controller/application-service/repository layers. +`GET /api/patients/{patientId}/observations/latest` returns `200` with that patient's observation having the greatest measurement timestamp, regardless of recording order. It returns `404` when no observation is available. Equal measurement timestamps are resolved by greatest original recording timestamp (`created_at`), then greatest observation UUID under PostgreSQL UUID ordering if recording times also tie. Edits preserve original recording time and do not affect tie selection. Context completeness does not affect selection; the returned observation includes its own saved context. Selection happens in the Observation Service's own database through the documented controller/application-service/repository layers. -US-06 acceptance tests cover out-of-order measurements, patient-specific selection, retrieval after restart, and no available observation even when another patient has recorded measurements. No new dependencies or schema changes are required. +US-06 acceptance tests cover out-of-order measurements, patient-specific selection, context independent of suitability/completeness, recording-time ties, later edits, reproducible complete ties across restart, and no available observation even when another patient has recorded measurements. No new dependencies or schema changes are required. `GET /api/patients/{patientId}/observations?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with a JSON array of that patient's observations within the inclusive measurement-time bounds, ordered chronologically. A valid period with no matches returns `[]`. Both timestamps are required; missing, malformed, or reversed bounds return `400` validation problem details. Equal bounds are valid. Offset timestamps are normalized to UTC consistently with recording; encode `+` as `%2B` in query parameters. Equal measurement timestamps are ordered by observation identifier. The query runs in the Observation Service's own database; no patient-profile lookup is needed. diff --git a/tests/Observation.AcceptanceTests/LatestObservationTests.cs b/tests/Observation.AcceptanceTests/LatestObservationTests.cs index 1123b97..a171d18 100644 --- a/tests/Observation.AcceptanceTests/LatestObservationTests.cs +++ b/tests/Observation.AcceptanceTests/LatestObservationTests.cs @@ -1,4 +1,6 @@ using System.Net; +using Microsoft.EntityFrameworkCore; +using ObservationService.Domain; using System.Net.Http.Json; using Xunit; @@ -7,8 +9,9 @@ namespace Observation.AcceptanceTests; public sealed class LatestObservationTests(ObservationApiFixture fixture) : IClassFixture { private sealed record Profile(Guid PatientId); + private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes, string? BodyPosition); private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt, - int Systolic, int Diastolic, int Pulse, string? Context, string? Note); + int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext); private async Task CreatePatientAsync() { @@ -59,4 +62,96 @@ public sealed class LatestObservationTests(ObservationApiFixture fixture) : ICla Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.DoesNotContain("observationId", await response.Content.ReadAsStringAsync()); } + private async Task<(Guid OlderId, Guid NewerId)> SeedPair(Guid patientId, DateTime olderMeasured, + DateTime newerMeasured, DateTime olderRecorded, DateTime newerRecorded, + MeasurementContext olderContext, MeasurementContext newerContext) + { + // Make the older observation's identifier greater, so it cannot mask the recording-time rule. + var prefix = Guid.NewGuid().ToString("N")[..24]; + var olderId = Guid.ParseExact(prefix + "ffffffff", "N"); + var newerId = Guid.ParseExact(prefix + "00000001", "N"); + await using var db = fixture.CreateObservationDbContext(); + db.Observations.AddRange( + new BloodPressureObservation + { + ObservationId = newerId, PatientId = patientId, MeasuredAt = newerMeasured, + Systolic = 126, Diastolic = 80, Pulse = 66, MeasurementContext = newerContext, + CreatedAt = newerRecorded, UpdatedAt = newerRecorded + }, + new BloodPressureObservation + { + ObservationId = olderId, PatientId = patientId, MeasuredAt = olderMeasured, + Systolic = 130, Diastolic = 84, Pulse = 70, MeasurementContext = olderContext, + CreatedAt = olderRecorded, UpdatedAt = olderRecorded + }); + await db.SaveChangesAsync(); + return (olderId, newerId); + } + + private Task Latest(Guid patientId) => + fixture.Client.GetFromJsonAsync($"/api/patients/{patientId}/observations/latest"); + + [Fact] + public async Task Newer_after_activity_observation_is_returned_with_its_own_context() + { + var patient = await CreatePatientAsync(); + var time = new DateTime(2026, 9, 12, 8, 0, 0); + var pair = await SeedPair(patient, time.AddDays(-1), time, time.AddHours(2), time.AddHours(1), + new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5 }, + new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity", BodyPosition = "Standing" }); + var latest = (await Latest(patient))!; + Assert.Equal(pair.NewerId, latest.ObservationId); + Assert.Equal(new ContextData("Clinic", "AfterActivity", null, "Standing"), latest.MeasurementContext); + } + + [Fact] + public async Task Missing_context_does_not_replace_latest_with_an_older_complete_observation() + { + var patient = await CreatePatientAsync(); + var time = new DateTime(2026, 9, 12, 8, 0, 0); + var pair = await SeedPair(patient, time.AddDays(-1), time, time, time.AddHours(1), + new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5, + BodyPosition = "Seated", MeasuredArm = "Left", DeviceDetails = "Recorded device", CuffDetails = "Recorded cuff" }, + new MeasurementContext()); + var latest = (await Latest(patient))!; + Assert.Equal(pair.NewerId, latest.ObservationId); + Assert.Equal(new ContextData("Unknown", "Unknown", null, null), latest.MeasurementContext); + } + + [Fact] + public async Task Measurement_timestamp_ties_use_original_recording_time_and_ignore_later_edits() + { + var patient = await CreatePatientAsync(); + var time = new DateTime(2026, 9, 12, 8, 0, 0); + var pair = await SeedPair(patient, time, time, time.AddHours(1), time.AddHours(2), + new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest" }, + new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity" }); + Assert.Equal(pair.NewerId, (await Latest(patient))!.ObservationId); + using var correction = await fixture.Client.PutAsJsonAsync($"/api/observations/{pair.OlderId}", + new { systolic = 125, diastolic = 80, pulse = 65 }); + Assert.Equal(HttpStatusCode.OK, correction.StatusCode); + await using var db = fixture.CreateObservationDbContext(); + var corrected = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == pair.OlderId); + Assert.Equal(time.AddHours(1), corrected.CreatedAt); + Assert.True(corrected.UpdatedAt > time.AddHours(2)); + await fixture.RestartHostsAsync(); + var latest = (await Latest(patient))!; + Assert.Equal(pair.NewerId, latest.ObservationId); + Assert.Equal("Clinic", latest.MeasurementContext.Setting); + Assert.Equal("AfterActivity", latest.MeasurementContext.ActivityCondition); + } + + [Fact] + public async Task Complete_timestamp_ties_choose_greatest_identifier_reproducibly_across_restart() + { + var patient = await CreatePatientAsync(); + var time = new DateTime(2026, 9, 12, 8, 0, 0); + var pair = await SeedPair(patient, time, time, time.AddHours(1), time.AddHours(1), + new MeasurementContext { Setting = "Home" }, new MeasurementContext { Setting = "Clinic" }); + for (var i = 0; i < 3; i++) + Assert.Equal(pair.OlderId, (await Latest(patient))!.ObservationId); + await fixture.RestartHostsAsync(); + Assert.Equal(pair.OlderId, (await Latest(patient))!.ObservationId); + } + }