feature: qSOFA Scoring & Sepsis Bundle Compliance
This commit is contained in:
@@ -6,11 +6,24 @@ public static class DbResetHelper
|
||||
// the database, and preserves the schema (migrations do not re-run).
|
||||
public static async Task ResetAsync(AppDbContext db)
|
||||
{
|
||||
await db.Database.ExecuteSqlRawAsync(@"
|
||||
TRUNCATE TABLE reconciliation_alerts, outbox_events, orders,
|
||||
clinical_alerts, news2_scores, observations, encounters,
|
||||
alert_thresholds, patients
|
||||
RESTART IDENTITY CASCADE;
|
||||
");
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await db.Database.ExecuteSqlRawAsync(@"
|
||||
SET lock_timeout = '3s';
|
||||
TRUNCATE TABLE sepsis_bundle_elements, sepsis_bundles,
|
||||
reconciliation_alerts, outbox_events, orders,
|
||||
clinical_alerts, news2_scores, observations, encounters,
|
||||
alert_thresholds, patients
|
||||
RESTART IDENTITY CASCADE;
|
||||
");
|
||||
return;
|
||||
}
|
||||
catch when (attempt < 5)
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using FluentAssertions;
|
||||
using StackExchange.Redis;
|
||||
|
||||
public class QsofaCalculatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void MeetsCriterion_RespRate22_ReturnsTrue() =>
|
||||
QsofaCalculator.MeetsCriterion("RESP_RATE", 22m).Should().BeTrue();
|
||||
|
||||
[Fact]
|
||||
public void MeetsCriterion_RespRate21_ReturnsFalse() =>
|
||||
QsofaCalculator.MeetsCriterion("RESP_RATE", 21m).Should().BeFalse();
|
||||
|
||||
[Fact]
|
||||
public void MeetsCriterion_SystolicBp100_ReturnsTrue() =>
|
||||
QsofaCalculator.MeetsCriterion("SYSTOLIC_BP", 100m).Should().BeTrue();
|
||||
|
||||
[Fact]
|
||||
public void MeetsCriterion_SystolicBp101_ReturnsFalse() =>
|
||||
QsofaCalculator.MeetsCriterion("SYSTOLIC_BP", 101m).Should().BeFalse();
|
||||
|
||||
[Fact]
|
||||
public void MeetsCriterion_Avpu1_ReturnsTrue() =>
|
||||
QsofaCalculator.MeetsCriterion("AVPU", 1m).Should().BeTrue();
|
||||
|
||||
[Fact]
|
||||
public void MeetsCriterion_Avpu0_ReturnsFalse() =>
|
||||
QsofaCalculator.MeetsCriterion("AVPU", 0m).Should().BeFalse();
|
||||
|
||||
[Fact]
|
||||
public void CountActiveCriteria_TwoOfThree_Returns2()
|
||||
{
|
||||
var values = new RedisValue[] { "24", RedisValue.Null, "95" };
|
||||
|
||||
QsofaCalculator.CountActiveCriteria(values).Should().Be(2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using StackExchange.Redis;
|
||||
|
||||
[Collection("Integration")]
|
||||
public class QsofaDetectorTests : IAsyncLifetime
|
||||
{
|
||||
private readonly ApiFixture _fixture;
|
||||
private Guid _encounterId;
|
||||
private Guid _patientId;
|
||||
|
||||
public QsofaDetectorTests(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-QSOFA-001", FirstName = "qSOFA", 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. qSOFA", AdmittedAt = DateTimeOffset.UtcNow,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.Patients.Add(patient);
|
||||
db.Encounters.Add(encounter);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
_patientId = patient.Id;
|
||||
_encounterId = encounter.Id;
|
||||
|
||||
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
|
||||
var cache = redis.GetDatabase();
|
||||
foreach (var key in QsofaCalculator.AllCriterionKeys(_encounterId))
|
||||
await cache.KeyDeleteAsync(key);
|
||||
}
|
||||
|
||||
public Task DisposeAsync() => Task.CompletedTask;
|
||||
|
||||
[Fact]
|
||||
public async Task OneCriterionMet_NoAlert()
|
||||
{
|
||||
using var scope = _fixture.Services.CreateScope();
|
||||
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
|
||||
|
||||
var result = await detector.ProcessObservationAsync(
|
||||
_encounterId, _patientId, "RESP_RATE", 24m);
|
||||
|
||||
result.Outcome.Should().Be(QsofaOutcome.InsufficientCriteria);
|
||||
result.ActiveCriteria.Should().Be(1);
|
||||
|
||||
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
|
||||
var ttl = await redis.GetDatabase()
|
||||
.KeyTimeToLiveAsync(QsofaCalculator.CriterionKey(_encounterId, "RESP_RATE"));
|
||||
ttl.Should().NotBeNull().And.BeGreaterThan(TimeSpan.Zero);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TwoCriteriaMet_CreatesAlert()
|
||||
{
|
||||
using var scope = _fixture.Services.CreateScope();
|
||||
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
var r1 = await detector.ProcessObservationAsync(
|
||||
_encounterId, _patientId, "RESP_RATE", 24m);
|
||||
r1.Outcome.Should().Be(QsofaOutcome.InsufficientCriteria);
|
||||
|
||||
var r2 = await detector.ProcessObservationAsync(
|
||||
_encounterId, _patientId, "SYSTOLIC_BP", 95m);
|
||||
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.Status.Should().Be(AlertStatus.Open);
|
||||
alert.EncounterId.Should().Be(_encounterId);
|
||||
alert.PatientId.Should().Be(_patientId);
|
||||
alert.Details.Should().Contain("qSOFA score 2/3");
|
||||
|
||||
var outbox = await db.OutboxEvents.SingleAsync();
|
||||
outbox.Topic.Should().Be("alert.generated");
|
||||
outbox.PartitionKey.Should().Be(_encounterId.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CriterionNormalizes_KeyDeleted()
|
||||
{
|
||||
using var scope = _fixture.Services.CreateScope();
|
||||
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
|
||||
var cache = redis.GetDatabase();
|
||||
|
||||
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
|
||||
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
|
||||
|
||||
var result = await detector.ProcessObservationAsync(
|
||||
_encounterId, _patientId, "RESP_RATE", 18m);
|
||||
|
||||
var respKeyExists = await cache.KeyExistsAsync(
|
||||
QsofaCalculator.CriterionKey(_encounterId, "RESP_RATE"));
|
||||
respKeyExists.Should().BeFalse("a normalized respiratory rate must clear the criterion key");
|
||||
|
||||
var sbpKeyExists = await cache.KeyExistsAsync(
|
||||
QsofaCalculator.CriterionKey(_encounterId, "SYSTOLIC_BP"));
|
||||
sbpKeyExists.Should().BeTrue("the other active criterion must remain in Redis");
|
||||
|
||||
result.Outcome.Should().Be(QsofaOutcome.InsufficientCriteria);
|
||||
result.ActiveCriteria.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");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DuplicateAlert_Idempotent()
|
||||
{
|
||||
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 r3 = await detector.ProcessObservationAsync(
|
||||
_encounterId, _patientId, "SYSTOLIC_BP", 95m);
|
||||
|
||||
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");
|
||||
|
||||
var outboxCount = await db.OutboxEvents.CountAsync();
|
||||
outboxCount.Should().Be(1, "outbox event must be written exactly once");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NonQsofaCode_Ignored()
|
||||
{
|
||||
using var scope = _fixture.Services.CreateScope();
|
||||
var detector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
|
||||
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
|
||||
|
||||
var result = await detector.ProcessObservationAsync(
|
||||
_encounterId, _patientId, "HEART_RATE", 95m);
|
||||
|
||||
result.Outcome.Should().Be(QsofaOutcome.NotQsofaCode);
|
||||
|
||||
foreach (var key in QsofaCalculator.AllCriterionKeys(_encounterId))
|
||||
{
|
||||
var exists = await redis.GetDatabase().KeyExistsAsync(key);
|
||||
exists.Should().BeFalse("non-qSOFA codes must not create Redis state");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using StackExchange.Redis;
|
||||
|
||||
[Collection("Integration")]
|
||||
public class SepsisBundleTests : IAsyncLifetime
|
||||
{
|
||||
private readonly ApiFixture _fixture;
|
||||
private Guid _encounterId;
|
||||
private Guid _patientId;
|
||||
|
||||
public SepsisBundleTests(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-BUNDLE-001", FirstName = "Bundle", LastName = "Test",
|
||||
DateOfBirth = new DateOnly(1965, 3, 15), 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. Bundle", AdmittedAt = DateTimeOffset.UtcNow,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.Patients.Add(patient);
|
||||
db.Encounters.Add(encounter);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
_patientId = patient.Id;
|
||||
_encounterId = encounter.Id;
|
||||
|
||||
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
|
||||
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()
|
||||
{
|
||||
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 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.DeadlineAt.Should().BeCloseTo(bundle.RecognizedAt.AddHours(1), TimeSpan.FromSeconds(5));
|
||||
bundle.Elements.Should().HaveCount(4);
|
||||
|
||||
var orders = await db.Orders
|
||||
.Where(o => o.EncounterId == _encounterId)
|
||||
.ToListAsync();
|
||||
orders.Should().HaveCount(4);
|
||||
orders.Should().AllSatisfy(o =>
|
||||
{
|
||||
o.Status.Should().Be(OrderStatus.Pending);
|
||||
o.Description.Should().StartWith("SEP-1:");
|
||||
o.OrderedBy.Should().Be("sepsis-bundle-engine");
|
||||
});
|
||||
|
||||
var bundleOutbox = await db.OutboxEvents
|
||||
.Where(e => e.Topic == "sepsis.bundle.created")
|
||||
.SingleAsync();
|
||||
bundleOutbox.PartitionKey.Should().Be(_encounterId.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SirsAlert_CreatesBundle()
|
||||
{
|
||||
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);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
[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 db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
await qsofaDetector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m);
|
||||
await qsofaDetector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
|
||||
|
||||
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 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");
|
||||
|
||||
var orderCount = await db.Orders.CountAsync(o => o.EncounterId == _encounterId);
|
||||
orderCount.Should().Be(4, "no additional orders should be created for the duplicate bundle attempt");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
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);
|
||||
|
||||
var lactateElement = await db.SepsisBundleElements
|
||||
.Include(e => e.Order)
|
||||
.SingleAsync(e => e.ElementType == SepsisBundleElementType.SerumLactate);
|
||||
|
||||
await bundleService.OnOrderResultedAsync(lactateElement.OrderId!.Value);
|
||||
|
||||
var updated = await db.SepsisBundleElements
|
||||
.AsNoTracking()
|
||||
.SingleAsync(e => e.Id == lactateElement.Id);
|
||||
|
||||
updated.Status.Should().Be(SepsisBundleElementStatus.Completed);
|
||||
updated.CompletedAt.Should().NotBeNull();
|
||||
|
||||
var bundle = await db.SepsisBundles.AsNoTracking().SingleAsync();
|
||||
bundle.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.InProgress,
|
||||
"bundle should remain in progress until all 4 elements are completed");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
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);
|
||||
|
||||
var elements = await db.SepsisBundleElements.ToListAsync();
|
||||
foreach (var element in elements)
|
||||
await bundleService.OnOrderResultedAsync(element.OrderId!.Value);
|
||||
|
||||
var bundle = await db.SepsisBundles.AsNoTracking().SingleAsync();
|
||||
bundle.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.Compliant);
|
||||
bundle.CompletedAt.Should().NotBeNull();
|
||||
bundle.CompletedAt.Should().BeBefore(bundle.DeadlineAt,
|
||||
"all elements completed within the 1-hour window");
|
||||
|
||||
var outboxEvents = await db.OutboxEvents
|
||||
.Where(e => e.Topic == "sepsis.bundle.updated")
|
||||
.ToListAsync();
|
||||
outboxEvents.Should().HaveCount(4, "one outbox event per element completion");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
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);
|
||||
|
||||
var bundle = await db.SepsisBundles.SingleAsync();
|
||||
bundle.DeadlineAt = DateTimeOffset.UtcNow.AddHours(-1);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var elements = await db.SepsisBundleElements.ToListAsync();
|
||||
foreach (var element in elements)
|
||||
await bundleService.OnOrderResultedAsync(element.OrderId!.Value);
|
||||
|
||||
var updated = await db.SepsisBundles.AsNoTracking().SingleAsync();
|
||||
updated.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.NonCompliant);
|
||||
updated.CompletedAt.Should().NotBeNull();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user