Back to Blog
SageMaker ML Lineage Tracking: End-to-End Model Provenance for Compliance
AWS Governance·11 min read·

SageMaker ML Lineage Tracking: End-to-End Model Provenance for Compliance

C

Claw GRC Team

Claw GRC Team

How to use SageMaker ML Lineage Tracking for end-to-end model provenance, training data lineage, and audit-ready compliance evidence for SOC 2 and NIST AI RMF.

SageMaker ML Lineage Tracking: End-to-End Model Provenance for Compliance

An auditor asks: "Show me where this model's training data came from, what transformations were applied, who approved the training job, and which endpoint is serving this exact model version." Without lineage tracking, answering that question requires digging through CloudTrail logs, S3 bucket histories, and Slack messages. With SageMaker ML Lineage Tracking, the answer is a single API call.

ML lineage is the chain of custody for your model. It records the relationships between datasets, processing steps, training jobs, models, and endpoints. For compliance, lineage provides the provenance evidence that frameworks like NIST AI RMF, SOC 2, and the EU AI Act require.

This article covers how SageMaker lineage works, how to create lineage entities programmatically, and how to query lineage for audit evidence. For the broader AWS AI governance framework, see the Complete Guide to AWS AI/ML Governance.


Why ML Lineage Matters for Compliance

Three compliance requirements drive the need for lineage tracking:

Training data provenance. NIST AI RMF MS.2.1 requires test set integrity and data provenance. EU AI Act Article 10 requires documentation of data governance practices including "the origin of data." You need to prove where your training data came from and that it was not tampered with.

Model reproducibility. SOC 2 CC8.1 (change management) requires that you can trace any production artifact back to its source. If a model is behaving unexpectedly, you need to reproduce the exact training run that produced it -- same data, same code, same hyperparameters.

Audit trail continuity. Auditors follow chains. They start at the endpoint serving predictions to customers, trace back to the model artifact, then to the training job, then to the training data. If any link in that chain is missing, the audit finding is "incomplete change management documentation."

Lineage tracking makes these chains explicit, queryable, and exportable.


SageMaker Lineage Entities

SageMaker lineage is built on four entity types:

Context

A Context groups related lineage entities. It represents a high-level concept like an ML pipeline run, an experiment, or a project.

Example: "churn-predictor-v3-pipeline-run-20260315" is a Context that groups all artifacts, actions, and associations from a specific pipeline execution.

Artifact

An Artifact is a versioned data object. Artifacts represent:

  • Training datasets (S3 URIs)
  • Model artifacts (model.tar.gz in S3)
  • Evaluation reports
  • Feature engineering outputs
  • Docker images used for training

Each Artifact has a type (DataSet, Model, Image) and a URI pointing to its physical location.

Action

An Action represents a computation or transformation step. Actions represent:

  • Training jobs
  • Processing jobs (feature engineering, data validation)
  • Transform jobs (batch inference)
  • Model registration

Each Action has a type (Training, Processing, ModelRegistration) and references to the SageMaker job that performed the computation.

Association

An Association defines the relationship between two lineage entities. Associations have types:

  • ContributedTo: input artifact contributed to an action
  • Produced: an action produced an output artifact
  • DerivedFrom: one artifact was derived from another
  • AssociatedWith: general relationship

Together, these entities form a directed acyclic graph (DAG) that traces the complete path from raw data to production endpoint.

[Raw Dataset]  --ContributedTo-->  [Processing Job]  --Produced-->  [Feature Set]
                                                                        |
[Feature Set]  --ContributedTo-->  [Training Job]  --Produced-->  [Model Artifact]
                                                                        |
[Model Artifact]  --ContributedTo-->  [Model Registration]  --Produced-->  [Registered Model]
                                                                               |
[Registered Model]  --AssociatedWith-->  [Endpoint]

Creating Lineage Programmatically

SageMaker automatically creates some lineage entities when you use SageMaker Pipelines. However, for custom pipelines or additional provenance metadata, you need to create lineage entities explicitly.

Creating a Complete Lineage Chain

import boto3
import json
from datetime import datetime

sagemaker = boto3.client("sagemaker")


