Ir para o conteúdo

Sequence Diagrams — HDT-AF

Historical reference: this file contains older sequence diagrams and is not a complete description of the current implementation. Check the status note before using a diagram operationally; current architecture diagrams are maintained in docs/slides/diagramas/.


1. Complete Experiment Lifecycle

Diagrama PlantUML 1

Ver código-fonte PlantUML
    @startuml "HDT-AF - Complete Experiment Lifecycle"
    !theme plain
    skinparam shadowing false

    actor "Researcher" as P
    participant "Web Monitor" as M
    participant "AdminMonitoringService" as AMS
    participant "ExperimentContractChaincode" as ECC
    participant "ClientConsentChaincode" as CCC
    participant "LedgerPort (Fabric)" as LP

    P -> M : GET /experiments/new
    M --> P : Creation form
    P -> M : POST /experiments/new {id, coordinator, objective, taskType}
    M -> AMS : createExperiment(id, coordinator, objective, ...)
    AMS -> ECC : createExperimentContract(contract DRAFT)
    AMS --> M : ExperimentContract{status=DRAFT}
    M --> P : redirect /experiments/{id}

    P -> M : POST /experiments/{id}/publish
    M -> AMS : publishExperiment(id, version)
    AMS -> ECC : publishExperimentContract(id, version)
    AMS -> LP : publishExperimentContract(id, version)
    LP -> LP : writes to Fabric (required BLOCKCHAIN mode)

    loop For each client
        P -> M : POST /experiments/{id}/clients/{clientId}/accept
        M -> AMS : acceptClient(id, version, clientId)
        AMS -> CCC : acceptExperimentContract(...)
        AMS -> LP : acceptExperimentContract(...)
    end

    P -> M : POST /experiments/{id}/activate
    M -> AMS : activateExperiment(id, version)
    AMS -> ECC : activateExperimentContract(id, version)
    AMS -> LP : activateExperimentContract(id, version)

    loop N federated learning rounds
        P -> M : POST /experiments/{id}/start
        M -> AMS : startExperiment(id, version)
    end

    P -> M : POST /experiments/{id}/close {reason}
    M -> AMS : closeExperiment(id, version, reason)
    AMS -> ECC : closeExperimentContract(id, version, finalHash)
    AMS -> LP : (mirrors onto Fabric)

    @enduml

2. Flow of a Federated Training Round

Diagrama PlantUML 2

Ver código-fonte PlantUML
    @startuml "HDT-AF - Flow of a Federated Training Round"
    !theme plain
    skinparam shadowing false

    participant "AdminMonitoringService" as AMS
    participant "RoundCoordinator" as RC
    participant "MqttGateway" as MQTT
    participant "Client 1" as C1
    participant "Client N" as C2
    participant "FedAvgAggregationService" as AGG
    participant "ArtifactService" as ART
    participant "FederatedExperimentChaincode" as FEC

    AMS -> RC : startRoundWithHyperparameters(contract, roundId, hp)
    RC -> RC : select clients (FederatedRoundStrategy)
    RC -> MQTT : publish RoundConfig (signed, fl/experiments/.../config)
    RC -> FEC : registerTrainingRound(experimentId, roundId, configHash)

    par Parallel training per client
        MQTT --> C1 : RoundConfig
        C1 -> C1 : verify(envelope.signature)
        C1 -> C1 : preflight(DataProfileService)
        C1 -> C1 : TrainingLocalModel.train(authorizedView)
        C1 -> ART : store(localUpdate.bin, metrics.json)
        C1 -> MQTT : publish ClientUpdate (signed, fl/.../updates)
    else
        MQTT --> C2 : RoundConfig
        C2 -> C2 : verify → preflight → train → store
        C2 -> MQTT : publish ClientUpdate
    end

    MQTT -> AGG : MqttClientUpdateCollector.updatesFor(...)
    AGG -> AGG : selectValidUpdates (hash · signature · norm · dimension)
    AGG -> AGG : strategy.selectUpdates (FedAvg/FedMedian/Krum/...)
    AGG -> AGG : checkQuorum (minimumClients, minimumTotalExamples)
    AGG -> AGG : computeWeights
    AGG -> AGG : combine → globalModelVector
    AGG -> ART : store(globalModel.bin, aggregationReport.json)
    AGG -> FEC : registerAggregationHash(...)
    AGG -> FEC : registerGlobalModelVersion(...)
    AGG -> MQTT : publish GlobalModelPublication (signed)
    AGG -> AGG : clearRound(experimentId, roundId)

    AMS -> AMS : registerRoundLearningMetrics(metrics)

    @enduml

