feature: Sepsis Engine Refactor: Remove SIRS, Rewire qSOFA + Bundle

Frontend: GCS Entry, SOFA Display, Sepsis UI Refactor
This commit is contained in:
voltsrage
2026-06-21 03:56:27 +08:00
parent 93ea473d2b
commit bf46e6554a
48 changed files with 2686 additions and 714 deletions
@@ -0,0 +1,19 @@
using FluentAssertions;
public class AlertCreationGuardTests
{
[Fact]
public void CannotCreateNewSepsisWarning()
{
var act = () => AlertCreationGuard.EnsureAllowed(AlertType.SepsisWarning);
act.Should().Throw<InvalidOperationException>()
.WithMessage("*deprecated*");
}
[Fact]
public void AllowsSofaSepsis()
{
var act = () => AlertCreationGuard.EnsureAllowed(AlertType.SofaSepsis);
act.Should().NotThrow();
}
}
@@ -15,7 +15,7 @@ public class ObservabilityPhase8Tests
"alerts_unacknowledged_gauge",
"kafka_consumer_lag",
"outbox_pending_events",
"sirs_detections_total",
"qsofa_detections_total",
"escalations_total",
};
@@ -80,12 +80,12 @@ public class QsofaDetectorTests : IAsyncLifetime
r2.Outcome.Should().Be(QsofaOutcome.AlertCreated);
var alert = await db.ClinicalAlerts.SingleAsync();
alert.AlertType.Should().Be(AlertType.QsofaWarning);
alert.Severity.Should().Be(AlertSeverity.Critical);
alert.AlertType.Should().Be(AlertType.QsofaScreen);
alert.Severity.Should().Be(AlertSeverity.Warning);
alert.Status.Should().Be(AlertStatus.Open);
alert.EncounterId.Should().Be(_encounterId);
alert.PatientId.Should().Be(_patientId);
alert.Details.Should().Contain("qSOFA score 2/3");
alert.Details.Should().Contain("order SOFA labs");
var outbox = await db.OutboxEvents.SingleAsync(e => e.Topic == "alert.generated");
outbox.PartitionKey.Should().Be(_encounterId.ToString());
@@ -138,7 +138,7 @@ public class QsofaDetectorTests : IAsyncLifetime
r3.Outcome.Should().Be(QsofaOutcome.AlertAlreadyOpen);
var alertCount = await db.ClinicalAlerts.CountAsync();
alertCount.Should().Be(1, "WHERE NOT EXISTS prevents duplicate QSOFA_WARNING while one is open");
alertCount.Should().Be(1, "WHERE NOT EXISTS prevents duplicate QSOFA_SCREEN while one is open");
var outboxCount = await db.OutboxEvents.CountAsync(e => e.Topic == "alert.generated");
outboxCount.Should().Be(1, "outbox event must be written exactly once");
+54 -38
View File
@@ -43,28 +43,47 @@ public class SepsisBundleTests : IAsyncLifetime
var cache = redis.GetDatabase();
foreach (var key in QsofaCalculator.AllCriterionKeys(_encounterId))
await cache.KeyDeleteAsync(key);
foreach (var key in SirsEvaluator.AllCriterionKeys(_encounterId))
await cache.KeyDeleteAsync(key);
}
public Task DisposeAsync() => Task.CompletedTask;
[Fact]
public async Task QsofaAlert_CreatesBundleWithFourOrders()
private async Task CreateSofaSepsisBundleAsync(IServiceScope scope)
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var handler = scope.ServiceProvider.GetRequiredService<SepsisAlertHandler>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
var alertId = Guid.NewGuid();
db.ClinicalAlerts.Add(new ClinicalAlert
{
Id = alertId,
EncounterId = _encounterId,
PatientId = _patientId,
AlertType = AlertType.SofaSepsis,
Severity = AlertSeverity.Critical,
Details = "SOFA delta +2",
Status = AlertStatus.Open,
TriggeredAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync();
await handler.OnSepsisAlertCreatedAsync(
_encounterId, alertId, AlertType.SofaSepsis, CancellationToken.None);
}
[Fact]
public async Task SofaSepsisAlert_CreatesBundleWithFourOrders()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await CreateSofaSepsisBundleAsync(scope);
var bundle = await db.SepsisBundles
.Include(b => b.Elements)
.SingleAsync(b => b.EncounterId == _encounterId);
bundle.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.InProgress);
bundle.TriggeringAlertType.Should().Be("QSOFA_WARNING");
bundle.TriggeringAlertType.Should().Be("SOFA_SEPSIS");
bundle.DeadlineAt.Should().BeCloseTo(bundle.RecognizedAt.AddHours(1), TimeSpan.FromSeconds(5));
bundle.Elements.Should().HaveCount(4);
@@ -86,40 +105,45 @@ public class SepsisBundleTests : IAsyncLifetime
}
[Fact]
public async Task SirsAlert_CreatesBundle()
public async Task QsofaScreen_DoesNotTriggerBundle()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 95m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 38.5m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
var bundle = await db.SepsisBundles
.Include(b => b.Elements)
.SingleAsync(b => b.EncounterId == _encounterId);
bundle.TriggeringAlertType.Should().Be("SEPSIS_WARNING");
bundle.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.InProgress);
bundle.Elements.Should().HaveCount(4);
(await db.SepsisBundles.CountAsync()).Should().Be(0);
}
[Fact]
public async Task SecondAlert_IdempotentBundle()
{
using var scope = _fixture.Services.CreateScope();
var qsofaDetector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var sirsDetector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var handler = scope.ServiceProvider.GetRequiredService<SepsisAlertHandler>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await qsofaDetector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await qsofaDetector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
await CreateSofaSepsisBundleAsync(scope);
var bundleCountAfterFirst = await db.SepsisBundles.CountAsync(b => b.EncounterId == _encounterId);
bundleCountAfterFirst.Should().Be(1);
await sirsDetector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 95m);
await sirsDetector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 38.5m);
var secondAlertId = Guid.NewGuid();
db.ClinicalAlerts.Add(new ClinicalAlert
{
Id = secondAlertId,
EncounterId = _encounterId,
PatientId = _patientId,
AlertType = AlertType.SofaSepsis,
Severity = AlertSeverity.Critical,
Details = "SOFA delta +3",
Status = AlertStatus.Open,
TriggeredAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync();
await handler.OnSepsisAlertCreatedAsync(
_encounterId, secondAlertId, AlertType.SofaSepsis, CancellationToken.None);
var bundleCount = await db.SepsisBundles.CountAsync(b => b.EncounterId == _encounterId);
bundleCount.Should().Be(1, "a second bundle must not be created while one is IN_PROGRESS");
@@ -132,12 +156,10 @@ public class SepsisBundleTests : IAsyncLifetime
public async Task OrderResulted_CompletesElement()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var bundleService = scope.ServiceProvider.GetRequiredService<ISepsisBundleService>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
await CreateSofaSepsisBundleAsync(scope);
var lactateElement = await db.SepsisBundleElements
.Include(e => e.Order)
@@ -161,12 +183,10 @@ public class SepsisBundleTests : IAsyncLifetime
public async Task AllElementsResulted_BundleCompliant()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var bundleService = scope.ServiceProvider.GetRequiredService<ISepsisBundleService>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
await CreateSofaSepsisBundleAsync(scope);
var elements = await db.SepsisBundleElements.ToListAsync();
foreach (var element in elements)
@@ -188,12 +208,10 @@ public class SepsisBundleTests : IAsyncLifetime
public async Task DeadlinePassed_CompletionMarksNonCompliant()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var bundleService = scope.ServiceProvider.GetRequiredService<ISepsisBundleService>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
await CreateSofaSepsisBundleAsync(scope);
var bundle = await db.SepsisBundles.SingleAsync();
bundle.DeadlineAt = DateTimeOffset.UtcNow.AddHours(-1);
@@ -212,11 +230,9 @@ public class SepsisBundleTests : IAsyncLifetime
public async Task DeadlinePassed_MonitorMarksNonCompliant()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
await CreateSofaSepsisBundleAsync(scope);
var bundle = await db.SepsisBundles.SingleAsync();
bundle.DeadlineAt = DateTimeOffset.UtcNow.AddHours(-1);
@@ -0,0 +1,191 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
[Collection("Integration")]
public class SepsisRefactorTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private Guid _encounterId;
private Guid _patientId;
public SepsisRefactorTests(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-REFACTOR-001", FirstName = "Refactor", LastName = "Test",
DateOfBirth = new DateOnly(1960, 1, 1), 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. Refactor", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(encounter);
await db.SaveChangesAsync();
_patientId = patient.Id;
_encounterId = encounter.Id;
}
public Task DisposeAsync() => Task.CompletedTask;
[Fact]
public async Task SirsObservations_NoSepsisWarningAlert()
{
using var scope = _fixture.Services.CreateScope();
var qsofa = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await qsofa.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 39m);
await qsofa.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 110m);
await qsofa.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 22m);
await qsofa.ProcessObservationAsync(_encounterId, _patientId, "WBC_K_UL", 15m);
(await db.ClinicalAlerts.CountAsync(a => a.AlertType == AlertType.SepsisWarning))
.Should().Be(0);
}
[Fact]
public async Task SofaDelta2_TriggersSepsisBundleCreation()
{
using var scope = _fixture.Services.CreateScope();
var handler = scope.ServiceProvider.GetRequiredService<SepsisAlertHandler>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alertId = Guid.NewGuid();
db.ClinicalAlerts.Add(new ClinicalAlert
{
Id = alertId, EncounterId = _encounterId, PatientId = _patientId,
AlertType = AlertType.SofaSepsis, Severity = AlertSeverity.Critical,
Details = "SOFA delta +2", Status = AlertStatus.Open,
TriggeredAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync();
await handler.OnSepsisAlertCreatedAsync(
_encounterId, alertId, AlertType.SofaSepsis, CancellationToken.None);
(await db.SepsisBundles.CountAsync()).Should().Be(1);
}
[Fact]
public async Task QsofaScreen_DoesNotTriggerBundle()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
(await db.SepsisBundles.CountAsync()).Should().Be(0);
}
[Fact]
public async Task QsofaScreen_IsWarningNotCritical()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
var alert = await db.ClinicalAlerts.SingleAsync();
alert.AlertType.Should().Be(AlertType.QsofaScreen);
alert.Severity.Should().Be(AlertSeverity.Warning);
}
[Fact]
public void QsofaScreen_IsSuppressible()
{
AlertType.QsofaScreen.IsSuppressible().Should().BeTrue();
}
[Fact]
public async Task LegacySepsisWarning_StillQueryable()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alertService = scope.ServiceProvider.GetRequiredService<IAlertService>();
db.ClinicalAlerts.Add(new ClinicalAlert
{
Id = Guid.NewGuid(), EncounterId = _encounterId, PatientId = _patientId,
AlertType = AlertType.SepsisWarning, Severity = AlertSeverity.Critical,
Details = "Legacy SIRS alert", Status = AlertStatus.Resolved,
TriggeredAt = DateTimeOffset.UtcNow.AddDays(-1)
});
await db.SaveChangesAsync();
var page = await alertService.ListByEncounterAsync(_encounterId, null, 1, 10);
page.Items.Should().ContainSingle(a => a.AlertType == AlertType.SepsisWarning);
}
[Fact]
public void CannotCreateNewSepsisWarning()
{
var act = () => AlertCreationGuard.EnsureAllowed(AlertType.SepsisWarning);
act.Should().Throw<InvalidOperationException>()
.WithMessage("*deprecated*");
}
[Fact]
public async Task SepsisBundleCompliance_StillTracked()
{
using var scope = _fixture.Services.CreateScope();
var handler = scope.ServiceProvider.GetRequiredService<SepsisAlertHandler>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alertId = Guid.NewGuid();
db.ClinicalAlerts.Add(new ClinicalAlert
{
Id = alertId, EncounterId = _encounterId, PatientId = _patientId,
AlertType = AlertType.SofaSepsis, Severity = AlertSeverity.Critical,
Details = "SOFA delta +2", Status = AlertStatus.Open,
TriggeredAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync();
await handler.OnSepsisAlertCreatedAsync(
_encounterId, alertId, AlertType.SofaSepsis, CancellationToken.None);
var bundle = await db.SepsisBundles.SingleAsync();
bundle.DeadlineAt = DateTimeOffset.UtcNow.AddHours(-1);
await db.SaveChangesAsync();
var monitor = new SepsisBundleMonitorService(
_fixture.Services,
_fixture.Services.GetRequiredService<ClinicalMetrics>(),
_fixture.Services.GetRequiredService<ILogger<SepsisBundleMonitorService>>());
await monitor.ScanOverdueBundlesAsync(CancellationToken.None);
var updated = await db.SepsisBundles.AsNoTracking().SingleAsync();
updated.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.NonCompliant);
}
[Fact]
public async Task QsofaScreen_IncludesLabRecommendation()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
var alert = await db.ClinicalAlerts.SingleAsync();
alert.Details.Should().Contain("order SOFA labs");
}
}
@@ -1,213 +0,0 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
[Collection("Integration")]
public class SirsDetectorTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private Guid _encounterId;
private Guid _patientId;
public SirsDetectorTests(ApiFixture fixture) => _fixture = fixture;
public async Task InitializeAsync()
{
// Reset PostgreSQL test data
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-SIRS-001", FirstName = "SIRS", LastName = "Test",
DateOfBirth = new DateOnly(1960, 1, 1), 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. SIRS", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(encounter);
await db.SaveChangesAsync();
_patientId = patient.Id;
_encounterId = encounter.Id;
// Flush all SIRS keys for this encounter from Redis
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var cache = redis.GetDatabase();
foreach (var key in SirsEvaluator.AllCriterionKeys(_encounterId))
await cache.KeyDeleteAsync(key);
}
public Task DisposeAsync() => Task.CompletedTask;
private SirsDetector CreateDetector()
{
using var scope = _fixture.Services.CreateScope();
return scope.ServiceProvider.GetRequiredService<SirsDetector>();
}
// Test 1: one criterion met — insufficient for alert
[Fact]
public async Task OneCriterion_NoAlert()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 95m);
result.Outcome.Should().Be(SirsOutcome.InsufficientCriteria);
result.ActiveCount.Should().Be(1);
// Verify Redis key was set
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var ttl = await redis.GetDatabase()
.KeyTimeToLiveAsync(SirsEvaluator.CriterionKey(_encounterId, "HEART_RATE"));
ttl.Should().NotBeNull().And.BeGreaterThan(TimeSpan.Zero);
}
// Test 2: two criteria met — SEPSIS_WARNING alert created
[Fact]
public async Task TwoCriteriaMet_AlertCreated()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// Tachycardia
var r1 = await detector.ProcessObservationAsync(
_encounterId, _patientId, "HEART_RATE", 95m);
r1.Outcome.Should().Be(SirsOutcome.InsufficientCriteria);
// Fever — now count = 2 → alert
var r2 = await detector.ProcessObservationAsync(
_encounterId, _patientId, "TEMP_C", 38.5m);
r2.Outcome.Should().Be(SirsOutcome.AlertCreated);
// Verify clinical_alert row in PostgreSQL
var alert = await db.ClinicalAlerts.SingleAsync();
alert.AlertType.Should().Be(AlertType.SepsisWarning);
alert.Severity.Should().Be(AlertSeverity.Critical);
alert.Status.Should().Be(AlertStatus.Open);
alert.EncounterId.Should().Be(_encounterId);
alert.PatientId.Should().Be(_patientId);
// Verify outbox event was written in the same transaction
var outbox = await db.OutboxEvents.SingleAsync(e => e.Topic == "alert.generated");
outbox.PartitionKey.Should().Be(_encounterId.ToString());
}
// Test 3: third criterion met while alert already open — no second alert
[Fact]
public async Task ThreeCriteriaMet_NoSecondAlert()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 95m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 38.5m);
// Third criterion (tachypnea) — alert already open
var r3 = await detector.ProcessObservationAsync(
_encounterId, _patientId, "RESP_RATE", 22m);
r3.Outcome.Should().Be(SirsOutcome.AlertAlreadyOpen);
// Still exactly one alert — the WHERE NOT EXISTS prevented a duplicate
var alertCount = await db.ClinicalAlerts.CountAsync();
alertCount.Should().Be(1, "a second SEPSIS_WARNING must not be created while one is already open");
}
// Test 4: criterion clears — Redis key deleted, alert remains open
//
// This is the most important test in Phase 5. It verifies:
// (a) The DEL path works when a criterion is no longer met.
// (b) Clearing a criterion does not resolve the existing alert — the clinical
// workflow requires explicit acknowledgment. A patient whose temperature
// normalises may still be septic; the alert is for the clinician to evaluate.
[Fact]
public async Task CriterionClears_KeyDeleted_AlertRemainsOpen()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var cache = redis.GetDatabase();
// Establish two criteria and create the alert
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 95m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 38.5m);
// Temperature normalises
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "TEMP_C", 37.0m);
// TEMP_C key must be gone from Redis
var tempKeyExists = await cache.KeyExistsAsync(
SirsEvaluator.CriterionKey(_encounterId, "TEMP_C"));
tempKeyExists.Should().BeFalse("a cleared criterion must be deleted from Redis immediately");
// HEART_RATE key must still exist (criterion still met)
var hrKeyExists = await cache.KeyExistsAsync(
SirsEvaluator.CriterionKey(_encounterId, "HEART_RATE"));
hrKeyExists.Should().BeTrue("an active criterion must remain until its own TTL or a clearing observation");
// Active count is now 1, but alert must stay open
result.Outcome.Should().Be(SirsOutcome.InsufficientCriteria);
result.ActiveCount.Should().Be(1);
var alert = await db.ClinicalAlerts.SingleAsync();
alert.Status.Should().Be(AlertStatus.Open,
"the existing alert is not auto-resolved when criteria drop below 2 — " +
"clinical acknowledgment is required");
}
// Test 5: at-least-once redelivery — idempotency under simulated crash
[Fact]
public async Task DuplicateObservationEvent_AlertCreatedOnce()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 95m);
// Simulate: the consumer crashes after this call completes but before committing
// the Kafka offset. On restart, the same observation is redelivered.
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 38.5m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 38.5m); // duplicate
var alertCount = await db.ClinicalAlerts.CountAsync();
alertCount.Should().Be(1, "WHERE NOT EXISTS prevents duplicate alert on redelivery");
var outboxCount = await db.OutboxEvents.CountAsync(e => e.Topic == "alert.generated");
outboxCount.Should().Be(1, "outbox event must be written exactly once");
}
// Test 6: non-SIRS code — engine ignores it entirely
[Fact]
public async Task NonSirsCode_NoRedisInteraction()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "POTASSIUM_MEQ_L", 3.2m);
result.Outcome.Should().Be(SirsOutcome.NotSirsCode);
// No SIRS keys were created for this encounter
var anyKey = await redis.GetDatabase()
.KeyExistsAsync(SirsEvaluator.CriterionKey(_encounterId, "POTASSIUM_MEQ_L"));
anyKey.Should().BeFalse();
}
}
@@ -1,30 +0,0 @@
using FluentAssertions;
public class SirsEvaluatorTests
{
[Theory]
[InlineData("TEMP_C", 38.4, true)] // fever
[InlineData("TEMP_C", 35.9, true)] // hypothermia
[InlineData("TEMP_C", 37.0, false)] // normal
[InlineData("HEART_RATE", 91, true)]
[InlineData("HEART_RATE", 90, false)] // boundary: 90 is NOT tachycardia (> not >=)
[InlineData("RESP_RATE", 21, true)]
[InlineData("RESP_RATE", 20, false)] // boundary
[InlineData("WBC_K_UL", 12.1, true)] // leukocytosis
[InlineData("WBC_K_UL", 3.9, true)] // leukopenia
[InlineData("WBC_K_UL", 8.0, false)] // normal
[InlineData("POTASSIUM_MEQ_L", 4.0, false)] // not a SIRS code
public void MeetsCriterion_ReturnsExpected(string code, double value, bool expected)
{
SirsEvaluator.MeetsCriterion(code, (decimal)value).Should().Be(expected);
}
[Fact]
public void AllCriterionKeys_ReturnsFourKeys_AllDistinct()
{
var id = Guid.NewGuid();
var keys = SirsEvaluator.AllCriterionKeys(id);
keys.Should().HaveCount(4);
keys.Select(k => k.ToString()).Should().OnlyHaveUniqueItems();
}
}