Arquitectura de Datos

Data Mesh: Data Quality, Validations, and Observability, How to Build Reliable Data Products

Learn how to guarantee the reliability of your Data Products in a Data Mesh by combining data quality dimensions, SQL and Python validations, SLI/SLO/SLA indicators, and operational observability to detect anomalies before they impact consumers.

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

When a Green Pipeline Publishes Broken Data

On Monday at 07:00 UTC, every operational dashboard of the Sales domain at CommerceFlow showed green status indicators. The incremental synchronization process for the sales-orders data product had finished in 42 seconds without raising exceptions, the files in Amazon S3 had been updated on schedule, and the queries in Amazon Athena returned results in less than two seconds. From an infrastructure perspective, the publication pipeline worked without a single technical error.

At 08:30 UTC, the Finance team noticed that the weekend gross revenue report was 18% higher than the bank settlement records, while the BI team reported a strange spike in orders categorized as "UNKNOWN_STATE". When investigating the dataset, the Sales engineers found four simultaneous problems inside sales-orders:

  1. A retry bug in the checkout service had emitted duplicate order records under the same order_id.
  2. A new promotional flow deployed on Friday night wrote NULL in customer_id for guest checkouts, violating the expectation of downstream customer segmentation models.
  3. That same deployment introduced the status "AWAITING_PACKING" without updating the domain transformation rules, which mapped unrecognized values or left them outside the contracted catalog.
  4. Several refunded orders retained negative or zero values in total_amount while their status still appeared as "PAID".

None of these defects broke the SQL syntax or caused the job in AWS Glue to fail. The pipeline had executed cleanly, yet the published data was incomplete, inconsistent, and untrustworthy.

This scenario illustrates one of the most frequent misconceptions in data engineering: assuming that a successful pipeline execution guarantees data quality, or that a documented contract enforces itself automatically. In a Data Mesh architecture, where multiple autonomous domains publish and consume data products across organizational boundaries, technical availability is only the starting point. For a Data Product to be genuinely trustworthy, its owner team must combine explicit Data Quality validations with continuous Data Observability.


Data Quality, Service Quality, and Pipeline Observability

Before writing validation queries or configuring alerts, it is essential to separate three concepts that are often mixed together in daily operations:

+-------------------------------------------------------------------------+
|                    TRUSTWORTHY DATA PRODUCT                             |
|                                                                         |
|  1. Pipeline & Infrastructure Health (Technical Execution)              |
|     - Did the job run on schedule?                                      |
|     - What was the CPU/memory usage and execution duration?             |
|                                                                         |
|  2. Data Quality (Deterministic Verification of Known Rules)            |
|     - Does the dataset satisfy explicit schema, content, and            |
|       business invariants defined in the Data Contract?                 |
|                                                                         |
|  3. Data Observability (Continuous Telemetry & Anomaly Detection)       |
|     - What can we infer about freshness, volume, distribution shifts,   |
|       schema drift, and lineage impact from external outputs?           |
+-------------------------------------------------------------------------+
  1. Pipeline and infrastructure monitoring verifies whether jobs started, how long they took, whether permissions worked, and whether compute resources threw exceptions. A green status here only means the code ran to completion.
  2. Data Quality evaluates the state of the data against known expectations and business rules. Just as unit and integration tests verify predetermined conditions in application code, data quality checks validate explicit invariants: no duplicate primary keys, no null values in mandatory columns, and amounts greater than zero.
  3. Data Observability—borrowing the principle from control theory and distributed systems popularized in software engineering by Charity Majors and applied to data ecosystems by authors such as Barr Moses—is the ability to understand the internal health and behavior of a data system from its external outputs (metrics, logs, metadata, validation telemetry, and lineage). While validation tests check for known failure modes, observability helps detect unknown or unexpected shifts: a sudden 60% drop in daily order volume, a silent delay in upstream replication, or a statistical drift in average order value.

Separating these layers prevents a classic trap: relying exclusively on infrastructure metrics (such as AWS CloudWatch job status) and assuming that the business content inside sales-orders is accurate.


Core Dimensions of Data Quality in a Data Product

Not every defect has the same nature or the same impact on consumers. International standards such as ISO/IEC 25012 and modern data engineering frameworks classify data quality into complementary dimensions. Understanding their exact boundaries prevents you from confusing a format check with a proof of real-world truth:

DimensionWhat It MeasuresConcrete Question in sales-ordersCommon Trap to Avoid
CompletenessPresence of required attributes and expected records.Are customer_id, order_status, and created_at populated for all required rows?Checking only for IS NOT NULL when upstream systems send empty strings "" or placeholder strings like "N/A".
UniquenessAbsence of duplicate entities within the defined grain.Does each order_id appear exactly once in the published current-state table?Verifying uniqueness on a composite key when consumers join solely on order_id.
ValidityConformity to syntax, data types, allowed ranges, or catalogs.Does order_status belong to {PENDING, PAID, SHIPPED, CANCELLED, REFUNDED} and is currency a valid ISO 4217 code?Assuming that a valid format proves the value is true in the real world.
ConsistencyCoherence across attributes within the same dataset or across related datasets.If order_status = 'PAID', is total_amount > 0 and does paid_at >= created_at hold? Does the sum of line items match total_amount?Checking columns in isolation without validating cross-column invariants.
AccuracyDegree to which data correctly represents the real-world event or authoritative source.Does an order showing total_amount = 150.00 match the actual checkout transaction settled with the customer?Confusing validity with accuracy: total_amount = 99999.00 is syntactically valid and positive, yet completely inaccurate if the customer paid 99.99.
Timeliness / FreshnessHow up-to-date the data is relative to the event occurrence and consumer needs.Was an order placed at 10:00 UTC available in sales-orders within the agreed publication window?Measuring only when the pipeline ran instead of checking the maximum event timestamp (MAX(updated_at)) inside the table.

Selecting Indicators Based on Consumer Needs

A Data Product can have different consumers with distinct sensitivities:

  • Finance prioritizes accuracy, uniqueness, and reconciliation consistency on PAID and REFUNDED orders; a 30-minute delay is acceptable, but a 0.5% duplicate rate invalidates accounting closes.
  • Operations and Logistics prioritize freshness and status validity so warehouse dashboards reflect current fulfillment bottlenecks.
  • Marketing Segmentation prioritizes completeness of customer_id and historical consistency to avoid sending duplicate campaigns.

Types of Validations: From Schema Checks to Statistical Controls

To cover the dimensions above without turning the pipeline into an unmaintainable monolith, validations are organized into five complementary layers:

  1. Schema Tests: Verify that expected columns exist, data types match the contract (for example, total_amount is DECIMAL(12,2) and not VARCHAR), and non-nullability constraints hold at the structural level.
  2. Content Tests: Check row-level attribute values—null rates, uniqueness of order_id, accepted value sets (IN (...)), string patterns, and numerical bounds (total_amount >= 0).
  3. Business Rule Validations: Enforce domain invariants that depend on multiple columns or state transitions—for example, an order in status SHIPPED or PAID cannot have a NULL payment timestamp, and updated_at can never be earlier than created_at.
  4. Reconciliation Controls: Compare aggregate indicators between the source boundary and the published Data Product (or across two related products) over a defined time window—such as verifying that the count and total monetary sum of PAID orders in sales-orders match the operational checkout totals within a documented tolerance.
  5. Statistical Distribution Controls: Monitor aggregate properties over time—such as daily row count, percentage of orders per status, or average basket value—compared against a rolling historical baseline (e.g., the trailing 14-day average for the same day of the week). A sudden drop in row count from 25,000 to 1,200 rows does not violate any SQL schema constraint, but statistical monitoring flags the anomaly immediately.

Step-by-Step Mechanism: Designing Quality Checks for sales-orders

Let us examine how the Sales domain team at CommerceFlow designs and executes validations on the sales-orders product.

Initial State: A Batch Containing Realistic Defects

Suppose the staging table sales_orders_staging receives the following sample batch before publication to the curated interface of sales-orders:

order_idcustomer_idorder_statustotal_amountcurrencycreated_atupdated_atDefect Present
ORD-2001CUST-101PAID120.50USD2026-05-10 08:00:002026-05-10 08:05:00Valid record
ORD-2002CUST-102SHIPPED85.00USD2026-05-10 08:10:002026-05-10 09:00:00Valid record
ORD-2002CUST-102SHIPPED85.00USD2026-05-10 08:10:002026-05-10 09:00:00Duplicate order_id
ORD-2003NULLPAID45.00USD2026-05-10 08:15:002026-05-10 08:16:00Missing customer_id
ORD-2004CUST-104AWAITING_PACKING210.00USD2026-05-10 08:20:002026-05-10 08:25:00Uncataloged status
ORD-2005CUST-105PAID-15.00USD2026-05-10 08:30:002026-05-10 08:31:00Negative amount in PAID status
ORD-2006CUST-106CANCELLED0.00USD2026-05-10 08:40:002026-05-10 08:45:00Valid record (0.00 allowed for CANCELLED)