3. MQTT Dataset Ingestion (Replay Simulator → DataComponent)

Diagrama PlantUML 3

Ver código-fonte PlantUML
    @startuml "HDT-AF - MQTT Dataset Ingestion"
    !theme plain
    skinparam shadowing false

    participant "IotDatasetReplayApp" as SIM
    participant "HarMqttReplayAdapter\n(or EcgMqttReplayAdapter)" as ADAPTER
    participant "InMemoryMqttGateway" as MQTT
    participant "DataComponent" as DC
    participant "MqttTimeSeriesIngestor" as MTSI
    participant "CsvTimeSeriesStore" as CTSS
    participant "InMemoryLocalCdmRepository" as REPO

    SIM -> ADAPTER : replayAll()
    SIM -> DC : subscribeToMqttSource(clientId, experimentId, mqtt, signatures)
    DC -> MTSI : create and register ingestor
    MTSI -> MQTT : subscribe(iot/clients/{clientId}/entities/+/observations)
    MTSI -> MQTT : subscribe(iot/clients/{clientId}/entities/+/events)

    loop For each window/beat/observation
        ADAPTER -> MQTT : publish ObservationMessage (signed)
        MQTT --> MTSI : deliver ObservationMessage
        MTSI -> MTSI : verify(envelope.signature)
        MTSI -> CTSS : append(observation_ts.csv)
    end

    SIM -> DC : materializeDatasetFromStore(clientId, experimentId)
    DC -> CTSS : readAll(observations · events · entities)
    DC -> DC : convert → dataset.csv (CDM format)
    DC -> REPO : build InMemoryLocalCdmRepository


    @enduml

4. Web Monitor Sequence Diagram (Lifecycle via HTTP)

Diagrama PlantUML 4

Ver código-fonte PlantUML
    @startuml "HDT-AF - Web Monitor Sequence (Lifecycle via HTTP)"
    !theme plain
    skinparam shadowing false

    actor "Researcher (Browser)" as P
    participant "AdminWebServer" as AWS
    participant "AdminMonitoringService" as AMS
    participant "ExperimentContractFactory" as ECF
    participant "ExperimentContractChaincode" as ECC
    participant "LedgerPort" as LP

    P -> AWS : GET /experiments/new
    AWS --> P : renderNewExperimentForm() → HTML

    P -> AWS : POST /experiments/new {experimentId, objective, ...}
    AWS -> AMS : createExperiment(id, coordinator, objective, dtType, taskType)
    AMS -> ECF : buildDraft(id, version, ...)
    ECF --> AMS : ExperimentContract{DRAFT}
    AMS -> ECC : createExperimentContract(contract)
    AWS --> P : redirect /experiments/{id}?version=1.0.0

    P -> AWS : GET /experiments/{id}/lifecycle
    AWS -> AMS : experimentView(id, version)
    AMS --> AWS : ExperimentMonitorView{status=DRAFT}
    AWS --> P : renderLifecyclePage() → visual state machine

    P -> AWS : POST /experiments/{id}/publish
    AWS -> AMS : publishExperiment(id, version)
    AMS -> ECC : publishExperimentContract(id, version)
    AMS -> LP : publishExperimentContract(id, version)
    AWS --> P : redirect

    P -> AWS : POST /experiments/{id}/activate
    AWS -> AMS : activateExperiment(id, version)
    AMS -> ECC : activateExperimentContract(id, version)
    AMS -> LP : activateExperimentContract(id, version)
    AWS --> P : redirect

    P -> AWS : POST /experiments/{id}/start
    AWS -> AMS : startExperiment(id, version)
    AWS --> P : redirect → updated metrics

    P -> AWS : GET /experiments/{id}/blockchain
    AWS -> AMS : ledgerAssets(id, version)
    AWS -> AMS : auditEvents(id, roundId)
    AWS --> P : renderBlockchainExplorer() → assets + events

    @enduml

5. Federated Orchestration and Aggregation (Detailed)

Diagrama PlantUML 5