def create_training_lineage(
    pipeline_name: str,
    run_id: str,
    raw_data_uri: str,
    processed_data_uri: str,
    model_artifact_uri: str,
    training_job_arn: str,
    training_image_uri: str,
    data_owner: str,
    data_classification: str,
) -> dict:
    """Create a complete lineage chain for a training pipeline run."""

    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    lineage_arns = {}

    # 1. Create the pipeline run Context
    context_response = sagemaker.create_context(
        ContextName=f"{pipeline_name}-{run_id}",
        ContextType="MLPipelineRun",
        Description=f"Pipeline run {run_id} for {pipeline_name}",
        Properties={
            "pipeline_name": pipeline_name,
            "run_id": run_id,
            "started_at": timestamp,
            "data_classification": data_classification,
            "data_owner": data_owner,
        },
    )
    lineage_arns["context"] = context_response["ContextArn"]

    # 2. Create Artifact for raw training data
    raw_data_response = sagemaker.create_artifact(
        ArtifactName=f"{pipeline_name}-raw-data-{run_id}",
        ArtifactType="DataSet",
        Source={"SourceUri": raw_data_uri},
        Properties={
            "data_classification": data_classification,
            "data_owner": data_owner,
            "collection_date": timestamp,
            "description": "Raw training dataset before preprocessing",
        },
    )
    lineage_arns["raw_data"] = raw_data_response["ArtifactArn"]

    # 3. Create Action for data processing step
    processing_response = sagemaker.create_action(
        ActionName=f"{pipeline_name}-processing-{run_id}",
        ActionType="Processing",
        Description="Feature engineering and data validation",
        Properties={
            "processing_type": "feature_engineering",
            "run_id": run_id,
        },
    )
    lineage_arns["processing"] = processing_response["ActionArn"]

    # 4. Create Artifact for processed/feature-engineered data
    processed_data_response = sagemaker.create_artifact(
        ArtifactName=f"{pipeline_name}-processed-data-{run_id}",
        ArtifactType="DataSet",
        Source={"SourceUri": processed_data_uri},
        Properties={
            "data_classification": data_classification,
            "derived_from": raw_data_uri,
            "processing_date": timestamp,
        },
    )
    lineage_arns["processed_data"] = processed_data_response["ArtifactArn"]

    # 5. Create Artifact for training Docker image
    image_response = sagemaker.create_artifact(
        ArtifactName=f"{pipeline_name}-training-image-{run_id}",
        ArtifactType="Image",
        Source={"SourceUri": training_image_uri},
        Properties={
            "image_type": "training",
            "description": "Docker image used for model training",
        },
    )
    lineage_arns["training_image"] = image_response["ArtifactArn"]

    # 6. Create Action for training step
    training_response = sagemaker.create_action(
        ActionName=f"{pipeline_name}-training-{run_id}",
        ActionType="Training",
        Description="Model training execution",
        Properties={
            "training_job_arn": training_job_arn,
            "run_id": run_id,
        },
    )
    lineage_arns["training"] = training_response["ActionArn"]

    # 7. Create Artifact for model output
    model_response = sagemaker.create_artifact(
        ArtifactName=f"{pipeline_name}-model-{run_id}",
        ArtifactType="Model",
        Source={"SourceUri": model_artifact_uri},
        Properties={
            "training_job_arn": training_job_arn,
            "trained_at": timestamp,
            "model_version": run_id,
        },
    )
    lineage_arns["model"] = model_response["ArtifactArn"]

    # 8. Create Associations (the edges of the lineage graph)
    associations = [
        # Raw data contributed to processing
        (lineage_arns["raw_data"], lineage_arns["processing"], "ContributedTo"),
        # Processing produced processed data
        (lineage_arns["processing"], lineage_arns["processed_data"], "Produced"),
        # Processed data contributed to training
        (lineage_arns["processed_data"], lineage_arns["training"], "ContributedTo"),
        # Training image contributed to training
        (lineage_arns["training_image"], lineage_arns["training"], "ContributedTo"),
        # Training produced model
        (lineage_arns["training"], lineage_arns["model"], "Produced"),
        # Context association for all entities
        (lineage_arns["context"], lineage_arns["raw_data"], "AssociatedWith"),
        (lineage_arns["context"], lineage_arns["model"], "AssociatedWith"),
    ]

    for source_arn, dest_arn, assoc_type in associations:
        sagemaker.add_association(
            SourceArn=source_arn,
            DestinationArn=dest_arn,
            AssociationType=assoc_type,
        )

    return lineage_arns


