Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
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:
@@ -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.
|
||||
@@ -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.
|
||||
Reference in New Issue
Block a user