Validating Quality Dimensions with SQL

Before promoting staging data or immediately after materializing a candidate snapshot, the pipeline executes analytical SQL queries that return quantitative quality metrics rather than simple pass/fail booleans. Below is a self-contained SQL query set (compatible with PostgreSQL, DuckDB, and Amazon Athena) that detects row-level violations and computes aggregate quality indicators in a single pass:

-- 1. Detailed diagnostic query: identify every record that violates a rule
WITH duplicate_orders AS (
    SELECT order_id
    FROM sales_orders_staging
    GROUP BY order_id
    HAVING COUNT(*) > 1
),
row_diagnostics AS (
    SELECT
        s.order_id,
        s.customer_id,
        s.order_status,
        s.total_amount,
        s.created_at,
        s.updated_at,
        CASE WHEN d.order_id IS NOT NULL THEN 1 ELSE 0 END AS is_duplicate_key,
        CASE WHEN s.customer_id IS NULL OR TRIM(s.customer_id) = '' THEN 1 ELSE 0 END AS is_missing_customer,
        CASE WHEN s.order_status NOT IN ('PENDING', 'PAID', 'SHIPPED', 'CANCELLED', 'REFUNDED') THEN 1 ELSE 0 END AS is_invalid_status,
        CASE
            WHEN s.total_amount IS NULL OR s.total_amount < 0 THEN 1
            WHEN s.order_status IN ('PAID', 'SHIPPED') AND s.total_amount <= 0 THEN 1
            ELSE 0
        END AS is_invalid_amount,
        CASE WHEN s.updated_at < s.created_at THEN 1 ELSE 0 END AS is_invalid_timestamp_order
    FROM sales_orders_staging s
    LEFT JOIN duplicate_orders d
        ON s.order_id = d.order_id
)
SELECT
    COUNT(*) AS total_records,
    COUNT(DISTINCT order_id) AS distinct_order_ids,
    SUM(is_duplicate_key) AS affected_by_duplicate_key,
    SUM(is_missing_customer) AS null_customer_count,
    SUM(is_invalid_status) AS invalid_status_count,
    SUM(is_invalid_amount) AS invalid_amount_count,
    SUM(is_invalid_timestamp_order) AS invalid_timestamp_count,
    -- Completeness ratio for customer_id (0.0 to 1.0)
    ROUND(1.0 - (CAST(SUM(is_missing_customer) AS DECIMAL(10,4)) / NULLIF(COUNT(*), 0)), 4) AS customer_completeness_ratio,
    -- Uniqueness ratio for order_id (distinct keys / total rows)
    ROUND(CAST(COUNT(DISTINCT order_id) AS DECIMAL(10,4)) / NULLIF(COUNT(*), 0), 4) AS order_id_uniqueness_ratio,
    -- Freshness lag in minutes relative to the evaluation timestamp
    ROUND(EXTRACT(EPOCH FROM (TIMESTAMP '2026-05-10 09:30:00' - MAX(updated_at))) / 60.0, 2) AS freshness_lag_minutes
FROM row_diagnostics;

In addition, a reconciliation query compares the candidate snapshot of sales-orders against the source operational summary for the same time window:

-- 2. Cross-boundary reconciliation query for PAID orders
WITH source_summary AS (
    SELECT
        COUNT(*) AS source_paid_count,
        COALESCE(SUM(total_amount), 0) AS source_paid_total
    FROM operational_checkout_summary
    WHERE order_date = DATE '2026-05-10'
      AND order_status = 'PAID'
),
product_summary AS (
    SELECT
        COUNT(*) AS product_paid_count,
        COALESCE(SUM(total_amount), 0) AS product_paid_total
    FROM sales_orders_staging
    WHERE CAST(created_at AS DATE) = DATE '2026-05-10'
      AND order_status = 'PAID'
)
SELECT
    s.source_paid_count,
    p.product_paid_count,
    ABS(s.source_paid_count - p.product_paid_count) AS count_discrepancy,
    s.source_paid_total,
    p.product_paid_total,
    ABS(s.source_paid_total - p.product_paid_total) AS amount_discrepancy