# Example usage
lineage = create_training_lineage(
    pipeline_name="churn-predictor",
    run_id="v3-20260315",
    raw_data_uri="s3://ml-data/churn/raw/accounts-2024-2025.parquet",
    processed_data_uri="s3://ml-data/churn/processed/features-v3.parquet",
    model_artifact_uri="s3://ml-artifacts/churn-v3/model.tar.gz",
    training_job_arn="arn:aws:sagemaker:us-east-1:123456789:training-job/churn-v3-20260315",
    training_image_uri="123456789.dkr.ecr.us-east-1.amazonaws.com/ml-training:v3",
    data_owner="Data Engineering Team",
    data_classification="Confidential",
)

print(json.dumps(lineage, indent=2))

Key Takeaway: Notice the data_classification and data_owner properties on the raw data artifact. These are not required by SageMaker but are critical for compliance. They prove that you tracked data sensitivity from the point of ingestion through the entire pipeline.


Querying Lineage for Audit

When an auditor asks about a specific model, you need to traverse the lineage graph and produce a complete provenance report.

Tracing a Model Back to Its Training Data

def get_model_provenance(model_artifact_arn: str) -> dict:
    """Trace a model artifact back through its full lineage chain."""

    provenance = {
        "model_artifact": model_artifact_arn,
        "training_data_sources": [],
        "processing_steps": [],
        "training_details": None,
        "images_used": [],
        "pipeline_context": None,
    }

    # Get all upstream associations (what contributed to this model)
    def trace_upstream(entity_arn: str, depth: int = 0, max_depth: int = 10):
        if depth >= max_depth:
            return

        # List associations where this entity is the destination
        response = sagemaker.list_associations(
            DestinationArn=entity_arn,
        )

        for assoc in response.get("AssociationSummaries", []):
            source_arn = assoc["SourceArn"]
            assoc_type = assoc["AssociationType"]

            # Classify the source entity
            if ":artifact/" in source_arn:
                artifact = sagemaker.describe_artifact(ArtifactArn=source_arn)
                artifact_info = {
                    "arn": source_arn,
                    "name": artifact.get("ArtifactName", ""),
                    "type": artifact.get("ArtifactType", ""),
                    "uri": artifact.get("Source", {}).get("SourceUri", ""),
                    "properties": artifact.get("Properties", {}),
                    "created": str(artifact.get("CreationTime", "")),
                }

                if artifact["ArtifactType"] == "DataSet":
                    provenance["training_data_sources"].append(artifact_info)
                elif artifact["ArtifactType"] == "Image":
                    provenance["images_used"].append(artifact_info)

            elif ":action/" in source_arn:
                action = sagemaker.describe_action(ActionArn=source_arn)
                action_info = {
                    "arn": source_arn,
                    "name": action.get("ActionName", ""),
                    "type": action.get("ActionType", ""),
                    "properties": action.get("Properties", {}),
                }

                if action["ActionType"] == "Training":
                    provenance["training_details"] = action_info
                else:
                    provenance["processing_steps"].append(action_info)

            elif ":context/" in source_arn:
                context = sagemaker.describe_context(ContextArn=source_arn)
                provenance["pipeline_context"] = {
                    "arn": source_arn,
                    "name": context.get("ContextName", ""),
                    "properties": context.get("Properties", {}),
                }

            # Recurse upstream
            trace_upstream(source_arn, depth + 1)

    trace_upstream(model_artifact_arn)
    return provenance


# Generate provenance report for audit
provenance = get_model_provenance(lineage["model"])
print(json.dumps(provenance, indent=2, default=str))

Exporting Lineage for Auditor Review

