# Sets, Records & Fragments

Records and Fragments define the structural models for synthetic entities generated by SimHealth. They combine primitive fields, categorical sets, probabilistic distributions, and nested structures into coherent data schemas.

## Record definitions

A root record definition begins with `Record(name)` followed by one field declaration per line:

```text
Record(patient)
id              1       Seq(patientId)
firstName       1       Set(givenNames)
lastName        1       Set(familyNames)
gender          1       Set(genders)
birthDate       1       dateBetween("1940-01-01", "2020-01-01")
active          1       boolean(0.95)
```

Each field line consists of three tab- or space-separated components:

1. **Field Name**: Valid alphanumeric identifier (e.g. `patientId`, `dischargeDate`).
2. **Cardinality**: `1` (required single value), `0..1` (optional value), `0..N` (dynamic list), or an inclusive range like `1..5`.
3. **Generator Expression**: Reference to a `Set`, `Seq`, `P(...)`, built-in generator function, or nested `Fragment`.

## Field cardinalities

| Cardinality | Semantics | Output Shape | Example |
| --- | --- | --- | --- |
| `1` | Exactly one (Required) | Scalar or Object | `mrn 1 Seq(mrnSeq)` |
| `0..1` | Optional (Nullable) | Scalar, Object, or `null` | `middleName 0..1 Set(givenNames)` |
| `0..N` | Variable List | Array of length derived from count distribution | `encounters 0..N Fragment(encounter) ~ P(encounterCount)` |
| `1..3` | Bounded List | Array of 1 to 3 items | `phoneNumbers 1..3 Fragment(phoneNumber)` |

> [!TIP]
> When defining `0..N` array fields, pair the cardinality with a Count distribution `~ P(itemCount)`. This lets you model realistic skew (e.g., most patients have 1–2 visits, while a small cohort has 10+).

## Fragments for nested structures

A `Fragment(name)` defines a sub-structure that is embedded inside records but is not exposed as a top-level sampleable API endpoint:

```text
# Define the nested component
Fragment(bloodPressure)
systolic        1       normal(120, 15)
diastolic       1       normal(80, 10)
measuredAt      1       timestamp()

# Embed inside an encounter record
Record(encounter)
id              1       Seq(encounterId)
vitals          1       Fragment(bloodPressure)
```

Generated JSON preserves the nested hierarchy:

```json
{
  "id": "ENC-009182",
  "vitals": {
    "systolic": 118,
    "diastolic": 79,
    "measuredAt": "2024-10-02T14:32:00Z"
  }
}
```

> [!WARNING]
> Fragments must be submitted with `kind: "records"` when using the Catalog API. There is no separate `fragments` kind. The engine parses the `Fragment(...)` prefix in the source code to assign fragment semantics.
