Appearance
Behavioral & Invariant Specification: Subject Lifecycle & Enrollment
Slice: execution-subjectsBounded Context: Cadence.Apps.Execution (EDC Execution Runtime) Source Python Files:
apps/execution/subject_lifecycle.pyapps/execution/database/models/subject.pyapps/execution/application/services.py(SubjectLifecycleService)apps/execution/domain/ports.py(ISubjectRepository,IConsentRepository)apps/execution/demographics.pyapps/execution/presentation/routers/subjects.pyapps/execution/workers/consent_subscriber.pyapps/execution/database/models/compliance.py(SiteComplianceCache)
Cross-Cutting Dependencies (Out of Slice): the following are imported by the files above but are shared infrastructure owned by other slices/specs, and are referenced here only to explain observable behavior — their internals are not re-specified in this document:
apps/execution/database/audit.py— a session-flush write-guard shared by every write-guarded slice. It independently raises a plainPermissionError("Re-Consent Required - Demographics & Visit Forms Locked")(caught by the global handler inapps/execution/main.py, lines 481-494, mapping to HTTP 423) whenever a subject has an outstandingrequires_reconsentconsent row and nois_paper_overrideconsent exists — this is a second, independent enforcement path for the same re-consent contract documented in Rule 4 below (see §5, raise site #7).apps/execution/eligibility_service.py— screening eligibility evaluation (evaluate_subject_eligibility,verify_subject_eligible_for_randomization); its own rule engine is out of scope for this slice, which only documents how itseligibleverdict drives theSCREENING → SCREEN_FAILED / ENROLLEDtransition.apps/execution/site_execution_gatekeeper.py—require_site_mutation_authorization, invoked on subject creation when bothstudy_idandsite_idare supplied; the sovereign-site authorization rule itself belongs to a separate spec.apps/execution/cryptography.py(AllocationKeyManager) — RTSM allocation-envelope decryption used byget_subject_detail; the randomization/RTSM key-management contract belongs to the randomization slice.apps/execution/econsent_client.py— external eConsent service client; the eConsent service's own API is out of scope.ExecutionDOAUseCase(inapps/execution/application/services.py) /IExecutionDOARepository(inapps/execution/domain/ports.py) — Delegation-of-Authority code — remain excluded per the Phase 1 validation report's scoping note; DOA branches, raises, and dynamic-trap sites are not counted anywhere in this document.
Governing Regulatory & Architecture Standards:
- 21 CFR Part 11 (Audit trails, immutable records, electronic signatures)
- ICH GCP E6(R2) (Protocol compliance, participant safety, subject identification)
- PRD-SYS-001, PRD-SYS-042, PRD-SYS-053, PRD-SYS-121, PRD-SUB-001, PRD-SUB-007, PRD-SSU-003
- ADR-2202, ADR-2233, ADR-2428, ADR-2238
1. Contract Boundary & Data Schemas
1.1 Ingestion Schemas (Requests)
SubjectCreate
- Route:
POST /api/v1/execution/subjects - Payload Schema:
Field Type Required Default Invariants & Validation subject_idstringYes - Non-empty domain subject code (e.g. SUBJ-001). Max length: 255.study_idstringYes - Clinical study identifier (e.g. STUDY-001). Max length: 255.site_idstringNo nullSite identifier. Triggers sovereign site mutation check if provided. arm_idstringNo nullInitial assigned study arm (maps to treatment_group).demographicsobjectNo nullOptional patient demographics payload to be encrypted. DemographicsSchema:Field Type Required Default Invariants namestringNo nullDirect PII, strictly encrypted at rest via AES-GCM. birthdatestringNo nullISO 8601 date string ( YYYY-MM-DD). Encrypted at rest.genderstringNo nullEncrypted at rest. Normalized on evaluation to CDISC SEX ( M,F,U).racestringNo nullEncrypted at rest.
SubjectConsentRequest
Route:
POST /api/v1/execution/subjects/{subject_id}/consent&.../consentsPayload Schema:
Field Type Required Default Invariants protocol_versionobjectYes - Contains study_id(string),version_tag(string),version_index(int).icf_signedboolYes - Whether the Informed Consent Form was signed. icf_signed_datedatetimeNo nullIf omitted in Python, defaults to UTC now. requires_reconsentboolNo falseIf an amendment requires re-consent. is_paper_overrideboolNo falseSovereign site paper consent waiver indicator. IMPORTANT
Deliberate departure from legacy (#4824). Python defaulted an omitted
icf_signed_dateto the time of the request, so a consent entered days after signing recorded the wrong signed date. The .NET port never invents the date. A request withicf_signed: truemust carryicf_signed_dateunless a date is already on file for that consent version (Rule 9); otherwise it is rejected with 400 and codeICF_SIGNED_DATE_REQUIRED. An unsigned consent may leave the date empty.
SubjectStateUpdateRequest
- Route:
PATCH /api/v1/execution/subjects/{id}/state - Headers:
X-Change-Reason(Required 21 CFR Part 11 justification string) - Payload Schema:
Field Type Required Default Invariants statusstringNo nullTarget state name (e.g. ENROLLED,WITHDRAWN).statestringNo nullAlternative property name for status. One must be non-null.
SubjectDemographicsUpdateRequest
- Route:
PUT /api/v1/execution/subjects/{id}/demographics - Headers:
X-Change-Reason(Required) - Payload Schema:
Field Type Required Default Invariants demographicsobjectNo nullReplacement patient demographics payload. strat_factorsdict<string, any>No nullStratification factors. Locked post-randomization.
ETMFCompletenessWebhookPayload
- Route:
POST /api/v1/execution/webhooks/etmf - Payload Schema:
Field Type Required Default Invariants study_idstringYes - Clinical study identifier. site_idstringNo nullSite identifier. milestonestringYes - Compliance milestone name (e.g. SITE_ACTIVATION).is_completeboolYes - Whether the milestone is fully satisfied. missing_artifactslist<string>No []Persisted as a comma-joined string on SiteComplianceCache.missing_documents. - Behavior: upserts the
SiteComplianceCacherow keyed by(study_id, site_id, milestone). If a row exists, itsversionis incremented by 1 (optimistic version counter, not a concurrency token check); otherwise a new row is inserted withversion = 1. No audit-log entry is written for this mutation (unlike the site-activation and enrollment-blocking paths, which always write one).
SiteActivationRequest
- Route:
POST /api/v1/execution/sites/{site_id}/activate - Payload Schema:
Field Type Required Default Invariants study_idstringYes - Clinical study identifier. - Behavior: re-reads the
SiteComplianceCacherow for(study_id, site_id, "SITE_ACTIVATION"). If missing oris_complete == false, writes aBLOCKED_ACTIVATIONaudit-log entry (in its own nested session/transaction, committed independently of the outer one) and fails — see §5, raise site #9. Otherwise writes aSITE_ACTIVATIONaudit-log entry and succeeds. This endpoint does not itself flipSiteComplianceCache.is_complete; that only happens via the eTMF webhook above.
1.2 Egress Schemas (Responses)
SubjectResponse
- HTTP Status: 200 OK / 201 Created
- Fields:
Field Type Nullable Description idstringNo Primary key UUID. subject_idstringNo Domain-specific subject identifier. study_idstringNo Study identifier. site_idstringYes Clinical site code. treatment_groupstringYes Assigned treatment arm (if unblinded/authorized). statusstringNo Lifecycle state string ( SCREENING,ENROLLED, etc.).active_protocol_versionstringYes Currently active protocol version (default 1.0.0).encrypted_demographicsstringYes Ciphertext payload. Raw PII never leaked.
SubjectDetailResponse
- Route:
GET /api/v1/execution/subjects/{subject_id} - Blinding Rule: RTSM fields (
treatment_group,randomization_seed,investigational_product_id) are redacted (null) if caller holds a blinded role (e.g., CRC, CRA, Investigator) unless explicitly unblinded. - Fields:
subject_id,study_id,status,site_id,treatment_group,randomization_seed,investigational_product_id.
SubjectConsentResponse
- HTTP Status: 200 OK
- Fields:
id,subject_id,study_id,version_tag,version_index,icf_signed,icf_signed_date,requires_reconsent,is_paper_override,version.
ComplianceStatusResponse
- Route:
GET /api/v1/execution/sites/{site_id}/compliance-status - Query Params:
study_id(required),milestone(optional, default"SITE_ACTIVATION"). - HTTP Status: 200 OK (always — a missing cache row is not an error)
- Fields:
Field Type Nullable Description study_idstringNo Echoes the query/cache-row study. site_idstringYes Echoes the path/cache-row site. milestonestringNo Echoes the query/cache-row milestone. is_completeboolNo falsewhen no cache row exists yet (not an error/404).missing_documentslist<string>No Split from the cache row's comma-joined string; []when no row exists.
Site Activation & eTMF Webhook Responses (untyped success envelopes)
POST /api/v1/execution/sites/{site_id}/activatesuccess →200 OK,{"status": "success", "message": "Site {site_id} activated successfully."}.POST /api/v1/execution/webhooks/etmfsuccess →200 OK,{"status": "success", "message": "Compliance cache updated successfully."}.- Neither response uses a Pydantic response model in the legacy code (
dict[str, Any]return type) — the .NET port should still define typed response records for these two envelopes rather than reproduce the untyped shape.
2. Invariants & Algorithmic Rules
2.1 Regulated State Machine Transition Graph
The clinical trial subject state machine enforces strict directional progress to prevent protocol deviations and safeguard statistical integrity:
2.2 Invariant Rules
Rule 1: Stratification Factor Immutability Post-Randomization:
- Pre-randomization (
SCREENING,ENROLLED): Stratification factors (strat_factors) and demographics may be edited with justification. - Post-randomization (
RANDOMIZED,ACTIVE,COMPLETED,UNBLINDED,WITHDRAWN): Any attempt to modifystrat_factorsor demographics MUST fail immediately with422 Unprocessable Entity(LOCKED_FACTOR_MUTATION).
- Pre-randomization (
Rule 2: Sovereign Site Activation Gate for Enrollment:
- Advancing a subject to
ENROLLED(via screening evaluation or state update) is gated on site compliance. - The site must possess a verified milestone
SITE_ACTIVATIONentry inSiteComplianceCachewithis_complete == true. - If the site is non-compliant or missing, enrollment is blocked, an immutable
BLOCKED_ENROLLMENTaudit entry is created, and an HTTP400 Bad Requestis returned.
- Advancing a subject to
Rule 3: Re-Consent Cascading & Clearance:
- When a subject signs a new consent form version (
icf_signed == trueoris_paper_override == true) andrequires_reconsent == false, all prior consent records for that subject withrequires_reconsent == trueMUST be automatically cleared torequires_reconsent = false.
- When a subject signs a new consent form version (
Rule 4: Version Gating for Form Data Entry:
- Before allowing eCRF form submission,
validate_subject_version_gatingverifies whether the study amendment requires re-consent. If the subject's active protocol version does not match and no signed consent exists for the active version, form submission must fail withReConsentRequiredException(HTTP 423 Locked — corrected from an earlier "428 / 403" claim; see §5 raise site #7 for the verified source of this mapping and the adjacent, independent 423 write-guard documented in §5.2).
- Before allowing eCRF form submission,
Rule 5: Sequential Zero-Based Enrollment Index:
- Every subject enrolled in a study receives a monotonically increasing
enrollment_index(0, 1, 2, ...). - Must be concurrency-safe and immutable once assigned.
- Every subject enrolled in a study receives a monotonically increasing
Rule 6: 21 CFR Part 11 Audit Trail:
- Every mutation (
ENROLL_SUBJECT,RECORD_CONSENT,TRANSITION_<STATE>,UPDATE_DEMOGRAPHICS) must capture:table_name,record_id,action,user_id,change_reason, UTC timestamp,old_values,new_values.
- Must link into the cryptographically verifiable audit trail.
- GxP audit-context bridge (out-of-slice mechanism, documented here only because it changes what a .NET
GxPAuditInterceptormust replicate):current_user_id/current_change_reason(Pythoncontextvars) are propagated by abefore_flushsession-event listener inapps/execution/database/audit.py(not one of this slice's own source files) into PostgreSQL session-config variables —SELECT set_config('cadence.current_user_id', ...),('cadence.current_change_reason', ...),('cadence.app_writing', 'true', ...)— for a database-level trigger (installed separately viadeploy_database_triggers) to consume when writing the actual audit trail. This is a materially different architecture from theAuditLog-table writesSubjectLifecycleServiceperforms explicitly in application code (Rule 6's main bullet): the DB-trigger path is a second, independent, session-variable-driven audit-capture mechanism operating underneath the ORM, not a property theClinicalSubject/SubjectConsententities themselves carry — neither entity in this slice hasCreatedBy/UpdatedBy/ReasonForChange-style columns (AuditedModelonly definesid,version,is_deleted). The .NET port'sGxPAuditInterceptor(ADR-2428) is an EF CoreSaveChangesInterceptor— i.e. application-layer, not a database trigger — so this is a genuine architectural divergence to resolve deliberately in Phase 2, not a detail to silently drop: confirm whether the target interceptor must still write to a trigger-populated ledger table, or whether the DB-trigger mechanism is superseded entirely by the interceptor for this slice's audited tables.
- Every mutation (
Rule 7: Demographics Derivation, Normalization & Encryption Semantics (
apps/execution/demographics.py):- Encryption:
encrypt_demographics/decrypt_demographicsuse symmetric Fernet (AES-128-CBC + HMAC) with a hardcoded, non-configurable key derived from a fixed 32-byte ASCII string — already flagged in §3's dynamic-traps table as a hard blocker for the .NET port (must become a configuredAesGcmkey, never a literal). - Gender/sex normalization (
normalize_gender): case-insensitive, whitespace-trimmed mapping to CDISC SEX codes:Input (any case/whitespace) Output M,MALE,BOY,MANMF,FEMALE,GIRL,WOMANFU,UNKNOWN,UNK, empty/nullUAnything else, preserve_custom=FalseUAnything else, preserve_custom=TrueThe trimmed, upper-cased input verbatim (not normalized to any fixed vocabulary) get_safe_demographicsalways calls this withpreserve_customforwarded from its own caller-supplied parameter (defaultFalse). - Age calculation (
calculate_age,_parse_date_string): acceptsbirthdate/observation_dateindependently asdate,datetime(time-of-day discarded), a string, orNone.- String parsing tries ISO-8601 first (
datetime.fromisoformat, with a literalZsuffix rewritten to+00:00before parsing when aTseparator is present), then falls back to splitting on whitespace and parsing only the leading token as a baredate(handles"YYYY-MM-DD HH:MM:SS"-style strings that aren't validfromisoformatinput); returnsNoneif both attempts fail. - Age is
(observation_date − birthdate).days / 365.25— a fixed average-year-length approximation, not a calendar-accurate (leap-aware) year count. The .NET port must reproduce the/ 365.25divisor exactly for golden-master parity rather than substitutingPeriod/calendar-based age math, which will disagree at the margins. - Any missing input, unparseable string, or unexpected exception during computation returns
None(logged atwarning, never raised) — the function never throws.
- String parsing tries ISO-8601 first (
get_safe_demographicsfallback contract: always returns the shape{"gender": "U", "age": None}at minimum, and never raises, regardless of input:- Accepts
subjectas aClinicalSubject-like object (via.encrypted_demographics), adict(via["encrypted_demographics"]), or a raw ciphertextstringdirectly. - Missing/falsy ciphertext, a decrypted payload that isn't a
dict, anInvalidToken(wrong/corrupted ciphertext), or any other exception during decrypt/parse — all silently fall back to the default shape with awarninglog; none of these are ever surfaced to the caller as an error. - Decision for the .NET port (per Phase 1 remediation directive): preserve this silent-fallback-to-default contract. This function is consumed exclusively by read-only reference-range/eligibility evaluation logic that requires a non-throwing, always-safe demographic profile; it is not the authoritative demographics write path (that path —
update_subject_demographics_endpoint— already has its own explicit404/422error handling and must continue to fail loudly on genuine errors). Do not unify these two code paths' error-handling behavior.
- Accepts
- Encryption:
Rule 8: PubSub Auto-Enrollment (Background Consent-Completion Trigger) (
apps/execution/workers/consent_subscriber.py):- On receiving a Redis pub/sub message with
action == "consent_completed"on channelREDIS_CHANNEL_CONSENT(defaulteconsent_consent_completed),handle_consent_completed_messageruns inside one DB transaction:- Idempotency: looks up an existing
ClinicalSubjectbysubject_idOR internalidmatching the event'ssubject_id. If found, auto-creation is skipped entirely (log-only, no error, no duplicate). - Sequential enrollment index: if no existing subject, computes
next_idx = (MAX(enrollment_index) WHERE study_id = event.study_id) + 1, or0if the study has no subjects yet, inside the same transaction as the insert — same concurrent-race concern already flagged forSubjectLifecycleService.enroll_subjectin §3's traps table (two pub/sub messages for the same study processed concurrently can compute the samemax_idx). - Creates the
ClinicalSubjectwithstatus = "SCREENING"and writes anAuditLog(action="INSERT",user_id="system-pubsub"). - Independently, ensures a matching
SubjectConsentcache row exists for(subject_id, study_id, version_index)— if not, creates one withicf_signed=True,requires_reconsent=False,icf_signed_date=now(UTC), and writes a secondAuditLogrow. This consent-cache population happens even if step 1 found the subject already existing (i.e., consent-cache backfill is idempotent-but-independent of subject-creation idempotency).
- Malformed events (
subject_idorstudy_idmissing/falsy) are dropped with awarninglog — no error is raised, no dead-letter/retry occurs.
- Idempotency: looks up an existing
- Process lifecycle: the subscriber thread does not start at all when running under
pytest("pytest" in sys.modules), whenTESTING=true, or whenREDIS_HOSTis unset — in all three casesstart_consent_subscriberreturns immediately and silently. When running,_run_subscriber_syncreconnects with a 5-second backoff on any Redis connection failure or per-message processing exception (both logged atwarning, loop continues) and never terminates on its own outside ofstop_consent_subscriber(). - MIG-06 (hard blocker — do not transcribe as-is): per
docs/migration/phase0/03_migration_plan.md(Action Item Register, MIG-06), this fire-and-forget Redis pub/sub channel has no delivery durability and is documented as currently dormant in the reference stack. The .NET port of this behavior must not be a literal Redis-subscriber background thread; it must be redesigned onto the platform's MassTransit transactional-outbox event spine (ADR-2428), consuming anEConsentCompletedEvent-equivalent domain event with at-least-once delivery, while preserving exactly the idempotency (existing-subject skip), same-transaction sequential-index-assignment, and independent consent-cache-backfill semantics documented above — those are the observable behavioral contract; the transport mechanism is the part MIG-06 requires changing.
- On receiving a Redis pub/sub message with
Rule 9: Subject Resolution, Context-Fallback & Field-Merge Semantics:
- Dual-lookup by ID or code:
SubjectLifecycleService.advance_subject_stateand.update_demographics(apps/execution/application/services.py) resolve theirsubject_idparameter by tryingsubject_repo.get_by_id(...)first, falling back tosubject_repo.get_by_subject_code(...)if that returns nothing. The parameter is accepted as either the internal UUID primary key or the domainsubject_idcode, interchangeably;SubjectNotFoundErroris only raised once both lookups fail.update_subject_state_endpoint's own pre-check (§5 raise site #15) duplicates this same dual-lookup independently before calling the service. - Demographics dual-type acceptance:
enroll_subjectandupdate_demographicsboth accept theirdemographicsargument as either adict(encrypted viaencrypt_demographicsbefore storage) or an already-encryptedstr(stored as-is, assumed pre-encrypted by the caller). Callers must not be able to pass an arbitrary plaintext string expecting it to be encrypted — only thedictbranch encrypts. - Consent field-merge precedence on re-submission: when
record_consentfinds an existingSubjectConsentrow for(subject_id, study_id, version_index), the merge is field-by-field, not a full overwrite:version_tag,icf_signed,requires_reconsent,is_paper_overrideare unconditionally replaced from the incoming payload.icf_signed_date: replaced only if the incoming payload supplies one; otherwise the existing value is kept, unless the existing row has no date at all, in which case it is defaulted to "now" (UTC). .NET port (#4824): the "now" default is not carried over. A signed re-submission with no date, onto a row with no date, is rejected with 400ICF_SIGNED_DATE_REQUIREDand the row is left unchanged. See theSubjectConsentRequestnote in §1.protocol_version: replaced only if the incoming payload supplies a truthy value — an omitted/emptyprotocol_versionon a re-submission leaves the existing stored value untouched rather than nulling it out.
normalize_state(apps/execution/subject_lifecycle.py) is the single funnel both sides of every transition check pass through:None→None; anEnummember → its.valuefirst; anything else →str(x).strip().upper().replace(" ", "_")(so e.g."in progress"→"IN_PROGRESS").- Same-state is always a no-op:
guard_subject_transitionreturns immediately, without error, whenever normalized current and target states are equal — including for terminal states (re-submittingWITHDRAWN → WITHDRAWNsucceeds silently rather than raising). This check runs before theNone-current and unknown-state checks below. - Unknown/malformed state strings are rejected identically to legal-but-forbidden transitions: after the same-state and
None-current checks, if either normalized string doesn't match a knownSubjectStatevalue,InvalidStateTransitionErroris raised with no distinct error code from a well-formed-but-illegal transition (§5 raise site #6) — callers cannot distinguish "typo'd state name" from "that transition isn't allowed" from the response body alone. - Initial transition guard: when current state is
None(brand-new subject), the only legal target isSCREENING; any other target raisesInvalidStateTransitionError("None", target)(§5 raise site #5). - Context-var fallback in
evaluate_and_transition_screening:current_user_id.get()andcurrent_change_reason.get()(Pythoncontextvars.ContextVar.get()with no default registered) each raiseLookupErrorwhen unset rather than returningNone.subjects.pycatches each independently: an unsetcurrent_user_idfalls back to the literal string"system"; an unsetcurrent_change_reasonfalls back to the request'sX-Change-Reasonheader value if present, else the literal string"system_operation". This is the only place in the slice that catchesLookupErrorfrom these context vars — every other reader (e.g.create_subject,update_subject_state_endpoint) usescurrent_user_id.get() or "system"/similar truthy-fallback idioms instead, which behave the same for an unset var but would NOT behave the same if a caller ever explicitly set the var toNone(that raises noLookupError, so theorfallback still catches it, but a hypothetical.get()-without-orcall elsewhere would not). The .NET equivalent (AsyncLocal<T>) should use one consistent default-resolution pattern across all readers rather than reproducing this two-different-idioms split. SubjectResponseunder-population on 3 of its 4 return sites (newly identified during this remediation pass, not in the Phase 1 report):create_subject(line ~212) is the only handler that populates every field ofSubjectResponse.update_subject_state_endpoint(line ~646),update_subject_demographics_endpoint(line ~716), anddelete_subject_demographics_endpoint(line ~767) all construct the response with onlyid,subject_id,study_id, andencrypted_demographics— leavingsite_idandtreatment_groupasnulland, more consequentially, leavingstatusandactive_protocol_versionat the Pydantic model's hardcoded literal defaults ("SCREENING"and"1.0.0"respectively) regardless of the subject's actual current values. Concretely:PATCH .../statethat successfully transitions a subject toENROLLEDreturns a body whosestatusfield still reads"SCREENING". This is a real behavioral quirk of the legacy system, not a fixture error — the golden-master fixtures infixtures/reproduce it verbatim. It is an explicit decision point for Phase 2: reproduce the under-population as-is (byte-for-byte parity with a system whose response body already disagrees with its own database), or treat it as a bug fix and fully populate the DTO (a deliberate, documented behavioral improvement, not a silent one). This document does not mandate either choice — it only records that the ambiguity exists and must be resolved explicitly rather than accidentally.
- Dual-lookup by ID or code:
3. Dynamic Python Traps & Pitfalls
| Python Pattern in Source | Legacy Risk | Target .NET 10 Fix |
|---|---|---|
datetime.now() in subject_lifecycle.py:179 (unblind_subject_model) and :187 (withdraw_subject_model) | Both emit naive local system time, causing timezone drift and timestamp mismatch across servers. Every other timestamp in this slice (audit logs, record_consent's icf_signed_date default, the pubsub subscriber's icf_signed_date) uses datetime.now(UTC) — these two are the only naive-time outliers. | Standardize on DateTimeOffset.UtcNow across all models and services. |
if not site_id: in check_site_compliance_for_enrollment | Evaluates empty string "" as falsy, unintentionally bypassing site compliance checks. | Use string.IsNullOrWhiteSpace(siteId) and treat whitespace as invalid or non-compliant. |
normalize_state() accepting Any | Implicit string conversion on unexpected objects (e.g. dictionaries, numbers) producing strange states. | Strongly-typed enum SubjectState with explicit JSON converter; reject unmapped strings. |
max_idx = await repo.get_max_enrollment_index() race condition | Concurrent enrollments can read the same max index, causing duplicate enrollment_index values. Identical race exists independently in consent_subscriber.py's handle_consent_completed_message (see Rule 8). | Execute inside PostgreSQL transaction with row-level lock or dedicated study sequence; apply to both call sites. |
Hardcoded Fernet encryption key in demographics.py | Insecure key management; binary payload incompatible with .NET standard algorithms. | Implement IDemographicsEncryptionService using .NET System.Security.Cryptography.AesGcm with key from configuration. |
eval_list = [] loop in subjects.py:500 | N+1 object mapping allocations on screening response. | Use LINQ collection expressions [..evaluations.Select(...)] with pre-sized capacity. |
Dual route declarations (/api/v1/execution/subjects and /subjects) | Route collision and maintenance overhead. | Define canonical route group /api/v1/execution/subjects with optional fallback middleware if backward compatibility is required. |
Broad except Exception: decrypt-failure swallow in subjects.py:556 (get_subject_detail, RTSM allocation decrypt) | Any decrypt failure — corrupted ciphertext, wrong key, malformed payload — is silently mapped to the literal string treatment_group = "Decryption Failed", which then flows through apply_rtsm_blinded_filter as if it were a genuine (unblinded) treatment-group value. | Raise a typed decryption-failure exception and let the caller/response-mapping layer decide the safe blinded/error presentation; never smuggle an error state through a field that is otherwise a real clinical data value. |
with suppress(Exception): decrypt-failure swallow in subjects.py:698-701 (update_subject_demographics_endpoint) | A corrupted/undecryptable encrypted_demographics ciphertext is silently treated as "no demographics on file" (current_demo = {}), which then makes the post-randomization lock check at line 704 (current_demo != new_demo) spuriously see any non-empty submitted payload as a mutation — a LOCKED_FACTOR_MUTATION 422 can fire for a subject whose stored ciphertext is merely corrupted, not one whose demographics actually changed. | Fail loudly (5xx or a dedicated DECRYPTION_FAILED 4xx) instead of silently defaulting to an empty dict when the existing ciphertext fails to decrypt on a locked-state comparison path; do not let a storage-integrity failure masquerade as "no prior data." |
(o_dt - b_dt).days / 365.25 in demographics.py:166 (calculate_age) | Fixed average-year-length division rather than calendar-accurate (leap-aware) age computation; an intentional simplification, not a bug, but one that must be reproduced bit-for-bit for golden-master parity. | Compute age as (observationDate.DayNumber - birthDate.DayNumber) / 365.25 (or equivalent TimeSpan.Days / 365.25) — do not substitute Period.Between/calendar-based year math, which disagrees with the legacy value near year boundaries. |
Full truthiness (if (not )?x:) site inventory beyond the one already-mitigated site_id check — same empty-string/falsy-collection ambiguity as the mitigated row above. Mechanically re-verified against current source with grep -nE '^\s*(el)?if \(?not? ?[A-Za-z_][A-Za-z0-9_.]*\)?:' during this remediation pass (not just re-copied from the Phase 1 report): services.py:121,124,126,130,185,187,218,220 (SubjectLifecycleService only — the identical pattern at services.py:259,264,296,331,360,390 is inside the out-of-scope ExecutionDOAUseCase and is excluded here, correcting the Phase 1 report's inclusion of :390); subject_lifecycle.py:225,251; demographics.py:66,97,114,210; subjects.py:290,300,334,442,446,449,472,533,548,597,607,609,616,677,697,746,757; consent_subscriber.py:59,102,209 — 35 in-scope sites by this mechanical count (36 including the already-mitigated site_id row above), vs. the Phase 1 report's raw count of 37; the residual difference is attributable to the DOA exclusion plus minor grep-methodology variance and does not change which fields are risk-bearing (see next column). | Each site treats an empty string / empty collection identically to a semantically-null/absent value. For most of these the ambiguity is harmless (e.g. if rand: on an ORM query result, if existing: on a merge branch), but on fields that gate behavior — study_id (446/449), target_state (597), gender_str/date_str/encrypted_str (demographics.py) — an empty string silently takes the same branch as "not provided," which may not be the intended contract when a caller can distinguish "field omitted" from "field explicitly sent empty." | Use string.IsNullOrWhiteSpace(...)/explicit null checks per-field rather than a blanket falsy check, and decide per-field (during Phase 2 domain modeling) whether an empty string should be treated as invalid input (validation error) rather than as "absent." |
4. Test Scenarios from Code (Legacy Test Reverse-Engineering)
The following test suites were reverse-engineered to establish the functional parity test baseline:
apps/execution/tests/test_subject_lifecycle_service.pyapps/execution/tests/test_subject_randomization_lifecycle.pyapps/execution/tests/test_pubsub_auto_enrollment.py
Reverse-Engineered Assertions
SCN-001: Sequential Enrollment & Audit Trail
- Given an empty study
STUDY-001 - When
SUBJ-001is enrolled - Then status is
SCREENING,enrollment_indexis0, demographics are encrypted, and an audit log with actionENROLL_SUBJECTis saved. - When
SUBJ-002is enrolled in the same study - Then status is
SCREENING,enrollment_indexis1.
- Given an empty study
SCN-002: Re-Consent Cascading Clearance
- Given subject with consent version 1 having
requires_reconsent == true - When subject executes consent version 2 with
icf_signed == trueandrequires_reconsent == false - Then consent version 1 is updated to
requires_reconsent == false, and consent version 2 is persisted withrequires_reconsent == false.
- Given subject with consent version 1 having
SCN-003: State Machine Allowed vs Forbidden Pathways
- Given subject in
SCREENING - Allowed transitions:
SCREEN_FAILED,ENROLLED,WITHDRAWN,RECONSENT_REQUIRED. - Forbidden transition:
ACTIVE,RANDOMIZED,COMPLETED-> ThrowsInvalidStateTransitionException. - Given subject in
ENROLLED - Allowed transitions:
RANDOMIZED,WITHDRAWN,RECONSENT_REQUIRED. - Forbidden transition:
ACTIVE,SCREENING-> ThrowsInvalidStateTransitionException. - Given subject in
RANDOMIZED - Allowed transitions:
ACTIVE,WITHDRAWN,UNBLINDED,RECONSENT_REQUIRED. - Forbidden transition:
SCREENING,ENROLLED-> ThrowsInvalidStateTransitionException. - Given subject in
COMPLETED,WITHDRAWN, orSCREEN_FAILED - All outgoing transitions are forbidden (terminal states).
- Given subject in
SCN-004: Stratification Factors Immutability Post-Randomization
- Given subject in
SCREENING - Updating
strat_factorsfrom{"site": "A"}to{"site": "B"}succeeds. - When subject transitions to
ENROLLEDand thenRANDOMIZED - Updating
strat_factorsto{"site": "C"}throwsLockedFactorMutationException(HTTP 422). - Updating demographics to a modified payload throws
LockedFactorMutationException(HTTP 422). - Calling
DELETE /demographicsthrowsSoftDeleteBlockedException(HTTP 403).
- Given subject in
SCN-005: Sovereign Site Compliance Gating
- Given subject in
SCREENINGat siteSITE-101 - When site has no completed
SITE_ACTIVATIONmilestone - Attempting to transition subject to
ENROLLED(via screening or state update) fails with HTTP 400 and recordsBLOCKED_ENROLLMENTaudit log. - When site receives eTMF completeness webhook and is activated
- Transition to
ENROLLEDsucceeds.
- Given subject in
SCN-006: Pre-Randomization Demographics Update Succeeds (source:
test_update_demographics,test_subject_lifecycle_service.py:181)- Given a subject enrolled with initial demographics
{"weight": 70.5}(statusSCREENING, i.e. pre-randomization) - When
SubjectLifecycleService.update_demographicsis called with{"weight": 71.0, "height": 175} - Then the call succeeds,
encrypted_demographicsis updated (re-encrypted), and an audit log with actionUPDATE_DEMOGRAPHICSis saved. - Contrast with SCN-004, which covers the same operation's rejection once the subject is post-randomization.
- Given a subject enrolled with initial demographics
SCN-007: Model-Layer Initial-State Persistence Under an Active Audit Context (source:
test_subject_initial_state_and_persistence,test_subject_randomization_lifecycle.py:97)- Given
current_user_idcontext var set to"investigator_1"andcurrent_change_reasonset to"Enrolling new subject SUBJ-001" - When a
ClinicalSubjectis created and flushed directly against the ORM inside a@transactional-decorated unit of work (not via the HTTP/service layer — this is a lower-level persistence check than SCN-001) - Then the persisted row's initial state is
status="SCREENING",strat_factorsequals the supplied dict,is_unblinded=False,randomization_id=None,kit_reference=None. - Correction made during this remediation pass: this test's own assertions cover only the field values above — it does not assert that the audit-context values land on the entity itself (
ClinicalSubjecthas noCreatedBy/UpdatedBy-style columns to assert against). The context vars it sets are exercised by the separate, out-of-slice DB-trigger audit bridge documented in Rule 6 above; this scenario's purpose for the .NET port is narrower than its docstring implies: confirm that entity construction with an active audit context still produces the correct initial field values, no more.
- Given
SCN-008: Unblinding & Withdrawal Field Capture (source:
test_unblinding_and_withdrawal_behavior,test_subject_randomization_lifecycle.py:279)- Given a subject transitioned
SCREENING → ENROLLED → RANDOMIZED - When
subject.unblind(unblinded_by="doctor_smith", reason="SAE-Life-Threatening-Event")is invoked - Then
status="UNBLINDED",is_unblinded=True,unblinded_by="doctor_smith",unblinded_reason="SAE-Life-Threatening-Event",unblinded_atis a timestamp (naive local time — see §3 dynamic-traps table). - When
subject.withdraw(reason="Subject withdrew consent")is subsequently invoked - Then
status="WITHDRAWN",withdrawal_reason="Subject withdrew consent",withdrawn_atis a timestamp (also naive local time). - These field-capture writes bypass the
@validates("status")transition guard's normal HTTP-layer error translation entirely —unblind/withdrawset.statusdirectly, so an illegal call sequence (e.g.withdraw()on an already-terminal subject) surfaces as a rawInvalidStateTransitionErrorto whatever caller invoked the model method, not as a pre-formatted HTTP response.
- Given a subject transitioned
SCN-009: PubSub Auto-Enrollment on Consent Completion (source:
test_pubsub_auto_enrollment_screening,test_pubsub_auto_enrollment.py:93)- Given no existing subject
SUBJ-AUTO-01in studySTUDY-AUTO - When a
{"action": "consent_completed", "subject_id": "SUBJ-AUTO-01", "study_id": "STUDY-AUTO", "site_id": "SITE-AUTO-01", "version_tag": "1.0", "version_index": 1}event is dispatched tohandle_consent_completed_message - Then a
ClinicalSubjectis auto-created withstatus="SCREENING",enrollment_index=0, anAuditLogrow (action="INSERT",table_name="clinical_subjects") is written, and aSubjectConsentcache row is auto-created withicf_signed=True,is_paper_override=False,requires_reconsent=False. - See Rule 8 for the full idempotency/backoff/MIG-06 contract this scenario is a slice of.
- Given no existing subject
SCN-010: Manual Paper-Consent Override Bypasses the Re-Consent Write Guard (source:
test_manual_physical_paper_consent_override,test_pubsub_auto_enrollment.py:247)- Given a newly-created subject with no consent on file, and the eConsent service unreachable (
fetch_subject_consent_statusraising 404) - When a write requiring active consent is attempted (e.g.
POST /api/v1/execution/visits) - Then it fails with HTTP 423 and detail
"Re-Consent Required - Demographics & Visit Forms Locked"— this is the cross-cuttingapps/execution/database/audit.pywrite-guard (PermissionError→ global handler), not this slice's ownReConsentRequiredException/423 path (§5, raise site #7); the two are independent mechanisms that happen to agree on status code today. - When
POST /subjects/{id}/consentis then called withis_paper_override=True,icf_signed=True,requires_reconsent=False - Then the consent record is saved (
is_paper_override=Trueechoed in the response) and, per Rule 3, clearsrequires_reconsentcascading. - When the same write is retried
- Then it now succeeds (
200 OK) — the paper-override consent row satisfies the write guard'shas_any_paper_overridecheck.
- Given a newly-created subject with no consent on file, and the eConsent service unreachable (
5. Error Taxonomy & Response Envelopes
Response envelope shape: every error response in this slice — whether raised directly as HTTPException(status_code, detail=...) in a router, or raised as a domain exception caught by one of main.py's three relevant global handlers (LockedFactorMutationError, InvalidStateTransitionError, PermissionError) — serializes as the bare two-field shape {"detail": "<string>"}. This slice never uses the richer ProblemDetails model (type/title/status/instance/code) that other handlers in main.py (e.g. SubjectEligibilityError, CodingAssignmentNotFoundError) already use. The .NET 10 port's IProblemDetailsService mapping must, at minimum, populate detail and status to match the table below for wire-compatible golden-master parity; upgrading the remaining fields to the full RFC 9457 shape for consistency with the rest of the app is a Phase 2 design choice, not a behavior this table mandates preserving as-is.
No global not-found handler exists for this slice's own domain exceptions. Every other error family raised in this slice (LockedFactorMutationError, InvalidStateTransitionError, PermissionError, FastAPI's RequestValidationError) has a registered @app.exception_handler in apps/execution/main.py. SubjectNotFoundError (and its base classes EntityNotFoundError/DomainError from packages/hexagonal) does not — its 404 mapping exists today only because the one call site that can trigger it in production HTTP traffic (update_subject_state_endpoint) happens to wrap the service call in a local try/except. .NET decision: register a global handler for the EntityNotFoundError family mapping to 404, consistent with how every sibling exception type is already handled, rather than relying on call-site-local catches.
Corrections to the Phase 1 validation report, verified directly against the current source during this remediation pass:
ReConsentRequiredExceptionis HTTP 423, not "428 / 403". The only router call site that catches it (apps/execution/presentation/routers/amendments.py, lines 364-368, on/api/v1/execution/amendments/validate-gating) maps it tostatus.HTTP_423_LOCKED. Rule 4 (§2.2) and raise site #7 below reflect the corrected code.subjects.py's screening-transition catch (line 496) is not a bareexcept Exception as e:catch-all. It is scoped specifically toInvalidStateTransitionError, raised when theClinicalSubject.statusORM@validatesguard rejects theSCREEN_FAILED/ENROLLEDassignment made a few lines earlier in the same block. The actual bare catch-all in this slice is atsubjects.py:643-644(raise site #19 below) — a distinct location from the one the Phase 1 report named.
5.1 Full Raise-Site Inventory (25 of 25 mapped)
| # | Raise Site | Exception | HTTP Status | Response Body | Notes / .NET Mapping |
|---|---|---|---|---|---|
| 1 | services.py:188 (advance_subject_state) | SubjectNotFoundError | 404 (only via the one caller's local catch — see raise site #17) | {"detail": "Subject not found"} | No global handler backs this — see callout above. Register one. |
| 2 | services.py:221 (update_demographics) | SubjectNotFoundError | (unreachable from HTTP today) | n/a | update_subject_demographics_endpoint bypasses the service layer and does its own inline query/404 (raise site #20); this service method is exercised only by SCN-006's unit test. Preserve the same domain not-found type in .NET regardless, so a future HTTP caller is covered by the global handler above. |
| 3 | apps/execution/database/models/subject.py:79 (validate_strat_factors) | LockedFactorMutationError | 422 (global handler) | {"detail": "LOCKED_FACTOR_MUTATION"} | Already scenario'd (SCN-004). ORM-level enforcement path — see #21/#23 for the router-level duplicate. |
| 4 | subject_lifecycle.py:156 (guard_subject_transition, known-but-forbidden) | InvalidStateTransitionError | 400 (global handler or router-local, see #18) | {"detail": "INVALID_STATE_TRANSITION"} | Already scenario'd (SCN-003). |
| 5 | subject_lifecycle.py:143 (initial transition, current=None) | InvalidStateTransitionError | 400 | {"detail": "INVALID_STATE_TRANSITION"} | Closed by Rule 9. Same type/status as #4, distinct branch (any first transition other than → SCREENING). |
| 6 | subject_lifecycle.py:149 (unknown/malformed state string) | InvalidStateTransitionError | 400 | {"detail": "INVALID_STATE_TRANSITION"} | Closed by Rule 9. No distinct error code from #4 — a typo'd state name and a legitimately-forbidden transition are indistinguishable to the caller. |
| 7 | subject_lifecycle.py:252 (validate_subject_version_gating) | ReConsentRequiredException | 423 (corrected from the Phase 1 report's "428 / 403") | {"detail": "Protocol Amendment {version} is active. Subject {id} must execute re-consent before data entry on visit {visit_id}."} | Only reachable via POST /api/v1/execution/amendments/validate-gating (outside this slice's own router, but the exception type is defined in subject_lifecycle.py). The unrelated audit.py write-guard (out-of-slice PermissionError) independently produces the same 423 status with a fixed message for the /visits write path — see SCN-010. .NET should not conflate the two into one exception type unless intentionally consolidating both enforcement layers. |
| 8 | subject_lifecycle.py:226 (validate_subject_version_gating, subject not found) | bare ValueError | 404 (only because amendments.py:369-373 specifically catches ValueError) | {"detail": "Subject {subject_id} not found."} | Gap. Inconsistent typing vs. every other not-found site in this slice (SubjectNotFoundError). .NET should raise the same typed not-found exception here. |
| 9 | subjects.py:381-384 (activate_site_endpoint) | HTTPException | 400 | {"detail": "Site activation blocked: Site {site_id} is not compliant in eTMF. Missing expected documents."} | New endpoint, documented in §1.1/§1.2. Writes a BLOCKED_ACTIVATION audit entry first. |
| 10 | subjects.py:443 (evaluate_and_transition_screening) | HTTPException | 404 | {"detail": "Clinical subject not found."} | Not-found site 1 of 5. Detail string differs from the other four ("Clinical subject not found." vs "Subject not found") — .NET should standardize on one message. |
| 11 | subjects.py:450-453 | HTTPException | 400 | {"detail": "Study ID must be provided in the payload or resolved from the ClinicalSubject."} | Missing/unresolvable study_id. |
| 12 | subjects.py:496-497 (except InvalidStateTransitionError as e:) | InvalidStateTransitionError → HTTPException | 400 | {"detail": str(e)} (free-text, e.g. "Transition from SCREENING to ENROLLED is forbidden.") | Not a bare catch-all — see corrections callout above. Only site among #4-#6/#18 whose body is the exception's own message rather than the fixed "INVALID_STATE_TRANSITION" string; .NET should pick one response shape for this family. |
| 13 | subjects.py:534 (get_subject_detail) | HTTPException | 404 | {"detail": "Subject not found"} | Not-found site 2 of 5. |
| 14 | subjects.py:598-600 (update_subject_state_endpoint) | HTTPException | 400 | {"detail": "Either status or state must be provided."} | Missing both status and state. |
| 15 | subjects.py:610 (update_subject_state_endpoint, ENROLLED-gate pre-check) | HTTPException | 404 | {"detail": "Subject not found"} | Not-found site 3 of 5; duplicates the dual-lookup that advance_subject_state performs again a few lines later. |
| 16 | subjects.py:627-630 (update_subject_state_endpoint, ENROLLED gate) | HTTPException | 400 | {"detail": "Subject enrollment blocked: Site {site_id} is not compliant."} | Already scenario'd (SCN-005) — state-update path variant of #9's sibling pattern for enrollment rather than site activation. |
| 17 | subjects.py:639-640 (except SubjectNotFoundError:) | SubjectNotFoundError → HTTPException | 404 | {"detail": "Subject not found"} | This is the one local catch that stands in for the missing global handler discussed in raise site #1. |
| 18 | subjects.py:641-642 (except InvalidStateTransitionError:) | InvalidStateTransitionError → HTTPException | 400 | {"detail": "INVALID_STATE_TRANSITION"} | Already scenario'd (SCN-003) — fixed-string variant (contrast #12's free-text variant). |
| 19 | subjects.py:643-644 (except Exception as e:) | any Exception → HTTPException | 400 | {"detail": str(e)} | The genuine bare catch-all in this slice (see corrections callout). Masks any unexpected failure (e.g. a database error) as a generic 400. .NET must not reproduce a blanket catch (Exception) → 400. |
| 20 | subjects.py:678 (update_subject_demographics_endpoint) | HTTPException | 404 | {"detail": "Subject not found"} | Not-found site 4 of 5. |
| 21 | subjects.py:690-692 (strat_factors, post-rand) | HTTPException | 422 | {"detail": "LOCKED_FACTOR_MUTATION"} | Already scenario'd (SCN-004) — router-direct-raise path, contrast #3's ORM-level path. |
| 22 | subjects.py:697-701 (with suppress(Exception): demographics decrypt) | (suppressed — no exception surfaces) | n/a | n/a | Also a Gate 5 dynamic trap (§3). Silently defaults to current_demo = {} on decrypt failure, which can spuriously trigger #23's LOCKED_FACTOR_MUTATION for a post-rand subject with merely-corrupted (not actually mutated) stored ciphertext. .NET should fail loudly here instead. |
| 23 | subjects.py:705-707 (demographics, post-rand) | HTTPException | 422 | {"detail": "LOCKED_FACTOR_MUTATION"} | Already scenario'd (SCN-004). |
| 24 | subjects.py:747 (delete_subject_demographics_endpoint) | HTTPException | 404 | {"detail": "Subject not found"} | Not-found site 5 of 5. |
| 25 | subjects.py:758 (delete_subject_demographics_endpoint, post-rand) | HTTPException | 403 | {"detail": "SOFT_DELETE_BLOCKED"} | Already scenario'd (SCN-004). |
5.2 Adjacent Out-of-Slice Error Surface (context only, not re-specified here)
| Mechanism | Exception | HTTP Status | Response Body |
|---|---|---|---|
apps/execution/database/audit.py session-flush write-guard | PermissionError (global handler, main.py:481-494) | 423 | {"detail": "Re-Consent Required - Demographics & Visit Forms Locked"} |
This exists to explain SCN-010's observed behavior; the write-guard's own logic (which tables/operations it gates, its has_any_paper_override/higher_reconsent computation) belongs to whichever spec owns apps/execution/database/audit.py and is out of scope for this document beyond the fact of its interaction with this slice's consent records.