Ver código-fonte PlantUML
    @startuml "HDT-AF - Federated Orchestration and Aggregation (Detailed)"
    !theme plain
    skinparam shadowing false

    title Federated Orchestration and Aggregation Process — HDT-AF

    actor "Researcher" as Pesq
    participant "Web Monitor\n(Admin API)" as MON
    participant "RoundCoordinator" as ORC
    participant "ParticipationPolicy\n+ Strategy" as PP
    participant "ClientConsent\nChaincode" as CON
    participant "FederatedExperiment\nChaincode" as EXP
    participant "MQTT Gateway" as MQ
    participant "Federated Clients\n(C1, C2 … Cn)" as CLI
    participant "MqttClientUpdate\nCollector" as UC
    participant "FedAvgAggregation\nService" as AGG
    participant "ArtifactExperiment\nService" as ART
    participant "Hyperledger\nFabric" as FAB

    Pesq -> MON : POST /experiments/{id}/rounds/start
    MON -> ORC : startRound(contract, roundId, globalModelVersion)

    ORC -> ORC : resolveStrategy(contract)\n  → ParticipationPolicy.selectionStrategyId()\n  → layer 1: contract strategy\n  → layer 2: AggregationPolicy.participationStrategyId()\n  → layer 3: fallbackStrategy
    ORC -> ORC : resolveDeadlineSeconds(contract)\n  → ExperimentSchedule.roundTimeoutSeconds()\n  → fallback: env ROUND_DEADLINE_SECONDS\n  → fallback: 3600L

    ORC -> CON : listAcceptedClients(experimentId, contractVersion)
    CON --> ORC : [C1, C2, C3, C4, C5] — all who consented

    alt eligibleClientIds defined in ParticipationPolicy
        ORC -> ORC : filter pool → keep only eligible IDs
    end

    ORC -> PP : selectClients(acceptedPool, roundId)

    alt strategy = all_accepted
        PP --> ORC : [C1, C2, C3, C4, C5] — all
    else strategy = random_sampled (fraction=0.7)
        PP -> PP : shuffle pool with random seed
        PP --> ORC : [C1, C3, C5] — 70% sampled
    else strategy = round_robin (groupSize=2)
        PP -> PP : offset = roundId mod poolSize
        PP --> ORC : [C2, C4] — next slice of 2
    end

    ORC -> ORC : verify |selectedClients| ≥ minimumClients\n  (ParticipationPolicy.minimumClients)

    ORC -> EXP : getGlobalModel(experimentId, globalModelVersion)
    EXP --> ORC : GlobalModel(uri, hash, version)

    ORC -> ORC : buildRoundConfig(\n  roundId, selectedClients, deadline,\n  hyperparameters = {\n    participation_strategy,\n    round_timeout_seconds,\n    max_rounds,\n    termination_condition,\n    epochs, batch_size, …\n  }\n)

    ORC -> ORC : sign MQTT envelope

    ORC -> MQ : [MQTT] fl/experiments/{id}/rounds/{n}/config\n  RoundConfig(selectedClients, deadline, hyperparameters,\n    globalModelUri, globalModelHash, signature)

    ORC -> EXP : registerTrainingRound(experimentId, roundId,\n  selectedClients, hyperparameters, deadline)
    EXP --> FAB : TrainingRound asset written on-chain

    ORC --> MON : RoundConfig (200 OK)
    MON --> Pesq : round {n} started — {k} clients selected

    par Each client executes in parallel
        MQ -> CLI : receives RoundConfig
        CLI -> CLI : preflight + local training\n  (see diagram 6 — local training)
        CLI -> MQ : [MQTT] update with trained weights
        MQ -> UC : captures message on topic\n  fl/experiments/{id}/rounds/{n}/clients/{id}/update
    end

    ORC -> ORC : waitForUpdates(deadline, selectedClients,\n  nonResponsivePolicy)

    alt nonResponsivePolicy = PROCEED_WITH_AVAILABLE
        ORC -> ORC : after deadline: use received updates
    else nonResponsivePolicy = REQUIRE_FULL_PARTICIPATION
        ORC -> ORC : wait for ALL selected clients\n  or abort round
    else nonResponsivePolicy = REQUIRE_QUORUM_OF_SELECTED
        ORC -> ORC : verify |received| ≥ minimumClients (aggregation)
    end

    ORC -> AGG : aggregateFromMessages(contract, roundConfig, updates)

    AGG -> UC : updatesFor(experimentId, contractVersion, roundId)
    UC --> AGG : [ClientUpdate(C1), ClientUpdate(C3), ClientUpdate(C5)]

    AGG -> AGG : verify signature of each update
    AGG -> AGG : verify clientId ∈ selectedClients

    loop For each update received
        AGG -> AGG : compute update_norm = ‖w_i‖₂
        alt update_norm > maxUpdateNorm
            AGG -> AGG : reject update as outlier
        else clippingEnabled = true
            AGG -> AGG : clip: w_i = w_i × (maxNorm / norm)
        end
        AGG -> AGG : compute weight_i = sampleCount_i / totalSamples
        AGG -> AGG : apply maxClientWeight / minClientWeight
    end

    AGG -> AGG : verify |validUpdates| ≥ minimumClients (aggregation)
    AGG -> AGG : verify Σ sampleCount ≥ minimumExamples

    AGG -> AGG : compute W_global = weighted average

    AGG -> ART : store(experimentId + "/global/v{n+1}", "global_model.bin", bytes)
    ART --> AGG : ArtifactReference(uri, hash)

    AGG -> EXP : publishGlobalModel(experimentId, roundId,\n  modelHash, modelUri, aggregatorId)
    EXP --> FAB : GlobalModel v{n+1} asset written on-chain

    AGG --> ORC : AggregationReport(\n  globalModelVersion=n+1,\n  participantCount, totalExamples,\n  globalModelVector, rejectedClients,\n  evaluationMetrics\n)

    ORC -> MQ : [MQTT] fl/experiments/{id}/rounds/{n}/model\n  GlobalModel(uri, hash, version=n+1, signature)

    ORC -> MON : AggregationReport (persisted in the session)
    MON --> Pesq : round {n} metrics available on the dashboard

    alt schedule.terminationCondition = MAX_ROUNDS
        ORC -> ORC : shouldTerminateAfter(completedRounds)?
        alt completedRounds ≥ maxRounds
            ORC --> MON : EXPERIMENT CLOSED (MAX_ROUNDS reached)
            MON --> Pesq : automatic closing notification
        else
            ORC --> MON : ready for round {n+1}
        end
    else schedule.terminationCondition = MANUAL
        MON --> Pesq : awaiting researcher's decision
        Pesq -> MON : POST /experiments/{id}/rounds/start  ← next round
    end

    @enduml

