
# Kontinuální správa dat v MLOps pipelinech s Formize

Enterprises that ship machine‑learning models at scale face a paradox: the faster they iterate, the harder it becomes to guarantee that data used for training, validation, and inference complies with internal policies and external regulations. Traditional data‑governance approaches—manual audits, periodic reports, and static lineage maps—cannot keep up with the velocity of modern MLOps workflows.

Formize, a low‑code data‑lineage and compliance engine, was built for exactly this challenge. By embedding Formize into the CI/CD pipeline, organizations can **capture lineage in real time**, **enforce policy as code**, and **expose quality dashboards** that developers and auditors can query instantly.

In this article we will:

1. Outline the core concepts of continuous data governance.
2. Show how Formize integrates with popular MLOps tools (GitHub Actions, Jenkins, Kubeflow, MLflow).
3. Walk through a complete end‑to‑end implementation, from source‑control hooks to automated compliance checks.
4. Provide a Mermaid diagram that visualizes the data‑flow.
5. Discuss scaling considerations, security, and future‑proofing.

> **Klíčová myšlenka:** Když se Formize stane nativním krokem ve vašem CI/CD pipeline, linie dat, vynucování politik a monitorování kvality se stávají *kontinuálními* místo *periodických* aktivit.

---

## 1. Proč je důležitá kontinuální správa

| Tradiční přístup | Kontinuální přístup |
|------------------|---------------------|
| Audity probíhají čtvrtletně nebo po incidentu | Audity probíhají při každém commitu, buildu a nasazení |
| Manuální diagramy linie jsou zastaralé | Automatizované grafy linie odrážejí aktuální stav |
| Porušení politik objevena pozdě, nákladná na opravu | Porušení politik okamžitě blokuje pipeline |
| Omezená viditelnost pro netechnické zainteresované strany | Dashboardy v reálném čase posilují správce dat a auditory |

The shift from **periodic** to **continuous** mirrors the evolution from Waterfall to DevOps. In the same way that automated tests catch code defects early, automated governance catches data defects early.

---

## 2. Základní stavební bloky

1. **Formize Engine** – Poskytuje API pro zachycení linie, definování politik a ukládání auditních stop.
2. **MLOps Orchestrator** – Jenkins, GitHub Actions, Azure Pipelines nebo Kubeflow pipelines, které řídí trénink a nasazení modelu.
3. **Artifact Repository** – S3, Azure Blob nebo GCS, kde jsou uloženy datasety, binární soubory modelů a feature store.
4. **Policy‑as‑Code** – Pravidla v YAML/JSON, která kódují GDPR, HIPAA nebo interní politiky používání dat.
5. **Observability Layer** – Dashboardy Grafana/Prometheus, které zobrazují metriky Formize.

All components communicate via **RESTful endpoints** or **event streams** (Kafka, Pub/Sub). The following Mermaid diagram illustrates the data‑flow.

```mermaid
graph LR
    subgraph CI_CD["CI/CD Pipeline"]
        A["Git Commit"] --> B["Build Stage"]
        B --> C["Test Stage"]
        C --> D["Training Stage"]
        D --> E["Model Registry"]
    end

    subgraph Governance["Formize Governance"]
        F["Lineage Capture"] --> G["Policy Engine"]
        G --> H["Compliance Report"]
        H --> I["Dashboard"]
    end

    D -->|Dataset Access| F
    E -->|Model Artifact| F
    G -->|Violation Event| CI_CD
    CI_CD -->|Fail Build| B
    I -->|Alert| Developers
```

*All node labels are wrapped in double quotes as required for Mermaid.*

---

## 3. Integrace krok za krokem

### 3.1. Definujte Policy‑as‑Code

Create a `policies.yaml` file in the repository root:

```yaml
policies:
  - id: "PII-001"
    description: "No PII fields may be used in training without explicit consent"
    condition: "dataset.contains('ssn') or dataset.contains('email')"
    action: "block"
    severity: "high"

  - id: "DATA-RETENTION-01"
    description: "Training data older than 5 years must be archived"
    condition: "dataset.age > 5y"
    action: "warn"
    severity: "medium"
```

Formize reads this file during the **Lineage Capture** step and evaluates each rule against the incoming dataset metadata.

### 3.2. Přidejte Formize hook do pipeline

Below is a GitHub Actions snippet that runs after the training job finishes:

