# Ancestral Sampling

Ancestral sampling is the relational synthesis engine behind SimHealth. Rather than generating flat, disjoint tables that break relational integrity, SimHealth compiles your dictionary schema into a directed acyclic graph (DAG) and executes top-down probabilistic draws.

> [!NOTE]
> Ancestral sampling guarantees that child records never violate referential integrity. When an encounter references a patient, the patient's demographics, age constraints, and identifiers are strictly respected.

## Relational DAG compilation

When a catalog is published, SimHealth's Rust engine builds a dependency graph:

```text
       ┌──────────────┐
       │   Sequence   │ (e.g. mrnSequence)
       └──────┬───────┘
              ▼
       ┌──────────────┐
       │ Parent Record│ (e.g. Patient)
       └──────┬───────┘
              │
       ┌──────┴──────────────────┐
       ▼                         ▼
┌──────────────┐          ┌──────────────┐
│ Child Record │ (Encounter)│ Distribution │ (conditionRates)
└──────┬───────┘          └──────┬───────┘
       │                         │
       └──────────────┬──────────┘
                      ▼
               ┌──────────────┐
               │ Grandchild   │ (LabObservation)
               └──────────────┘
```

1. **Root Nodes**: Sequences, Sets, and independent Distributions without upstream dependencies.
2. **Entity Nodes**: Records and Fragments whose fields consume values from root definitions or sibling entities.
3. **Topological Evaluation**: Nodes are resolved in topological order. Independent seeds sample root states; dependent nodes receive bound variables as ancestral context.

## Coherent cross-table constraints

Consider an encounter that requires a clinical date matching or following the patient's admission date:

```text
Record(encounter)
id          1       Seq(encounterId)
patientId   1       parent.patientId
admitDate   1       dateBetween("2024-01-01", "2024-12-31")
dischargeDate 1     dateAfter(admitDate, 1, 14)
```

Because `admitDate` is evaluated prior to `dischargeDate`, the generator can evaluate `dateAfter(admitDate, 1, 14)` conditionally without backtracking or rejection sampling penalties.

## Fragment composition vs flat records

SimHealth distinguishes between top-level sampleable root records and reusable fragments:

- **Root Records (`Record(...)`)**: Exposed directly via `GET /v1/projects/{project_id}/random/{recordType}`. Can be streamed in bulk to Avro OCF, NDJSON, or JSON.
- **Nested Fragments (`Fragment(...)`)**: Embedded components representing recurring structures (e.g. postal addresses, contact points, or order line items). Fragments cannot be sampled as standalone endpoints.

```text
# Reusable address component
Fragment(postalAddress)
street      1       Set(streetName)
city        1       Set(cityName)
state       1       Set(stateCode)
postalCode  1       Seq(zipSequence)

# Root patient record embedding the fragment
Record(patient)
mrn         1       Seq(mrnSequence)
name        1       Fragment(personName)
address     1       Fragment(postalAddress)
```

> [!TIP]
> Use Fragments for repeated sub-structures to keep your dictionary modular and DRY. Fragments share the parent entity's PRNG state branch, ensuring deterministic replay.