6. Local Training (Detailed)

Diagrama PlantUML 6

Ver código-fonte PlantUML
    @startuml "HDT-AF - Local Training (Detailed)"
    !theme plain
    skinparam shadowing false

    title Local Training Process — HDT-AF

    actor "Researcher" as Pesquisador
    participant "ExperimentContract\nChaincode" as CC
    participant "ClientConsent\nChaincode" as CON
    participant "FederatedClient\nService" as CLI
    participant "DataComponent" as DC
    participant "LocalCDM\nRepository" as CDM
    participant "Preflight\nChecker" as PRE
    participant "TrainingLocalModel" as TLM
    participant "MQTT Gateway" as MQ
    participant "Hyperledger\nFabric" as FAB

    Pesquisador -> CC : createExperimentContract(contract)
    CC --> FAB : ExperimentContract asset written on-chain
    Pesquisador -> CC : registerTrainingCode(experimentId, codeHash, manifestHash)
    Pesquisador -> CC : publishExperimentContract(experimentId, version)
    Pesquisador -> CC : activateExperimentContract(experimentId, version)
    CC --> FAB : status = ACTIVE registered on-chain

    CLI -> CC : getExperimentContract(experimentId, version)
    CC --> CLI : ExperimentContract(ACTIVE)
    CLI -> CLI : verify contract hash
    CLI -> CON : acceptExperimentContract(experimentId, version,\n  clientId, contractHash, signature)
    CON --> FAB : ConsentRecord written on-chain
    CON --> CLI : OK — consent recorded

    MQ -> CLI : [MQTT] fl/experiments/{id}/rounds/{n}/config\n  RoundConfig(roundId, modelVersion, deadline,\n  hyperparameters, participationStrategy)
    CLI -> CLI : verify MQTT envelope signature
    CLI -> CLI : verify clientId is in the participant list

    CLI -> DC : loadLocalCdmRepository(clientId, experimentId)
    DC -> CDM : read data/{clientId}/{experimentId}/
    CDM --> DC : LocalCdmRepository
    DC --> CLI : dataset authorized by the contract

    CLI -> PRE : runPreflightChecks(contract, dataset)

    PRE -> PRE : verify sampleCount ≥ minimumSamples
    PRE -> PRE : verify positiveCount ≥ minimumPositives
    PRE -> PRE : verify entityCount ≥ minimumEntities
    PRE -> PRE : verify completeness ≥ completenessMin
    PRE -> PRE : verify prohibited fields are absent

    alt preflight PASSED
        PRE --> CLI : PreflightResult(OK, sampleCount, positiveCount)
    else preflight FAILED
        PRE --> CLI : PreflightResult(FAILED, failedChecks=[...])
        CLI -> MQ : [MQTT] fl/experiments/{id}/rounds/{n}/clients/{id}/status\n  {status: PREFLIGHT_FAILED, checks: [...]}
    end

    CLI -> TLM : execute(TrainingContext(dataset, hyperparameters,\n  globalModel, contract))

    TLM -> TLM : load global model (globalModelVersion)
    TLM -> TLM : initialize weights (He init or received model)

    loop For each epoch (1..epochs)
        TLM -> TLM : forward pass (batch)
        TLM -> TLM : compute loss (cross_entropy / MSE)
        TLM -> TLM : backpropagation
        TLM -> TLM : apply FedProx: g = g + μ(w - w_global)
        TLM -> TLM : apply L2 weight decay
        TLM -> TLM : gradient clipping (L2 norm)
        TLM -> TLM : update weights via Adam (β1, β2, ε)
        TLM -> TLM : compute epoch metrics
        alt early stopping
            TLM -> TLM : verify delta < minDelta for patience epochs
        end
    end

    TLM -> TLM : serialize weights → vector of doubles (CSV)
    TLM -> TLM : compute update_norm (L2 norm of the vector)
    TLM --> CLI : TrainingResult(updateVector, metrics, status=SUCCESS)

    CLI -> CLI : verify update_norm ≤ maxUpdateNorm from the contract
    CLI -> CLI : sign MQTT envelope (HmacSignatureService)

    CLI -> MQ : [MQTT] fl/experiments/{id}/rounds/{n}/clients/{id}/update\n  ClientUpdate(updateVector, metrics, sampleCount,\n  modelVersion, clientId, signature)

    CLI -> FAB : register evidence: roundId, clientId,\n  updateHash, sampleCount, timestamp
    FAB --> CLI : TX confirmed on-chain

    CLI -> MQ : [MQTT] fl/experiments/{id}/rounds/{n}/clients/{id}/status\n  {status: COMPLETED, metrics: {...}}

    @enduml