FROM source_summary s
CROSS JOIN product_summary p;

Notice why these two queries complement each other: the first verifies internal consistency, validity, completeness, and uniqueness inside sales-orders, while the second detects missing batches or monetary drift against the source boundary.


Defining SLI, SLO, and SLA Without Universal Dogmas

Once quality dimensions can be measured quantitatively, how do we decide whether the observed values are acceptable? Borrowed from Site Reliability Engineering (SRE) and adapted to Data Products, three distinct concepts structure this decision:

  • SLI (Service Level Indicator): The exact quantitative metric measured over a defined window. Examples: customer_completeness_ratio = 99.85%, order_id_uniqueness_ratio = 100.0%, or freshness_lag_minutes = 18.5.
  • SLO (Service Level Objective): The target threshold or range that an SLI must satisfy for the Data Product to be considered healthy. Examples: order_id_uniqueness_ratio == 100.0%, customer_completeness_ratio >= 99.5%, or freshness_lag_minutes <= 60.
  • SLA (Service Level Agreement): The formal organizational commitment agreed between the producer domain (Sales) and its consumers (Finance, BI), which explicitly defines the expected reaction time, escalation path, communication protocol, and remediation obligations when an SLO is breached.

Contracted Target vs. Observed Reality

A critical principle in Data Mesh governance is distinguishing documented expectations from observed evidence. Writing freshness_max_minutes: 60 inside a YAML Data Contract does not make the dataset fresh; it only declares the SLO target. The Data Product is healthy only when the continuous telemetry emitted by validation runs confirms that the observed SLI meets that SLO.

Furthermore, there are no universal quality thresholds:

  • For order_id uniqueness in a financial table, the SLO is typically 100.0% (0 duplicates allowed), because a single duplicate distorts revenue recognition.
  • For an optional marketing attribution field such as utm_campaign, a completeness SLO of 85.0% might be completely normal because direct traffic has no campaign tag.
  • For freshness, a daily batch analytical product may define an SLO of <= 1440 minutes (24 hours), whereas an operational warehouse dashboard may require <= 15 minutes.

Below is a declarative YAML representation showing how the Sales domain configures didactic SLOs and severity levels for sales-orders based on its Data Contract:

# Didactic quality and observability specification for sales-orders
dataProduct: sales-orders
domain: sales
contractVersion: 2.1.0

serviceLevelObjectives:
  - id: slo_order_id_uniqueness
    dimension: uniqueness
    sliMetric: order_id_uniqueness_ratio
    operator: "=="
    target: 1.0000
    severity: critical
    onFailureAction: block_publication

  - id: slo_valid_order_status
    dimension: validity
    sliMetric: valid_status_ratio
    operator: "=="
    target: 1.0000
    severity: critical
    onFailureAction: block_publication

  - id: slo_valid_monetary_amount
    dimension: consistency
    sliMetric: valid_amount_ratio
    operator: "=="
    target: 1.0000
    severity: critical
    onFailureAction: block_publication

  - id: slo_customer_id_completeness
    dimension: completeness
    sliMetric: customer_completeness_ratio
    operator: ">="
    target: 0.9900
    severity: warning
    onFailureAction: publish_with_degraded_badge_and_alert

  - id: slo_publication_freshness
    dimension: timeliness
    sliMetric: freshness_lag_minutes
    operator: "<="
    target: 60.0
    severity: warning
    onFailureAction: alert_domain_owner

serviceLevelAgreement:
  consumers:
    - team: finance-reporting
      criticalIncidentResponseMinutes: 30
      remediationTargetHours: 4
      notificationChannel: "#sales-data-incidents"

Notice the field onFailureAction: not every violation requires the same operational response. Critical violations (order_id duplicates, negative PAID amounts, unknown statuses) trigger a Circuit Breaker (block_publication) that prevents corrupting the published table, keeping the previous valid snapshot accessible to consumers while alerting the owner team. Less severe deviations (such as a minor dip in non-key completeness or a 10-minute freshness delay) publish the update while marking the product status as DEGRADED in the Data Catalog and notifying the domain team.


End-to-End Implementation: Automated Validator and Observability Engine in Python

To see how validations, SLI calculation, SLO evaluation, volume anomaly detection, and alert routing work together in code, let us build a self-contained Python module. It uses only the Python standard library (dataclasses, datetime, typing), requires no external services to run, and includes automated assertions verifying both a defective batch and a clean batch.

