Chapter 06: Phase 3 — Federation Protocol

6.1 Phase 3 in one paragraph

A night of sleep data rarely stays where it was recorded. A wearable vendor's cloud holds the raw session. A different organisation may score it. A hospital sleep clinic wants the scored result in its dashboard or chart. A university cohort wants a de-identified copy. Phase 3 of WIA-MED-021 defines how these independent hosts come to trust one another, how they exchange sessions without merging databases, how they resist replayed messages, and how they enforce the patient's consent at every hop. The first two phases defined what a sleep session looks like and how one host exposes it. This phase answers a different question: who may ask for it, on what authority, and what evidence remains afterwards.

The design follows the shape of sleep medicine itself. Data is large, since a single overnight polysomnography (PSG) produces 100–500 MB of EDF data. Records live for a long time, since clinics typically retain raw EDF for 7–25 years depending on local regulation. Scoring rules change over time, because the AASM Manual for the Scoring of Sleep and Associated Events is revised every few years. The patients are sometimes children, who cannot sign their own consent. Every mechanism in this chapter exists because one of those four facts makes a naive "copy the file to the other system" approach unsafe or impractical.

6.2 Roles

The protocol names five roles. They describe what a host does in a particular exchange, not what kind of company it is, and a single legal entity MAY play several of them.

RoleWhat it does
Recording hostHolds the raw session data and signs envelopes for downstream consumers
Scoring servicePerforms AASM-compliant scoring against a session's raw recording
Clinical hostA hospital sleep-clinic platform; receives scored sessions under consent
Research aggregatorReceives de-identified session data under explicit research consent
CustodianHolds the legally binding consent record: the patient, or the guardian for a minor

Two properties of this list matter in practice. First, the recording host is the authority for raw data. Scoring services and consumers come to it, rather than it pushing copies outward, so a withdrawal of consent has one place to take effect. Second, the custodian is a role rather than a server. For an adult it is usually the patient. For a paediatric patient it is the legal guardian, who must be cleared through the WIA-OMNI-API guardian-link flow before a consent envelope naming them is honoured. Sleep apnoea is increasingly recognised in children, so the guardian path is a routine case and not an edge case.

Because roles can be combined, a hospital might act as clinical host for its own patients and as recording host for an in-lab PSG, while sending scoring to an outside service. The standard does not assume a tidy one-organisation-per-role world. Trust is established per pair of peers by handshake and recorded in signed receipts, not inferred from what a peer is.

6.3 Federation handshake

Before two hosts exchange anything, they perform a federation handshake. The handshake deliberately reuses the receipt shape from WIA-SOCIAL Phase 3 §5, so a vendor that already ships a federation library for another WIA family standard can reuse it here. The receipt lifecycle is a small state machine:

IDLE → PENDING (origin verifies signature) → ACCEPTED → optional REVOKED

A host starts at IDLE with respect to a peer. When the peer presents a signed handshake, the state becomes PENDING while the origin verifies the signature. Once verification succeeds the receipt is ACCEPTED and both sides keep it. Either side may later move the relationship to REVOKED. Implementing this state machine is the first conformance requirement of the phase. Receipts persist for at least 25 years, matching typical clinical sleep-record retention norms. A receipt that disappears before the clinical record it justified is itself an audit finding.

The appendix of the standard contains a worked trace using three parties: a sleep lab on a vendor cloud (α), an academic research consortium (β), and a patient (λ). It is the clearest picture of how the handshake, consent and read fit together:

T-1d  λ publishes patient_consent (research_de_identified scope)
T+0   β → α: federation handshake (research aggregator role)
T+5s  α verifies + receipt issued; β stores receipt
T+10s β: GET /sm/session?patient_id=λ&kind=polysomnography
T+11s α: verifies consent + audience scope; returns de-identified
      session list (k-anonymity ≥ 5; no patient_id, only cohort token)
T+1h  λ revokes research consent
T+1h+1s α emits notice envelope; β confirms data destruction within
        the consent's redaction_window (24 hours default)
T+1d  β publishes signed destruction receipt

Note the order. The patient's consent exists a day before the handshake, so the research consortium never gains access merely by being a trusted peer. Trust between hosts is necessary but not sufficient. The read at T+10s succeeds only because the handshake receipt and a valid consent envelope are both present. If consent verification fails at any point, the recording host returns a problem document of type …/consent-not-found and the read is denied.

Trust between hosts also has to be maintained over time. Each host keeps a signed trust list of its federated peers: recording hosts, scoring services, clinical hosts and research aggregators. Lists are republished at least monthly, and peers refuse a list older than 60 days. Waiting for the next refresh would be too slow when a peer is compromised, so any peer may self-publish a revocation envelope that drops trust immediately.