```yaml
name: MLOps CI/CD

on:
  push:
    branches: [ main ]

jobs:
  train-and-govern:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Run training script
        id: train
        run: |
          python train.py --data s3://bucket/raw-data/2024-08-01.csv --output model.pkl

      - name: Capture lineage & enforce policy
        env:
          FORMIZE_API_KEY: ${{ secrets.FORMIZE_API_KEY }}
        run: |
          curl -X POST https://api.formize.io/v1/lineage \
            -H "Authorization: Bearer $FORMIZE_API_KEY" \
            -H "Content-Type: application/json" \
            -d @- <<EOF
          {
            "pipeline_id": "github-actions-mlops",
            "run_id": "${{ github.run_id }}",
            "artifact": "model.pkl",
            "dataset": "s3://bucket/raw-data/2024-08-01.csv",
            "metadata": {
              "commit_sha": "${{ github.sha }}",
              "author": "${{ github.actor }}",
              "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
            },
            "policy_file": "policies.yaml"
          }
          EOF
```

If any policy returns `block`, the step exits with a non‑zero status, causing the entire job to fail. This **fail‑fast** behavior guarantees that non‑compliant data never reaches production.

### 3.3. Uložte linie do centrálního grafu

Formize automatically writes a directed acyclic graph (DAG) to its internal Neo4j store. You can query it with Cypher:

```cypher
MATCH (d:Dataset)-[:USED_IN]->(t:TrainingRun)-[:PRODUCED]->(m:Model)
WHERE d.name CONTAINS 'raw-data'
RETURN d.name, t.run_id, m.version
ORDER BY t.timestamp DESC
LIMIT 10;
```

The result can be visualized in the Formize UI or exported to Grafana for custom dashboards.

### 3.4. Dashboard v reálném čase

Create a Prometheus exporter that scrapes Formize metrics:

```go
package main

import (
    "net/http"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
    policyViolations = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "formize_policy_violations_total",
            Help: "Total number of policy violations detected",
        },
        []string{"policy_id", "severity"},
    )
)

func main() {
    // Assume we receive webhook events from Formize
    http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
        // Parse JSON, increment counters...
    })
    prometheus.MustRegister(policyViolations)
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":9090", nil)
}
```

Grafana can now plot `formize_policy_violations_total` per pipeline, giving data stewards instant visibility.

---

## 4. Škálování vrstvy správy

| Výzva | Doporučené řešení |
|-------|-------------------|
| **Vysokofrekvenční pipeline** (stovky běhů denně) | Nasadit Formize v **klastrovém** režimu za load balancer; povolit **batch ingest** událostí linie. |
| **Multi‑cloud datové zdroje** | Použít **cloud‑agnostické konektory** Formize (S3, Azure Blob, GCS) a nastavit jednotné schéma **identifikátorů zdrojů**. |
| **Vlastnictví politik napříč týmy** | Využít **role‑based access control (RBAC)** Formize, aby každý doménový tým vlastnil své soubory politik, zatímco centrální tým řídí engine. |
| **Neměnnost auditních stop** | Spojit Formize s **blockchain anchor** (např. Ethereum nebo Hyperledger) pro kryptografické zapečetění každé transakce linie. |

---

## 5. Bezpečnostní a souladové úvahy

1. **Správa API klíčů** – Ukládejte `FORMIZE_API_KEY` v manažerech tajemství (GitHub Secrets, Azure Key Vault). Klíče rotujte čtvrtletně.
2. **Minimalizace dat** – Posílejte Formize pouze **metadata** (hashy, schéma, časové značky); nikdy nepřenášejte surové PII.
3. **Šifrování během přenosu** – Všechny endpointy Formize vyžadují TLS 1.3.
4. **Politiky uchovávání** – Nastavte Formize tak, aby mazalo linie starší než retenční období organizace, v souladu s [GDPR](https://gdpr.eu/) „právo být zapomenut“.

---

## 6. Budoucí zabezpečení vaší správy

- **AI‑asistovaná generace politik**: Použijte LLM k navrhování nových pravidel politik na základě pozorovaných vzorů posunu dat.
- **Událostmi řízená architektura**: Nahraďte HTTP volání Kafka tématy (`lineage.events`, `policy.violations`) pro ultra‑nízkou latenci.
- **Portály samoobsluhy**: Umožněte datovým vědcům požádat o dočasné výjimky politik prostřednictvím UI poháněného Formize, s automatizovanými schvalovacími workflow.

---

## 7. Shrnutí

Embedding Formize into MLOps CI/CD pipelines transforms data governance from a **reactive checkpoint** into a **continuous, automated safeguard**. By capturing lineage at every stage, evaluating policy‑as‑code, and surfacing real‑time metrics, organizations can:

- Reduce compliance risk and audit effort.
- Accelerate model delivery without sacrificing data quality.
- Provide transparent, auditable trails for regulators and internal auditors.

Start with a single pipeline, iterate on policy definitions, and scale horizontally. The result is a resilient, trustworthy AI delivery platform that keeps pace with modern development velocity.