from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Dict, List, Optional, Set


ALLOWED_STATUSES: Set[str] = {
    "PENDING",
    "PAID",
    "SHIPPED",
    "CANCELLED",
    "REFUNDED",
}


@dataclass(frozen=True)
class OrderRecord:
    order_id: str
    customer_id: Optional[str]
    order_status: str
    total_amount: float
    currency: str
    created_at: datetime
    updated_at: datetime


@dataclass(frozen=True)
class SLODefinition:
    slo_id: str
    dimension: str
    sli_name: str
    operator: str  # "==", ">=", "<="
    target: float
    severity: str  # "CRITICAL" or "WARNING"
    block_on_failure: bool


@dataclass
class ValidationFinding:
    order_id: str
    rule_id: str
    dimension: str
    message: str


@dataclass
class SLOEvaluation:
    slo_id: str
    dimension: str
    sli_name: str
    observed_value: float
    target_value: float
    operator: str
    passed: bool
    severity: str
    block_on_failure: bool


@dataclass
class ObservabilityReport:
    run_id: str
    data_product: str
    evaluated_at: str
    total_records: int
    slis: Dict[str, float]
    slo_evaluations: List[SLOEvaluation]
    row_findings: List[ValidationFinding] = field(default_factory=list)
    publication_allowed: bool = True
    operational_status: str = "HEALTHY"  # HEALTHY, DEGRADED, FAILED
    alerts: List[str] = field(default_factory=list)


def compare_sli_to_target(observed: float, operator: str, target: float) -> bool:
    if operator == "==":
        return abs(observed - target) < 1e-9
    if operator == ">=":
        return observed >= target
    if operator == "<=":
        return observed <= target
    raise ValueError(f"Unsupported operator: {operator}")