def export_lineage_report(model_name: str, provenance: dict) -> str:
    """Generate a human-readable lineage report for auditor review."""

    report_lines = [
        f"# ML Lineage Report: {model_name}",
        f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}",
        "",
        "## Model Artifact",
        f"- ARN: {provenance['model_artifact']}",
        "",
        "## Pipeline Context",
    ]

    if provenance["pipeline_context"]:
        ctx = provenance["pipeline_context"]
        report_lines.append(f"- Name: {ctx['name']}")
        for key, value in ctx.get("properties", {}).items():
            report_lines.append(f"- {key}: {value}")
    else:
        report_lines.append("- No pipeline context recorded")

    report_lines.extend(["", "## Training Data Sources"])
    for ds in provenance["training_data_sources"]:
        report_lines.append(f"### {ds['name']}")
        report_lines.append(f"- URI: {ds['uri']}")
        report_lines.append(f"- Type: {ds['type']}")
        report_lines.append(f"- Created: {ds['created']}")
        for key, value in ds.get("properties", {}).items():
            report_lines.append(f"- {key}: {value}")
        report_lines.append("")

    report_lines.extend(["## Processing Steps"])
    for step in provenance["processing_steps"]:
        report_lines.append(f"### {step['name']}")
        report_lines.append(f"- Type: {step['type']}")
        for key, value in step.get("properties", {}).items():
            report_lines.append(f"- {key}: {value}")
        report_lines.append("")

    report_lines.extend(["## Training Details"])
    if provenance["training_details"]:
        td = provenance["training_details"]
        report_lines.append(f"- Name: {td['name']}")
        for key, value in td.get("properties", {}).items():
            report_lines.append(f"- {key}: {value}")

    report_lines.extend(["", "## Container Images Used"])
    for img in provenance["images_used"]:
        report_lines.append(f"- {img['uri']}")

    return "\n".join(report_lines)

Compliance Tip: Store lineage reports in your GRC platform as evidence artifacts. Tag them with the compliance framework and control ID they satisfy. When the auditor asks for NIST AI RMF MS.2.1 evidence, you pull the lineage report directly instead of reconstructing it.


Lineage for Training Data Provenance (NIST AI RMF MS.2.1)

NIST AI RMF Measure Subcategory MS.2.1 states: "Test sets, metrics, and details about the tools used during testing are documented."

Lineage tracking addresses MS.2.1 by recording:

  • The exact S3 URI of every dataset used in training and evaluation
  • The processing steps applied to raw data before training
  • The properties of each dataset (classification, owner, collection date)
  • The association chain proving which datasets produced which model

To strengthen your MS.2.1 evidence, add these properties to your data artifacts:

Property Description Why It Matters
data_classification Sensitivity level (Public, Internal, Confidential, Restricted) Proves you tracked data sensitivity
data_owner Team or individual responsible Establishes accountability
collection_date When the data was collected Proves data freshness
record_count Number of records in the dataset Enables reproducibility
schema_hash Hash of the dataset schema Detects schema changes
content_hash Hash of the dataset content Detects data tampering
retention_policy How long the data is retained Proves data governance
consent_basis Legal basis for data use (if PII) GDPR/privacy compliance

Lineage for Model Reproducibility

Reproducibility means that given the same inputs (data, code, configuration), you can produce the same model. Lineage enables reproducibility by capturing all inputs to the training process.

For a model to be reproducible, your lineage must record:

  1. Exact dataset version -- S3 URI with version ID or content hash
  2. Exact code version -- Docker image URI with digest (not just tag)
  3. Exact hyperparameters -- stored as properties on the Training Action
  4. Exact infrastructure -- instance type, count, stored on the Training Action
  5. Random seed -- if your algorithm uses random initialization
# When creating the training Action, include reproducibility metadata
sagemaker.create_action(
    ActionName=f"{pipeline_name}-training-{run_id}",
    ActionType="Training",
    Description="Model training execution",
    Properties={
        "training_job_arn": training_job_arn,
        "instance_type": "ml.p3.2xlarge",
        "instance_count": "1",
        "hyperparameters": json.dumps({
            "max_depth": 6,
            "eta": 0.3,
            "objective": "binary:logistic",
            "num_round": 200,
            "seed": 42,
        }),
        "framework_version": "xgboost-1.7",
        "random_seed": "42",
    },
)

Key Takeaway: Auditors testing your change management (SOC 2 CC8.1) may ask you to demonstrate that a model can be reproduced. If your lineage captures all inputs to the training process, you can point to the lineage graph and say "every input is recorded and versioned." Without lineage, you are relying on tribal knowledge.


Automated Lineage Compliance Checks

Just as we validated Model Cards in the previous article, lineage should be validated automatically.