The cryptographic suite is the usual modern set, fixed so that independent implementations interoperate:

UseAlgorithmReference
Identity signingEd25519IETF RFC 8032
HTTP message signingEd25519 over RFC 9421RFC 9421
Hashing (including EDF integrity)SHA-256FIPS 180-4
TransportTLS 1.3IETF RFC 8446
EDF at restAES-256-GCMFIPS 197 / NIST SP 800-38D

The SHA-256 row has a sleep-specific purpose. A multi-hundred-megabyte EDF file is moved or fetched between organisations, and a hash lets the receiver show that the recording a scoring service scored is the recording the recording host holds.

6.4 Patient consent envelope

The patient consent envelope is the gating control on cross-host data flow. It is a signed document, issued by the custodian, that names who may see which class of data and for how long:

{
  "wia_sleep_monitoring_version": "1.0.0",
  "type": "patient_consent",
  "patient_id": "did:wia:patient:01HXY",
  "custodian_id": "did:wia:patient:01HXY",
  "scopes": ["clinical_dashboard", "ehr_export", "research_de_identified"],
  "audiences": [
    { "audience_id": "did:wia:clinical-host:hospital-sleep-clinic-A", "scope": "clinical_dashboard" },
    { "audience_id": "did:wia:research:univ-X-sleep-cohort",          "scope": "research_de_identified" }
  ],
  "valid_from": "2026-04-01T00:00:00Z",
  "valid_until": "2027-04-01T00:00:00Z",
  "revocable": true,
  "signature": { "alg": "Ed25519", "value": "AY3o…" }
}

Three design choices stand out. First, consent is scoped, not binary. The same patient can allow a hospital clinic to see a dashboard while allowing a university cohort only a de-identified view, and the audiences array binds each named recipient to exactly one scope. Second, consent is time-bounded by valid_from and valid_until, so a one-year research participation does not silently become permanent. Third, consent is revocable, and the worked trace shows what revocation costs the recipient: a notice envelope, followed by confirmed destruction within the consent's redaction_window (24 hours by default) and a signed destruction receipt. In this envelope custodian_id equals patient_id. For a child, the two differ, and the guardian must have been cleared through the guardian-link flow before the host honours the envelope.

Scope is then translated into read behaviour by an audience matrix. Hosts MUST refuse any cross-class enrichment that would defeat it, for instance joining a de-identified research extract against a clinical table to re-attach identity.

AudienceVisibility
publicAggregate sleep statistics only
patientFull own data
caregiverPer-scope summaries, typically stage histograms rather than raw events
clinicianFull data for patients under active care
ehr_bridgeScoring summary only; raw events require elevated consent
research_de_identifiedDe-identified per HIPAA Safe Harbor §164.514(b)(2), under explicit research consent, k-anonymity ≥ 5

The matrix mirrors how sleep data is actually used. A caregiver looking after an elderly parent gets a stage histogram, which answers "is Dad sleeping better?", without the event-level trace. An electronic health record bridge gets the scoring summary, such as the headline indices a chart needs, while raw events stay behind a higher bar. A research aggregator never receives a patient identifier, only a cohort token, and the k-anonymity floor of 5 stops rare combinations of age, region and diagnosis from singling out one person.

When a patient changes clinic, the same machinery handles the move. The patient signs a session_move envelope. The new clinic then fetches the session history from the old one through a federated read, and the old clinic answers the original session URL with 301 Moved Permanently for at least 12 months. Anyone holding an old link is redirected to the new custodian of the record, not met with a dead end, and the patient's history follows the patient and is not trapped in the first clinic.

Every cross-host read leaves evidence. The audit log records the requesting peer's federation receipt, the consent envelope that was relied on, the scope actually returned, and the timestamp. It is append-only, and operators MUST NOT mutate earlier entries. It is the primary evidence for HIPAA, GDPR and AASM accreditation reviews, and for the same reason a host that fails over to a standby region has to replay any missed scoring envelopes from the primary's log. Sleep studies are typically scored within one to three days, so failover is rarely urgent, but a gap in the evidence trail is exactly what an auditor will flag.

6.5 Replay defence

A signed envelope is valid wherever it is presented, so an attacker who captures one, whether a consent grant, a stage batch or a scoring result, could resend it later. The standard blocks this with two ingredients on every signed envelope (session, stage batch, event, scoring, consent): a 96-bit nonce and an RFC 3339 timestamp. Receivers MUST then apply three rules:

The two windows work together. The 300-second skew bound means a stolen envelope goes stale quickly, and the 600-second cache means a replay inside the freshness window is caught. The cache only has to cover the span in which an envelope could still pass the skew check, which keeps it small.