def evaluate_sales_orders_batch(
    run_id: str,
    records: List[OrderRecord],
    evaluation_time: datetime,
    expected_paid_total_source: float,
    historical_avg_volume: int,
    slos: List[SLODefinition],
) -> ObservabilityReport:
    """
    Evaluates quality dimensions, reconciles PAID totals with source,
    checks volume anomalies, and compares observed SLIs against SLOs.
    """
    total_count = len(records)
    if total_count == 0:
        return ObservabilityReport(
            run_id=run_id,
            data_product="sales-orders",
            evaluated_at=evaluation_time.isoformat(),
            total_records=0,
            slis={},
            slo_evaluations=[],
            publication_allowed=False,
            operational_status="FAILED",
            alerts=["CRITICAL: Batch contains 0 records (empty dataset)."],
        )

    findings: List[ValidationFinding] = []
    seen_ids: Dict[str, int] = {}
    for rec in records:
        seen_ids[rec.order_id] = seen_ids.get(rec.order_id, 0) + 1

    duplicate_rows = 0
    missing_customer_rows = 0
    invalid_status_rows = 0
    invalid_amount_rows = 0
    invalid_timestamp_rows = 0
    published_paid_total = 0.0

    for rec in records:
        # 1. Uniqueness check
        if seen_ids[rec.order_id] > 1:
            duplicate_rows += 1
            findings.append(
                ValidationFinding(
                    order_id=rec.order_id,
                    rule_id="RULE_UNIQUE_ORDER_ID",
                    dimension="uniqueness",
                    message=f"Duplicate order_id detected ({seen_ids[rec.order_id]} occurrences).",
                )
            )

        # 2. Completeness check on customer_id
        if rec.customer_id is None or rec.customer_id.strip() == "":
            missing_customer_rows += 1
            findings.append(
                ValidationFinding(
                    order_id=rec.order_id,
                    rule_id="RULE_CUSTOMER_COMPLETENESS",
                    dimension="completeness",
                    message="customer_id is null or empty.",
                )
            )

        # 3. Validity check on order_status
        if rec.order_status not in ALLOWED_STATUSES:
            invalid_status_rows += 1
            findings.append(
                ValidationFinding(
                    order_id=rec.order_id,
                    rule_id="RULE_STATUS_CATALOG",
                    dimension="validity",
                    message=f"Status '{rec.order_status}' is outside the contracted catalog.",
                )
            )

        # 4. Consistency and domain rule check on total_amount
        amount_invalid = False
        if rec.total_amount < 0:
            amount_invalid = True
        elif rec.order_status in {"PAID", "SHIPPED"} and rec.total_amount <= 0:
            amount_invalid = True

        if amount_invalid:
            invalid_amount_rows += 1
            findings.append(
                ValidationFinding(
                    order_id=rec.order_id,
                    rule_id="RULE_MONETARY_CONSISTENCY",
                    dimension="consistency",
                    message=(
                        f"Inconsistent total_amount={rec.total_amount} "
                        f"for status='{rec.order_status}'."
                    ),
                )
            )

        # 5. Temporal consistency check
        if rec.updated_at < rec.created_at:
            invalid_timestamp_rows += 1
            findings.append(
                ValidationFinding(
                    order_id=rec.order_id,
                    rule_id="RULE_TEMPORAL_ORDER",
                    dimension="consistency",
                    message="updated_at is earlier than created_at.",
                )
            )

        if rec.order_status == "PAID" and not amount_invalid:
            published_paid_total += rec.total_amount

    # Compute quantitative SLIs
    distinct_ids = len(seen_ids)
    latest_update = max(r.updated_at for r in records)
    freshness_lag_minutes = (evaluation_time - latest_update).total_seconds() / 60.0
    reconciliation_diff = abs(expected_paid_total_source - published_paid_total)
    volume_ratio_vs_baseline = total_count / float(historical_avg_volume)

    slis: Dict[str, float] = {
        "order_id_uniqueness_ratio": round(distinct_ids / total_count, 4),
        "customer_completeness_ratio": round((total_count - missing_customer_rows) / total_count, 4),
        "valid_status_ratio": round((total_count - invalid_status_rows) / total_count, 4),
        "valid_amount_ratio": round((total_count - invalid_amount_rows) / total_count, 4),
        "temporal_consistency_ratio": round((total_count - invalid_timestamp_rows) / total_count, 4),
        "freshness_lag_minutes": round(freshness_lag_minutes, 2),
        "paid_reconciliation_diff_usd": round(reconciliation_diff, 2),
        "volume_ratio_vs_baseline": round(volume_ratio_vs_baseline, 4),
    }

    # Evaluate SLIs against declared SLOs
    slo_evaluations: List[SLOEvaluation] = []
    publication_allowed = True
    operational_status = "HEALTHY"
    alerts: List[str] = []

    for slo in slos:
        observed_val = slis[slo.sli_name]
        passed = compare_sli_to_target(observed_val, slo.operator, slo.target)
        slo_evaluations.append(
            SLOEvaluation(
                slo_id=slo.slo_id,
                dimension=slo.dimension,
                sli_name=slo.sli_name,
                observed_value=observed_val,
                target_value=slo.target,
                operator=slo.operator,
                passed=passed,
                severity=slo.severity,
                block_on_failure=slo.block_on_failure,
            )
        )
        if not passed:
            alerts.append(
                f"[{slo.severity}] SLO '{slo.slo_id}' breached: "
                f"{slo.sli_name}={observed_val} (expected {slo.operator} {slo.target})"
            )
            if slo.block_on_failure:
                publication_allowed = False
                operational_status = "FAILED"
            elif operational_status != "FAILED":
                operational_status = "DEGRADED"

    return ObservabilityReport(
        run_id=run_id,
        data_product="sales-orders",
        evaluated_at=evaluation_time.isoformat(),
        total_records=total_count,
        slis=slis,
        slo_evaluations=slo_evaluations,
        row_findings=findings,
        publication_allowed=publication_allowed,
        operational_status=operational_status,
        alerts=alerts,
    )