def validate_lineage_compliance(model_artifact_arn: str) -> dict:
    """Validate that a model's lineage chain is complete for compliance."""

    provenance = get_model_provenance(model_artifact_arn)
    findings = []

    # Check: model has at least one training data source
    if not provenance["training_data_sources"]:
        findings.append({
            "severity": "CRITICAL",
            "check": "training_data_provenance",
            "message": "No training data sources found in lineage",
            "frameworks": ["NIST AI RMF MS.2.1", "EU AI Act Art. 10"],
        })

    # Check: training data has classification and owner
    for ds in provenance["training_data_sources"]:
        props = ds.get("properties", {})
        if not props.get("data_classification"):
            findings.append({
                "severity": "HIGH",
                "check": "data_classification",
                "message": f"Data source '{ds['name']}' missing data_classification",
                "frameworks": ["SOC 2 CC6.7", "NIST AI RMF Map 3.1"],
            })
        if not props.get("data_owner"):
            findings.append({
                "severity": "MEDIUM",
                "check": "data_owner",
                "message": f"Data source '{ds['name']}' missing data_owner",
                "frameworks": ["NIST AI RMF Govern 2.1"],
            })

    # Check: training details exist
    if not provenance["training_details"]:
        findings.append({
            "severity": "CRITICAL",
            "check": "training_details",
            "message": "No training action found in lineage",
            "frameworks": ["SOC 2 CC8.1", "EU AI Act Art. 11(1)(b)"],
        })
    else:
        # Check: training action has reproducibility metadata
        props = provenance["training_details"].get("properties", {})
        if not props.get("training_job_arn"):
            findings.append({
                "severity": "HIGH",
                "check": "training_job_reference",
                "message": "Training action missing training_job_arn",
                "frameworks": ["SOC 2 CC8.1"],
            })
        if not props.get("hyperparameters"):
            findings.append({
                "severity": "MEDIUM",
                "check": "hyperparameters",
                "message": "Training action missing hyperparameters for reproducibility",
                "frameworks": ["NIST AI RMF Measure 2.2"],
            })

    # Check: container image is recorded
    if not provenance["images_used"]:
        findings.append({
            "severity": "MEDIUM",
            "check": "training_image",
            "message": "No training container image recorded in lineage",
            "frameworks": ["SOC 2 CC8.1", "NIST AI RMF MS.2.1"],
        })

    # Check: pipeline context exists
    if not provenance["pipeline_context"]:
        findings.append({
            "severity": "LOW",
            "check": "pipeline_context",
            "message": "No pipeline context grouping lineage entities",
            "frameworks": ["NIST AI RMF Govern 1.1"],
        })

    return {
        "model_artifact": model_artifact_arn,
        "finding_count": len(findings),
        "findings": findings,
        "compliant": len([f for f in findings if f["severity"] in ("CRITICAL", "HIGH")]) == 0,
        "data_sources_tracked": len(provenance["training_data_sources"]),
        "processing_steps_tracked": len(provenance["processing_steps"]),
        "has_training_details": provenance["training_details"] is not None,
    }

Run this validation as a gate in your ML pipeline. Block model registration if critical or high-severity lineage findings exist.


Evidence Collection Strategy

Evidence Artifact Collection Method Frequency Framework
Lineage provenance report export_lineage_report() On each model registration SOC 2 CC8.1, NIST MS.2.1
Lineage compliance validation validate_lineage_compliance() On each model registration All frameworks
Data source inventory Query all DataSet artifacts Quarterly NIST AI RMF Map 3.1, EU AI Act Art. 10
Training job cross-reference Match lineage training_job_arn to CloudTrail Quarterly SOC 2 CC8.1
Lineage graph visualization SageMaker Studio lineage explorer export On auditor request All frameworks
Data classification audit Query data_classification properties Quarterly SOC 2 CC6.7

Claw GRC integrates with SageMaker lineage to automatically collect provenance reports, run compliance validation, and store results as framework-mapped evidence. When your auditor requests NIST AI RMF MS.2.1 evidence, the lineage report is already in your evidence library.



Start your AWS AI governance assessment →

CG

Get started with Claw GRC

AI-native compliance automation. 1,026+ controls. MCP-native. Free workspace, no credit card.

Start Free →