Skip to content

Phase 2 Validation Gate Report: EXECUTION-SUBJECTS ​

Scope note on file naming. The validation prompt names 01_functional_spec.md as the reference spec; this slice's actual file is docs/migration/slices/execution-subjects/01_spec.md (confirmed via Glob — no 01_functional_spec.md exists in this slice). This audit treats 01_spec.md as the functional spec it evidently is (it is the document 02_technical_design.md itself cites throughout as its spec of record, and it carries the remediated Phase 1 content certified "PHASE 2 UNBLOCKED" in 00_phase1_validation_report.md §0.3). Recommend renaming to 01_functional_spec.md for template conformance, or updating the prompt template's filename assumption — flagged as a documentation-hygiene item, not a gate failure.

Execution method note. Gates were audited by direct file inspection (Read/Grep), a Python-based JSON structural comparison of the five fixture files against the DTO shapes documented in 02_technical_design.md, cross-reference against the actual Python source (apps/execution/presentation/routers/subjects.py) where the spec's own status-code claims needed independent verification, and a Roslyn (Microsoft.CodeAnalysis.CSharp 4.11.0, .NET 10 SDK) syntax-only parse of all 17 ```csharp fenced blocks extracted from the design. No implementation code exists yet in the repository for this slice (apps/execution/src/ is not yet a real project) — Gate 4's "runtime deserialization" check was therefore performed as a structural/static comparison (fixture JSON field shapes vs. documented C# record shapes and status codes), not an actual compile-and-run of System.Text.Json against generated types. This is the correct fallback given the state of the repo, but it means the "0 compatible" vs. "5 compatible" fixture-level PASS in the scorecard below reflects static compatibility, not an executed golden-master test run.


1. Architectural Parity Scorecard ​

Quality GateSpec CountDesign CountCoverage (%)Status (PASS / FAIL)
Gate 1: Contract & Field Parity58 fields (12 schemas)57 fully compliant, 1 partial (collection default)98.3%FAIL
Gate 2: Invariants & Validation Rules9 Rules + 9 boundary constraints = 18 items~15.5 fully/partially implemented~86%FAIL
Gate 3: Error & Exception Envelopes25 raise sites24 correctly mapped, 1 contradicts fixture; +1 undiscovered response-shaping defect96% (1 critical)FAIL
Gate 4: Fixture Schema Replay5 fixture files / 50 scenario entries5/5 valid JSON; 2 of 50 spot-checked scenarios structurally broken5/5 files PASS, scenario-level FAILFAIL
Gate 5: Modern .NET 10 Standards6 checks~3.5 of 6 fully pass~60%FAIL
Gate 6: C# Syntax Smoke Check17 code blocks17/17 zero syntax errors (Roslyn-verified)100%PASS

2. Identified Gaps & Discrepancies ​

2.1 Gate 1 — Contract & Field Parity (98.3%, FAIL) ​

Every one of the 58 spec-documented fields across the 12 request/response schemas (SubjectCreate+Demographics, SubjectConsentRequest+ProtocolVersion, SubjectStateUpdateRequest, SubjectDemographicsUpdateRequest, ETMFCompletenessWebhookPayload, SiteActivationRequest, SubjectResponse, SubjectDetailResponse, SubjectConsentResponse, ComplianceStatusResponse, the two untyped success envelopes) has a corresponding C# DTO property with correct nullability — this is a strong result and the design's SubjectResponse nullability profile (§2.6) is a byte-for-byte match against the spec's §1.2 table. Two concrete gaps:

  1. ETMFCompletenessWebhookPayload.MissingArtifacts collection-default handling is not explicit. Spec §1.1: missing_artifacts defaults to []. Design (02_technical_design.md:574): IReadOnlyList<string>? MissingArtifacts — nullable, no = [] collection-expression default and no FluentValidation/mapping-layer normalization shown that turns an omitted array into [] rather than null before it reaches SiteComplianceCache.Create(...). Gate 1.2 explicitly requires this default to be "explicitly handled ... initialized to []."
  2. SubjectResponse.SubjectId_ (design line 471) requires a manual [JsonPropertyName("subject_id")] override that the design never states. The design defers all JSON casing to "a snake_case naming policy registered once in Program.cs" (line 499). A blanket JsonNamingPolicy.SnakeCaseLower policy applied to the C# property name SubjectId_ (chosen specifically to avoid colliding with Id) would serialize to "subject_id_" — a trailing underscore — not "subject_id". This one property needs an explicit per-property [JsonPropertyName] attribute that overrides the policy; the design's blanket "not shown here for brevity" statement is exactly the kind of unverified claim Gate 1 exists to catch, because this specific property is the one case where the blanket policy is provably wrong.

2.2 Gate 2 — Invariants & Validation Rules (~86%, FAIL) ​

Validation rule coverage (8/9 constraints, 88.9%): SiteActivationRequest.StudyId is documented as required in spec §1.1 but has no AbstractValidator<SiteActivationRequest> anywhere in §2.7, and the /sites/{site_id}/activate endpoint registration in §3.3 has no .AddEndpointFilter<ValidationFilter<SiteActivationRequest>>() (contrast every other POST/PUT/PATCH endpoint, which all wire a ValidationFilter<T>). An empty-string study_id would flow straight into ActivateSiteAsync unvalidated.

Decision-logic mapping (partial on 3 of 9 Rules): The state-transition graph itself (Rule 9's core) is the best-executed part of this design — SubjectStateCodec/SubjectTransitionGraph.Guard reproduces the exact same-state-no-op → null-current → unknown-string → known-but-forbidden check ordering from the spec, with inline citations to the exact raise sites it closes. However:

  • Rule 3 (Re-Consent Cascading Clearance) has no orchestration code. SubjectConsent.ClearReconsentRequirement() (§2.4) is the primitive that clears one row, but the actual cascade — "find every other SubjectConsent row for this subject with requires_reconsent == true and clear them" — is never shown. RecordConsentAsync, the one handler that would contain this logic, is explicitly omitted ("follow the same shape ... omitted here for brevity", §3.2 comment block). SCN-002 in the fixtures directly tests this cascade; there is no C# construct in the design to audit against it.
  • Rule 6 (GxP audit interceptor internals) is a documented TODO, not a design. §4.4 correctly identifies that GxPAuditInterceptor doesn't yet handle non-string-keyed aggregates or write AuditLogEntry/Merkle-chain rows, and prescribes required fixes — but ships zero code for either fix. This is honestly flagged as an open item in §7, which is good practice, but it means Rule 6 is not "mapped to an explicit C# construct" as Gate 2.2 requires; it's a to-do list.
  • Rule 7 (gender normalization / age calculation) has an interface name and zero implementation. IDemographicsNormalizationService is listed in the file layout (§1.1) and its contract is described in prose (§5.1, one paragraph), but the normalize_gender case table (M/MALE/BOY/MAN → M, etc., with the preserve_custom branch) and the (observationDate.DayNumber - birthDate.DayNumber) / 365.25 age formula are never rendered as C# — no switch/pattern-match, no method signature, nothing extractable for Gate 6's syntax check either (0 of the 17 code blocks touch this file). This is the single largest undocumented-in-code invariant, and it is also the invariant the spec is most insistent about reproducing bit-for-bit (explicit "not Period/calendar math" warning, twice).

Dynamic-truthiness mitigation (the if not x: → string.IsNullOrWhiteSpace translation Gate 2.2's second bullet asks for) is well handled everywhere it's visible: SiteCode's constructor, SubjectStateUpdateRequestValidator, the EConsentCompletedConsumer's msg.SiteId is { Length: > 0 } check. No regressions found here.

2.3 Gate 3 — Error Taxonomy & ProblemDetails (96%, 1 critical, FAIL) ​

§3.5's raise-site table nominally reaches 25/25, and the "not ported" decisions for #19 (bare catch-all) and #22 (suppressed decrypt failure) are individually well-reasoned — but one of them is factually incompatible with the golden-master fixture the design itself designates as the source of truth:

  • Raise site #19 vs. fixture INV-018. Design §3.4/§3.5: "Raise site #19 ... is explicitly NOT ported. No handler in this design catches Exception and maps it to a 400. An unexpected exception ... falls through to ASP.NET Core's global IExceptionHandler ... 500." But fixtures/input_invalid_validation_errors.json scenario INV-018 (raise_site: 19, a PATCH .../state with an injected repository fault) pairs with fixtures/output_expected_errors.json's INV-018, which asserts "status": 400 with detail equal to the injected exception's message — i.e., the fixture encodes the legacy catch-all behavior as the required golden-master outcome, not the design's improved (silent-fallthrough-to-500) behavior. 02_technical_design.md §2.6 states plainly that "Step 5's parity harness is graded against those fixtures as the source of truth" — so this is a self-contradiction within the same document, not a subjective preference between two reasonable choices. This must be resolved explicitly before Phase 3: either the design's 500-fallthrough decision is corrected to preserve the legacy 400 (with a stated rationale for why this one bare-catch trap is being reproduced rather than fixed, unlike every other trap in this slice), or fixtures/output_expected_errors.json's INV-018 entry is updated to assert 500 and the fixture-authoring rationale is revised to match.

Newly found (not in the spec's own raise-site inventory, but a real defect in the design's own code): the /{subjectId}/consents alias route (02_technical_design.md:699-702) returns svc.RecordConsentAsync(subjectId, request, ct) directly — a bare Task<Result<SubjectConsentResponse>> — instead of the .Match(Results.Ok, e => e.ToProblemResult()) every sibling endpoint uses. Result<T> is a custom domain type, not IResult; ASP.NET Core Minimal APIs that return a non-IResult, non-primitive value serialize it directly as the 200 OK JSON body. Concretely: this alias endpoint would return HTTP 200 with the internal Result<SubjectConsentResponse> wrapper shape (whatever IsSuccess/Value/Error fields it has) on every call, including ones that should 404 or 400 — it can never produce the correct error envelope, and its success shape doesn't match SubjectConsentResponse either. This is purely additive to what Gate 6's syntax parse would catch (the block is syntactically valid C#) — it is a semantic/wiring defect that only a careful read catches.

2.4 Gate 4 — Fixture Schema Replay (file-level PASS, scenario-level FAIL) ​

All 5 required files exist and parse as valid JSON (input_valid_nominal.json, input_valid_edge_cases.json, input_invalid_validation_errors.json, output_expected_nominal.json, output_expected_errors.json — 19 + 10 + 21 = 50 total scenario/result entries across the three input/output pairs). Two concrete, verified structural breaks were found on spot-check (not an exhaustive line-by-line pass of all 50 — a full mechanical replay requires the actual implementation and is recommended before Phase 3 sign-off, see §3 below):

  1. POST /api/v1/execution/subjects status code. output_expected_nominal.json scenarios SCN-001-A and SCN-001-B both assert "status": 200. The design's SubjectEndpoints.MapSubjectEndpoints (§3.3) returns Results.Created($"/api/v1/execution/subjects/{r.SubjectId_}", r) on success — HTTP 201. Verified independently against the actual legacy source (apps/execution/presentation/routers/subjects.py, lines 180-181): @router.post("/api/v1/execution/subjects", response_model=SubjectResponse) carries no status_code= kwarg, so FastAPI's default (200) applies. Both the fixture and the real legacy behavior agree on 200; the design's 201 Created is the outlier and would fail the golden-master test on the very first nominal scenario.
  2. Raise site #19 / INV-018, detailed in §2.3 above — a Gate 3 finding that is simultaneously a Gate 4 fixture-replay failure (expected 400, design produces 500).

All other spot-checked status codes (SCN-002-A/B consent recording → 200, matches Results.Ok; SCN-005-C compliance-status → 200, matches; the full INV-001 through INV-021 status/detail-string pairs against the §5.1 raise-site table → all 20 of the remaining 21 match exactly, including the free-text-vs-fixed-string split between raise sites #12 and #18 that the spec calls out as a subtlety) are internally consistent between spec, fixtures, and design.

2.5 Gate 5 — .NET 10 / C# 14 Idiomacy (~60%, FAIL) ​

CheckResult
CancellationToken ct on every handler/service methodPASS — all 7 ISubjectApplicationService methods carry it; repository port interfaces (ISubjectRepository etc.) are never rendered as code, so this cannot be verified for the EF Core query layer itself (unverifiable, not failed)
Task<T>/ValueTask<T> returnsPASS
Primary constructorsPASS — SubjectApplicationService, AesGcmDemographicsEncryptionService, HttpCurrentAuditContextAccessor, EConsentCompletedConsumer all use them
Collection expressionsPASS — [.. nonce, .. ciphertext, .. tag] (§5.1)
field keyword for property validationFAIL — never used. SubjectCode/StudyCode/SiteCode (§2.1) use classic constructor-throw validation on readonly record struct types instead, which is a legitimate equivalent pattern but not the field-keyword idiom this gate asks to verify
Strongly-typed IDs instead of raw primitives for PKs/FKsPARTIAL FAIL — SubjectId, SubjectConsentId are correctly strongly-typed; SiteComplianceCache : AggregateRoot<Guid> (§2.5, line 427) uses a bare Guid as its primary key, the exact primitive-obsession pattern this gate flags, on the one aggregate in this slice that doesn't get a typed ID wrapper
EF Core 10 Complex Types / ToJson() / value convertersINTERNALLY INCONSISTENT — §4.3's mapping table claims strat_factors uses OwnsOne(...).ToJson(), but §4.1's actual ClinicalSubjectConfiguration code explicitly does the opposite and says why: "object? values rule out EF Core's typed .ToJson() owned-entity mapping ... maps the private backing field directly through a value converter instead." One of these two statements is wrong; as written, the document contradicts itself on its own headline EF Core 10 feature-adoption claim. Additionally, protocol_version's claimed ComplexProperty mapping (§4.3) and SiteComplianceCacheConfiguration/SubjectConsentConfiguration (both named in §1.1's file layout) are never rendered as code — only ClinicalSubjectConfiguration exists as an actual snippet, 1 of 3 configuration classes
Microsoft.Extensions.Resilience for retriesPASS — DbUpdateConcurrencyException retry pipeline specified in §4.2

2.6 Gate 6 — C# Syntax Smoke Test (100%, PASS) ​

All 17 ```csharp fenced blocks in 02_technical_design.md were extracted and parsed with Microsoft.CodeAnalysis.CSharp 4.11.0 (CSharpSyntaxTree.ParseText, LanguageVersion.Latest, .NET 10 SDK) — zero syntax diagnostics across all 17 blocks (unmatched braces, missing semicolons, malformed generics — none found). No use of dynamic; the only object/Dictionary<string, object?> usage is on strat_factors/demographics payloads, both explicitly justified in-spec as arbitrary untyped JSON per Gate 6.3's own carve-out. This gate is clean.


3. Remediation Directives ​

Concrete edits required in 02_technical_design.md (and, in one case, the fixtures) to reach 100% compliance:

  1. Fix the POST /subjects status code. Change SubjectEndpoints.MapSubjectEndpoints's create-subject delegate (§3.3) from Results.Created(...) to Results.Ok(r), matching both the legacy source (subjects.py:180, no status_code= override → FastAPI default 200) and fixtures/output_expected_nominal.json's SCN-001-A/SCN-001-B. Update the .Produces<SubjectResponse>(StatusCodes.Status201Created) annotation to Status200OK to match.
  2. Resolve the raise-site #19 contradiction. Either (a) reproduce the legacy bare-catch-all's 400 response for this one documented trap (with an explicit note on why this specific trap is preserved rather than fixed, since every other trap in this slice is being fixed), and remove the "explicitly NOT ported" language in §3.4/§3.5; or (b) keep the 500-fallthrough design decision and update fixtures/input_invalid_validation_errors.json and fixtures/output_expected_errors.json's INV-018 entries to assert 500, with a note explaining the fixture was intentionally changed from the legacy behavior. Do not leave the design and the fixtures asserting opposite outcomes for the same scenario.
  3. Fix the /consents alias endpoint (§3.3, ~line 699) to call .Match(Results.Ok, e => e.ToProblemResult()) like every other endpoint, instead of returning the bare Task<Result<SubjectConsentResponse>>.
  4. Add SiteActivationRequestValidator (RuleFor(x => x.StudyId).NotEmpty()) to §2.7 and wire .AddEndpointFilter<ValidationFilter<SiteActivationRequest>>() onto the /sites/{site_id}/activate endpoint in §3.3.
  5. Render RecordConsentAsync's Rule 3 cascade explicitly — the "find all other SubjectConsent rows for this subject with RequiresReconsent == true and call ClearReconsentRequirement() on each" loop needs its own code block (or at minimum its own method signature + body), not a "follows the same shape, omitted for brevity" comment, since it's the one piece of business logic SCN-002 exists specifically to test.
  6. Render IDemographicsNormalizationService's actual implementation — the normalize_gender mapping table and CalculateAge's 365.25-divisor formula, both currently prose-only in §5.1, need to become real C# (switch expression / pattern match + the exact date-arithmetic method signature) so Gate 2/6 can audit them the same way every other Rule in this design already is.
  7. Reconcile §4.1 vs. §4.3 on strat_factors' EF Core mapping. §4.3's table claims OwnsOne(...).ToJson(); §4.1's code uses a manual value converter to jsonb and explains why ToJson() doesn't apply here. Fix the table row to match the code (the code's rationale reads as correct — ToJson() requires a concrete CLR shape, which an object?-valued dictionary doesn't have).
  8. Add a strongly-typed SiteComplianceCacheId and change SiteComplianceCache : AggregateRoot<Guid> to AggregateRoot<SiteComplianceCacheId>, consistent with the other two aggregates in this slice and with Gate 5's own stated standard.
  9. Add the missing SubjectConsentConfiguration and SiteComplianceCacheConfiguration code blocks (both named in §1.1's file layout, neither ever rendered) — in particular the protocol_version ComplexProperty(...) mapping claimed in §4.3 needs to actually exist somewhere before Gate 5's Complex Types claim can be verified.
  10. Add an explicit [JsonPropertyName("subject_id")] note (or rename the property) for SubjectResponse.SubjectId_, since the blanket snake_case naming policy alone would produce "subject_id_".
  11. Add = [] (or equivalent explicit default) to EtmfCompletenessWebhookPayload.MissingArtifacts to match the spec's documented [] default for an omitted missing_artifacts field.

4. Phase 3 Gate Verdict ​

PHASE 3 BLOCKED:

  • Gate 1 (Contract & Field Parity): FAIL — 98.3% (2 discrepancies: MissingArtifacts collection default, SubjectId_ JSON-naming override)
  • Gate 2 (Invariants & Validation Rules): FAIL — ~86% (missing SiteActivationRequest validator; Rules 3, 6, 7 lack rendered C# implementations)
  • Gate 3 (Error & Exception Envelopes): FAIL — 96%, 1 critical self-contradiction (raise site #19 vs. INV-018 fixture) plus a genuine response-wiring defect on the /consents alias route
  • Gate 4 (Fixture Schema Replay): FAIL at the scenario level — files are valid, but SCN-001-A/SCN-001-B (status code) and INV-018 (status code) are structurally incompatible with the design as written
  • Gate 5 (Modern .NET 10 Standards): FAIL — ~60% (SiteComplianceCache's untyped Guid PK, the field-keyword gap, and the §4.1/§4.3 ToJson() self-contradiction)
  • Gate 6 (C# Syntax Smoke Check): PASS — 100%, 0 syntax errors across all 17 extracted blocks

None of the findings above are large — this is a well-constructed, unusually self-documenting design (its own inline citations back to spec Rule numbers and raise-site numbers made this audit tractable), and the state-machine/transition-graph and demographics-encryption sections in particular are complete and correct. But Gate 3's raise-site #19 contradiction and Gate 4's create-subject status-code mismatch are exactly the class of "quietly break the golden-master harness on day one" defects this gate exists to catch before Phase 3 ticketing locks them in as accepted scope. Apply remediation directives 1–11 above, re-run this gate, and this slice should clear all six gates on the next pass — the underlying architecture does not need to change, only be completed and corrected in the specific spots enumerated.