if __name__ == "__main__":
    # Define didactic SLOs for the sales-orders product
    sales_orders_slos = [
        SLODefinition("slo_unique_id", "uniqueness", "order_id_uniqueness_ratio", "==", 1.0, "CRITICAL", True),
        SLODefinition("slo_valid_status", "validity", "valid_status_ratio", "==", 1.0, "CRITICAL", True),
        SLODefinition("slo_valid_amount", "consistency", "valid_amount_ratio", "==", 1.0, "CRITICAL", True),
        SLODefinition("slo_reconciliation", "accuracy", "paid_reconciliation_diff_usd", "<=", 0.01, "CRITICAL", True),
        SLODefinition("slo_customer_complete", "completeness", "customer_completeness_ratio", ">=", 0.95, "WARNING", False),
        SLODefinition("slo_freshness", "timeliness", "freshness_lag_minutes", "<=", 60.0, "WARNING", False),
    ]

    eval_time = datetime(2026, 5, 10, 9, 30, 0, tzinfo=timezone.utc)

    # Case 1: Defective batch containing the 4 issues from our scenario
    defective_batch = [
        OrderRecord("ORD-2001", "CUST-101", "PAID", 120.50, "USD",
                    datetime(2026, 5, 10, 8, 0, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 5, tzinfo=timezone.utc)),
        OrderRecord("ORD-2002", "CUST-102", "SHIPPED", 85.00, "USD",
                    datetime(2026, 5, 10, 8, 10, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 9, 0, tzinfo=timezone.utc)),
        OrderRecord("ORD-2002", "CUST-102", "SHIPPED", 85.00, "USD",
                    datetime(2026, 5, 10, 8, 10, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 9, 0, tzinfo=timezone.utc)),  # Duplicate key
        OrderRecord("ORD-2003", None, "PAID", 45.00, "USD",
                    datetime(2026, 5, 10, 8, 15, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 16, tzinfo=timezone.utc)),  # Null customer_id
        OrderRecord("ORD-2004", "CUST-104", "AWAITING_PACKING", 210.00, "USD",
                    datetime(2026, 5, 10, 8, 20, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 25, tzinfo=timezone.utc)),  # Invalid status
        OrderRecord("ORD-2005", "CUST-105", "PAID", -15.00, "USD",
                    datetime(2026, 5, 10, 8, 30, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 31, tzinfo=timezone.utc)),  # Negative PAID amount
        OrderRecord("ORD-2006", "CUST-106", "CANCELLED", 0.00, "USD",
                    datetime(2026, 5, 10, 8, 40, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 45, tzinfo=timezone.utc)),
    ]

    report_bad = evaluate_sales_orders_batch(
        run_id="run-20260510-0930-bad",
        records=defective_batch,
        evaluation_time=eval_time,
        expected_paid_total_source=165.50,
        historical_avg_volume=7,
        slos=sales_orders_slos,
    )

    # Verify that the circuit breaker blocks publication and captures every defect
    assert report_bad.publication_allowed is False
    assert report_bad.operational_status == "FAILED"
    assert report_bad.slis["order_id_uniqueness_ratio"] == round(6 / 7, 4)
    assert report_bad.slis["customer_completeness_ratio"] == round(6 / 7, 4)
    assert report_bad.slis["valid_status_ratio"] == round(6 / 7, 4)
    assert report_bad.slis["valid_amount_ratio"] == round(6 / 7, 4)
    assert len(report_bad.alerts) == 4

    # Case 2: Clean batch after remediating source mappings and deduplication
    clean_batch = [
        OrderRecord("ORD-2001", "CUST-101", "PAID", 120.50, "USD",
                    datetime(2026, 5, 10, 8, 0, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 5, tzinfo=timezone.utc)),
        OrderRecord("ORD-2002", "CUST-102", "SHIPPED", 85.00, "USD",
                    datetime(2026, 5, 10, 8, 10, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 9, 0, tzinfo=timezone.utc)),
        OrderRecord("ORD-2003", "GUEST-9901", "PAID", 45.00, "USD",
                    datetime(2026, 5, 10, 8, 15, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 16, tzinfo=timezone.utc)),
        OrderRecord("ORD-2004", "CUST-104", "PAID", 210.00, "USD",
                    datetime(2026, 5, 10, 8, 20, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 25, tzinfo=timezone.utc)),
        OrderRecord("ORD-2005", "CUST-105", "REFUNDED", 15.00, "USD",
                    datetime(2026, 5, 10, 8, 30, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 31, tzinfo=timezone.utc)),
        OrderRecord("ORD-2006", "CUST-106", "CANCELLED", 0.00, "USD",
                    datetime(2026, 5, 10, 8, 40, tzinfo=timezone.utc),
                    datetime(2026, 5, 10, 8, 45, tzinfo=timezone.utc)),
    ]

    report_clean = evaluate_sales_orders_batch(
        run_id="run-20260510-0945-clean",
        records=clean_batch,
        evaluation_time=eval_time,
        expected_paid_total_source=375.50,  # 120.50 + 45.00 + 210.00
        historical_avg_volume=6,
        slos=sales_orders_slos,
    )

    assert report_clean.publication_allowed is True
    assert report_clean.operational_status == "HEALTHY"
    assert len(report_clean.alerts) == 0
    assert report_clean.slis["freshness_lag_minutes"] == 30.0
    print("All quality and observability assertions passed successfully.")

Loading conversation…

Keep learning