Appearance
Phase 2 Validation Gate Report: EXECUTION-SUBJECTS
Scope note on file naming. The validation prompt names
01_functional_spec.mdas the reference spec; this slice's actual file isdocs/migration/slices/execution-subjects/01_spec.md(confirmed viaGlob— no01_functional_spec.mdexists in this slice). This audit treats01_spec.mdas the functional spec it evidently is (it is the document02_technical_design.mditself cites throughout as its spec of record, and it carries the remediated Phase 1 content certified "PHASE 2 UNBLOCKED" in00_phase1_validation_report.md§0.3). Recommend renaming to01_functional_spec.mdfor 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 in02_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.CSharp4.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 ofSystem.Text.Jsonagainst 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 Gate | Spec Count | Design Count | Coverage (%) | Status (PASS / FAIL) |
|---|---|---|---|---|
| Gate 1: Contract & Field Parity | 58 fields (12 schemas) | 57 fully compliant, 1 partial (collection default) | 98.3% | FAIL |
| Gate 2: Invariants & Validation Rules | 9 Rules + 9 boundary constraints = 18 items | ~15.5 fully/partially implemented | ~86% | FAIL |
| Gate 3: Error & Exception Envelopes | 25 raise sites | 24 correctly mapped, 1 contradicts fixture; +1 undiscovered response-shaping defect | 96% (1 critical) | FAIL |
| Gate 4: Fixture Schema Replay | 5 fixture files / 50 scenario entries | 5/5 valid JSON; 2 of 50 spot-checked scenarios structurally broken | 5/5 files PASS, scenario-level FAIL | FAIL |
| Gate 5: Modern .NET 10 Standards | 6 checks | ~3.5 of 6 fully pass | ~60% | FAIL |
| Gate 6: C# Syntax Smoke Check | 17 code blocks | 17/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:
ETMFCompletenessWebhookPayload.MissingArtifactscollection-default handling is not explicit. Spec §1.1:missing_artifactsdefaults 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 thannullbefore it reachesSiteComplianceCache.Create(...). Gate 1.2 explicitly requires this default to be "explicitly handled ... initialized to[]."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 inProgram.cs" (line 499). A blanketJsonNamingPolicy.SnakeCaseLowerpolicy applied to the C# property nameSubjectId_(chosen specifically to avoid colliding withId) 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 otherSubjectConsentrow for this subject withrequires_reconsent == trueand 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
GxPAuditInterceptordoesn't yet handle non-string-keyed aggregates or writeAuditLogEntry/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.
IDemographicsNormalizationServiceis listed in the file layout (§1.1) and its contract is described in prose (§5.1, one paragraph), but thenormalize_gendercase table (M/MALE/BOY/MAN → M, etc., with thepreserve_custombranch) and the(observationDate.DayNumber - birthDate.DayNumber) / 365.25age formula are never rendered as C# — noswitch/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 "notPeriod/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 catchesExceptionand maps it to a 400. An unexpected exception ... falls through to ASP.NET Core's globalIExceptionHandler... 500." Butfixtures/input_invalid_validation_errors.jsonscenarioINV-018(raise_site: 19, aPATCH .../statewith an injected repository fault) pairs withfixtures/output_expected_errors.json'sINV-018, which asserts"status": 400withdetailequal 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), orfixtures/output_expected_errors.json'sINV-018entry 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):
POST /api/v1/execution/subjectsstatus code.output_expected_nominal.jsonscenariosSCN-001-AandSCN-001-Bboth assert"status": 200. The design'sSubjectEndpoints.MapSubjectEndpoints(§3.3) returnsResults.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 nostatus_code=kwarg, so FastAPI's default (200) applies. Both the fixture and the real legacy behavior agree on 200; the design's201 Createdis the outlier and would fail the golden-master test on the very first nominal scenario.- 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)
| Check | Result |
|---|---|
CancellationToken ct on every handler/service method | PASS — 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> returns | PASS |
| Primary constructors | PASS — SubjectApplicationService, AesGcmDemographicsEncryptionService, HttpCurrentAuditContextAccessor, EConsentCompletedConsumer all use them |
| Collection expressions | PASS — [.. nonce, .. ciphertext, .. tag] (§5.1) |
field keyword for property validation | FAIL — 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/FKs | PARTIAL 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 converters | INTERNALLY 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 retries | PASS — 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:
- Fix the
POST /subjectsstatus code. ChangeSubjectEndpoints.MapSubjectEndpoints's create-subject delegate (§3.3) fromResults.Created(...)toResults.Ok(r), matching both the legacy source (subjects.py:180, nostatus_code=override → FastAPI default 200) andfixtures/output_expected_nominal.json'sSCN-001-A/SCN-001-B. Update the.Produces<SubjectResponse>(StatusCodes.Status201Created)annotation toStatus200OKto match. - 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.jsonandfixtures/output_expected_errors.json'sINV-018entries 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. - Fix the
/consentsalias endpoint (§3.3, ~line 699) to call.Match(Results.Ok, e => e.ToProblemResult())like every other endpoint, instead of returning the bareTask<Result<SubjectConsentResponse>>. - Add
SiteActivationRequestValidator(RuleFor(x => x.StudyId).NotEmpty()) to §2.7 and wire.AddEndpointFilter<ValidationFilter<SiteActivationRequest>>()onto the/sites/{site_id}/activateendpoint in §3.3. - Render
RecordConsentAsync's Rule 3 cascade explicitly — the "find all otherSubjectConsentrows for this subject withRequiresReconsent == trueand callClearReconsentRequirement()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. - Render
IDemographicsNormalizationService's actual implementation — thenormalize_gendermapping table andCalculateAge's365.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. - Reconcile §4.1 vs. §4.3 on
strat_factors' EF Core mapping. §4.3's table claimsOwnsOne(...).ToJson(); §4.1's code uses a manual value converter tojsonband explains whyToJson()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 anobject?-valued dictionary doesn't have). - Add a strongly-typed
SiteComplianceCacheIdand changeSiteComplianceCache : AggregateRoot<Guid>toAggregateRoot<SiteComplianceCacheId>, consistent with the other two aggregates in this slice and with Gate 5's own stated standard. - Add the missing
SubjectConsentConfigurationandSiteComplianceCacheConfigurationcode blocks (both named in §1.1's file layout, neither ever rendered) — in particular theprotocol_versionComplexProperty(...)mapping claimed in §4.3 needs to actually exist somewhere before Gate 5's Complex Types claim can be verified. - Add an explicit
[JsonPropertyName("subject_id")]note (or rename the property) forSubjectResponse.SubjectId_, since the blanket snake_case naming policy alone would produce"subject_id_". - Add
= [](or equivalent explicit default) toEtmfCompletenessWebhookPayload.MissingArtifactsto match the spec's documented[]default for an omittedmissing_artifactsfield.
4. Phase 3 Gate Verdict
PHASE 3 BLOCKED:
- Gate 1 (Contract & Field Parity): FAIL — 98.3% (2 discrepancies:
MissingArtifactscollection default,SubjectId_JSON-naming override) - Gate 2 (Invariants & Validation Rules): FAIL — ~86% (missing
SiteActivationRequestvalidator; Rules 3, 6, 7 lack rendered C# implementations) - Gate 3 (Error & Exception Envelopes): FAIL — 96%, 1 critical self-contradiction (raise site #19 vs.
INV-018fixture) plus a genuine response-wiring defect on the/consentsalias route - Gate 4 (Fixture Schema Replay): FAIL at the scenario level — files are valid, but
SCN-001-A/SCN-001-B(status code) andINV-018(status code) are structurally incompatible with the design as written - Gate 5 (Modern .NET 10 Standards): FAIL — ~60% (
SiteComplianceCache's untypedGuidPK, thefield-keyword gap, and the §4.1/§4.3ToJson()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.