7. Experiment Contract State Machine

Diagrama PlantUML 7

Ver código-fonte PlantUML
    @startuml "HDT-AF - Experiment Contract State Machine"
    !theme plain
    skinparam shadowing false

    [*] --> DRAFT : createExperiment()\nExperimentContractFactory.buildDraft()

    DRAFT --> PUBLISHED : publishExperiment()\nECC.publishExperimentContract()
    DRAFT --> REVOKED : revokeExperiment(reason)

    PUBLISHED --> ACTIVE : activateExperiment()\nECC.activateExperimentContract()
    PUBLISHED --> REVOKED : revokeExperiment(reason)

    ACTIVE --> PAUSED : pauseExperiment()\nECC.pauseExperimentContract()
    ACTIVE --> CLOSED : closeExperiment(note)\nECC.closeExperimentContract()
    ACTIVE --> REVOKED : revokeExperiment(reason)

    PAUSED --> ACTIVE : activateExperiment()\n(reactivation)
    PAUSED --> CLOSED : closeExperiment(note)
    PAUSED --> REVOKED : revokeExperiment(reason)

    CLOSED --> [*] : ArtifactRetentionPolicy\n(LGPD Art. 15 — delete artifacts)
    REVOKED --> [*] : ArtifactRetentionPolicy\n(ethical revocation)



    @enduml

8. Federated Training with IoT Simulator and Hyperledger Fabric