The size of that cache is worked out in the standard's appendix. Consider a sleep-lab cloud receiving 50 session-stage batches per second across all customers at the peak of post-overnight upload. The cache must hold roughly 50 × 600 = 30,000 entries. With 16-byte nonce keys plus a 4-byte timestamp, a strict footprint is about 30,000 × 24 ≈ 720 KiB. Hosts SHOULD provision at least double that to absorb morning-upload bursts, since sleep data arrives in a sharp daily wave when many users wake and sync at once.

For high-volume bulk stage submission the cache MAY be a Bloom filter, which trades a little certainty for a smaller memory footprint. The standard puts a safety rule on that trade: a false positive MUST trigger a re-fetch through the standard's pull endpoints and MUST NOT cause a silent drop. Quietly discarding a real stage batch would punch a hole in a patient's night with no one aware of it. A forced re-fetch turns that error into a harmless extra request.

Replay state also has to survive failure. When a host fails over from primary to standby, the standby MUST reload the persistent seen-nonce cache before resuming envelope processing. It MUST also re-issue handshakes to peers whose receipts it does not hold, and send a notice envelope announcing the switchover with an estimated restore_at for the primary. Starting with an empty cache would give an attacker a free replay window right after an outage.

6.6 Cross-host scoring re-computation

Scoring is the interpretive step that turns a raw recording into sleep stages and events, and the AASM Manual changes over time. When a new Manual is published, existing sessions may need re-scoring under the new rules. Re-shipping hundreds of megabytes per session between organisations would be costly and would multiply copies of sensitive data, so the standard does it without moving the raw data around:

  1. The recording host keeps the original scoring_metadata.
  2. A scoring service, possibly a different organisation, federates with the recording host, fetches the EDF recording, scores it under the new algorithm, and POSTs a new scoring_metadata back to the recording host with supersedes referencing the prior one.
  3. The recording host preserves both scoring_metadata records.
  4. Downstream consumers choose which scoring to trust for their use case.

The word "supersedes" means the new record is a successor in a chain, and the old record is not deleted. That matters for the fourth step. A research consortium typically pins to one algorithm version so that results across a cohort are comparable, and it would be a methodological problem if the numbers shifted because an upstream host quietly re-scored. A clinic, by contrast, usually wants the latest rules. Both can be served from the same recording host. Supporting this chain is a conformance requirement of the phase.

Paediatric data needs particular care here. The AASM rules for children differ from the adult rules, so the scoring_algorithm field must distinguish them, for example AASM-2024-paediatric. Without that, an adult-rule comparison against a child's recording could be made without anyone noticing. The reference container ships a built-in AASM-2024-default scoring algorithm for the consumer-grade part of the workload, which is a reminder that the default is not automatically right for every patient.

Cross-Chapter Anchors

Where to Look Next

Hosts that publish bridge_profile=Full should run the black-box conformance suite and its extension tests for at least one third-party scoring algorithm and one vendor wearable platform. These tests exercise the most failure-prone parts of this chapter: consent enforcement, replay bounds and the scoring chain. The wia/sleep-monitoring-host:1.0.0 reference container implements every endpoint of the phase with mock data, so an integrator can rehearse a handshake, a consent revocation and a supersedes re-score before touching real patient data. Its SQLite-backed store suits small-to-medium clinical-research deployments, up to 100,000 sessions.

For planning, remember the cost the standard says integrators underestimate. Cold storage for EDF files typically dominates the budget, more than the signature or nonce machinery, so retention policy deserves attention before the cryptography does.

Patient and Clinician Considerations

For patients, the practical meaning of this phase is control that survives distribution. A consent envelope says who may see what and until when, a revocation triggers a notice and a destruction receipt within the redaction window, and a caregiver or an EHR bridge sees only a summary unless a higher consent is given. Parents or guardians exercise the same rights on behalf of a child, once the guardian link has been cleared. A patient who changes clinics carries the history through a session_move, with the old clinic redirecting for at least 12 months.

For clinicians, the phase supplies assurance about what a received record is. A scored session arrives with a handshake receipt and a consent reference behind it, and the scoring algorithm and version are stated. When a later re-score exists, both versions remain visible and the chain shows which supersedes which. Clinicians should check the scoring_algorithm before comparing a child's study against adult norms, and should expect an EHR-bridge view to hold a summary rather than raw events.

To summarise the chapter: federation in sleep monitoring rests on five mechanisms. Roles say who does what. A handshake with a long-lived receipt establishes trust. A scoped, time-bounded, revocable consent envelope gates every read. Nonce-and-timestamp replay defence protects signed traffic. A supersedes chain lets scoring be redone across organisations without moving the recording. An append-only audit log ties them together. The chapter that follows moves on to Phase 4, the last of the four phases, picking up from the point where hosts can already trust one another, exchange data and prove what they did.