|
| 1 | +"""Suite execution result models for capturing validation outcomes.""" |
| 2 | + |
| 3 | +from datetime import datetime |
| 4 | +from typing import Any, Dict, List, Literal, Optional |
| 5 | + |
| 6 | +from pydantic import BaseModel, Field, computed_field |
| 7 | + |
| 8 | +from dataframe_expectations.core.types import DataFrameType, DataFrameLike |
| 9 | +from dataframe_expectations.core.tagging import TagSet |
| 10 | + |
| 11 | + |
| 12 | +from enum import Enum |
| 13 | + |
| 14 | + |
| 15 | +class ExpectationStatus(str, Enum): |
| 16 | + PASSED = "passed" |
| 17 | + FAILED = "failed" |
| 18 | + SKIPPED = "skipped" |
| 19 | + |
| 20 | + |
| 21 | +class ExpectationResult(BaseModel): |
| 22 | + """ |
| 23 | + Representation of a single expectation result within a suite execution. |
| 24 | + Captures the outcome (passed, failed, skipped) using status. |
| 25 | + Does not store raw dataframes, only serialized violation samples. |
| 26 | + """ |
| 27 | + |
| 28 | + expectation_name: str = Field(..., description="Name of the expectation class") |
| 29 | + description: str = Field(..., description="Human-readable description of the expectation") |
| 30 | + status: ExpectationStatus = Field(..., description="Outcome status: passed, failed, or skipped") |
| 31 | + tags: Optional[TagSet] = Field( |
| 32 | + default=None, description="User-defined tags for this specific expectation" |
| 33 | + ) |
| 34 | + error_message: Optional[str] = Field( |
| 35 | + default=None, description="Error message if expectation failed" |
| 36 | + ) |
| 37 | + violation_count: Optional[int] = Field( |
| 38 | + default=None, description="Total count of violations (if applicable)" |
| 39 | + ) |
| 40 | + violation_sample: Optional[List[Dict[str, Any]]] = Field( |
| 41 | + default=None, |
| 42 | + description="Sample of violations as list of dicts (limited by violation_sample_limit)", |
| 43 | + ) |
| 44 | + |
| 45 | + model_config = {"frozen": True, "arbitrary_types_allowed": True} # Make immutable, allow TagSet |
| 46 | + |
| 47 | + |
| 48 | +class SuiteExecutionResult(BaseModel): |
| 49 | + """Result of a complete suite execution. |
| 50 | + Captures all metadata about the suite run including timing, dataframe info, |
| 51 | + and individual expectation results. Does not store raw dataframes. |
| 52 | + """ |
| 53 | + |
| 54 | + suite_name: Optional[str] = Field(default=None, description="Optional name for the suite") |
| 55 | + context: Dict[str, Any] = Field( |
| 56 | + default_factory=dict, description="Additional runtime metadata (e.g., job_id, environment)" |
| 57 | + ) |
| 58 | + applied_filters: TagSet = Field( |
| 59 | + default_factory=TagSet, description="Tag filters that were applied to select expectations" |
| 60 | + ) |
| 61 | + tag_match_mode: Optional[Literal["any", "all"]] = Field( |
| 62 | + default=None, description="How tags were matched: 'any' (OR) or 'all' (AND)" |
| 63 | + ) |
| 64 | + results: List[ExpectationResult] = Field( |
| 65 | + ..., description="Results for each expectation in execution order (including skipped)" |
| 66 | + ) |
| 67 | + start_time: datetime = Field(..., description="Suite execution start timestamp") |
| 68 | + end_time: datetime = Field(..., description="Suite execution end timestamp") |
| 69 | + dataframe_type: DataFrameType = Field(..., description="Type of dataframe validated") |
| 70 | + dataframe_row_count: int = Field(..., description="Number of rows in validated dataframe") |
| 71 | + dataframe_was_cached: bool = Field( |
| 72 | + default=False, description="Whether PySpark dataframe was cached during execution" |
| 73 | + ) |
| 74 | + |
| 75 | + model_config = {"frozen": True, "arbitrary_types_allowed": True} # Make immutable, allow TagSet |
| 76 | + |
| 77 | + @computed_field # type: ignore[misc] |
| 78 | + @property |
| 79 | + def total_duration_seconds(self) -> float: |
| 80 | + """Total execution time in seconds.""" |
| 81 | + return (self.end_time - self.start_time).total_seconds() |
| 82 | + |
| 83 | + @computed_field # type: ignore[misc] |
| 84 | + @property |
| 85 | + def total_expectations(self) -> int: |
| 86 | + """Total number of expectations in the suite (including skipped).""" |
| 87 | + return len(self.results) |
| 88 | + |
| 89 | + @computed_field # type: ignore[misc] |
| 90 | + @property |
| 91 | + def total_passed(self) -> int: |
| 92 | + """Number of expectations that passed.""" |
| 93 | + return sum(1 for r in self.results if r.status == ExpectationStatus.PASSED) |
| 94 | + |
| 95 | + @computed_field # type: ignore[misc] |
| 96 | + @property |
| 97 | + def total_failed(self) -> int: |
| 98 | + """Number of expectations that failed.""" |
| 99 | + return sum(1 for r in self.results if r.status == ExpectationStatus.FAILED) |
| 100 | + |
| 101 | + @computed_field # type: ignore[misc] |
| 102 | + @property |
| 103 | + def total_skipped(self) -> int: |
| 104 | + """Number of expectations that were skipped due to tag filtering.""" |
| 105 | + return sum(1 for r in self.results if r.status == ExpectationStatus.SKIPPED) |
| 106 | + |
| 107 | + @computed_field # type: ignore[misc] |
| 108 | + @property |
| 109 | + def pass_rate(self) -> float: |
| 110 | + """Percentage of expectations that passed (0.0 to 1.0).""" |
| 111 | + executed = self.total_passed + self.total_failed |
| 112 | + if executed == 0: |
| 113 | + return 1.0 |
| 114 | + return self.total_passed / executed |
| 115 | + |
| 116 | + @computed_field # type: ignore[misc] |
| 117 | + @property |
| 118 | + def success(self) -> bool: |
| 119 | + """Whether all executed expectations passed (ignores skipped).""" |
| 120 | + return self.total_failed == 0 |
| 121 | + |
| 122 | + @computed_field # type: ignore[misc] |
| 123 | + @property |
| 124 | + def passed_expectations(self) -> List[ExpectationResult]: |
| 125 | + """List of expectations that passed.""" |
| 126 | + return [r for r in self.results if r.status == ExpectationStatus.PASSED] |
| 127 | + |
| 128 | + @computed_field # type: ignore[misc] |
| 129 | + @property |
| 130 | + def failed_expectations(self) -> List[ExpectationResult]: |
| 131 | + """List of expectations that failed.""" |
| 132 | + return [r for r in self.results if r.status == ExpectationStatus.FAILED] |
| 133 | + |
| 134 | + @computed_field # type: ignore[misc] |
| 135 | + @property |
| 136 | + def skipped_expectations(self) -> List[ExpectationResult]: |
| 137 | + """List of expectations that were skipped due to tag filtering.""" |
| 138 | + return [r for r in self.results if r.status == ExpectationStatus.SKIPPED] |
| 139 | + |
| 140 | + |
| 141 | +def serialize_violations( |
| 142 | + violations_df: Optional[DataFrameLike], |
| 143 | + df_type: DataFrameType, |
| 144 | + limit: int = 5, |
| 145 | +) -> tuple[Optional[int], Optional[List[Dict[str, Any]]]]: |
| 146 | + """Serialize violation dataframe to count and sample for storage. |
| 147 | +
|
| 148 | + Converts dataframes to JSON-serializable format without storing raw dataframes. |
| 149 | +
|
| 150 | + :param violations_df: DataFrame containing violations (pandas or PySpark). |
| 151 | + :param df_type: Type of the violations dataframe. |
| 152 | + :param limit: Maximum number of violation rows to include in sample. |
| 153 | + :return: Tuple of (total_count, sample_as_list_of_dicts). |
| 154 | + """ |
| 155 | + if violations_df is None: |
| 156 | + return None, None |
| 157 | + |
| 158 | + count: Optional[int] = None |
| 159 | + sample: Optional[list[dict[str, Any]]] = None |
| 160 | + |
| 161 | + try: |
| 162 | + if df_type == DataFrameType.PANDAS: |
| 163 | + pandas_df = violations_df # type: ignore[assignment] |
| 164 | + count = len(pandas_df) # type: ignore[arg-type] |
| 165 | + sample = pandas_df.head(limit).to_dict("records") # type: ignore[assignment,union-attr] |
| 166 | + elif df_type == DataFrameType.PYSPARK: |
| 167 | + pyspark_df = violations_df # type: ignore[assignment] |
| 168 | + count = pyspark_df.count() # type: ignore[assignment] |
| 169 | + sample = pyspark_df.limit(limit).toPandas().to_dict("records") # type: ignore[assignment,operator] |
| 170 | + |
| 171 | + return count, sample |
| 172 | + except Exception: |
| 173 | + # If serialization fails, return None to avoid breaking the suite |
| 174 | + return None, None |
0 commit comments