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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Data Governance Module (Ch.7)
|
| 3 |
+
==============================
|
| 4 |
+
CLO7: Data Lineage, RLS simulation, Anonymization, Audit Trail
|
| 5 |
+
|
| 6 |
+
Implements:
|
| 7 |
+
1. Data Lineage Tracker (source → transform → target)
|
| 8 |
+
2. Row-Level Security simulation
|
| 9 |
+
3. K-Anonymity & Differential Privacy
|
| 10 |
+
4. Blockchain-based Audit Trail
|
| 11 |
+
5. Data Quality Monitoring
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import os, json, hashlib, logging
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ==============================================================================
|
| 26 |
+
# 1. DATA LINEAGE TRACKER
|
| 27 |
+
# ==============================================================================
|
| 28 |
+
|
| 29 |
+
class DataLineageTracker:
|
| 30 |
+
"""Track data transformations from source to target."""
|
| 31 |
+
|
| 32 |
+
def __init__(self):
|
| 33 |
+
self.lineage = []
|
| 34 |
+
|
| 35 |
+
def record(self, source: str, target: str, transform: str, rows_in: int,
|
| 36 |
+
rows_out: int, columns: list = None):
|
| 37 |
+
entry = {
|
| 38 |
+
'timestamp': datetime.now().isoformat(),
|
| 39 |
+
'source': source,
|
| 40 |
+
'target': target,
|
| 41 |
+
'transform': transform,
|
| 42 |
+
'rows_in': rows_in,
|
| 43 |
+
'rows_out': rows_out,
|
| 44 |
+
'rows_dropped': rows_in - rows_out,
|
| 45 |
+
'columns': columns or [],
|
| 46 |
+
}
|
| 47 |
+
self.lineage.append(entry)
|
| 48 |
+
logger.info(f"[LINEAGE] {source} → {target}: {rows_in} → {rows_out} ({transform})")
|
| 49 |
+
|
| 50 |
+
def get_lineage_for(self, table: str):
|
| 51 |
+
return [e for e in self.lineage if e['source'] == table or e['target'] == table]
|
| 52 |
+
|
| 53 |
+
def export(self, path: str):
|
| 54 |
+
with open(path, 'w') as f:
|
| 55 |
+
json.dump(self.lineage, f, indent=2)
|
| 56 |
+
logger.info(f"[LINEAGE] Exported {len(self.lineage)} entries to {path}")
|
| 57 |
+
|
| 58 |
+
def print_lineage_graph(self):
|
| 59 |
+
print("\n DATA LINEAGE GRAPH:")
|
| 60 |
+
print(" " + "=" * 60)
|
| 61 |
+
for e in self.lineage:
|
| 62 |
+
print(f" {e['source']}")
|
| 63 |
+
print(f" │ {e['transform']}")
|
| 64 |
+
print(f" │ ({e['rows_in']} → {e['rows_out']} rows)")
|
| 65 |
+
print(f" ▼")
|
| 66 |
+
print(f" {e['target']}")
|
| 67 |
+
print()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# ==============================================================================
|
| 71 |
+
# 2. ROW-LEVEL SECURITY SIMULATION
|
| 72 |
+
# ==============================================================================
|
| 73 |
+
|
| 74 |
+
class RowLevelSecurity:
|
| 75 |
+
"""Simulate Row-Level Security policies."""
|
| 76 |
+
|
| 77 |
+
def __init__(self):
|
| 78 |
+
self.policies = {}
|
| 79 |
+
|
| 80 |
+
def add_policy(self, table: str, role: str, filter_col: str, allowed_values: list):
|
| 81 |
+
key = f"{table}:{role}"
|
| 82 |
+
self.policies[key] = {'column': filter_col, 'allowed': allowed_values}
|
| 83 |
+
logger.info(f"[RLS] Policy added: {role} can see {table} where {filter_col} in {allowed_values}")
|
| 84 |
+
|
| 85 |
+
def apply(self, df: pd.DataFrame, table: str, role: str) -> pd.DataFrame:
|
| 86 |
+
key = f"{table}:{role}"
|
| 87 |
+
if key not in self.policies:
|
| 88 |
+
logger.warning(f"[RLS] No policy for {key}, returning empty DataFrame")
|
| 89 |
+
return df.head(0)
|
| 90 |
+
policy = self.policies[key]
|
| 91 |
+
filtered = df[df[policy['column']].isin(policy['allowed'])]
|
| 92 |
+
logger.info(f"[RLS] {table} for {role}: {len(df)} → {len(filtered)} rows")
|
| 93 |
+
return filtered
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# ==============================================================================
|
| 97 |
+
# 3. COLUMN MASKING
|
| 98 |
+
# ==============================================================================
|
| 99 |
+
|
| 100 |
+
def mask_column(df: pd.DataFrame, column: str, role: str = 'analyst') -> pd.DataFrame:
|
| 101 |
+
"""Dynamic Column Masking based on role."""
|
| 102 |
+
df = df.copy()
|
| 103 |
+
if role == 'admin':
|
| 104 |
+
return df # Full access
|
| 105 |
+
elif role == 'analyst':
|
| 106 |
+
if df[column].dtype == 'object':
|
| 107 |
+
df[column] = df[column].apply(lambda x: x[:3] + '***' if isinstance(x, str) and len(x) > 3 else '***')
|
| 108 |
+
else:
|
| 109 |
+
df[column] = df[column].apply(lambda x: round(x, -2) if pd.notna(x) else x)
|
| 110 |
+
else:
|
| 111 |
+
df[column] = '***MASKED***'
|
| 112 |
+
return df
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ==============================================================================
|
| 116 |
+
# 4. K-ANONYMITY
|
| 117 |
+
# ==============================================================================
|
| 118 |
+
|
| 119 |
+
def k_anonymize(df: pd.DataFrame, quasi_identifiers: list, k: int = 5) -> pd.DataFrame:
|
| 120 |
+
"""
|
| 121 |
+
K-Anonymity: generalize quasi-identifiers until each group has >= k records.
|
| 122 |
+
"""
|
| 123 |
+
df = df.copy()
|
| 124 |
+
# Generalize: city → state, age → age_range
|
| 125 |
+
for qi in quasi_identifiers:
|
| 126 |
+
if qi == 'customer_city' and qi in df.columns:
|
| 127 |
+
# Suppress city (replace with state)
|
| 128 |
+
df[qi] = '***'
|
| 129 |
+
elif df[qi].dtype in ['int64', 'float64']:
|
| 130 |
+
# Bin numeric values
|
| 131 |
+
df[qi] = pd.qcut(df[qi], q=10, labels=False, duplicates='drop')
|
| 132 |
+
|
| 133 |
+
# Check k-anonymity
|
| 134 |
+
groups = df.groupby(quasi_identifiers).size()
|
| 135 |
+
violations = (groups < k).sum()
|
| 136 |
+
min_group = groups.min()
|
| 137 |
+
logger.info(f"[K-ANON] k={k}: {violations} groups violate k-anonymity (min group size={min_group})")
|
| 138 |
+
|
| 139 |
+
# Suppress violating groups
|
| 140 |
+
if violations > 0:
|
| 141 |
+
valid_groups = groups[groups >= k].reset_index()[quasi_identifiers]
|
| 142 |
+
df = df.merge(valid_groups, on=quasi_identifiers, how='inner')
|
| 143 |
+
logger.info(f"[K-ANON] After suppression: {len(df)} rows remain")
|
| 144 |
+
|
| 145 |
+
return df
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# ==============================================================================
|
| 149 |
+
# 5. DIFFERENTIAL PRIVACY
|
| 150 |
+
# ==============================================================================
|
| 151 |
+
|
| 152 |
+
def dp_aggregate(df: pd.DataFrame, column: str, epsilon: float = 1.0, operation: str = 'mean'):
|
| 153 |
+
"""
|
| 154 |
+
Differential Privacy: add Laplace noise to aggregate queries.
|
| 155 |
+
ε (epsilon): privacy budget. Smaller = more private, less accurate.
|
| 156 |
+
"""
|
| 157 |
+
if operation == 'mean':
|
| 158 |
+
true_value = df[column].mean()
|
| 159 |
+
sensitivity = (df[column].max() - df[column].min()) / len(df)
|
| 160 |
+
elif operation == 'sum':
|
| 161 |
+
true_value = df[column].sum()
|
| 162 |
+
sensitivity = df[column].max() - df[column].min()
|
| 163 |
+
elif operation == 'count':
|
| 164 |
+
true_value = len(df)
|
| 165 |
+
sensitivity = 1
|
| 166 |
+
|
| 167 |
+
noise = np.random.laplace(0, sensitivity / epsilon)
|
| 168 |
+
noisy_value = true_value + noise
|
| 169 |
+
|
| 170 |
+
logger.info(f"[DP] {operation}({column}): true={true_value:.2f}, "
|
| 171 |
+
f"noisy={noisy_value:.2f}, ε={epsilon}, noise={noise:.4f}")
|
| 172 |
+
return noisy_value
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ==============================================================================
|
| 176 |
+
# 6. BLOCKCHAIN AUDIT TRAIL
|
| 177 |
+
# ==============================================================================
|
| 178 |
+
|
| 179 |
+
class AuditBlock:
|
| 180 |
+
def __init__(self, index, data, previous_hash):
|
| 181 |
+
self.index = index
|
| 182 |
+
self.timestamp = datetime.now().isoformat()
|
| 183 |
+
self.data = data
|
| 184 |
+
self.previous_hash = previous_hash
|
| 185 |
+
self.hash = self._calculate_hash()
|
| 186 |
+
|
| 187 |
+
def _calculate_hash(self):
|
| 188 |
+
block_str = json.dumps({
|
| 189 |
+
'index': self.index, 'timestamp': self.timestamp,
|
| 190 |
+
'data': self.data, 'previous_hash': self.previous_hash
|
| 191 |
+
}, sort_keys=True)
|
| 192 |
+
return hashlib.sha256(block_str.encode()).hexdigest()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class AuditChain:
|
| 196 |
+
"""Immutable blockchain-based audit trail."""
|
| 197 |
+
|
| 198 |
+
def __init__(self):
|
| 199 |
+
self.chain = [AuditBlock(0, {"event": "Genesis block"}, "0")]
|
| 200 |
+
|
| 201 |
+
def add_event(self, event_type: str, user: str, details: dict):
|
| 202 |
+
data = {'event_type': event_type, 'user': user, **details}
|
| 203 |
+
block = AuditBlock(len(self.chain), data, self.chain[-1].hash)
|
| 204 |
+
self.chain.append(block)
|
| 205 |
+
logger.info(f"[AUDIT] Block #{block.index}: {event_type} by {user}")
|
| 206 |
+
return block
|
| 207 |
+
|
| 208 |
+
def verify_integrity(self) -> tuple:
|
| 209 |
+
for i in range(1, len(self.chain)):
|
| 210 |
+
current = self.chain[i]
|
| 211 |
+
previous = self.chain[i - 1]
|
| 212 |
+
if current.hash != current._calculate_hash():
|
| 213 |
+
return False, f"Block {i}: hash tampered"
|
| 214 |
+
if current.previous_hash != previous.hash:
|
| 215 |
+
return False, f"Block {i}: chain broken"
|
| 216 |
+
return True, f"Chain valid ({len(self.chain)} blocks)"
|
| 217 |
+
|
| 218 |
+
def export(self, path: str):
|
| 219 |
+
chain_data = []
|
| 220 |
+
for block in self.chain:
|
| 221 |
+
chain_data.append({
|
| 222 |
+
'index': block.index, 'timestamp': block.timestamp,
|
| 223 |
+
'data': block.data, 'hash': block.hash[:16] + '...',
|
| 224 |
+
'previous_hash': block.previous_hash[:16] + '...',
|
| 225 |
+
})
|
| 226 |
+
with open(path, 'w') as f:
|
| 227 |
+
json.dump(chain_data, f, indent=2)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# ==============================================================================
|
| 231 |
+
# DEMO
|
| 232 |
+
# ==============================================================================
|
| 233 |
+
|
| 234 |
+
def demo():
|
| 235 |
+
print("=" * 70)
|
| 236 |
+
print(" DATA GOVERNANCE DEMO")
|
| 237 |
+
print("=" * 70)
|
| 238 |
+
|
| 239 |
+
# 1. Lineage
|
| 240 |
+
lineage = DataLineageTracker()
|
| 241 |
+
lineage.record('olist_orders.csv', 'silver_orders.parquet', 'dedup + type_cast + validate', 99441, 98207)
|
| 242 |
+
lineage.record('silver_orders.parquet', 'fact_orders.parquet', 'join dims + aggregate + enrich', 98207, 96461)
|
| 243 |
+
lineage.record('fact_orders.parquet', 'agg_daily_revenue.parquet', 'daily aggregation', 96461, 730)
|
| 244 |
+
lineage.print_lineage_graph()
|
| 245 |
+
|
| 246 |
+
# 2. RLS
|
| 247 |
+
rls = RowLevelSecurity()
|
| 248 |
+
rls.add_policy('fact_orders', 'seller_SP', 'customer_state', ['SP'])
|
| 249 |
+
rls.add_policy('fact_orders', 'seller_RJ', 'customer_state', ['RJ'])
|
| 250 |
+
rls.add_policy('fact_orders', 'admin', 'customer_state',
|
| 251 |
+
['SP', 'RJ', 'MG', 'RS', 'PR', 'BA', 'SC'])
|
| 252 |
+
|
| 253 |
+
# 3. Differential Privacy demo
|
| 254 |
+
print("\n DIFFERENTIAL PRIVACY:")
|
| 255 |
+
np.random.seed(42)
|
| 256 |
+
sample = pd.DataFrame({'revenue': np.random.lognormal(5, 1, 1000)})
|
| 257 |
+
for eps in [0.1, 0.5, 1.0, 5.0]:
|
| 258 |
+
dp_aggregate(sample, 'revenue', epsilon=eps, operation='mean')
|
| 259 |
+
|
| 260 |
+
# 4. Audit trail
|
| 261 |
+
print("\n BLOCKCHAIN AUDIT TRAIL:")
|
| 262 |
+
audit = AuditChain()
|
| 263 |
+
audit.add_event('SCHEMA_CHANGE', 'data_engineer', {'table': 'fact_orders', 'action': 'add_column delivery_delay'})
|
| 264 |
+
audit.add_event('ETL_RUN', 'airflow', {'pipeline': 'daily_etl', 'rows_processed': 5000})
|
| 265 |
+
audit.add_event('QUERY', 'analyst_1', {'query': 'SELECT * FROM dim_customer', 'rows_returned': 99441})
|
| 266 |
+
audit.add_event('MODEL_DEPLOY', 'ml_engineer', {'model': 'satisfaction_v2', 'auc': 0.85})
|
| 267 |
+
|
| 268 |
+
valid, msg = audit.verify_integrity()
|
| 269 |
+
print(f" Chain integrity: {msg}")
|
| 270 |
+
|
| 271 |
+
print(f"\n{'='*70}")
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
if __name__ == '__main__':
|
| 275 |
+
demo()
|