Complete flow of a round initiated by the web monitor's Simulation Session, going through: dataset replay via MQTT → ingestion and materialization by DataComponent → preflight → local training with on-chain registration → aggregation with global model publication on Fabric.

Stale beyond the store rename below. Only the CsvTimeSeriesStore/observation_ts.csv references in this diagram were corrected (BL-146). The round protocol (fl/) shown here as raw MQTT publish/subscribe happens to match current production again: BL-241/BL-242 had temporarily moved it to REST+SSE for every JVM/Docker composition root, but that migration was reverted (BL-259) at the user's request, so plain MQTT is once more accurate for this part of the diagram. SimulationRoundEngine no longer touches MqttGateway directly (BL-246); and the aggregation phase further down predates BL-244 (the aggregator is now a pure function called directly by the orchestrator, not an independent MQTT subscriber). A full rewrite of this diagram is out of scope for this pass — see the actively maintained docs/slides/diagramas/07-fluxo-simulacao.puml, 04-status-cliente-rodada.puml, and 01-arquitetura.puml for the current architecture.

Diagrama PlantUML 8

Ver código-fonte PlantUML
    @startuml "HDT-AF - Federated Round with IoT Simulator and Hyperledger Fabric"
    !theme plain
    skinparam shadowing false

    title Federated Round: IoT Simulator + Hyperledger Fabric — HDT-AF

    actor "Researcher\n(Web Monitor)" as P
    participant "SimulationRoundEngine" as SRE
    participant "HarMqttReplayAdapter\n(or EcgMqttReplayAdapter)" as ADP
    participant "InMemoryMqttGateway" as MQ
    participant "MqttTimeSeriesIngestor" as INJ
    participant "CsvTimeSeriesStore" as CSV
    participant "DataComponent" as DC
    participant "RoundCoordinator" as ORC
    participant "FederatedClientService\n(C1 … Cn)" as CLI
    participant "LocalArtifactExperimentService" as ART
    participant "FedAvgAggregationService" as AGG
    participant "LedgerPort\n(FabricCliLedgerMirror)" as LP
    participant "Hyperledger Fabric\n(FederatedExperimentChaincode)" as FAB

    P -> SRE : POST /sim-session/start\n{type, path, maxClients, totalRounds}
    SRE -> SRE : create SimulationSession{status=ACTIVE,\ncurrentRound=0, totalRounds=N}
    SRE --> P : redirect /sim-session ("▶ Session" tab)

    P -> SRE : POST /sim-session/send-round (or run-all)
    SRE -> SRE : cache adapter: "har:path:k" → HarMqttReplayAdapter\n(avoids reloading the CSV every round)

    SRE -> ADP : replayAllRound(roundNumber=1, totalRounds=N)
    ADP -> ADP : deterministic slicing\nfromRow=(round-1)*chunkSize\ntoRow=round*chunkSize (last one absorbs the remainder)

    loop For each client (C1 … Cn) in parallel
        ADP -> MQ : publish MqttEnvelope<ObservationMessage>\n[iot/clients/{id}/entities/{e}/observations]
        MQ --> INJ : deliver (subscribe wildcard iot/clients/{id}/entities/+/observations)
        INJ -> INJ : envelope.verify(signatureService)\n→ silently rejects invalid message
        INJ -> CSV : append(observation_ts.csv)
    end

    SRE -> DC : materializeDatasetFromStore(clientId, experimentId)
    DC -> CSV : readAll(observations · events · entities)
    DC -> DC : convert → dataset.csv (CDM format)\nwrite to data/{clientId}/{experimentId}/

    SRE -> ORC : startRound(contract, roundId, globalModelVersion)
    ORC -> ORC : select clients\n(all_accepted / random_sampled / round_robin)
    ORC -> ORC : resolveDeadline\n(ExperimentSchedule → env ROUND_DEADLINE_SECONDS → 3600s)
    ORC -> ORC : buildRoundConfig(roundId, selectedClients,\nhyperparameters, deadline, globalModelUri)
    ORC -> ORC : sign HMAC envelope

    ORC -> MQ : publish MqttEnvelope<RoundConfig>\n[fl/experiments/{id}/rounds/{n}/config]
    ORC -> LP : registerTrainingRound(experimentId, roundId,\nselectedClients, configHash)
    LP -> FAB : peer chaincode invoke\nFederatedExperimentChaincode:registerTrainingRound\n→ TrainingRound asset written on-chain
    FAB --> LP : TX confirmed

    par Parallel execution per client
        MQ --> CLI : receives RoundConfig
        CLI -> CLI : envelope.verify(signatureService)
        CLI -> CLI : verify clientId ∈ selectedClients

        CLI -> DC : loadLocalCdmRepository(clientId, experimentId)
        DC --> CLI : materialized dataset (dataset.csv)

        CLI -> CLI : DataProfileService.runPreflight(contract, repo)\n→ checks sampleCount, positiveCount,\n  completeness, prohibited fields

        alt preflight PASSED
            CLI -> CLI : TrainingLocalModel.execute(\n  authorizedView, hyperparameters, globalModel)
            CLI -> CLI : epoch loop: forward → loss → backprop\n  → FedProx → L2 → clip → Adam → EpochPoint


            CLI -> ART : store(local_update.bin · metrics.json · data_profile.json)
            ART --> CLI : ArtifactReference(uri, hash)

            CLI -> LP : registerPreflightHash(experimentId, roundId, clientId, hash)
            LP -> FAB : peer chaincode invoke\nregisterPreflightHash\n→ AuditEventAsset on-chain
            CLI -> LP : registerLocalUpdateHash(experimentId, roundId, clientId, updateHash)
            LP -> FAB : peer chaincode invoke\nregisterLocalUpdateHash\n→ AuditEventAsset on-chain

            CLI -> MQ : publish MqttEnvelope<ClientUpdateMessage>\n[fl/experiments/{id}/rounds/{n}/clients/{id}/update]

        else preflight FAILED
            CLI -> MQ : publish status PREFLIGHT_FAILED\n(failedChecks without raw data)
        end
    end

    MQ -> AGG : MqttClientUpdateCollector.updatesFor(experimentId, roundId)

    AGG -> AGG : verify signature of each update
    AGG -> AGG : verify clientId ∈ selectedClients
    AGG -> AGG : recompute hash of each downloaded update
    AGG -> AGG : validate: norm · dimension · finiteness · no duplicates

    AGG -> AGG : strategy.selectUpdates(validUpdates, policy)\n(FedAvg / FedMedian / TrimmedMean / Krum / FedAdam / FedYogi)
    AGG -> AGG : checkQuorum(|selected| ≥ minimumClients,\nΣsamples ≥ minimumTotalExamples)
    AGG -> AGG : strategy.computeWeights(selected, policy)
    AGG -> AGG : strategy.combine(selected, weights, currentGlobal)\n→ globalModelVector

    AGG -> ART : store(global_model.bin · aggregation_report.json)
    ART --> AGG : ArtifactReference(modelUri, modelHash)

    AGG -> LP : registerAggregationHash(experimentId, roundId, reportHash)
    LP -> FAB : peer chaincode invoke\nregisterAggregationHash\n→ AuditEventAsset on-chain
    FAB --> LP : TX confirmed

    AGG -> LP : registerGlobalModelVersion(experimentId, roundId,\nmodelHash, modelUri, aggregatorId)
    LP -> FAB : peer chaincode invoke\nregisterGlobalModelVersion\n→ GlobalModel asset on-chain (v{n+1})
    FAB --> LP : TX confirmed

    AGG -> AGG : clearRound(experimentId, roundId)\n(frees collector memory)
    AGG -> MQ : publish MqttEnvelope<GlobalModelPublication>\n[fl/experiments/{id}/rounds/{n}/model]

    AGG --> SRE : AggregationReport (globalModelVersion=n+1, metrics)
    SRE -> SRE : session.withRoundSent(roundNumber)\n→ SimulationSession{currentRound=1, status=ACTIVE}
    SRE --> P : SSE event: sim-round-sent (if run-all)\nor 303 redirect /sim-session (if send-round)

    P -> P : auto-refresh 30s\n→ monitor displays round {n} metrics:\n  loss · local metric · global metric · average norm

    alt session.currentRound < session.totalRounds and status=ACTIVE
    else session.currentRound == session.totalRounds
        SRE -> SRE : session.withStatus("DONE")
    end

    @enduml

