Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
CI / changes (push) Successful in 17s
CI / frontend (push) Skipped
CI / backend (push) Successful in 15m10s

Stop consumers from committing past failed offsets, harden Rabbit/DataLake/gateway backpressure, dispose JsonDocument/MinIO correctly, and batch expensive DB/HTTP paths. Track progress in docs/performance.
This commit is contained in:
2026-11-30 21:32:43 +08:00
parent 1c1065938f
commit 68a2ab3204
54 changed files with 959 additions and 311 deletions
@@ -32,8 +32,7 @@ public sealed class CentralReachabilityService : BackgroundService
try
{
var client = _http.CreateClient("central");
client.BaseAddress = new Uri(_central.BaseUrl);
var resp = await client.GetAsync("/health/ready", ct);
var resp = await client.GetAsync("health/ready", ct);
_isReachable = resp.IsSuccessStatusCode;
}
catch
@@ -46,13 +46,10 @@ public sealed class EncounterReplicaSyncService : BackgroundService
await using var scope = _scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<GatewayDbContext>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var centralOpts = scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value;
var client = _http.CreateClient("central");
client.BaseAddress = new Uri(centralOpts.BaseUrl);
ConfigureAuth(client);
if (client.DefaultRequestHeaders.Authorization is null)
var jwt = Environment.GetEnvironmentVariable("GATEWAY_SYNC_JWT");
if (string.IsNullOrEmpty(jwt))
{
_logger.LogWarning(
"GATEWAY_SYNC_JWT not set — skipping encounter replica sync (seed local replica manually for dev)");
@@ -61,8 +58,8 @@ public sealed class EncounterReplicaSyncService : BackgroundService
try
{
var syncedCount = await SyncEncountersAsync(client, db, ct);
await SyncThresholdsAsync(client, db, redis, ct);
var syncedCount = await SyncEncountersAsync(client, jwt, db, ct);
await SyncThresholdsAsync(client, jwt, db, redis, ct);
var state = await db.SyncState.FirstOrDefaultAsync(ct)
?? db.SyncState.Add(new GatewaySyncState { Id = Guid.NewGuid() }).Entity;
@@ -79,7 +76,7 @@ public sealed class EncounterReplicaSyncService : BackgroundService
}
private async Task<int> SyncEncountersAsync(
HttpClient client, GatewayDbContext db, CancellationToken ct)
HttpClient client, string jwt, GatewayDbContext db, CancellationToken ct)
{
var dept = Uri.EscapeDataString(_gateway.Department);
var summaries = new List<CentralWardEncounterSummary>();
@@ -87,10 +84,14 @@ public sealed class EncounterReplicaSyncService : BackgroundService
while (true)
{
var listResp = await client.GetFromJsonAsync<ApiResponse<CentralEncounterListPage>>(
$"/api/v1/encounters?status=ACTIVE&department={dept}&page={page}&pageSize={EncounterPageSize}",
CentralApiJson.Options,
ct);
using var listReq = new HttpRequestMessage(
HttpMethod.Get,
$"api/v1/encounters?status=ACTIVE&department={dept}&page={page}&pageSize={EncounterPageSize}");
listReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
using var listHttp = await client.SendAsync(listReq, ct);
listHttp.EnsureSuccessStatusCode();
var listResp = await listHttp.Content.ReadFromJsonAsync<ApiResponse<CentralEncounterListPage>>(
CentralApiJson.Options, ct);
if (listResp?.Data?.Items is null || listResp.Data.Items.Count == 0)
break;
@@ -106,10 +107,28 @@ public sealed class EncounterReplicaSyncService : BackgroundService
var synced = 0;
foreach (var summary in summaries)
{
var detailResp = await client.GetFromJsonAsync<ApiResponse<CentralEncounterDetail>>(
$"/api/v1/encounters/{summary.EncounterId}",
CentralApiJson.Options,
ct);
var existingPatient = await db.Patients.FindAsync([summary.PatientId], ct);
if (existingPatient is not null
&& !string.IsNullOrEmpty(summary.Mrn)
&& !string.IsNullOrEmpty(summary.FirstName))
{
UpsertFromSummary(db, summary, existingPatient);
synced++;
continue;
}
using var detailReq = new HttpRequestMessage(
HttpMethod.Get, $"api/v1/encounters/{summary.EncounterId}");
detailReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
using var detailHttp = await client.SendAsync(detailReq, ct);
if (!detailHttp.IsSuccessStatusCode)
{
_logger.LogWarning("Central returned no detail for encounter {EncounterId}", summary.EncounterId);
continue;
}
var detailResp = await detailHttp.Content.ReadFromJsonAsync<ApiResponse<CentralEncounterDetail>>(
CentralApiJson.Options, ct);
if (detailResp?.Data is null)
{
@@ -124,6 +143,43 @@ public sealed class EncounterReplicaSyncService : BackgroundService
return synced;
}
private static void UpsertFromSummary(
GatewayDbContext db, CentralWardEncounterSummary summary, ReplicaPatient existingPatient)
{
var now = DateTimeOffset.UtcNow;
if (!string.IsNullOrEmpty(summary.Mrn)) existingPatient.Mrn = summary.Mrn;
if (!string.IsNullOrEmpty(summary.FirstName)) existingPatient.FirstName = summary.FirstName!;
if (!string.IsNullOrEmpty(summary.LastName)) existingPatient.LastName = summary.LastName!;
existingPatient.SyncedAt = now;
var enc = db.Encounters.Find(summary.EncounterId);
if (enc is null)
{
db.Encounters.Add(new ReplicaEncounter
{
Id = summary.EncounterId,
PatientId = summary.PatientId,
EncounterType = EncounterType.Inpatient,
Status = summary.Status,
Department = summary.Department,
AttendingPhysician = summary.AttendingPhysician ?? "unknown",
RoomBed = summary.RoomBed,
AdmittedAt = summary.AdmittedAt == default ? now : summary.AdmittedAt,
SyncedAt = now
});
}
else
{
enc.PatientId = summary.PatientId;
enc.Status = summary.Status;
enc.Department = summary.Department;
enc.AttendingPhysician = summary.AttendingPhysician ?? enc.AttendingPhysician;
enc.RoomBed = summary.RoomBed;
if (summary.AdmittedAt != default) enc.AdmittedAt = summary.AdmittedAt;
enc.SyncedAt = now;
}
}
private static void UpsertReplica(GatewayDbContext db, CentralEncounterDetail detail)
{
var now = DateTimeOffset.UtcNow;
@@ -184,14 +240,17 @@ public sealed class EncounterReplicaSyncService : BackgroundService
private async Task SyncThresholdsAsync(
HttpClient client,
string jwt,
GatewayDbContext db,
IConnectionMultiplexer redis,
CancellationToken ct)
{
var thrResp = await client.GetFromJsonAsync<ApiResponse<List<CentralAlertThreshold>>>(
"/api/v1/alert-thresholds",
CentralApiJson.Options,
ct);
using var thrReq = new HttpRequestMessage(HttpMethod.Get, "api/v1/alert-thresholds");
thrReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
using var thrHttp = await client.SendAsync(thrReq, ct);
thrHttp.EnsureSuccessStatusCode();
var thrResp = await thrHttp.Content.ReadFromJsonAsync<ApiResponse<List<CentralAlertThreshold>>>(
CentralApiJson.Options, ct);
if (thrResp?.Data is null)
return;
@@ -216,12 +275,4 @@ public sealed class EncounterReplicaSyncService : BackgroundService
await ThresholdCacheLoader.RefreshAsync(db, redis, _logger, ct);
}
private static void ConfigureAuth(HttpClient client)
{
client.DefaultRequestHeaders.Authorization = null;
var jwt = Environment.GetEnvironmentVariable("GATEWAY_SYNC_JWT");
if (!string.IsNullOrEmpty(jwt))
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
}
}
@@ -1,3 +1,4 @@
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
@@ -45,15 +46,16 @@ public sealed class GatewayHeartbeatService : BackgroundService
try
{
var client = _http.CreateClient("central");
client.BaseAddress = new Uri(
scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value.BaseUrl);
client.DefaultRequestHeaders.Remove("X-Api-Key");
client.DefaultRequestHeaders.Remove("X-Gateway-Id");
client.DefaultRequestHeaders.Add("X-Api-Key", _config["ApiKey:Gateway"]);
client.DefaultRequestHeaders.Add("X-Gateway-Id", _gateway.GatewayId.ToString());
using var message = new HttpRequestMessage(
HttpMethod.Patch,
$"api/v1/gateways/{_gateway.GatewayId}/heartbeat")
{
Content = JsonContent.Create(req)
};
message.Headers.TryAddWithoutValidation("X-Api-Key", _config["ApiKey:Gateway"]);
message.Headers.TryAddWithoutValidation("X-Gateway-Id", _gateway.GatewayId.ToString());
var resp = await client.PatchAsJsonAsync(
$"/api/v1/gateways/{_gateway.GatewayId}/heartbeat", req, ct);
var resp = await client.SendAsync(message, ct);
if (!resp.IsSuccessStatusCode)
_logger.LogWarning("Heartbeat failed: {Status}", resp.StatusCode);
}
@@ -52,7 +52,7 @@ public sealed class LocalEscalationWorkerService : BackgroundService
using var connection = factory.CreateConnection("gateway-escalation-worker");
using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 5, global: false);
channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (_, ea) =>
@@ -70,7 +70,7 @@ public sealed class LocalEscalationWorkerService : BackgroundService
private async Task HandleEscalationAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{
var payload = Encoding.UTF8.GetString(ea.Body.Span);
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
_logger.LogCritical("[ESCALATION] Paging on-call backup for alert {AlertId}", alertId);
@@ -87,7 +87,7 @@ public sealed class LocalPagingWorkerService : BackgroundService
{
var o = _opts.Value;
var payload = Encoding.UTF8.GetString(ea.Body.Span);
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
var encounterId = doc.RootElement.GetProperty("encounterId").GetString();
var details = doc.RootElement.TryGetProperty("details", out var d) ? d.GetString() : null;
@@ -104,7 +104,7 @@ public sealed class LocalPagingWorkerService : BackgroundService
while (DateTimeOffset.UtcNow < deadline && !ct.IsCancellationRequested)
{
await Task.Delay(2_000, ct);
await Task.Delay(5_000, ct);
if (await IsAlertAcknowledgedAsync(alertId, ct))
{
@@ -68,20 +68,29 @@ public sealed class SyncUploaderService : BackgroundService
var request = BuildBatchRequest(batchRef, pending);
var client = scope.ServiceProvider.GetRequiredService<IHttpClientFactory>().CreateClient("central");
client.BaseAddress = new Uri(
scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value.BaseUrl);
client.DefaultRequestHeaders.Add("X-Api-Key", _config["ApiKey:Gateway"]!);
client.DefaultRequestHeaders.Add("X-Gateway-Id", _gateway.GatewayId.ToString());
var apiKey = _config["ApiKey:Gateway"]!;
var gatewayId = _gateway.GatewayId.ToString();
var submit = await client.PostAsJsonAsync("/api/v1/sync/batches", request, ct);
using (var submitMsg = new HttpRequestMessage(HttpMethod.Post, "api/v1/sync/batches")
{
Content = JsonContent.Create(request)
})
{
submitMsg.Headers.TryAddWithoutValidation("X-Api-Key", apiKey);
submitMsg.Headers.TryAddWithoutValidation("X-Gateway-Id", gatewayId);
var submit = await client.SendAsync(submitMsg, ct);
submit.EnsureSuccessStatusCode();
var batchId = (await submit.Content.ReadFromJsonAsync<ApiResponse<SyncBatchStatus>>(ct))!.Data!.BatchId;
for (var i = 0; i < 30; i++)
{
await Task.Delay(2000, ct);
var status = await client.GetFromJsonAsync<ApiResponse<SyncBatchStatus>>(
$"/api/v1/sync/batches/{batchId}", ct);
using var statusMsg = new HttpRequestMessage(HttpMethod.Get, $"api/v1/sync/batches/{batchId}");
statusMsg.Headers.TryAddWithoutValidation("X-Api-Key", apiKey);
statusMsg.Headers.TryAddWithoutValidation("X-Gateway-Id", gatewayId);
using var statusResp = await client.SendAsync(statusMsg, ct);
statusResp.EnsureSuccessStatusCode();
var status = await statusResp.Content.ReadFromJsonAsync<ApiResponse<SyncBatchStatus>>(ct);
if (status?.Data?.Status is "APPLIED")
{
foreach (var item in pending)
@@ -106,6 +115,7 @@ public sealed class SyncUploaderService : BackgroundService
_logger.LogWarning("Sync batch {BatchId} still processing after poll window", batchId);
}
}
private ClinicalSyncBatchRequest BuildBatchRequest(Guid batchRef, List<BufferedSyncItem> items)
{
@@ -51,7 +51,7 @@ public class ThresholdCacheLoader : IHostedService
{
try
{
WriteThresholds(redis, thresholds);
await WriteThresholdsAsync(redis, thresholds);
logger.LogInformation(
"Loaded {Count} alert thresholds into gateway Redis cache", thresholds.Count);
return;
@@ -73,10 +73,12 @@ public class ThresholdCacheLoader : IHostedService
maxAttempts);
}
private static void WriteThresholds(IConnectionMultiplexer redis, List<ReplicaAlertThreshold> thresholds)
private static async Task WriteThresholdsAsync(
IConnectionMultiplexer redis, List<ReplicaAlertThreshold> thresholds)
{
var cache = redis.GetDatabase();
var batch = cache.CreateBatch();
var setTasks = new List<Task>(thresholds.Count);
foreach (var t in thresholds)
{
@@ -86,9 +88,10 @@ public class ThresholdCacheLoader : IHostedService
t.WarningLow,
t.WarningHigh,
t.CriticalHigh));
_ = batch.StringSetAsync($"threshold:{t.ObservationCode}", json);
setTasks.Add(batch.StringSetAsync($"threshold:{t.ObservationCode}", json));
}
batch.Execute();
await Task.WhenAll(setTasks);
}
}
@@ -9,6 +9,13 @@ public sealed class GatewayOptions
public int HeartbeatIntervalSeconds { get; init; } = 60;
public int SyncBatchSize { get; init; } = 500;
/// <summary>
/// Hard cap on unsynced <c>buffered_sync_items</c>. When reached, local ingest
/// that would enqueue more sync work is rejected (backpressure) so disk and
/// catch-up memory stay bounded during prolonged central outages.
/// </summary>
public int MaxBufferedSyncItems { get; init; } = 50_000;
/// <summary>
/// When true (default), applies EF migrations at startup. The gateway is
/// single-instance by design, so startup migration is safe. Set false if
@@ -7,10 +7,22 @@ public sealed class CentralEncounterListPage
public int TotalPages { get; set; }
}
/// <summary>
/// Mirrors central <c>WardEncounterSummary</c> list payload so replica sync can
/// upsert without a detail GET when the patient already exists locally.
/// </summary>
public sealed class CentralWardEncounterSummary
{
public Guid EncounterId { get; set; }
public Guid PatientId { get; set; }
public string? Mrn { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? RoomBed { get; set; }
public Department Department { get; set; }
public EncounterStatus Status { get; set; }
public string? AttendingPhysician { get; set; }
public DateTimeOffset AdmittedAt { get; set; }
}
public sealed class CentralEncounterDetail
+7 -1
View File
@@ -49,7 +49,13 @@ try
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
builder.Services.AddHttpClient("central");
builder.Services.AddHttpClient("central", (sp, client) =>
{
var baseUrl = sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<CentralApiOptions>>()
.Value.BaseUrl.TrimEnd('/') + "/";
client.BaseAddress = new Uri(baseUrl);
client.Timeout = TimeSpan.FromSeconds(30);
});
builder.Services.AddSingleton<CentralReachabilityService>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<CentralReachabilityService>());
@@ -1,4 +1,5 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
public static class BufferedSyncWriter
{
@@ -8,8 +9,21 @@ public static class BufferedSyncWriter
object payload,
string idempotencyKey,
Guid encounterId,
DateTimeOffset recordedAt)
DateTimeOffset recordedAt,
int maxUnsyncedItems = 50_000)
{
var persisted = db.BufferedSyncItems.Count(b => !b.Synced);
var pendingAdd = db.ChangeTracker.Entries<BufferedSyncItem>()
.Count(e => e.State == EntityState.Added);
if (persisted + pendingAdd >= maxUnsyncedItems)
{
throw new ConflictException(
$"Sync buffer is full ({maxUnsyncedItems} unsynced items). " +
"Central sync must catch up before accepting more buffered events.",
"SYNC_BUFFER_FULL");
}
db.BufferedSyncItems.Add(new BufferedSyncItem
{
Id = Guid.NewGuid(),
@@ -1,10 +1,16 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
public class LocalAlertService : ILocalAlertService
{
private readonly GatewayDbContext _db;
private readonly GatewayOptions _gateway;
public LocalAlertService(GatewayDbContext db) => _db = db;
public LocalAlertService(GatewayDbContext db, IOptions<GatewayOptions> gateway)
{
_db = db;
_gateway = gateway.Value;
}
public async Task<LocalClinicalAlert> AcknowledgeAsync(
Guid id, AcknowledgeAlertRequest req, string clinicianId)
@@ -26,7 +32,8 @@ public class LocalAlertService : ILocalAlertService
clinicianId,
acknowledgedAt = alert.AcknowledgedAt,
req.Note
}, $"ack:{alert.ClientAlertId}:{alert.AcknowledgedAt:o}", alert.EncounterId, alert.AcknowledgedAt!.Value);
}, $"ack:{alert.ClientAlertId}:{alert.AcknowledgedAt:o}", alert.EncounterId, alert.AcknowledgedAt!.Value,
_gateway.MaxBufferedSyncItems);
await _db.SaveChangesAsync();
return alert;
@@ -50,7 +57,8 @@ public class LocalAlertService : ILocalAlertService
clinicianId = alert.AcknowledgedBy,
resolvedAt = alert.ResolvedAt,
note = (string?)null
}, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value);
}, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value,
_gateway.MaxBufferedSyncItems);
await _db.SaveChangesAsync();
return alert;
@@ -1,5 +1,6 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
public class LocalObservationService : ILocalObservationService
@@ -8,6 +9,7 @@ public class LocalObservationService : ILocalObservationService
private readonly IConnectionMultiplexer _redis;
private readonly LocalWarningEvaluator _warnings;
private readonly LocalPagingPublisher _paging;
private readonly GatewayOptions _gateway;
private readonly ILogger<LocalObservationService> _logger;
public LocalObservationService(
@@ -15,12 +17,14 @@ public class LocalObservationService : ILocalObservationService
IConnectionMultiplexer redis,
LocalWarningEvaluator warnings,
LocalPagingPublisher paging,
IOptions<GatewayOptions> gateway,
ILogger<LocalObservationService> logger)
{
_db = db;
_redis = redis;
_warnings = warnings;
_paging = paging;
_gateway = gateway.Value;
_logger = logger;
}
@@ -94,7 +98,8 @@ public class LocalObservationService : ILocalObservationService
severity = alert.Severity.ToDbString(),
alert.Details,
generatedAt = triggeredAt
}, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt);
}, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt,
_gateway.MaxBufferedSyncItems);
await _paging.PublishCriticalAsync(alert, encounter);
}
@@ -114,7 +119,8 @@ public class LocalObservationService : ILocalObservationService
req.Unit,
source = req.Source.ToDbString(),
req.RecordedAt
}, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt);
}, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt,
_gateway.MaxBufferedSyncItems);
await _db.SaveChangesAsync();
await tx.CommitAsync();
@@ -1,13 +1,19 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
public class LocalWarningEvaluator
{
private readonly GatewayDbContext _db;
private readonly GatewayOptions _gateway;
private readonly ILogger<LocalWarningEvaluator> _logger;
public LocalWarningEvaluator(GatewayDbContext db, ILogger<LocalWarningEvaluator> logger)
public LocalWarningEvaluator(
GatewayDbContext db,
IOptions<GatewayOptions> gateway,
ILogger<LocalWarningEvaluator> logger)
{
_db = db;
_gateway = gateway.Value;
_logger = logger;
}
@@ -52,7 +58,8 @@ public class LocalWarningEvaluator
severity = AlertSeverity.Warning.ToDbString(),
details,
generatedAt = triggeredAt
}, $"alert:{clientAlertId}", encounterId, triggeredAt);
}, $"alert:{clientAlertId}", encounterId, triggeredAt,
_gateway.MaxBufferedSyncItems);
_logger.LogInformation(
"WARNING alert {AlertId} created locally for encounter {EncounterId}",
+1
View File
@@ -27,6 +27,7 @@
"CentralReachabilityIntervalSeconds": 30,
"HeartbeatIntervalSeconds": 60,
"SyncBatchSize": 500,
"MaxBufferedSyncItems": 50000,
"AutoMigrate": true
},
"ApiKey": {
@@ -0,0 +1,89 @@
using System.Text.Json;
using Confluent.Kafka;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
public class KafkaConsumerRetryTests
{
[Fact]
public void PoisonPillGuard_PermanentError_SkipsImmediately()
{
var guard = new PoisonPillGuard("test-group", maxRetries: 5, NullLogger.Instance);
var result = BuildConsumeResult("test-topic", 0, 0, "bad payload");
guard.ShouldSkip(result, new JsonException("Invalid JSON"))
.Should().BeTrue();
}
[Fact]
public void PoisonPillGuard_TransientError_RetriesUpToMax()
{
const int maxRetries = 3;
var guard = new PoisonPillGuard("test-group", maxRetries, NullLogger.Instance);
var result = BuildConsumeResult("test-topic", 0, 42, "payload");
var transientError = new TimeoutException("Connection timed out");
for (var i = 1; i < maxRetries; i++)
guard.ShouldSkip(result, transientError).Should().BeFalse();
guard.ShouldSkip(result, transientError).Should().BeTrue();
}
[Fact]
public async Task KafkaConsumerRetry_TransientError_SeeksBackWithoutCommit()
{
var guard = new PoisonPillGuard("test-group", maxRetries: 5, NullLogger.Instance);
var result = BuildConsumeResult("test-topic", 0, 42, "payload");
TopicPartitionOffset? sought = null;
ConsumeResult<string, string>? committed = null;
await KafkaConsumerRetry.HandleFailureAsync(
seek: tpo => sought = tpo,
commit: r => committed = r,
result,
new TimeoutException("transient"),
guard,
NullLogger.Instance,
"TestService",
CancellationToken.None,
delayMs: 1);
sought.Should().NotBeNull();
sought!.Offset.Value.Should().Be(42);
committed.Should().BeNull();
}
[Fact]
public async Task KafkaConsumerRetry_PermanentError_CommitsWithoutSeek()
{
var guard = new PoisonPillGuard("test-group", maxRetries: 5, NullLogger.Instance);
var result = BuildConsumeResult("test-topic", 0, 7, "bad");
TopicPartitionOffset? sought = null;
ConsumeResult<string, string>? committed = null;
await KafkaConsumerRetry.HandleFailureAsync(
seek: tpo => sought = tpo,
commit: r => committed = r,
result,
new JsonException("bad json"),
guard,
NullLogger.Instance,
"TestService",
CancellationToken.None,
delayMs: 1);
sought.Should().BeNull();
committed.Should().NotBeNull();
committed!.Offset.Value.Should().Be(7);
}
private static ConsumeResult<string, string> BuildConsumeResult(
string topic, int partition, long offset, string value) =>
new()
{
Topic = topic,
Partition = new Partition(partition),
Offset = new Offset(offset),
Message = new Message<string, string> { Key = "test-key", Value = value }
};
}
@@ -28,7 +28,7 @@ public sealed class ClinicalSyncBatchConsumer : BackgroundService
using var connection = factory.CreateConnection("clinical-sync-consumer");
using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 5, global: false);
channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (_, ea) =>
@@ -58,7 +58,7 @@ public sealed class ClinicalSyncBatchConsumer : BackgroundService
private async Task HandleMessageAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{
var payload = Encoding.UTF8.GetString(ea.Body.Span);
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var batchId = Guid.Parse(doc.RootElement.GetProperty("batchId").GetString()!);
await using var scope = _scopes.CreateAsyncScope();
@@ -74,16 +74,9 @@ public class EsIndexerService : BackgroundService
}
catch (Exception ex)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
consumer.Commit(result);
continue;
}
_logger.LogError(ex,
"EsIndexer failed processing topic={Topic} offset={Offset} — will retry",
result?.Topic, result?.Offset.Value);
await Task.Delay(1000, stoppingToken);
await KafkaConsumerRetry.HandleFailureAsync(
consumer, result, ex, guard, _logger, nameof(EsIndexerService), stoppingToken,
delayMs: 1000);
}
}
}
@@ -46,7 +46,7 @@ public class GcsScoringService : BackgroundService
var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
ClinicalEventJson.Options)!;
using var scope = _services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<GcsDetector>();
@@ -76,16 +76,8 @@ public class GcsScoringService : BackgroundService
}
catch (Exception ex)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
consumer.Commit(result);
continue;
}
_logger.LogError(ex,
"GcsScoringService failed on topic={Topic} offset={Offset} — will retry",
result?.Topic, result?.Offset.Value);
await Task.Delay(2000, stoppingToken);
await KafkaConsumerRetry.HandleFailureAsync(
consumer, result, ex, guard, _logger, nameof(GcsScoringService), stoppingToken);
}
}
}
@@ -46,7 +46,7 @@ public class News2ScoringService : BackgroundService
var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
ClinicalEventJson.Options)!;
using var scope = _services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
@@ -76,16 +76,8 @@ public class News2ScoringService : BackgroundService
}
catch (Exception ex)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
consumer.Commit(result);
continue;
}
_logger.LogError(ex,
"News2ScoringService failed on topic={Topic} offset={Offset} — will retry",
result?.Topic, result?.Offset.Value);
await Task.Delay(2000, stoppingToken);
await KafkaConsumerRetry.HandleFailureAsync(
consumer, result, ex, guard, _logger, nameof(News2ScoringService), stoppingToken);
}
}
}
@@ -2,6 +2,7 @@ using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Minio;
using Minio.DataModel.Args;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
@@ -10,17 +11,20 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
{
private readonly IOptions<RabbitMqOptions> _rabbitOpts;
private readonly IOptions<MinioOptions> _minioOpts;
private readonly IMinioClient _minio;
private readonly IServiceScopeFactory _scopes;
private readonly ILogger<DischargeSummaryWorkerService> _logger;
public DischargeSummaryWorkerService(
IOptions<RabbitMqOptions> rabbitOpts,
IOptions<MinioOptions> minioOpts,
IMinioClient minio,
IServiceScopeFactory scopes,
ILogger<DischargeSummaryWorkerService> logger)
{
_rabbitOpts = rabbitOpts;
_minioOpts = minioOpts;
_minio = minio;
_scopes = scopes;
_logger = logger;
}
@@ -35,7 +39,7 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
using var connection = factory.CreateConnection("discharge-summary-worker");
using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 3, global: false);
channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (sender, ea) =>
@@ -53,7 +57,7 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
private async Task HandleDischargeSummaryAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{
var payload = Encoding.UTF8.GetString(ea.Body.Span);
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var encounterId = Guid.Parse(doc.RootElement.GetProperty("encounterId").GetString()!);
try
@@ -128,22 +132,22 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
private async Task UploadToMinioAsync(Guid encounterId, string content, CancellationToken ct)
{
var mo = _minioOpts.Value;
var client = MinioClientFactory.Build(mo);
var bucket = mo.BucketName;
var exists = await client.BucketExistsAsync(
var exists = await _minio.BucketExistsAsync(
new BucketExistsArgs().WithBucket(bucket), ct);
if (!exists)
await client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), ct);
await _minio.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), ct);
var objectKey = $"discharge-summaries/{encounterId}/summary.pdf";
var bytes = Encoding.UTF8.GetBytes(content);
await client.PutObjectAsync(new PutObjectArgs()
await using var stream = new MemoryStream(bytes);
await _minio.PutObjectAsync(new PutObjectArgs()
.WithBucket(bucket)
.WithObject(objectKey)
.WithStreamData(new MemoryStream(bytes))
.WithStreamData(stream)
.WithObjectSize(bytes.Length)
.WithContentType("text/plain"),
ct);
@@ -34,7 +34,7 @@ public sealed class EscalationWorkerService : BackgroundService
using var connection = factory.CreateConnection("escalation-worker");
using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 5, global: false);
channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (sender, ea) =>
@@ -52,7 +52,7 @@ public sealed class EscalationWorkerService : BackgroundService
private async Task HandleEscalationAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{
var payload = Encoding.UTF8.GetString(ea.Body.Span);
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
var encounterId = Guid.Parse(doc.RootElement.GetProperty("encounterId").GetString()!);
@@ -85,13 +85,8 @@ public sealed class NotificationPublisherService : BackgroundService
}
catch (Exception ex)
{
if (guard.ShouldSkip(result, ex))
{
consumer.Commit(result);
continue;
}
_logger.LogError(ex, "NotificationPublisher failed to process message from {Topic} — will retry", result.Topic);
await KafkaConsumerRetry.HandleFailureAsync(
consumer, result, ex, guard, _logger, nameof(NotificationPublisherService), stoppingToken);
}
}
}
@@ -104,7 +99,7 @@ public sealed class NotificationPublisherService : BackgroundService
private Task HandleAlertGeneratedAsync(
IModel chan, IBasicProperties props, string payload, CancellationToken ct)
{
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var severity = doc.RootElement.GetProperty("severity").GetString();
if (!string.Equals(severity, "Critical", StringComparison.OrdinalIgnoreCase))
@@ -142,7 +137,7 @@ public sealed class NotificationPublisherService : BackgroundService
private Task HandleEncounterStatusChangedAsync(
IModel chan, IBasicProperties props, string payload, CancellationToken ct)
{
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var newStatus = doc.RootElement.GetProperty("newStatus").GetString();
if (!string.Equals(newStatus, "Discharged", StringComparison.OrdinalIgnoreCase))
@@ -69,7 +69,7 @@ public sealed class PagingWorkerService : BackgroundService
{
var o = _opts.Value;
var payload = Encoding.UTF8.GetString(ea.Body.Span);
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
var encounterId = doc.RootElement.GetProperty("encounterId").GetString();
var details = doc.RootElement.TryGetProperty("details", out var d) ? d.GetString() : null;
@@ -84,7 +84,7 @@ public sealed class PagingWorkerService : BackgroundService
while (DateTimeOffset.UtcNow < deadline && !ct.IsCancellationRequested)
{
await Task.Delay(2_000, ct);
await Task.Delay(5_000, ct);
var acknowledged = await IsAlertAcknowledgedAsync(alertId, ct);
if (acknowledged)
@@ -2,6 +2,8 @@ using Microsoft.EntityFrameworkCore;
public class PatientPhiMigrationService : IHostedService
{
private const int BatchSize = 500;
private readonly IServiceProvider _services;
private readonly ILogger<PatientPhiMigrationService> _logger;
@@ -19,10 +21,23 @@ public class PatientPhiMigrationService : IHostedService
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var crypto = scope.ServiceProvider.GetRequiredService<IPhiEncryptionService>();
var patients = await db.Patients.ToListAsync(ct);
var totalMigrated = 0;
Guid? afterId = null;
while (!ct.IsCancellationRequested)
{
IQueryable<Patient> query = db.Patients.OrderBy(p => p.Id);
if (afterId is Guid cursor)
query = query.Where(p => p.Id.CompareTo(cursor) > 0);
var batch = await query.Take(BatchSize).ToListAsync(ct);
if (batch.Count == 0)
break;
afterId = batch[^1].Id;
var migrated = 0;
foreach (var patient in patients)
foreach (var patient in batch)
{
if (patient.NameSearchToken is not null && crypto.IsEncrypted(patient.FirstName))
continue;
@@ -35,10 +50,18 @@ public class PatientPhiMigrationService : IHostedService
if (migrated > 0)
{
await db.SaveChangesAsync(ct);
totalMigrated += migrated;
}
db.ChangeTracker.Clear();
}
if (totalMigrated > 0)
{
_logger.LogInformation(
"PHI migration: updated {Count} patient search tokens", migrated);
"PHI migration: updated {Count} patient search tokens", totalMigrated);
}
}
public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
@@ -55,14 +55,21 @@ public sealed class DisconnectedMonitorsCheck
return 0;
}
var inserted = 0;
var encounterIds = stale.Select(e => e.EncounterId).ToList();
var alreadyOpen = (await _db.ReconciliationAlerts
.AsNoTracking()
.Where(r => r.CheckType == CheckType
&& r.ResolvedAt == null
&& r.EncounterId != null
&& encounterIds.Contains(r.EncounterId.Value))
.Select(r => r.EncounterId!.Value)
.ToListAsync(ct))
.ToHashSet();
var created = new List<ReconciliationAlert>();
foreach (var enc in stale)
{
var alreadyOpen = await _db.ReconciliationAlerts
.AnyAsync(r => r.CheckType == CheckType
&& r.EncounterId == enc.EncounterId
&& r.ResolvedAt == null, ct);
if (alreadyOpen) continue;
if (alreadyOpen.Contains(enc.EncounterId)) continue;
var lastObs = enc.LastObservationAt.HasValue
? $"last observation {enc.LastObservationAt:u}"
@@ -73,7 +80,7 @@ public sealed class DisconnectedMonitorsCheck
var rec = new ReconciliationAlert
{
Id = Guid.NewGuid(),
CheckType = CheckType, // ReconciliationCheckType enum
CheckType = CheckType,
EncounterId = enc.EncounterId,
PatientId = enc.PatientId,
Details = details,
@@ -81,16 +88,20 @@ public sealed class DisconnectedMonitorsCheck
};
_db.ReconciliationAlerts.Add(rec);
await _db.SaveChangesAsync(ct);
await _publisher.PublishAsync(rec, ct);
created.Add(rec);
_logger.LogWarning(
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {LastObs}",
CheckType, enc.EncounterId, lastObs);
inserted++;
}
return inserted;
if (created.Count > 0)
{
await _db.SaveChangesAsync(ct);
foreach (var rec in created)
await _publisher.PublishAsync(rec, ct);
}
return created.Count;
}
}
@@ -52,14 +52,21 @@ public sealed class PendingOrdersCheck
.GroupBy(o => new { o.EncounterId, o.PatientId })
.ToList();
var inserted = 0;
var encounterIds = byEncounter.Select(g => g.Key.EncounterId).ToList();
var alreadyOpen = (await _db.ReconciliationAlerts
.AsNoTracking()
.Where(r => r.CheckType == CheckType
&& r.ResolvedAt == null
&& r.EncounterId != null
&& encounterIds.Contains(r.EncounterId.Value))
.Select(r => r.EncounterId!.Value)
.ToListAsync(ct))
.ToHashSet();
var created = new List<ReconciliationAlert>();
foreach (var group in byEncounter)
{
var alreadyOpen = await _db.ReconciliationAlerts
.AnyAsync(r => r.CheckType == CheckType
&& r.EncounterId == group.Key.EncounterId
&& r.ResolvedAt == null, ct);
if (alreadyOpen) continue;
if (alreadyOpen.Contains(group.Key.EncounterId)) continue;
var lines = group.Select(o =>
$" [{o.OrderType.ToDbString()}] {o.Description} (ordered {o.OrderedAt:u}, "
@@ -70,7 +77,7 @@ public sealed class PendingOrdersCheck
var rec = new ReconciliationAlert
{
Id = Guid.NewGuid(),
CheckType = CheckType, // ReconciliationCheckType enum
CheckType = CheckType,
EncounterId = group.Key.EncounterId,
PatientId = group.Key.PatientId,
Details = details,
@@ -78,16 +85,20 @@ public sealed class PendingOrdersCheck
};
_db.ReconciliationAlerts.Add(rec);
await _db.SaveChangesAsync(ct);
await _publisher.PublishAsync(rec, ct);
created.Add(rec);
_logger.LogWarning(
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Count} stale order(s)",
CheckType, group.Key.EncounterId, group.Count());
inserted++;
}
return inserted;
if (created.Count > 0)
{
await _db.SaveChangesAsync(ct);
foreach (var rec in created)
await _publisher.PublishAsync(rec, ct);
}
return created.Count;
}
}
@@ -27,7 +27,6 @@ public sealed class UnacknowledgedAlertsCheck
var cutoff = DateTimeOffset.UtcNow
.AddMinutes(-_opts.UnacknowledgedAlertThresholdMinutes);
// Load all stale critical alerts, grouped by encounter.
var staleAlerts = await _db.ClinicalAlerts
.Where(a => a.Severity == AlertSeverity.Critical
&& a.Status == AlertStatus.Open
@@ -41,21 +40,25 @@ public sealed class UnacknowledgedAlertsCheck
return 0;
}
// Group by encounter so one reconciliation_alert covers all alerts in that encounter.
var byEncounter = staleAlerts
.GroupBy(a => new { a.EncounterId, a.PatientId })
.ToList();
var inserted = 0;
var encounterIds = byEncounter.Select(g => g.Key.EncounterId).ToList();
var alreadyOpen = (await _db.ReconciliationAlerts
.AsNoTracking()
.Where(r => r.CheckType == CheckType
&& r.ResolvedAt == null
&& r.EncounterId != null
&& encounterIds.Contains(r.EncounterId.Value))
.Select(r => r.EncounterId!.Value)
.ToListAsync(ct))
.ToHashSet();
var created = new List<ReconciliationAlert>();
foreach (var group in byEncounter)
{
// Deduplication: skip if an open reconciliation_alert already exists
// for this check type and encounter (partial index makes this fast).
var alreadyOpen = await _db.ReconciliationAlerts
.AnyAsync(r => r.CheckType == CheckType
&& r.EncounterId == group.Key.EncounterId
&& r.ResolvedAt == null, ct);
if (alreadyOpen) continue;
if (alreadyOpen.Contains(group.Key.EncounterId)) continue;
var alertIds = group.Select(a => a.Id).ToList();
var oldest = group.Min(a => a.TriggeredAt);
@@ -66,7 +69,7 @@ public sealed class UnacknowledgedAlertsCheck
var rec = new ReconciliationAlert
{
Id = Guid.NewGuid(),
CheckType = CheckType, // ReconciliationCheckType enum
CheckType = CheckType,
EncounterId = group.Key.EncounterId,
PatientId = group.Key.PatientId,
Details = details,
@@ -74,16 +77,20 @@ public sealed class UnacknowledgedAlertsCheck
};
_db.ReconciliationAlerts.Add(rec);
await _db.SaveChangesAsync(ct);
await _publisher.PublishAsync(rec, ct);
created.Add(rec);
_logger.LogWarning(
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Details}",
CheckType, group.Key.EncounterId, details);
inserted++;
}
return inserted;
if (created.Count > 0)
{
await _db.SaveChangesAsync(ct);
foreach (var rec in created)
await _publisher.PublishAsync(rec, ct);
}
return created.Count;
}
}
@@ -78,16 +78,8 @@ public class SepsisEngineService : BackgroundService
}
catch (Exception ex)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
consumer.Commit(result);
continue;
}
_logger.LogError(ex,
"SepsisEngine failed on topic={Topic} offset={Offset} — will retry",
result?.Topic, result?.Offset.Value);
await Task.Delay(2000, stoppingToken);
await KafkaConsumerRetry.HandleFailureAsync(
consumer, result, ex, guard, _logger, nameof(SepsisEngineService), stoppingToken);
}
}
}
@@ -55,7 +55,7 @@ public class SofaScoringService : BackgroundService
{
var gcsEvt = JsonSerializer.Deserialize<GcsScoredEvent>(
result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
ClinicalEventJson.Options)!;
var outcome = await detector.ProcessGcsScoredAsync(
gcsEvt.EncounterId, gcsEvt.PatientId, stoppingToken);
@@ -73,7 +73,7 @@ public class SofaScoringService : BackgroundService
{
var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
ClinicalEventJson.Options)!;
var outcome = await detector.ProcessObservationAsync(
evt.EncounterId,
@@ -102,16 +102,8 @@ public class SofaScoringService : BackgroundService
}
catch (Exception ex)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
consumer.Commit(result);
continue;
}
_logger.LogError(ex,
"SofaScoringService failed on topic={Topic} offset={Offset} — will retry",
result?.Topic, result?.Offset.Value);
await Task.Delay(2000, stoppingToken);
await KafkaConsumerRetry.HandleFailureAsync(
consumer, result, ex, guard, _logger, nameof(SofaScoringService), stoppingToken);
}
}
}
@@ -34,6 +34,7 @@ public class ThresholdCacheLoader : IHostedService
{
var cache = _redis.GetDatabase();
var batch = cache.CreateBatch();
var setTasks = new List<Task>(thresholds.Count);
foreach (var t in thresholds)
{
@@ -45,10 +46,11 @@ public class ThresholdCacheLoader : IHostedService
t.WarningHigh,
t.CriticalHigh
});
_ = batch.StringSetAsync($"threshold:{t.ObservationCode}", json);
setTasks.Add(batch.StringSetAsync($"threshold:{t.ObservationCode}", json));
}
batch.Execute();
await Task.WhenAll(setTasks);
_logger.LogInformation("Loaded {Count} alert thresholds into Redis cache", thresholds.Count);
return;
}
@@ -46,7 +46,7 @@ public class TrendAnalyzerService : BackgroundService
var evt = JsonSerializer.Deserialize<TrendObservationEvent>(
result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
ClinicalEventJson.Options)!;
using var scope = _services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>();
@@ -77,16 +77,8 @@ public class TrendAnalyzerService : BackgroundService
}
catch (Exception ex)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
consumer.Commit(result);
continue;
}
_logger.LogError(ex,
"TrendAnalyzerService failed on topic={Topic} offset={Offset} — will retry",
result?.Topic, result?.Offset.Value);
await Task.Delay(2000, stoppingToken);
await KafkaConsumerRetry.HandleFailureAsync(
consumer, result, ex, guard, _logger, nameof(TrendAnalyzerService), stoppingToken);
}
}
}
@@ -46,7 +46,7 @@ public class WarningAlertService : BackgroundService
var evt = JsonSerializer.Deserialize<WarningObservationEvent>(
result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
ClinicalEventJson.Options)!;
using var scope = _services.CreateScope();
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
@@ -68,16 +68,8 @@ public class WarningAlertService : BackgroundService
}
catch (Exception ex)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
consumer.Commit(result);
continue;
}
_logger.LogError(ex,
"WarningAlertService failed on topic={Topic} offset={Offset} — will retry",
result?.Topic, result?.Offset.Value);
await Task.Delay(2000, stoppingToken);
await KafkaConsumerRetry.HandleFailureAsync(
consumer, result, ex, guard, _logger, nameof(WarningAlertService), stoppingToken);
}
}
}
@@ -9,7 +9,8 @@ public static class DataLakeEventParser
{
public static ObservationRow ParseObservationRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
var encounterId = GetString(d, "encounterId");
var observationId = GetString(d, "observationId");
if (string.IsNullOrEmpty(observationId))
@@ -31,7 +32,8 @@ public static class DataLakeEventParser
public static AlertRow ParseAlertRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
return new AlertRow(
AlertId : GetString(d, "alertId"),
EncounterId : GetString(d, "encounterId"),
@@ -47,7 +49,8 @@ public static class DataLakeEventParser
public static EncounterStatusRow ParseEncounterRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
return new EncounterStatusRow(
EncounterId : GetString(d, "encounterId"),
PatientId : GetString(d, "patientId"),
@@ -62,7 +65,7 @@ public static class DataLakeEventParser
{
try
{
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var ts = topic switch
{
var t when t == topics.ObservationRecorded => GetTimestamp(doc.RootElement, "recordedAt"),
@@ -11,6 +11,13 @@ public sealed class DataLakeOptions
// Production: 300 seconds (5 minutes). Tests: 10 seconds.
public int FlushIntervalSeconds { get; init; } = 300;
/// <summary>
/// Hard cap on in-memory buffered events across all partitions. When reached,
/// consume seeks back and pauses until a flush frees space (prevents OOM when
/// MinIO is down while Kafka keeps delivering).
/// </summary>
public int MaxBufferedEvents { get; init; } = 50_000;
// MinIO bucket. The discharge summary worker from Phase 6 uses the same bucket
// under a different prefix — all VigilCare data stays in one bucket.
public string BucketName { get; init; } = "vigilcare";
@@ -1,6 +1,7 @@
using System.Text.Json;
using Confluent.Kafka;
using Microsoft.Extensions.Options;
using Minio;
using Minio.DataModel.Args;
public sealed class DataLakeWriterService : BackgroundService
@@ -8,6 +9,7 @@ public sealed class DataLakeWriterService : BackgroundService
private readonly KafkaOptions _kafkaOptions;
private readonly DataLakeOptions _opts;
private readonly MinioOptions _minioOpts;
private readonly IMinioClient _minio;
private readonly ILogger<DataLakeWriterService> _logger;
// Buffer key: identifies one Parquet file-to-be.
@@ -24,11 +26,13 @@ public sealed class DataLakeWriterService : BackgroundService
IOptions<KafkaOptions> kafkaOptions,
IOptions<DataLakeOptions> opts,
IOptions<MinioOptions> minioOpts,
IMinioClient minio,
ILogger<DataLakeWriterService> logger)
{
_kafkaOptions = kafkaOptions.Value;
_opts = opts.Value;
_minioOpts = minioOpts.Value;
_minio = minio;
_logger = logger;
}
@@ -51,8 +55,8 @@ public sealed class DataLakeWriterService : BackgroundService
});
_logger.LogInformation(
"DataLakeWriterService started. FlushCount={FlushCount} FlushIntervalSeconds={FlushInterval}",
_opts.FlushCount, _opts.FlushIntervalSeconds);
"DataLakeWriterService started. FlushCount={FlushCount} FlushIntervalSeconds={FlushInterval} MaxBufferedEvents={MaxBuffered}",
_opts.FlushCount, _opts.FlushIntervalSeconds, _opts.MaxBufferedEvents);
var lastFlush = DateTimeOffset.UtcNow;
@@ -72,7 +76,24 @@ public sealed class DataLakeWriterService : BackgroundService
}
if (result is not null)
{
var totalBefore = _buffer.Values.Sum(v => v.Count);
if (totalBefore >= _opts.MaxBufferedEvents)
{
// Consume advanced the position — seek back so we do not drop the message.
consumer.Seek(result.TopicPartitionOffset);
_logger.LogCritical(
"[DATA-LAKE] Buffer at cap {Cap} — pausing consume until flush frees space",
_opts.MaxBufferedEvents);
await FlushAsync(consumer, ct);
lastFlush = DateTimeOffset.UtcNow;
if (_buffer.Values.Sum(v => v.Count) >= _opts.MaxBufferedEvents)
await Task.Delay(5_000, ct);
continue;
}
AddToBuffer(result);
}
var totalBuffered = _buffer.Values.Sum(v => v.Count);
var shouldFlushCount = totalBuffered >= _opts.FlushCount;
@@ -245,18 +266,18 @@ public sealed class DataLakeWriterService : BackgroundService
private async Task UploadToMinioAsync(string objectKey, byte[] bytes, CancellationToken ct)
{
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _opts.BucketName;
var exists = await client.BucketExistsAsync(
var exists = await _minio.BucketExistsAsync(
new BucketExistsArgs().WithBucket(bucket), ct);
if (!exists)
await client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), ct);
await _minio.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), ct);
await client.PutObjectAsync(new PutObjectArgs()
await using var stream = new MemoryStream(bytes);
await _minio.PutObjectAsync(new PutObjectArgs()
.WithBucket(bucket)
.WithObject(objectKey)
.WithStreamData(new MemoryStream(bytes))
.WithStreamData(stream)
.WithObjectSize(bytes.Length)
.WithContentType("application/octet-stream"),
ct);
@@ -0,0 +1,13 @@
using System.Text.Json;
/// <summary>
/// Shared JSON options for Kafka clinical event deserialization.
/// <see cref="JsonSerializerOptions"/> construction is expensive — reuse one instance.
/// </summary>
public static class ClinicalEventJson
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true
};
}
@@ -0,0 +1,55 @@
using Confluent.Kafka;
/// <summary>
/// Shared transient-failure handling for Kafka consumers that use
/// <see cref="PoisonPillGuard"/>. After <c>Consume</c>, the client position
/// advances; without <c>Seek</c>, the next successful <c>Commit</c> would skip
/// the failed offset. This helper seeks back before delaying so retries truly
/// reprocess the same message.
/// </summary>
public static class KafkaConsumerRetry
{
public static Task HandleFailureAsync(
IConsumer<string, string> consumer,
ConsumeResult<string, string>? result,
Exception ex,
PoisonPillGuard guard,
ILogger logger,
string serviceName,
CancellationToken ct,
int delayMs = 2000) =>
HandleFailureAsync(
seek: tpo => consumer.Seek(tpo),
commit: r => consumer.Commit(r),
result, ex, guard, logger, serviceName, ct, delayMs);
/// <summary>
/// Testable overload — production code should prefer the <see cref="IConsumer{TKey,TValue}"/> overload.
/// </summary>
public static async Task HandleFailureAsync(
Action<TopicPartitionOffset> seek,
Action<ConsumeResult<string, string>> commit,
ConsumeResult<string, string>? result,
Exception ex,
PoisonPillGuard guard,
ILogger logger,
string serviceName,
CancellationToken ct,
int delayMs = 2000)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
commit(result);
return;
}
logger.LogError(ex,
"{Service} failed on topic={Topic} offset={Offset} — will retry",
serviceName, result?.Topic, result?.Offset.Value);
if (result is not null)
seek(result.TopicPartitionOffset);
await Task.Delay(delayMs, ct);
}
}
+4
View File
@@ -1,6 +1,7 @@
using Elastic.Clients.Elasticsearch;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Minio;
using Prometheus;
using Serilog;
using StackExchange.Redis;
@@ -16,6 +17,7 @@ using Microsoft.AspNetCore.Authorization;
using System.Text;
using Microsoft.OpenApi;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Options;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
@@ -114,6 +116,8 @@ try
builder.Configuration.GetSection(RabbitMqOptions.Section));
builder.Services.Configure<MinioOptions>(
builder.Configuration.GetSection(MinioOptions.Section));
builder.Services.AddSingleton<IMinioClient>(sp =>
MinioClientFactory.Build(sp.GetRequiredService<IOptions<MinioOptions>>().Value));
builder.Services.AddSingleton<RabbitMqTopologyProvisioner>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<RabbitMqTopologyProvisioner>());
@@ -8,11 +8,16 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
{
private readonly AppDbContext _db;
private readonly MinioOptions _minioOpts;
private readonly IMinioClient _minio;
public DischargeSummaryService(AppDbContext db, IOptions<MinioOptions> minioOpts)
public DischargeSummaryService(
AppDbContext db,
IOptions<MinioOptions> minioOpts,
IMinioClient minio)
{
_db = db;
_minioOpts = minioOpts.Value;
_minio = minio;
}
public async Task<DischargeSummaryInfo> GetInfoAsync(Guid encounterId, CancellationToken ct = default)
@@ -68,12 +73,11 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
"DISCHARGE_SUMMARY_PENDING");
}
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _minioOpts.BucketName;
var objectKey = ObjectKey(encounterId);
var ms = new MemoryStream();
await client.GetObjectAsync(new GetObjectArgs()
await _minio.GetObjectAsync(new GetObjectArgs()
.WithBucket(bucket)
.WithObject(objectKey)
.WithCallbackStream(stream => stream.CopyTo(ms)), ct);
@@ -84,13 +88,12 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
private async Task<bool> ObjectExistsAsync(Guid encounterId, CancellationToken ct)
{
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _minioOpts.BucketName;
var objectKey = ObjectKey(encounterId);
try
{
await client.StatObjectAsync(new StatObjectArgs()
await _minio.StatObjectAsync(new StatObjectArgs()
.WithBucket(bucket)
.WithObject(objectKey), ct);
return true;
@@ -74,13 +74,12 @@ public class EncounterService : IEncounterService
var encounterIds = encounters.Select(e => e.Id).ToList();
var news2ByEncounter = (await _db.News2Scores
var news2ByEncounter = await _db.News2Scores
.AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId)
.ToDictionary(g => g.Key, g => g.First());
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
.ToDictionaryAsync(s => s.EncounterId);
var openAlertCounts = await _db.ClinicalAlerts
.AsNoTracking()
@@ -89,29 +88,26 @@ public class EncounterService : IEncounterService
.Select(g => new { EncounterId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.EncounterId, x => x.Count);
var bundlesByEncounter = (await _db.SepsisBundles
var bundlesByEncounter = await _db.SepsisBundles
.AsNoTracking()
.Where(b => encounterIds.Contains(b.EncounterId))
.OrderByDescending(b => b.RecognizedAt)
.ToListAsync())
.GroupBy(b => b.EncounterId)
.ToDictionary(g => g.Key, g => g.First());
.Select(g => g.OrderByDescending(b => b.RecognizedAt).First())
.ToDictionaryAsync(b => b.EncounterId);
var sofaByEncounter = (await _db.SofaScores
var sofaByEncounter = await _db.SofaScores
.AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId)
.ToDictionary(g => g.Key, g => g.First());
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
.ToDictionaryAsync(s => s.EncounterId);
var gcsByEncounter = (await _db.GcsScores
var gcsByEncounter = await _db.GcsScores
.AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId)
.ToDictionary(g => g.Key, g => g.First());
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
.ToDictionaryAsync(s => s.EncounterId);
var lastObservationByEncounter = await _db.Observations
.AsNoTracking()
@@ -246,8 +242,15 @@ public class EncounterService : IEncounterService
});
}
// Bound timeline payloads for long-stay encounters (recent window + row caps).
const int maxEventsPerType = 500;
var timelineCutoff = DateTimeOffset.UtcNow.AddDays(-7);
var observations = await _db.Observations
.Where(o => o.EncounterId == encounterId)
.AsNoTracking()
.Where(o => o.EncounterId == encounterId && o.RecordedAt >= timelineCutoff)
.OrderByDescending(o => o.RecordedAt)
.Take(maxEventsPerType)
.Select(o => new
{
type = "observation",
@@ -260,7 +263,10 @@ public class EncounterService : IEncounterService
events.AddRange(observations);
var alerts = await _db.ClinicalAlerts
.Where(a => a.EncounterId == encounterId)
.AsNoTracking()
.Where(a => a.EncounterId == encounterId && a.TriggeredAt >= timelineCutoff)
.OrderByDescending(a => a.TriggeredAt)
.Take(maxEventsPerType)
.Select(a => new
{
type = "alert",
@@ -273,7 +279,10 @@ public class EncounterService : IEncounterService
events.AddRange(alerts);
var orders = await _db.Orders
.Where(o => o.EncounterId == encounterId)
.AsNoTracking()
.Where(o => o.EncounterId == encounterId && o.OrderedAt >= timelineCutoff)
.OrderByDescending(o => o.OrderedAt)
.Take(maxEventsPerType)
.Select(o => new
{
type = "order",
@@ -286,7 +295,10 @@ public class EncounterService : IEncounterService
events.AddRange(orders);
var medications = await _db.MedicationAdministrations
.Where(m => m.EncounterId == encounterId)
.AsNoTracking()
.Where(m => m.EncounterId == encounterId && m.AdministeredAt >= timelineCutoff)
.OrderByDescending(m => m.AdministeredAt)
.Take(maxEventsPerType)
.Select(m => new
{
type = "medication",
@@ -1,6 +1,7 @@
public interface IPhiAccessLogService
{
Task LogViewAsync(Guid patientId, string resourcePath);
Task LogViewsAsync(IReadOnlyList<Guid> patientIds, string resourcePath);
Task LogListAsync(string resourcePath, int resultCount, string? searchQuery = null);
Task LogCreateAsync(Guid patientId, string resourcePath);
Task LogUpdateAsync(Guid patientId, string resourcePath);
@@ -197,7 +197,6 @@ public class ObservationService : IObservationService
if (encounter.Status != EncounterStatus.Active)
throw new ValidationException("Encounter not active.", "ENCOUNTER_NOT_ACTIVE");
await using var tx = await _db.Database.BeginTransactionAsync(ct);
try
{
var observation = new Observation
@@ -267,11 +266,10 @@ public class ObservationService : IObservationService
}, obs.EncounterId.ToString()));
await _db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
}
catch (DbUpdateException ex) when (IsUniqueViolation(ex))
{
await tx.RollbackAsync(ct);
_db.ChangeTracker.Clear();
// silent skip — idempotency key already applied
}
}
@@ -113,8 +113,9 @@ public class PatientService : IPatientService
var path = _http.HttpContext?.Request.Path.Value ?? "/api/v1/patients";
await _phiAccess.LogListAsync(path, patients.Count, q);
foreach (var p in patients)
await _phiAccess.LogViewAsync(p.Id, $"{path}?page={page}");
await _phiAccess.LogViewsAsync(
patients.Select(p => p.Id).ToList(),
$"{path}?page={page}");
return new PagedResult<Patient>(patients, page, pageSize, total);
}
@@ -27,6 +27,37 @@ public class PhiAccessLogService : IPhiAccessLogService
public async Task LogViewAsync(Guid patientId, string resourcePath) =>
await WriteAsync(PhiAccessType.View, patientId, resourcePath);
public async Task LogViewsAsync(IReadOnlyList<Guid> patientIds, string resourcePath)
{
if (patientIds.Count == 0) return;
if (!_currentUser.IsAuthenticated || _currentUser.UserId is null) return;
var now = DateTimeOffset.UtcNow;
var userId = _currentUser.UserId.Value;
var display = _currentUser.DisplayName ?? _currentUser.Username ?? "Unknown";
var ip = _currentUser.IpAddress;
var correlationId = _http.HttpContext?.Items["CorrelationId"]?.ToString();
foreach (var patientId in patientIds)
{
_db.PhiAccessLogs.Add(new PhiAccessLog
{
Id = Guid.NewGuid(),
AccessType = PhiAccessType.View,
PatientId = patientId,
UserId = userId,
UserDisplayName = display,
ResourcePath = resourcePath,
IpAddress = ip,
CorrelationId = correlationId,
AccessedAt = now
});
}
await _db.SaveChangesAsync();
_metrics.PhiAccessLogsTotal.WithLabels(PhiAccessType.View.ToDbString()).Inc(patientIds.Count);
}
public async Task LogCreateAsync(Guid patientId, string resourcePath) =>
await WriteAsync(PhiAccessType.Create, patientId, resourcePath);
@@ -176,19 +176,21 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
public async Task StopAsync(CancellationToken cancellationToken)
{
var running = new List<Task>();
foreach (var ctx in _runs.Values)
{
if (ctx.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running)
ctx.Cts.Cancel();
if (ctx.ExecuteTask is not null)
running.Add(ctx.ExecuteTask);
}
var deadline = DateTimeOffset.UtcNow.AddSeconds(5);
while (DateTimeOffset.UtcNow < deadline
&& _runs.Values.Any(c =>
c.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running))
{
await Task.Delay(50, cancellationToken);
}
if (running.Count == 0) return;
var all = Task.WhenAll(running);
var completed = await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(5), cancellationToken));
if (completed != all)
_logger.LogWarning("Simulation stop timed out waiting for {Count} run task(s)", running.Count);
}
private async Task<SimulationRunState> RegisterAndStartAsync(
@@ -224,7 +226,7 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
if (!_runs.TryAdd(runId, ctx))
throw new ConflictException("Failed to register simulation run.", "SIMULATION_REGISTER_FAILED");
_ = Task.Run(() => ExecuteAsync(ctx, CancellationToken.None), CancellationToken.None);
ctx.ExecuteTask = Task.Run(() => ExecuteAsync(ctx, CancellationToken.None), CancellationToken.None);
return state.Snapshot();
}
@@ -365,5 +367,6 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
public SimulationRunState State { get; } = state;
public CancellationTokenSource Cts { get; } = cts;
public ScenarioFile Scenario { get; } = scenario;
public Task? ExecuteTask { get; set; }
}
}
+23 -5
View File
@@ -41,18 +41,30 @@ public class TrendDetector
var cache = _redis.GetDatabase();
var key = TrendCalculator.HistoryKey(encounterId, observationCode);
var lockKey = key + ":lock";
// Append new entry to history list
List<TrendHistoryEntry> history;
var entry = new TrendHistoryEntry(value, recordedAt);
var cutoff = recordedAt.AddMinutes(-_options.WindowMinutes);
// Short Redis lock so concurrent observations for the same key do not lose history.
var locked = false;
for (var attempt = 0; attempt < 8 && !locked; attempt++)
{
locked = await cache.StringSetAsync(
lockKey, "1", TimeSpan.FromSeconds(2), When.NotExists);
if (!locked)
await Task.Delay(15, ct);
}
try
{
var historyJson = await cache.StringGetAsync(key);
var history = historyJson.HasValue
history = historyJson.HasValue
? JsonSerializer.Deserialize<List<TrendHistoryEntry>>(historyJson!) ?? new()
: new List<TrendHistoryEntry>();
history.Add(entry);
// Trim to max entries and evict entries outside window
var cutoff = recordedAt.AddMinutes(-_options.WindowMinutes);
history = history
.Where(e => e.RecordedAt >= cutoff)
.TakeLast(_options.MaxHistoryEntries)
@@ -62,6 +74,12 @@ public class TrendDetector
key,
JsonSerializer.Serialize(history),
TimeSpan.FromSeconds(_options.HistoryTtlSeconds));
}
finally
{
if (locked)
await cache.KeyDeleteAsync(lockKey);
}
if (history.Count < 2)
return new TrendResult(TrendOutcome.InsufficientHistory, observationCode);
+2 -1
View File
@@ -84,7 +84,8 @@
},
"DataLake": {
"FlushCount": 1000,
"FlushIntervalSeconds": 300
"FlushIntervalSeconds": 300,
"MaxBufferedEvents": 50000
},
"TrendDetection": {
"WindowMinutes": 30,
+4
View File
@@ -58,3 +58,7 @@ Kafka consumer lag, ready probe failing, gateway offline, unacked CRITICAL alert
Optionally a second signal for the ward gateway with
`Application = 'VigilCare.WardGateway'`.
## Related
- [CPU / Memory Remediation Roadmap (Phases 41–44)](../performance/cpu-memory-remediation-roadmap.md)
@@ -0,0 +1,96 @@
# VigilCare Clinical — CPU / Memory Remediation Roadmap
**Internal document | Phases 41–44**
**Prerequisites:** Phases 1–40 clinical platform, climate resilience (20–24), and alert optimization foundations in place.
**Source:** Static performance/reliability audit of `VigilCareClinicalAPI` and `VigilCare.WardGateway` (CPU, memory, EF, HttpClient, concurrency).
---
## Problem Statement
Under normal traffic the platform is largely correct. Under **peak observation storms**, **sustained outages** (MinIO / central unreachable), and **long-running process lifetime**, several defects cause:
| Risk | Symptom |
|------|---------|
| Silent Kafka loss | Transient consumer failures advance past failed offsets (“retry” never re-seeks) |
| Rabbit channel corruption | Prefetch > 1 + async handlers sharing one `IModel` |
| Unbounded memory / disk | DataLake in-memory buffer and gateway `buffered_sync_items` grow without a hard cap |
| GC / socket pressure | Undisposed `JsonDocument`, per-upload MinIO clients, per-message `JsonSerializerOptions` |
| Sync / API latency | Per-item `SaveChanges`, N+1 reconciliation and HTTP detail fetches, unbounded timeline loads |
---
## Design Principles
1. **Correctness before throughput** — never commit past a failed Kafka offset without intentional poison skip.
2. **Bound everything that can grow under outage** — buffers must plateau; lag is preferable to OOM.
3. **Dispose pooled / unmanaged resources** on every hot path.
4. **Measure with tools, not invented numbers** — `dotnet-counters`, lag metrics, existing unit tests.
---
## Phase Map
| Phase | Name | Audit findings | Status |
|-------|------|----------------|--------|
| **41** | Correctness & backpressure | 1, 2, 3, 7 | Complete |
| **42** | Resource leaks & GC | 4, 5, 8, 15 | Complete |
| **43** | Throughput hot paths | 6, 9, 10, 11, 12, 13 | Complete |
| **44** | Hardening | 14, 16, 17, 18, 19, 20 | Complete |
### Dependency graph
```
Phase 41 → Phase 42 → Phase 43 → Phase 44
```
Docs (this folder) are written first; checklist items flip to **Complete** as code lands.
### Phase plans
- [phase-41-correctness-backpressure.md](phase-41-correctness-backpressure.md)
- [phase-42-resource-leaks-gc.md](phase-42-resource-leaks-gc.md)
- [phase-43-throughput-hot-paths.md](phase-43-throughput-hot-paths.md)
- [phase-44-hardening.md](phase-44-hardening.md)
---
## Severity Matrix (audit reference)
| ID | Severity | Finding |
|----|----------|---------|
| 1 | Critical | Kafka failure path advances past failed offset |
| 2 | High | RabbitMQ `IModel` + prefetch > 1 |
| 3 | High | DataLake buffer unbounded on flush failure |
| 4 | High | Undisposed `JsonDocument` |
| 5 | High | MinIO client per upload, never disposed |
| 6 | High | Clinical sync per-observation SaveChanges |
| 7 | High | Gateway buffered sync unbounded |
| 8 | Medium–High | Per-message `JsonSerializerOptions` |
| 9 | High | Patient list PHI N+1 SaveChanges |
| 10 | Medium–High | Reconciliation N+1 |
| 11 | High | Encounter replica sync N+1 HTTP / HttpClient misuse |
| 12 | Medium | Encounter timeline unbounded |
| 13 | Medium | Ward list over-fetches score history |
| 14 | Medium | Simulation fire-and-forget Task.Run |
| 15 | Medium | Redis threshold batch tasks discarded |
| 16 | Medium | Trend Redis RMW race |
| 17 | Medium | Paging worker long poll hold |
| 18 | Medium | Parquet double allocation |
| 19 | Medium | PHI migration loads full table |
| 20 | Low | Health-check Task.Run blocking |
---
## Diagnostic Tools
| Symptom | Tools |
|---------|--------|
| Allocations / GC | `dotnet-counters`, `dotnet-gcdump` |
| Leaks | `dotnet-dump` + SOS |
| Kafka loss / lag | Consumer lag + `kafka_poison_pills_skipped_total` |
| DB amplification | EF logging, `pg_stat_statements` |
Related: [../ops/production-observability.md](../ops/production-observability.md)
@@ -0,0 +1,47 @@
# Phase 41 — Correctness & Backpressure
| Field | Value |
|-------|-------|
| Status | Complete |
| Audit findings | 1, 2, 3, 7 |
| Depends on | Docs roadmap |
## Goal
Stop silent Kafka message loss, make RabbitMQ channel use safe under concurrency, and hard-cap DataLake / gateway buffers so outages produce lag instead of OOM or unbounded disk growth.
## What exists
- Kafka consumers use `PoisonPillGuard` and log “will retry” but do not `Seek` after transient failure
- Escalation / clinical sync / discharge / local escalation use `prefetchCount: 5` with shared `IModel`
- `DataLakeWriterService` retains failed partition buffers while continuing to consume
- `BufferedSyncWriter.Enqueue` has no depth limit
## What to build
- [x] Shared Kafka Seek-on-retry helper used by all scoring / indexing / notification consumers
- [x] NotificationPublisher: Seek + delay on transient failure (same as scorers)
- [x] Unit tests for Seek-retry behavior; keep PoisonPillGuard tests green
- [x] RabbitMQ `prefetchCount: 1` on Escalation, ClinicalSync, DischargeSummary, LocalEscalation
- [x] `DataLakeOptions.MaxBufferedEvents` + pause/skip buffer when at cap after failed flush
- [x] Gateway sync buffer max depth (config) with reject when full (`SYNC_BUFFER_FULL`)
## Key files
- `VigilCareClinicalAPI/Infrastructure/PoisonPillGuard.cs`
- `VigilCareClinicalAPI/BackgroundServices/*ScoringService.cs`, `EsIndexerService.cs`, `NotificationPublisherService.cs`
- `VigilCareClinicalAPI/DataLake/DataLakeWriterService.cs`, `DataLakeOptions.cs`
- Rabbit workers under `BackgroundServices/Notifications/` and Ward `LocalEscalationWorkerService`
- `VigilCare.WardGateway/Services/BufferedSyncWriter.cs`
## Acceptance criteria
- Transient failure re-seeks to the same offset until success or intentional poison skip
- Rabbit workers with former prefetch 5 now use prefetch 1
- Forced MinIO / central outage: buffers plateau at configured caps
- Affected unit tests green
## Verification notes
- Added `KafkaConsumerRetry` + unit tests for Seek vs poison Commit.
- Consumers wired to helper; Rabbit prefetch set to 1; DataLake/Gateway caps configured (50_000 default).
@@ -0,0 +1,37 @@
# Phase 42 — Resource Leaks & GC
| Field | Value |
|-------|-------|
| Status | Complete |
| Audit findings | 4, 5, 8, 15 |
| Depends on | Phase 41 |
## Goal
Dispose pooled JSON parsers, stop creating MinIO clients per upload, reuse `JsonSerializerOptions` on Kafka hot paths, and await Redis threshold batch tasks.
## What to build
- [x] `using` for all hot-path `JsonDocument.Parse` (DataLakeEventParser + Rabbit/Kafka handlers)
- [x] Long-lived `IMinioClient` via DI; dispose `MemoryStream` on upload
- [x] Static shared `JsonSerializerOptions` on News2/Sofa/Gcs/Warning/Trend consumers (`ClinicalEventJson`)
- [x] Await Redis `StringSetAsync` tasks after `batch.Execute()` in both ThresholdCacheLoaders
## Key files
- `VigilCareClinicalAPI/DataLake/DataLakeEventParser.cs`
- `VigilCareClinicalAPI/Storage/MinioClientFactory.cs`
- `VigilCareClinicalAPI/DataLake/DataLakeWriterService.cs`
- Kafka scoring consumers; ThresholdCacheLoader (API + WardGateway)
## Acceptance criteria
- No undisposed JsonDocument on listed paths
- MinIO not constructed per upload
- Threshold cache load awaits all sets
- DataLake parser tests pass
## Verification notes
- MinIO registered as singleton `IMinioClient` in Program.cs; DataLake/Discharge paths inject it.
- Hot-path JsonDocument uses `using`; scoring consumers share `ClinicalEventJson.Options`.
@@ -0,0 +1,41 @@
# Phase 43 — Throughput Hot Paths
| Field | Value |
|-------|-------|
| Status | Complete |
| Audit findings | 6, 9, 10, 11, 12, 13 |
| Depends on | Phase 42 |
## Goal
Cut DB and HTTP round-trips under peak traffic and gateway catch-up without changing clinical scoring semantics.
## What to build
- [x] Clinical sync: removed nested TX around ApplySyncedObservation (SaveChanges + Clear on conflict)
- [x] PHI list audit: `LogViewsAsync` batch + one SaveChanges
- [x] Reconciliation checks: preload open keys + single SaveChanges
- [x] Ward `AddHttpClient("central")`: BaseAddress + 30s timeout; per-request headers (no DefaultRequestHeaders mutation)
- [x] Encounter replica sync: upsert from list summary when patient exists; detail GET only for new patients
- [x] Encounter timeline: 7-day window + Take(500) per event type
- [x] Ward list: latest-per-encounter GroupBy/First for NEWS2/SOFA/GCS/sepsis
## Key files
- `ClinicalSyncBatchProcessor.cs`, `ObservationService.cs`
- `PatientService.cs`, `PhiAccessLogService.cs`
- Reconciliation checks under `BackgroundServices/Reconciliation/`
- `VigilCare.WardGateway/Program.cs`, `EncounterReplicaSyncService.cs`
- `EncounterService.cs`
## Acceptance criteria
- Fewer commits per sync batch / patient list / reconciliation run
- Named HttpClient configured once with timeout
- Timeline and ward-list score queries bounded
- Relevant tests green
## Verification notes
- API + WardGateway build green after changes.
- Focused unit tests (PoisonPill/KafkaConsumerRetry/DataLakeEventParser) green.
+39
View File
@@ -0,0 +1,39 @@
# Phase 44 — Hardening
| Field | Value |
|-------|-------|
| Status | Complete |
| Audit findings | 14, 16, 17, 18, 19, 20 |
| Depends on | Phase 43 |
## Goal
Tighten lifecycle, concurrency, and startup paths that worsen under long-running operation.
## What to build
- [x] SimulationRunner: track run Task; await on stop (5s timeout)
- [x] TrendDetector: Redis lock around GET/modify/SET history
- [x] Paging workers: JsonDocument `using` (Phase 42); poll interval 5s (was 2s)
- [x] PatientPhiMigrationService: keyset-batched updates (500)
- [x] Light polish: deferred Parquet rewrite; health checks unchanged (low severity)
## Key files
- `SimulationRunner.cs`
- `TrendDetector.cs`
- `PagingWorkerService.cs`, `LocalPagingWorkerService.cs`
- `PatientPhiMigrationService.cs`
- `ParquetFileBuilder.cs`, Kafka/Rabbit health checks
## Acceptance criteria
- Simulation stop awaits tracked run task
- Trend history correct under concurrency
- PHI migration does not load fully migrated rows
- Suite green
## Verification notes
- Simulation stop awaits tracked execute tasks.
- Trend history updates under a short Redis lock key.