dataguard-drift 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dataguard/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """DataGuard - Data Quality Framework with Lineage Tracking"""
2
+
3
+ __version__ = "0.1.0"
4
+ __author__ = "Ayush Varma"
dataguard/cli.py ADDED
@@ -0,0 +1,424 @@
1
+ """DataGuard CLI - Data Quality Framework"""
2
+
3
+ import typer
4
+ import os
5
+ from pathlib import Path
6
+ from rich.console import Console
7
+ from rich.table import Table
8
+ from rich.panel import Panel
9
+
10
+ from dataguard.core.schema import SchemaInferer
11
+ from dataguard.storage.metadata import MetadataStore
12
+ from dataguard.storage.models import Dataset
13
+ from dataguard.core.drift import DriftDetector
14
+ from dataguard.core.validator import RuleParser, ValidationExecutor
15
+
16
+ app = typer.Typer(
17
+ name="dataguard",
18
+ help="🛡️ DataGuard - Data Quality Framework with Lineage Tracking",
19
+ add_completion=False,
20
+ )
21
+ console = Console()
22
+
23
+ # Initialize store (in a real app, path might be configurable via env var)
24
+ STORE_PATH = "dataguard.db"
25
+
26
+ # Schema subcommand group
27
+ schema_app = typer.Typer(help="Schema operations")
28
+ app.add_typer(schema_app, name="schema")
29
+
30
+
31
+ def get_store() -> MetadataStore:
32
+ """Get metadata store instance."""
33
+ return MetadataStore(STORE_PATH)
34
+
35
+
36
+ @app.command()
37
+ def version():
38
+ """Show DataGuard version."""
39
+ console.print("[bold green]DataGuard[/bold green] v0.1.0")
40
+
41
+
42
+ @schema_app.command("infer")
43
+ def schema_infer(
44
+ file_path: str = typer.Argument(..., help="Path to data file (CSV/Parquet)"),
45
+ name: str = typer.Option(..., "--name", "-n", help="Dataset name"),
46
+ ):
47
+ """Infer and store schema from a data file."""
48
+ path = Path(file_path).resolve()
49
+ if not path.exists():
50
+ console.print(f"[bold red]Error:[/bold red] File not found: {path}")
51
+ raise typer.Exit(code=1)
52
+
53
+ console.print(f"🔍 Inferring schema for [cyan]{name}[/cyan] from {path.name}...")
54
+
55
+ # 1. Infer Schema
56
+ inferer = SchemaInferer()
57
+ try:
58
+ schema = inferer.infer(str(path), name)
59
+ finally:
60
+ inferer.close()
61
+
62
+ # 2. Register Dataset & Save Schema
63
+ store = get_store()
64
+
65
+ # Register dataset if new
66
+ dataset = Dataset(
67
+ name=name,
68
+ file_path=str(path),
69
+ format=path.suffix.lstrip('.')
70
+ )
71
+ store.register_dataset(dataset)
72
+
73
+ # Save snapshot
74
+ store.save_schema_snapshot(name, schema)
75
+
76
+ console.print(f"[green]✅ Schema inferred and saved for dataset:[/green] [bold]{name}[/bold]")
77
+ console.print(f" Columns detected: {len(schema.columns)}")
78
+
79
+
80
+ @schema_app.command("show")
81
+ def schema_show(
82
+ name: str = typer.Argument(..., help="Dataset name"),
83
+ ):
84
+ """Show current schema for a dataset."""
85
+ store = get_store()
86
+ schema = store.get_latest_schema(name)
87
+
88
+ if not schema:
89
+ console.print(f"[bold red]Error:[/bold red] No schema found for dataset '{name}'")
90
+ raise typer.Exit(code=1)
91
+
92
+ table = Table(title=f"Schema: {name}")
93
+ table.add_column("Column", style="cyan")
94
+ table.add_column("Type", style="green")
95
+ table.add_column("Nullable", justify="center")
96
+
97
+ for col in schema.columns:
98
+ table.add_row(
99
+ col.name,
100
+ col.dtype,
101
+ "Yes" if col.nullable else "No"
102
+ )
103
+
104
+ console.print(table)
105
+
106
+
107
+ @schema_app.command("diff")
108
+ def schema_diff(
109
+ name: str = typer.Argument(..., help="Dataset name (baseline)"),
110
+ file_path: str = typer.Option(None, "--file", "-f", help="New file to compare against"),
111
+ ):
112
+ """Check for schema drift."""
113
+ if not file_path:
114
+ console.print("[yellow]Please provide a file to check drift against: --file <path>[/yellow]")
115
+ raise typer.Exit(code=1)
116
+
117
+ store = get_store()
118
+ old_schema = store.get_latest_schema(name)
119
+
120
+ if not old_schema:
121
+ console.print(f"[bold red]Error:[/bold red] No baseline schema found for '{name}'")
122
+ raise typer.Exit(code=1)
123
+
124
+ path = Path(file_path).resolve()
125
+ if not path.exists():
126
+ console.print(f"[bold red]Error:[/bold red] File not found: {path}")
127
+ raise typer.Exit(code=1)
128
+
129
+ # Infer new schema
130
+ console.print(f"🔍 Comparing '[bold]{name}[/bold]' against '{path.name}'...")
131
+ inferer = SchemaInferer()
132
+ try:
133
+ new_schema = inferer.infer(str(path), name)
134
+ finally:
135
+ inferer.close()
136
+
137
+ # Detect Drift
138
+ detector = DriftDetector()
139
+ diff = detector.detect_drift(old_schema, new_schema)
140
+
141
+ if not diff.has_drift:
142
+ console.print(Panel("[bold green]No Drift Detected[/bold green]\nSchemas are identical.", title="Drift Report"))
143
+ else:
144
+ # Build changes summary
145
+ msg = []
146
+ if diff.added_columns:
147
+ msg.append(f"[green]+ Added columns ({len(diff.added_columns)}):[/green]")
148
+ for col in diff.added_columns:
149
+ msg.append(f" - {col.name} ({col.dtype})")
150
+
151
+ if diff.removed_columns:
152
+ msg.append(f"[red]- Removed columns ({len(diff.removed_columns)}):[/red]")
153
+ for col in diff.removed_columns:
154
+ msg.append(f" - {col.name}")
155
+
156
+ if diff.changed_columns:
157
+ msg.append(f"[yellow]~ Changed columns ({len(diff.changed_columns)}):[/yellow]")
158
+ for change in diff.changed_columns:
159
+ cname = change['column_name']
160
+ details = []
161
+ if 'dtype' in change:
162
+ details.append(f"Type: {change['dtype']['old']} -> {change['dtype']['new']}")
163
+ if 'nullable' in change:
164
+ details.append(f"Nullable: {change['nullable']['old']} -> {change['nullable']['new']}")
165
+ msg.append(f" - {cname}: {', '.join(details)}")
166
+
167
+ console.print(Panel("\n".join(msg), title="[bold red]Drift Detected![/bold red]", border_style="red"))
168
+ raise typer.Exit(code=1) # Non-zero exit code for CI/CD pipelines
169
+
170
+
171
+ @app.command()
172
+ def validate(
173
+ file_path: str = typer.Argument(..., help="Path to data file"),
174
+ rules: str = typer.Option(..., "--rules", "-r", help="Path to rules YAML"),
175
+ ):
176
+ """Run validations against a data file."""
177
+ path = Path(file_path).resolve()
178
+ rules_path = Path(rules).resolve()
179
+
180
+ if not path.exists():
181
+ console.print(f"[bold red]Error:[/bold red] Data file not found: {path}")
182
+ raise typer.Exit(code=1)
183
+
184
+ if not rules_path.exists():
185
+ console.print(f"[bold red]Error:[/bold red] Rules file not found: {rules_path}")
186
+ raise typer.Exit(code=1)
187
+
188
+ # 1. Parse Rules
189
+ console.print(f"📋 Loading rules from {rules_path.name}...")
190
+ try:
191
+ parsed_rules = RuleParser.parse_yaml(str(rules_path))
192
+ except Exception as e:
193
+ console.print(f"[bold red]Error parsing rules:[/bold red] {e}")
194
+ raise typer.Exit(code=1)
195
+
196
+ if not parsed_rules:
197
+ console.print("[yellow]No rules found in validation file.[/yellow]")
198
+ return
199
+
200
+ # Determine if file_path is an actual path or a dataset name
201
+ path = Path(file_path)
202
+ if path.exists():
203
+ path = path.resolve()
204
+ dataset_name = path.stem
205
+ # Register if new
206
+ store = get_store()
207
+ existing_ds = store.get_dataset(dataset_name)
208
+ if not existing_ds:
209
+ ds = Dataset(name=dataset_name, file_path=str(path), format=path.suffix.lstrip('.'))
210
+ store.register_dataset(ds)
211
+
212
+ else:
213
+ # Argument is likely a DATASET NAME, not a file path
214
+ dataset_name = file_path
215
+ store = get_store()
216
+ existing_ds = store.get_dataset(dataset_name)
217
+
218
+ if not existing_ds:
219
+ console.print(f"[bold red]Error:[/bold red] Data file not found: {file_path}")
220
+ console.print(f"Also tried looking up dataset '{dataset_name}' but it was not found in the metadata store.")
221
+ raise typer.Exit(code=1)
222
+
223
+ # Use stored path
224
+ path = Path(existing_ds.file_path).resolve()
225
+ if not path.exists():
226
+ console.print(f"[bold red]Error:[/bold red] Registered file for dataset '{dataset_name}' does not exist at: {path}")
227
+ raise typer.Exit(code=1)
228
+
229
+ # console.print(f"Using registered dataset '{dataset_name}' -> {path}")
230
+
231
+ # 4. Execute
232
+ console.print(f"🚀 Running {len(parsed_rules)} checks against [cyan]{dataset_name}[/cyan]...")
233
+ executor = ValidationExecutor()
234
+ run = executor.validate(dataset_name, str(path), parsed_rules)
235
+
236
+ # 5. Save Results
237
+ store.save_validation_run(run)
238
+
239
+ # 6. Report
240
+ table = Table(title=f"Validation Results: {dataset_name}")
241
+ table.add_column("Column", style="cyan")
242
+ table.add_column("Rule", style="magenta")
243
+ table.add_column("Status", justify="center")
244
+ table.add_column("Failures", justify="right", style="red")
245
+
246
+ for res in run.results:
247
+ status = "[green]PASS[/green]" if res.passed else "[bold red]FAIL[/bold red]"
248
+ failures = str(res.failure_count) if not res.passed else "-"
249
+ # Format rule type + params
250
+ rule_desc = f"{res.rule.type}"
251
+ if res.rule.params:
252
+ rule_desc += f" {res.rule.params}"
253
+
254
+ table.add_row(
255
+ res.rule.column,
256
+ rule_desc,
257
+ status,
258
+ failures
259
+ )
260
+
261
+ console.print(table)
262
+
263
+ if run.failed_checks > 0:
264
+ console.print(f"\n[bold red]❌ Validation Failed![/bold red] {run.failed_checks} checks failed.")
265
+ raise typer.Exit(code=1)
266
+ else:
267
+ console.print(f"\n[bold green]✅ Validation Passed![/bold green] All {run.total_checks} checks passed.")
268
+
269
+
270
+ # Lineage subcommand group
271
+ lineage_app = typer.Typer(help="Lineage operations")
272
+ app.add_typer(lineage_app, name="lineage")
273
+
274
+
275
+ @lineage_app.command("show")
276
+ def lineage_show(
277
+ name: str = typer.Argument(..., help="Dataset or Process name"),
278
+ format: str = typer.Option("text", "--format", "-f", help="Output format: text, mermaid"),
279
+ ):
280
+ """Show lineage dependencies for a dataset."""
281
+ store = get_store()
282
+ graph = store.get_lineage_graph()
283
+
284
+ # Check if node exists in graph (either as source or target)
285
+ # Graph is {source: [targets]}
286
+ all_nodes = set(graph.keys())
287
+ for targets in graph.values():
288
+ all_nodes.update(targets)
289
+
290
+ if name not in all_nodes:
291
+ console.print(f"[bold red]Node '{name}' not found in lineage graph.[/bold red]")
292
+ return # Don't exit 1, just informational
293
+
294
+ if format == "mermaid":
295
+ console.print("graph TD;")
296
+ for src, targets in graph.items():
297
+ for tgt in targets:
298
+ console.print(f" {src} --> {tgt};")
299
+ return
300
+
301
+ # Text format: Simple BFS to show downstream
302
+ console.print(f"🔗 Lineage for [cyan]{name}[/cyan]")
303
+
304
+ # downstream
305
+ console.print("[bold]Downstream (Impacts):[/bold]")
306
+ queue = [(name, 0)]
307
+ visited = {name}
308
+
309
+ if name not in graph:
310
+ console.print(" (None)")
311
+ else:
312
+ while queue:
313
+ curr, level = queue.pop(0)
314
+ if level > 0:
315
+ indent = " " * level
316
+ console.print(f"{indent}↳ {curr}")
317
+
318
+ if curr in graph:
319
+ for neighbor in graph[curr]:
320
+ if neighbor not in visited:
321
+ visited.add(neighbor)
322
+ queue.append((neighbor, level + 1))
323
+
324
+ # Upstream (Sources) - Inefficient but works for small graphs
325
+ # We need to reverse the graph
326
+ rev_graph = {}
327
+ for src, targets in graph.items():
328
+ for tgt in targets:
329
+ if tgt not in rev_graph:
330
+ rev_graph[tgt] = []
331
+ rev_graph[tgt].append(src)
332
+
333
+ console.print("[bold]Upstream (Sources):[/bold]")
334
+ queue = [(name, 0)]
335
+ visited = {name}
336
+
337
+ if name not in rev_graph:
338
+ console.print(" (None)")
339
+ else:
340
+ while queue:
341
+ curr, level = queue.pop(0)
342
+ if level > 0:
343
+ indent = " " * level
344
+ console.print(f"{indent}↳ {curr}")
345
+
346
+ if curr in rev_graph:
347
+ for neighbor in rev_graph[curr]:
348
+ if neighbor not in visited:
349
+ visited.add(neighbor)
350
+ queue.append((neighbor, level + 1))
351
+
352
+
353
+ # Contract subcommand group
354
+ contract_app = typer.Typer(help="Data Contract operations")
355
+ app.add_typer(contract_app, name="contract")
356
+
357
+ @contract_app.command("generate")
358
+ def contract_generate(
359
+ dataset: str = typer.Argument(..., help="Dataset name"),
360
+ rules: str = typer.Option(None, "--rules", "-r", help="Path to rules YAML"),
361
+ out: str = typer.Option("contract.json", "--out", "-o", help="Output file path"),
362
+ ):
363
+ """Generate a Data Contract from schema and rules."""
364
+ from dataguard.core.contracts import ContractManager
365
+
366
+ manager = ContractManager(get_store())
367
+
368
+ try:
369
+ console.print(f"📜 Generating contract for [cyan]{dataset}[/cyan]...")
370
+ contract = manager.generate_contract(dataset, rules)
371
+
372
+ # Save to file
373
+ with open(out, "w") as f:
374
+ f.write(contract.model_dump_json(indent=2, by_alias=True))
375
+
376
+ console.print(f"[green]✅ Contract saved to:[/green] {out}")
377
+
378
+ except ValueError as e:
379
+ console.print(f"[bold red]Error:[/bold red] {e}")
380
+ raise typer.Exit(code=1)
381
+
382
+ @contract_app.command("verify")
383
+ def contract_verify(
384
+ file_path: str = typer.Argument(..., help="Path to data file to verify"),
385
+ contract_path: str = typer.Option(..., "--contract", "-c", help="Path to contract JSON/YAML"),
386
+ ):
387
+ """Verify a file against an existing Data Contract."""
388
+ from dataguard.core.contracts import ContractManager
389
+ from dataguard.storage.models import DataContract
390
+
391
+ # 1. Load Contract
392
+ try:
393
+ with open(contract_path, "r") as f:
394
+ # We assume JSON for now as generated by 'generate', but Pydantic handles JSON pretty well
395
+ contract_data = f.read()
396
+ contract = DataContract.model_validate_json(contract_data)
397
+ except Exception as e:
398
+ console.print(f"[bold red]Error loading contract:[/bold red] {e}")
399
+ raise typer.Exit(code=1)
400
+
401
+ console.print(f"📜 Verifying [bold]{file_path}[/bold] against contract for [cyan]{contract.dataset_name}[/cyan]...")
402
+
403
+ manager = ContractManager(get_store())
404
+
405
+ try:
406
+ # 2. Verify
407
+ run = manager.verify_contract(file_path, contract)
408
+
409
+ # 3. Report Results
410
+ if run.failed_checks > 0:
411
+ console.print(f"\n[bold red]❌ Contract Violated![/bold red] {run.failed_checks} validation rules failed.")
412
+ raise typer.Exit(code=1)
413
+ else:
414
+ console.print("\n[bold green]✅ Contract Method Verified![/bold green]")
415
+ console.print(f" - Schema: STRICT MATCH (No drift)")
416
+ console.print(f" - Rules: {run.total_checks} checks passed")
417
+
418
+ except ValueError as e:
419
+ console.print(f"\n[bold red]❌ Schema Contract Violation![/bold red]")
420
+ console.print(str(e))
421
+ raise typer.Exit(code=1)
422
+
423
+ if __name__ == "__main__":
424
+ app()
@@ -0,0 +1,18 @@
1
+ from .schema import SchemaInferer
2
+ from .drift import DriftDetector, DriftReport, SchemaDiff
3
+ from .validator import RuleParser, SQLGenerator, ValidationExecutor
4
+ from .lineage import LineageTracker, track_lineage
5
+ from .contracts import ContractManager
6
+
7
+ __all__ = [
8
+ "SchemaInferer",
9
+ "DriftDetector",
10
+ "DriftReport",
11
+ "SchemaDiff",
12
+ "RuleParser",
13
+ "SQLGenerator",
14
+ "ValidationExecutor",
15
+ "LineageTracker",
16
+ "track_lineage",
17
+ "ContractManager"
18
+ ]
@@ -0,0 +1,82 @@
1
+ from typing import List, Dict, Any, Optional
2
+ from dataguard.storage.metadata import MetadataStore
3
+ from dataguard.storage.models import DataContract, ValidationRule, TableSchema
4
+ from dataguard.core.validator import RuleParser
5
+
6
+ class ContractManager:
7
+ """Manages creation and verification of Data Contracts."""
8
+
9
+ def __init__(self, store: Optional[MetadataStore] = None):
10
+ self.store = store or MetadataStore()
11
+
12
+ def generate_contract(self, dataset_name: str, rules_path: Optional[str] = None, slo: Dict[str, Any] = None) -> DataContract:
13
+ """
14
+ Generate a Data Contract for a given dataset.
15
+
16
+ Args:
17
+ dataset_name: Name of the dataset to target.
18
+ rules_path: Path to rules.yaml file (optional).
19
+ slo: Dictionary of SLOs (optional).
20
+
21
+ Returns:
22
+ DataContract object.
23
+ """
24
+ # 1. Fetch Schema
25
+ schema = self.store.get_latest_schema(dataset_name)
26
+ if not schema:
27
+ raise ValueError(f"No schema found for dataset '{dataset_name}'. Please infer schema first.")
28
+
29
+ # 2. Fetch Rules
30
+ rules = []
31
+ if rules_path:
32
+ rules = RuleParser.parse_yaml(rules_path)
33
+
34
+ # 3. Assemble
35
+ contract = DataContract(
36
+ dataset_name=dataset_name,
37
+ schema=schema,
38
+ rules=rules,
39
+ slo=slo or {}
40
+ )
41
+
42
+ return contract
43
+
44
+ def verify_contract(self, file_path: str, contract: DataContract) -> Any:
45
+ """
46
+ Verify a data file against a Data Contract.
47
+
48
+ Args:
49
+ file_path: Path to the data file.
50
+ contract: The DataContract object to verify against.
51
+
52
+ Returns:
53
+ ValidationRun object containing results.
54
+
55
+ Raises:
56
+ ValueError: If schema drift is detected (Strict Schema Check).
57
+ """
58
+ from dataguard.core.schema import SchemaInferer
59
+ from dataguard.core.drift import DriftDetector
60
+ from dataguard.core.validator import ValidationExecutor
61
+
62
+ # 1. Strict Schema Check
63
+ # We infer the schema of the FILE and compare it to the CONTRACT schema.
64
+ inferer = SchemaInferer()
65
+ file_schema = inferer.infer(file_path, "contract_check")
66
+
67
+ detector = DriftDetector()
68
+ diff = detector.detect_drift(contract.schema_snap, file_schema)
69
+
70
+ if diff.has_drift:
71
+ # For contracts, any drift is a violation
72
+ raise ValueError(f"Contract Schema Violation:\nAdded: {diff.added_columns}\nRemoved: {diff.removed_columns}\nChanged: {diff.changed_columns}")
73
+
74
+ # 2. Rule Validation
75
+ # If schema matches, we run the rules defined in the contract
76
+ executor = ValidationExecutor()
77
+
78
+ # We reuse the existing validate method
79
+ run = executor.validate(contract.dataset_name, file_path, contract.rules)
80
+ return run
81
+
82
+
@@ -0,0 +1,77 @@
1
+ from typing import List, Dict, Optional, Any
2
+ from pydantic import BaseModel, Field
3
+ from dataguard.storage.models import TableSchema, ColumnSchema
4
+
5
+ class SchemaDiff(BaseModel):
6
+ """Represents the difference between two schemas."""
7
+ added_columns: List[ColumnSchema] = Field(default_factory=list)
8
+ removed_columns: List[ColumnSchema] = Field(default_factory=list)
9
+ changed_columns: List[Dict[str, Any]] = Field(default_factory=list)
10
+
11
+ @property
12
+ def has_drift(self) -> bool:
13
+ return bool(self.added_columns or self.removed_columns or self.changed_columns)
14
+
15
+ class DriftReport(BaseModel):
16
+ """Report containing schema drift details."""
17
+ dataset_name: str
18
+ drift_detected: bool
19
+ diff: SchemaDiff
20
+ detected_at: str # ISO timestamp
21
+
22
+ class DriftDetector:
23
+ """
24
+ Detects schema drift between two TableSchema objects.
25
+ """
26
+
27
+ def detect_drift(self, old_schema: TableSchema, new_schema: TableSchema) -> SchemaDiff:
28
+ """
29
+ Compare old and new schemas to find differences.
30
+
31
+ Args:
32
+ old_schema: The baseline schema (e.g., from metadata store)
33
+ new_schema: The current inferred schema
34
+
35
+ Returns:
36
+ SchemaDiff object detailing the changes
37
+ """
38
+ diff = SchemaDiff()
39
+
40
+ old_cols = {c.name: c for c in old_schema.columns}
41
+ new_cols = {c.name: c for c in new_schema.columns}
42
+
43
+ # 1. Detect removed columns (in old but not in new)
44
+ for name, col in old_cols.items():
45
+ if name not in new_cols:
46
+ diff.removed_columns.append(col)
47
+
48
+ # 2. Detect added columns (in new but not in old)
49
+ for name, col in new_cols.items():
50
+ if name not in old_cols:
51
+ diff.added_columns.append(col)
52
+
53
+ # 3. Detect changed columns (in both, but properties changed)
54
+ for name, new_col in new_cols.items():
55
+ if name in old_cols:
56
+ old_col = old_cols[name]
57
+ changes = {}
58
+
59
+ # Check dtype
60
+ if old_col.dtype != new_col.dtype:
61
+ changes['dtype'] = {
62
+ 'old': old_col.dtype,
63
+ 'new': new_col.dtype
64
+ }
65
+
66
+ # Check nullability
67
+ if old_col.nullable != new_col.nullable:
68
+ changes['nullable'] = {
69
+ 'old': old_col.nullable,
70
+ 'new': new_col.nullable
71
+ }
72
+
73
+ if changes:
74
+ changes['column_name'] = name
75
+ diff.changed_columns.append(changes)
76
+
77
+ return diff
@@ -0,0 +1,85 @@
1
+ import functools
2
+ import inspect
3
+ from typing import List, Union, Optional
4
+ from pathlib import Path
5
+ from dataguard.storage.metadata import MetadataStore
6
+
7
+ class LineageTracker:
8
+ """Helper to log lineage events."""
9
+
10
+ def __init__(self):
11
+ self.store = MetadataStore()
12
+
13
+ def log_process_run(self, process_name: str, inputs: List[str], outputs: List[str]):
14
+ """
15
+ Log a process execution.
16
+
17
+ Args:
18
+ process_name: Name of the function or job.
19
+ inputs: List of input file paths or dataset names.
20
+ outputs: List of output file paths or dataset names.
21
+ """
22
+ # Save Inputs -> Process
23
+ for inp in inputs:
24
+ # We treat inputs as Datasets and Process as a Job
25
+ self.store.save_lineage_edge(
26
+ source_id=self._normalize_name(inp),
27
+ target_id=process_name,
28
+ source_type="dataset",
29
+ target_type="job"
30
+ )
31
+
32
+ # Save Process -> Outputs
33
+ for out in outputs:
34
+ self.store.save_lineage_edge(
35
+ source_id=process_name,
36
+ target_id=self._normalize_name(out),
37
+ source_type="job",
38
+ target_type="dataset"
39
+ )
40
+
41
+ def _normalize_name(self, path_or_name: str) -> str:
42
+ """
43
+ Normalize file paths to just the filename for cleaner graphs.
44
+ If it's a full path, return stem+suffix.
45
+ """
46
+ return Path(path_or_name).name
47
+
48
+ def track_lineage(inputs: Union[str, List[str]], outputs: Union[str, List[str]]):
49
+ """
50
+ Decorator to automatically track data lineage.
51
+
52
+ Usage:
53
+ @track_lineage(inputs=["raw.csv"], outputs=["clean.csv"])
54
+ def clean_data():
55
+ ...
56
+ """
57
+ def decorator(func):
58
+ @functools.wraps(func)
59
+ def wrapper(*args, **kwargs):
60
+ # 1. Execute the function
61
+ result = func(*args, **kwargs)
62
+
63
+ # 2. Log Lineage (only if successful)
64
+ try:
65
+ tracker = LineageTracker()
66
+
67
+ # Handle single string input/output convenience
68
+ input_list = [inputs] if isinstance(inputs, str) else inputs
69
+ output_list = [outputs] if isinstance(outputs, str) else outputs
70
+
71
+ # Resolve runtime values if they are arguments?
72
+ # For simplicity v1: we assume static strings or file paths passed to decorator.
73
+ # Advanced v2: could inspect *args to find matching filenames.
74
+
75
+ tracker.log_process_run(
76
+ process_name=func.__name__,
77
+ inputs=input_list,
78
+ outputs=output_list
79
+ )
80
+ except Exception as e:
81
+ print(f"Warning: Failed to log lineage for {func.__name__}: {e}")
82
+
83
+ return result
84
+ return wrapper
85
+ return decorator