9. Android Multiexperiment Training through MDPL

One Android service handles multiple consented contracts. MQTT and sensor capture are shared; round state and SQLite observations are isolated by experiment and contract version. The MDPL package is optional and independent from the APK and server experiment package.

Diagrama PlantUML 9

Ver código-fonte PlantUML
    @startuml "HDT-AF - Android Multiexperiment Training with MDPL"
    !theme plain
    skinparam shadowing false

    actor "Participant" as USER
    participant "MainActivity /\nExperimentDetailActivity" as UI
    participant "FederatedMqttService" as APP
    participant "ConsentManager" as CONSENT
    participant "Remote MQTT Broker" as MQTT
    participant "CDDL Sensor\nCapture" as SENSOR
    database "SQLite\n(expId, contractVersion)" as DB
    participant "REST Artifact API" as REST
    participant "MdplTrainingTopicBridge" as BRIDGE
    participant "CDDL Local Microbroker" as CDDL
    participant "FederatedMdplInferenceEngineService\n(OnArrivalPhenotypeInferenceEngine)" as MDPL
    participant "Verified DEX Plugin" as PLUGIN
    participant "ClientUpdateRelay" as RELAY
    participant "Aggregator" as AGG

    USER -> UI : explicitly accept contract A/v1 and B/v2
    UI -> CONSENT : save consent(A, v1), consent(B, v2)
    USER -> UI : start shared client service
    UI -> APP : start foreground service
    APP -> MQTT : subscribe ALL_EXPERIMENT_ROUND_CONFIGS\nALL_EXPERIMENT_ROUND_FINALIZATIONS\nALL_EXPERIMENT_CONTRACT_PUBLICATIONS
    APP -> SENSOR : start shared CDDL/CDAL capture

    par Round for experiment A/v1
        MQTT --> APP : signed RoundConfig(A, v1, rA)
        APP -> APP : verify signature, integrity and payload identity
        APP -> CONSENT : isAllowed(A, v1)
        CONSENT --> APP : allowed
        APP -> REST : GET code manifest and client package(A, v1)
        REST --> APP : manifest + .hdtclient.zip
        APP -> APP : verify Ed25519, checksums,\nexperiment/version and algorithm descriptor
        APP -> MDPL : register verified plugin(A, v1)
        APP -> DB : append observations under (A, v1)
        MQTT --> APP : signed finalization(A, v1, rA)
        APP -> BRIDGE : execute MdplTrainingWorkItem(A, v1, rA)
        BRIDGE -> CDDL : publish mdpl/.../training/requests
        CDDL --> MDPL : OnArrival request callback
        MDPL -> PLUGIN : train(request)
        PLUGIN --> MDPL : TrainingOutcome
        MDPL -> CDDL : publish mdpl/.../training/results
        CDDL --> BRIDGE : matching MdplTrainingResult
        BRIDGE --> APP : TrainingOutcome
        APP -> REST : upload update/metrics/profile artifacts
        REST --> APP : URIs + hashes
        APP -> MQTT : signed ClientUpdateMessage(A, v1, rA)
    else Round for experiment B/v2
        MQTT --> APP : signed RoundConfig(B, v2, rB)
        APP -> APP : independent lifecycle and consent gate
        APP -> DB : append observations under (B, v2)
        MQTT --> APP : signed finalization(B, v2, rB)
        APP -> BRIDGE : execute MdplTrainingWorkItem(B, v2, rB)
        BRIDGE -> CDDL : publish local request
        CDDL --> MDPL : OnArrival request callback
        MDPL -> PLUGIN : train with plugin registered for (B, v2)
        PLUGIN --> MDPL : TrainingOutcome
        MDPL -> CDDL : publish local result
        CDDL --> BRIDGE : matching result
        BRIDGE --> APP : TrainingOutcome
        APP -> REST : upload scoped round artifacts
        REST --> APP : URIs + hashes
        APP -> MQTT : signed ClientUpdateMessage(B, v2, rB)
    end

    MQTT -> RELAY : receive client-facing updates
    RELAY -> MQTT : relay signed envelopes to aggregator-facing topics
    MQTT -> AGG : deliver relayed updates

    alt consent revoked for A/v1
        USER -> UI : revoke A/v1
        UI -> APP : local revocation broadcast
        APP -> DB : delete data scoped to A/v1
        APP -> APP : remove A/v1 lifecycle and plugin
        note over APP,SENSOR : B/v2 continues; stop capture only when\nno consented experiments remain
    end

    @enduml