feature: Trend Detection & Alert Suppression Windows

This commit is contained in:
voltsrage
2026-06-18 21:18:13 +08:00
parent e6f7989298
commit 3c54feb38a
31 changed files with 2751 additions and 18 deletions
@@ -0,0 +1,194 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
[Collection("Integration")]
public class AlertSuppressionTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private Guid _patientId;
private Guid _encounterId;
public AlertSuppressionTests(ApiFixture fixture) => _fixture = fixture;
public async Task InitializeAsync() => await ResetAndSeedThresholdAsync();
public Task DisposeAsync() => Task.CompletedTask;
private async Task ResetAndSeedThresholdAsync()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DbResetHelper.ResetAsync(db);
var patient = new Patient
{
Id = Guid.NewGuid(), Mrn = "MRN-SUP-001", FirstName = "Suppress", LastName = "Test",
DateOfBirth = new DateOnly(1982, 8, 10), Gender = "M", CreatedAt = DateTimeOffset.UtcNow
};
var encounter = new Encounter
{
Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient,
Status = EncounterStatus.Active, Department = Department.Icu,
AttendingPhysician = "Dr. Suppress", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(encounter);
db.AlertThresholds.Add(new AlertThreshold
{
Id = Guid.NewGuid(), ObservationCode = "HEART_RATE",
DisplayName = "Heart Rate", Unit = "bpm",
CriticalLow = 30, WarningLow = 50, WarningHigh = 100, CriticalHigh = 150,
CreatedAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await redis.GetDatabase().StringSetAsync("threshold:HEART_RATE",
"""{"ObservationCode":"HEART_RATE","CriticalLow":30,"WarningLow":50,"WarningHigh":100,"CriticalHigh":150}""");
_patientId = patient.Id;
_encounterId = encounter.Id;
}
[Fact]
public async Task AcknowledgeWarning_SetsSuppressionKey()
{
await ResetAndSeedThresholdAsync();
var alertId = await SeedAlertAsync(AlertType.WarningHeartRate, AlertSeverity.Warning);
using var scope = _fixture.Services.CreateScope();
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("nurse-1", "monitoring"));
var key = AlertSuppressionService.SuppressionKey(_encounterId, AlertType.WarningHeartRate);
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeTrue();
}
[Fact]
public async Task SuppressedWarning_SkipsAlertCreation()
{
await ResetAndSeedThresholdAsync();
var alertId = await SeedAlertAsync(AlertType.WarningHeartRate, AlertSeverity.Warning);
using var scope = _fixture.Services.CreateScope();
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("nurse-1", "monitoring"));
await alerts.ResolveAsync(alertId);
var created = await evaluator.EvaluateAsync(
Guid.NewGuid(), _encounterId, _patientId, "HEART_RATE", 105m);
created.Should().BeFalse();
(await db.ClinicalAlerts.CountAsync()).Should().Be(1,
"suppressed warning must not create a new alert after resolve");
}
[Fact]
public async Task CriticalAlert_NotSuppressible()
{
await ResetAndSeedThresholdAsync();
var alertId = await SeedAlertAsync(AlertType.CriticalHeartRate, AlertSeverity.Critical);
using var scope = _fixture.Services.CreateScope();
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("dr-1", "treating"));
var key = AlertSuppressionService.SuppressionKey(_encounterId, AlertType.CriticalHeartRate);
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeFalse();
}
[Fact]
public async Task News2Emergency_NotSuppressible()
{
await ResetAndSeedThresholdAsync();
var alertId = await SeedAlertAsync(AlertType.News2Emergency, AlertSeverity.Critical);
using var scope = _fixture.Services.CreateScope();
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("dr-1", "reviewed"));
var key = AlertSuppressionService.SuppressionKey(_encounterId, AlertType.News2Emergency);
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeFalse();
}
[Fact]
public async Task News2Warning_Suppressible()
{
await ResetAndSeedThresholdAsync();
var alertId = await SeedAlertAsync(AlertType.News2Warning, AlertSeverity.Warning);
using var scope = _fixture.Services.CreateScope();
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("nurse-1", "monitoring"));
var key = AlertSuppressionService.SuppressionKey(_encounterId, AlertType.News2Warning);
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeTrue();
}
[Fact]
public async Task SuppressionExpires_AllowsNewAlert()
{
await ResetAndSeedThresholdAsync();
using var scope = _fixture.Services.CreateScope();
var suppression = scope.ServiceProvider.GetRequiredService<IAlertSuppressionService>();
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await suppression.SetSuppressionAsync(
_encounterId, AlertType.WarningHeartRate, TimeSpan.FromSeconds(1));
var blocked = await evaluator.EvaluateAsync(
Guid.NewGuid(), _encounterId, _patientId, "HEART_RATE", 105m);
blocked.Should().BeFalse();
await Task.Delay(1500);
var created = await evaluator.EvaluateAsync(
Guid.NewGuid(), _encounterId, _patientId, "HEART_RATE", 105m);
created.Should().BeTrue();
var alert = await db.ClinicalAlerts.SingleAsync();
alert.AlertType.Should().Be(AlertType.WarningHeartRate);
}
private async Task<Guid> SeedAlertAsync(AlertType alertType, AlertSeverity severity)
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = new ClinicalAlert
{
Id = Guid.NewGuid(),
EncounterId = _encounterId,
PatientId = _patientId,
AlertType = alertType,
Severity = severity,
Details = $"Test {alertType.ToDbString()} alert.",
Status = AlertStatus.Open,
TriggeredAt = DateTimeOffset.UtcNow
};
db.ClinicalAlerts.Add(alert);
await db.SaveChangesAsync();
return alert.Id;
}
}
@@ -32,12 +32,17 @@ public class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
public async Task InitializeAsync()
{
// Apply migrations against the test database on first run
// Apply migrations before the host starts — background services such as
// ThresholdCacheLoader query the database during StartAsync.
var connectionString = "Host=localhost;Port=5436;Database=vigilcare_test;Username=postgres;Password=password";
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseNpgsql(connectionString)
.Options;
await using (var migrateDb = new AppDbContext(options))
await migrateDb.Database.MigrateAsync();
using var scope = Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
// Flush the test Redis database (db=1) to avoid cross-test cache pollution
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var server = redis.GetServer(redis.GetEndPoints().First());
await server.FlushDatabaseAsync(1);
@@ -0,0 +1,58 @@
using FluentAssertions;
public class TrendCalculatorTests
{
private static readonly DateTimeOffset BaseTime =
new(2026, 6, 18, 12, 0, 0, TimeSpan.Zero);
[Fact]
public void ComputeRatePerMinute_TwoEntries_ReturnsCorrectRate()
{
var entries = new List<TrendHistoryEntry>
{
new(72m, BaseTime),
new(95m, BaseTime.AddMinutes(10))
};
var rate = TrendCalculator.ComputeRatePerMinute(entries, windowMinutes: 30);
rate.Should().Be(2.3m);
}
[Fact]
public void ComputeRatePerMinute_SingleEntry_ReturnsNull()
{
var entries = new List<TrendHistoryEntry> { new(72m, BaseTime) };
TrendCalculator.ComputeRatePerMinute(entries, windowMinutes: 30)
.Should().BeNull();
}
[Fact]
public void ExceedsThreshold_HeartRateRise_ReturnsTrue()
{
TrendCalculator.ExceedsThreshold("HEART_RATE", 0.6m, 0.5m).Should().BeTrue();
}
[Fact]
public void ExceedsThreshold_Spo2Decline_ReturnsTrue()
{
TrendCalculator.ExceedsThreshold("SPO2", -0.3m, 0.2m).Should().BeTrue();
}
[Fact]
public void ExceedsThreshold_StableRate_ReturnsFalse()
{
TrendCalculator.ExceedsThreshold("HEART_RATE", 0.3m, 0.5m).Should().BeFalse();
}
[Fact]
public void DescribeTrend_FormatsCorrectly()
{
TrendCalculator.DescribeTrend("HEART_RATE", 0.77m, 95m)
.Should().Be("Rapid rise: HEART_RATE rising at 0.77/min (current 95)");
TrendCalculator.DescribeTrend("SPO2", -0.25m, 92m)
.Should().Be("Rapid decline: SPO2 falling at 0.25/min (current 92)");
}
}
@@ -0,0 +1,147 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
[Collection("Integration")]
public class TrendDetectorTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private Guid _encounterId;
private Guid _patientId;
private static readonly DateTimeOffset BaseTime =
new(2026, 6, 18, 10, 0, 0, TimeSpan.Zero);
public TrendDetectorTests(ApiFixture fixture) => _fixture = fixture;
public async Task InitializeAsync()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DbResetHelper.ResetAsync(db);
var patient = new Patient
{
Id = Guid.NewGuid(), Mrn = "MRN-TREND-001", FirstName = "Trend", LastName = "Test",
DateOfBirth = new DateOnly(1970, 3, 1), Gender = "F",
CreatedAt = DateTimeOffset.UtcNow
};
var encounter = new Encounter
{
Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient,
Status = EncounterStatus.Active, Department = Department.Icu,
AttendingPhysician = "Dr. Trend", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(encounter);
await db.SaveChangesAsync();
_patientId = patient.Id;
_encounterId = encounter.Id;
await ClearTrendHistoryAsync(scope.ServiceProvider);
}
public Task DisposeAsync() => Task.CompletedTask;
[Fact]
public async Task RapidHeartRateClimb_CreatesAlert()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>();
await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 72m, BaseTime);
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 95m, BaseTime.AddMinutes(10));
result.Outcome.Should().Be(TrendOutcome.RapidDeterioration);
result.AlertCreated.Should().BeTrue();
result.RatePerMinute.Should().Be(2.3m);
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = await db.ClinicalAlerts.SingleAsync();
alert.AlertType.Should().Be(AlertType.RapidDeterioration);
alert.Severity.Should().Be(AlertSeverity.Warning);
alert.Details.Should().Contain("HEART_RATE");
}
[Fact]
public async Task StableHighHeartRate_NoTrendAlert()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>();
await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 95m, BaseTime);
await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 95m, BaseTime.AddMinutes(10));
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 95m, BaseTime.AddMinutes(20));
result.Outcome.Should().Be(TrendOutcome.Stable);
result.AlertCreated.Should().BeFalse();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
(await db.ClinicalAlerts.CountAsync()).Should().Be(0);
}
[Fact]
public async Task InsufficientHistory_NoAlert()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>();
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 72m, BaseTime);
result.Outcome.Should().Be(TrendOutcome.InsufficientHistory);
result.AlertCreated.Should().BeFalse();
}
[Fact]
public async Task NonTrendCode_Ignored()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "POTASSIUM_MEQ_L", 4.0m, BaseTime);
result.Outcome.Should().Be(TrendOutcome.NotTrendCode);
var key = TrendCalculator.HistoryKey(_encounterId, "POTASSIUM_MEQ_L");
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeFalse();
}
[Fact]
public async Task DuplicateTrendAlert_Idempotent()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 72m, BaseTime);
await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 95m, BaseTime.AddMinutes(10));
var second = await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 98m, BaseTime.AddMinutes(20));
second.Outcome.Should().Be(TrendOutcome.AlertAlreadyOpen);
second.AlertCreated.Should().BeFalse();
(await db.ClinicalAlerts.CountAsync()).Should().Be(1,
"second rapid climb must not duplicate while first RAPID_DETERIORATION is open");
}
private async Task ClearTrendHistoryAsync(IServiceProvider services)
{
var redis = services.GetRequiredService<IConnectionMultiplexer>();
var cache = redis.GetDatabase();
foreach (var key in TrendCalculator.AllHistoryKeys(_encounterId))
await cache.KeyDeleteAsync(key);
}
}