-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathstore.py
More file actions
1075 lines (957 loc) · 37.7 KB
/
Copy pathstore.py
File metadata and controls
1075 lines (957 loc) · 37.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2026 The Feast Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
OpenLineage lineage store for Feast.
Provides CRUD operations for OpenLineage events, jobs, datasets, runs,
and lineage edges using SQLAlchemy Core, consistent with Feast's SQL registry.
"""
import json
import logging
import time
from typing import Any, Dict, List, Optional
from sqlalchemy import create_engine, func, select
from sqlalchemy.engine import Engine
from feast.openlineage.models import OL_TABLES, ol_metadata
logger = logging.getLogger(__name__)
class OpenLineageStore:
"""
Storage layer for OpenLineage lineage data.
Stores events, jobs, datasets, runs, and lineage graph edges
in PostgreSQL (or SQLite for dev/testing).
"""
def __init__(
self, engine: Optional[Engine] = None, connection_string: Optional[str] = None
):
if engine:
self._engine = engine
elif connection_string:
self._engine = create_engine(connection_string)
else:
raise ValueError("Either engine or connection_string must be provided")
def initialize(self):
ol_metadata.create_all(self._engine)
logger.info("OpenLineage store tables created/verified")
@property
def engine(self) -> Engine:
return self._engine
def store_event(self, event_id: str, event_data: Dict[str, Any]):
now = int(time.time() * 1000)
event_type = _classify_event_type(event_data)
job = event_data.get("job", {})
run = event_data.get("run", {})
dataset = event_data.get("dataset", {})
if job:
ns = job.get("namespace", "")
name = job.get("name", "")
elif dataset:
ns = dataset.get("namespace", "")
name = dataset.get("name", "")
else:
ns = ""
name = ""
row = {
"event_id": event_id,
"event_type": event_type,
"event_time": _parse_timestamp(event_data.get("eventTime", "")),
"producer": event_data.get("producer"),
"job_namespace": ns,
"job_name": name,
"run_id": run.get("runId") if run else None,
"event_json": json.dumps(event_data),
"created_at": now,
}
tbl = OL_TABLES["events"]
with self._engine.begin() as conn:
conn.execute(tbl.insert().values(**row))
def upsert_job(
self,
namespace: str,
name: str,
job_data: Dict[str, Any],
producer: Optional[str] = None,
):
now = int(time.time() * 1000)
facets = job_data.get("facets", {})
job_type = None
# Prefer Feast semantic kind over generic OL jobType processingType.
if "feast_jobKind" in facets:
kind = facets["feast_jobKind"]
if isinstance(kind, dict):
job_type = kind.get("kind")
if not job_type and "jobType" in facets:
jt = facets["jobType"]
job_type = jt.get("processingType", jt.get("integration"))
description = None
if "documentation" in facets:
description = facets["documentation"].get("description")
tbl = OL_TABLES["jobs"]
with self._engine.begin() as conn:
existing = conn.execute(
select(tbl).where(
tbl.c.job_namespace == namespace,
tbl.c.job_name == name,
)
).first()
if existing:
update_vals = {
"job_type": job_type or existing.job_type,
"description": description or existing.description,
"facets_json": json.dumps(facets)
if facets
else existing.facets_json,
"updated_at": now,
}
if producer:
update_vals["producer"] = producer
conn.execute(
tbl.update()
.where(tbl.c.job_namespace == namespace, tbl.c.job_name == name)
.values(**update_vals)
)
else:
conn.execute(
tbl.insert().values(
job_namespace=namespace,
job_name=name,
job_type=job_type,
producer=producer,
description=description,
facets_json=json.dumps(facets) if facets else None,
updated_at=now,
)
)
def upsert_dataset(
self,
namespace: str,
name: str,
facets: Optional[Dict[str, Any]] = None,
feast_mapping: Optional[Dict[str, str]] = None,
producer: Optional[str] = None,
):
now = int(time.time() * 1000)
facets = facets or {}
schema_json = None
if "schema" in facets:
schema_json = json.dumps(facets["schema"])
description = None
if "documentation" in facets:
description = facets["documentation"].get("description")
source_type = None
if "dataSource" in facets:
source_type = facets["dataSource"].get("name")
feast_obj_type = feast_mapping.get("type") if feast_mapping else None
feast_obj_name = feast_mapping.get("name") if feast_mapping else None
feast_project = feast_mapping.get("project") if feast_mapping else None
tbl = OL_TABLES["datasets"]
with self._engine.begin() as conn:
existing = conn.execute(
select(tbl).where(
tbl.c.dataset_namespace == namespace,
tbl.c.dataset_name == name,
)
).first()
values: Dict[str, Any] = {
"updated_at": now,
}
if producer:
values["producer"] = producer
# Preserve richer metadata when a later event (e.g. materialize)
# re-touches the dataset without facets.
if facets:
values["facets_json"] = json.dumps(facets)
if source_type is not None:
values["source_type"] = source_type
if description is not None:
values["description"] = description
if schema_json is not None:
values["schema_json"] = schema_json
elif not existing:
values["facets_json"] = None
values["source_type"] = source_type
values["description"] = description
values["schema_json"] = schema_json
if feast_obj_type and feast_obj_type != "unknown":
values["feast_object_type"] = feast_obj_type
if feast_obj_name:
values["feast_object_name"] = feast_obj_name
if feast_project:
values["feast_project"] = feast_project
elif not existing:
# First sighting with no resolvable Feast type
values["feast_object_type"] = feast_obj_type
values["feast_object_name"] = feast_obj_name
values["feast_project"] = feast_project
if existing:
conn.execute(
tbl.update()
.where(
tbl.c.dataset_namespace == namespace,
tbl.c.dataset_name == name,
)
.values(**values)
)
else:
values["dataset_namespace"] = namespace
values["dataset_name"] = name
conn.execute(tbl.insert().values(**values))
def upsert_run(
self,
run_id: str,
job_namespace: str,
job_name: str,
state: str,
facets: Optional[Dict] = None,
):
now = int(time.time() * 1000)
tbl = OL_TABLES["runs"]
with self._engine.begin() as conn:
existing = conn.execute(select(tbl).where(tbl.c.run_id == run_id)).first()
if existing:
update_vals: Dict[str, Any] = {"state": state, "updated_at": now}
if state in ("COMPLETE", "FAIL", "ABORT"):
update_vals["ended_at"] = now
if facets:
update_vals["facets_json"] = json.dumps(facets)
conn.execute(
tbl.update().where(tbl.c.run_id == run_id).values(**update_vals)
)
else:
conn.execute(
tbl.insert().values(
run_id=run_id,
job_namespace=job_namespace,
job_name=job_name,
state=state,
started_at=now if state == "START" else None,
ended_at=now
if state in ("COMPLETE", "FAIL", "ABORT")
else None,
facets_json=json.dumps(facets) if facets else None,
updated_at=now,
)
)
tbl_jobs = OL_TABLES["jobs"]
conn.execute(
tbl_jobs.update()
.where(
tbl_jobs.c.job_namespace == job_namespace,
tbl_jobs.c.job_name == job_name,
)
.values(latest_run_id=run_id, updated_at=now)
)
def store_run_io(
self,
run_id: str,
dataset_namespace: str,
dataset_name: str,
io_type: str,
facets: Optional[Dict] = None,
):
tbl = OL_TABLES["run_io"]
with self._engine.begin() as conn:
existing = conn.execute(
select(tbl).where(
tbl.c.run_id == run_id,
tbl.c.dataset_namespace == dataset_namespace,
tbl.c.dataset_name == dataset_name,
tbl.c.io_type == io_type,
)
).first()
if not existing:
conn.execute(
tbl.insert().values(
run_id=run_id,
dataset_namespace=dataset_namespace,
dataset_name=dataset_name,
io_type=io_type,
facets_json=json.dumps(facets) if facets else None,
)
)
def upsert_lineage_edge(
self,
source_type: str,
source_namespace: str,
source_name: str,
target_type: str,
target_namespace: str,
target_name: str,
edge_type: Optional[str] = None,
):
now = int(time.time() * 1000)
tbl = OL_TABLES["lineage_edges"]
with self._engine.begin() as conn:
existing = conn.execute(
select(tbl).where(
tbl.c.source_type == source_type,
tbl.c.source_namespace == source_namespace,
tbl.c.source_name == source_name,
tbl.c.target_type == target_type,
tbl.c.target_namespace == target_namespace,
tbl.c.target_name == target_name,
)
).first()
if existing:
conn.execute(
tbl.update()
.where(
tbl.c.source_type == source_type,
tbl.c.source_namespace == source_namespace,
tbl.c.source_name == source_name,
tbl.c.target_type == target_type,
tbl.c.target_namespace == target_namespace,
tbl.c.target_name == target_name,
)
.values(edge_type=edge_type, updated_at=now)
)
else:
conn.execute(
tbl.insert().values(
source_type=source_type,
source_namespace=source_namespace,
source_name=source_name,
target_type=target_type,
target_namespace=target_namespace,
target_name=target_name,
edge_type=edge_type,
updated_at=now,
)
)
# ── Query methods ──
def get_events(
self,
namespace: Optional[str] = None,
job_name: Optional[str] = None,
limit: int = 100,
offset: int = 0,
namespaces: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
tbl = OL_TABLES["events"]
query = (
select(tbl).order_by(tbl.c.event_time.desc()).limit(limit).offset(offset)
)
if namespace:
query = query.where(tbl.c.job_namespace == namespace)
elif namespaces:
query = query.where(tbl.c.job_namespace.in_(namespaces))
if job_name:
query = query.where(tbl.c.job_name == job_name)
with self._engine.connect() as conn:
rows = conn.execute(query).fetchall()
return [dict(row._mapping) for row in rows]
def get_jobs(
self,
namespaces: Optional[List[str]] = None,
limit: int = 0,
offset: int = 0,
) -> List[Dict[str, Any]]:
tbl = OL_TABLES["jobs"]
query = select(tbl).order_by(tbl.c.updated_at.desc())
if namespaces:
query = query.where(tbl.c.job_namespace.in_(namespaces))
if limit > 0:
query = query.limit(limit).offset(offset)
with self._engine.connect() as conn:
rows = conn.execute(query).fetchall()
return [dict(row._mapping) for row in rows]
def count_jobs(self, namespaces: Optional[List[str]] = None) -> int:
tbl = OL_TABLES["jobs"]
query = select(func.count()).select_from(tbl)
if namespaces:
query = query.where(tbl.c.job_namespace.in_(namespaces))
with self._engine.connect() as conn:
return conn.execute(query).scalar() or 0
def get_datasets(
self,
namespaces: Optional[List[str]] = None,
limit: int = 0,
offset: int = 0,
) -> List[Dict[str, Any]]:
tbl = OL_TABLES["datasets"]
query = select(tbl).order_by(tbl.c.updated_at.desc())
if namespaces:
query = query.where(tbl.c.dataset_namespace.in_(namespaces))
if limit > 0:
query = query.limit(limit).offset(offset)
with self._engine.connect() as conn:
rows = conn.execute(query).fetchall()
return [dict(row._mapping) for row in rows]
def count_datasets(self, namespaces: Optional[List[str]] = None) -> int:
tbl = OL_TABLES["datasets"]
query = select(func.count()).select_from(tbl)
if namespaces:
query = query.where(tbl.c.dataset_namespace.in_(namespaces))
with self._engine.connect() as conn:
return conn.execute(query).scalar() or 0
def get_lineage_graph(
self,
node_type: str,
namespace: str,
name: str,
depth: int = 10,
direction: str = "both",
allowed_namespaces: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""
Get the lineage graph for a node, traversing upstream and/or downstream.
Returns a dict with 'nodes' and 'edges' suitable for UI rendering.
"""
nodes: Dict[str, Dict[str, Any]] = {}
edges: List[Dict[str, Any]] = []
tbl = OL_TABLES["lineage_edges"]
with self._engine.connect() as conn:
if direction in ("both", "downstream"):
self._traverse(
conn,
tbl,
node_type,
namespace,
name,
depth,
"downstream",
nodes,
edges,
allowed_namespaces,
)
if direction in ("both", "upstream"):
self._traverse(
conn,
tbl,
node_type,
namespace,
name,
depth,
"upstream",
nodes,
edges,
allowed_namespaces,
)
root_key = f"{node_type}:{namespace}:{name}"
if root_key not in nodes:
nodes[root_key] = {
"type": node_type,
"namespace": namespace,
"name": name,
}
return {
"nodes": list(nodes.values()),
"edges": edges,
}
def _traverse(
self,
conn,
tbl,
node_type: str,
namespace: str,
name: str,
depth: int,
direction: str,
nodes: Dict[str, Dict],
edges: List[Dict],
allowed_namespaces: Optional[List[str]],
):
visited = set()
queue = [(node_type, namespace, name, 0)]
while queue:
n_type, n_ns, n_name, d = queue.pop(0)
key = f"{n_type}:{n_ns}:{n_name}"
if key in visited or d > depth:
continue
visited.add(key)
if direction == "downstream":
query = select(tbl).where(
tbl.c.source_type == n_type,
tbl.c.source_namespace == n_ns,
tbl.c.source_name == n_name,
)
else:
query = select(tbl).where(
tbl.c.target_type == n_type,
tbl.c.target_namespace == n_ns,
tbl.c.target_name == n_name,
)
rows = conn.execute(query).fetchall()
for row in rows:
r = row._mapping
src_key = (
f"{r['source_type']}:{r['source_namespace']}:{r['source_name']}"
)
tgt_key = (
f"{r['target_type']}:{r['target_namespace']}:{r['target_name']}"
)
if allowed_namespaces:
if (
r["source_namespace"] not in allowed_namespaces
or r["target_namespace"] not in allowed_namespaces
):
continue
edge = {
"source_type": r["source_type"],
"source_namespace": r["source_namespace"],
"source_name": r["source_name"],
"target_type": r["target_type"],
"target_namespace": r["target_namespace"],
"target_name": r["target_name"],
"edge_type": r.get("edge_type"),
}
if edge not in edges:
edges.append(edge)
for node_key, nt, ns, nn in [
(
src_key,
r["source_type"],
r["source_namespace"],
r["source_name"],
),
(
tgt_key,
r["target_type"],
r["target_namespace"],
r["target_name"],
),
]:
if node_key not in nodes:
nodes[node_key] = {
"type": nt,
"namespace": ns,
"name": nn,
}
if direction == "downstream":
next_key = tgt_key
next_type = r["target_type"]
next_ns = r["target_namespace"]
next_name = r["target_name"]
else:
next_key = src_key
next_type = r["source_type"]
next_ns = r["source_namespace"]
next_name = r["source_name"]
if next_key not in visited:
queue.append((next_type, next_ns, next_name, d + 1))
def upsert_dataset_symlink(
self,
dataset_namespace: str,
dataset_name: str,
linked_namespace: str,
linked_name: str,
link_type: str = "symlink",
):
"""Store a symlink between two dataset identifiers (bidirectional lookup)."""
now = int(time.time() * 1000)
tbl = OL_TABLES["dataset_symlinks"]
with self._engine.begin() as conn:
existing = conn.execute(
select(tbl).where(
tbl.c.dataset_namespace == dataset_namespace,
tbl.c.dataset_name == dataset_name,
tbl.c.linked_namespace == linked_namespace,
tbl.c.linked_name == linked_name,
)
).first()
if existing:
conn.execute(
tbl.update()
.where(
tbl.c.dataset_namespace == dataset_namespace,
tbl.c.dataset_name == dataset_name,
tbl.c.linked_namespace == linked_namespace,
tbl.c.linked_name == linked_name,
)
.values(link_type=link_type, updated_at=now)
)
else:
conn.execute(
tbl.insert().values(
dataset_namespace=dataset_namespace,
dataset_name=dataset_name,
linked_namespace=linked_namespace,
linked_name=linked_name,
link_type=link_type,
updated_at=now,
)
)
def get_dataset_aliases(self, namespace: str, name: str) -> List[Dict[str, str]]:
"""Get all known aliases for a dataset (both directions)."""
tbl = OL_TABLES["dataset_symlinks"]
results = []
with self._engine.connect() as conn:
rows = conn.execute(
select(tbl).where(
tbl.c.dataset_namespace == namespace,
tbl.c.dataset_name == name,
)
).fetchall()
for r in rows:
results.append(
{
"namespace": r._mapping["linked_namespace"],
"name": r._mapping["linked_name"],
"link_type": r._mapping["link_type"],
}
)
rows = conn.execute(
select(tbl).where(
tbl.c.linked_namespace == namespace,
tbl.c.linked_name == name,
)
).fetchall()
for r in rows:
results.append(
{
"namespace": r._mapping["dataset_namespace"],
"name": r._mapping["dataset_name"],
"link_type": r._mapping["link_type"],
}
)
return results
def find_datasets_by_uri(self, uri: str) -> List[Dict[str, str]]:
"""Find all datasets whose dataSource facet contains the given URI."""
tbl = OL_TABLES["datasets"]
with self._engine.connect() as conn:
rows = conn.execute(
select(
tbl.c.dataset_namespace, tbl.c.dataset_name, tbl.c.facets_json
).where(tbl.c.facets_json.isnot(None))
).fetchall()
matches = []
for r in rows:
try:
facets = json.loads(r._mapping["facets_json"])
ds_uri = facets.get("dataSource", {}).get("uri", "")
if ds_uri and ds_uri == uri:
matches.append(
{
"namespace": r._mapping["dataset_namespace"],
"name": r._mapping["dataset_name"],
}
)
except (json.JSONDecodeError, AttributeError):
pass
return matches
def get_all_symlinks(self) -> List[Dict[str, Any]]:
"""Get all dataset symlinks."""
tbl = OL_TABLES["dataset_symlinks"]
with self._engine.connect() as conn:
rows = conn.execute(select(tbl)).fetchall()
return [dict(r._mapping) for r in rows]
# ── Cleanup methods ──
def delete_dataset(self, namespace: str, name: str):
"""Delete a specific dataset and its related edges, runs, and jobs."""
with self._engine.begin() as conn:
tbl_edges = OL_TABLES["lineage_edges"]
conn.execute(
tbl_edges.delete().where(
(
(tbl_edges.c.source_namespace == namespace)
& (tbl_edges.c.source_name == name)
)
| (
(tbl_edges.c.target_namespace == namespace)
& (tbl_edges.c.target_name == name)
)
)
)
tbl_sym = OL_TABLES["dataset_symlinks"]
conn.execute(
tbl_sym.delete().where(
(
(tbl_sym.c.dataset_namespace == namespace)
& (tbl_sym.c.dataset_name == name)
)
| (
(tbl_sym.c.linked_namespace == namespace)
& (tbl_sym.c.linked_name == name)
)
)
)
tbl_rio = OL_TABLES["run_io"]
conn.execute(
tbl_rio.delete().where(
(tbl_rio.c.dataset_namespace == namespace)
& (tbl_rio.c.dataset_name == name)
)
)
tbl_ds = OL_TABLES["datasets"]
conn.execute(
tbl_ds.delete().where(
(tbl_ds.c.dataset_namespace == namespace)
& (tbl_ds.c.dataset_name == name)
)
)
logger.info(f"Deleted OL dataset: {namespace}/{name}")
def delete_job(self, namespace: str, name: str):
"""Delete a specific job and its related runs, events, and edges."""
with self._engine.begin() as conn:
tbl_runs = OL_TABLES["runs"]
run_ids_q = select(tbl_runs.c.run_id).where(
(tbl_runs.c.job_namespace == namespace) & (tbl_runs.c.job_name == name)
)
run_ids = [r[0] for r in conn.execute(run_ids_q).fetchall()]
if run_ids:
tbl_rio = OL_TABLES["run_io"]
conn.execute(tbl_rio.delete().where(tbl_rio.c.run_id.in_(run_ids)))
conn.execute(tbl_runs.delete().where(tbl_runs.c.run_id.in_(run_ids)))
tbl_ev = OL_TABLES["events"]
conn.execute(
tbl_ev.delete().where(
(tbl_ev.c.job_namespace == namespace) & (tbl_ev.c.job_name == name)
)
)
tbl_edges = OL_TABLES["lineage_edges"]
conn.execute(
tbl_edges.delete().where(
(
(tbl_edges.c.source_namespace == namespace)
& (tbl_edges.c.source_name == name)
)
| (
(tbl_edges.c.target_namespace == namespace)
& (tbl_edges.c.target_name == name)
)
)
)
tbl_jobs = OL_TABLES["jobs"]
conn.execute(
tbl_jobs.delete().where(
(tbl_jobs.c.job_namespace == namespace)
& (tbl_jobs.c.job_name == name)
)
)
logger.info(f"Deleted OL job: {namespace}/{name}")
def purge_all(self):
"""Delete all data from all OpenLineage tables."""
table_order = [
"run_io",
"runs",
"lineage_edges",
"dataset_symlinks",
"events",
"datasets",
"jobs",
]
with self._engine.begin() as conn:
for tbl_name in table_order:
conn.execute(OL_TABLES[tbl_name].delete())
logger.info("Purged all OpenLineage data")
def purge_namespace(self, namespace: str):
"""Delete all data associated with a specific namespace."""
with self._engine.begin() as conn:
tbl_runs = OL_TABLES["runs"]
run_ids_q = select(tbl_runs.c.run_id).where(
tbl_runs.c.job_namespace == namespace
)
run_ids = [r[0] for r in conn.execute(run_ids_q).fetchall()]
if run_ids:
tbl_rio = OL_TABLES["run_io"]
conn.execute(tbl_rio.delete().where(tbl_rio.c.run_id.in_(run_ids)))
conn.execute(tbl_runs.delete().where(tbl_runs.c.run_id.in_(run_ids)))
tbl_ev = OL_TABLES["events"]
conn.execute(tbl_ev.delete().where(tbl_ev.c.job_namespace == namespace))
tbl_edges = OL_TABLES["lineage_edges"]
conn.execute(
tbl_edges.delete().where(
(tbl_edges.c.source_namespace == namespace)
| (tbl_edges.c.target_namespace == namespace)
)
)
tbl_sym = OL_TABLES["dataset_symlinks"]
conn.execute(
tbl_sym.delete().where(
(tbl_sym.c.dataset_namespace == namespace)
| (tbl_sym.c.linked_namespace == namespace)
)
)
tbl_ds = OL_TABLES["datasets"]
conn.execute(tbl_ds.delete().where(tbl_ds.c.dataset_namespace == namespace))
tbl_jobs = OL_TABLES["jobs"]
conn.execute(tbl_jobs.delete().where(tbl_jobs.c.job_namespace == namespace))
logger.info(f"Purged OpenLineage data for namespace: {namespace}")
# ── Run query methods ──
def get_runs(
self,
job_namespace: Optional[str] = None,
job_name: Optional[str] = None,
limit: int = 50,
offset: int = 0,
namespaces: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
"""Get runs, optionally filtered by job and/or RBAC-allowed namespaces."""
tbl = OL_TABLES["runs"]
query = (
select(tbl).order_by(tbl.c.updated_at.desc()).limit(limit).offset(offset)
)
if job_namespace:
query = query.where(tbl.c.job_namespace == job_namespace)
if job_name:
query = query.where(tbl.c.job_name == job_name)
if namespaces is not None:
query = query.where(tbl.c.job_namespace.in_(namespaces))
with self._engine.connect() as conn:
rows = conn.execute(query).fetchall()
return [dict(row._mapping) for row in rows]
def get_run_detail(self, run_id: str) -> Optional[Dict[str, Any]]:
"""Get a single run with its I/O datasets."""
tbl_runs = OL_TABLES["runs"]
tbl_rio = OL_TABLES["run_io"]
with self._engine.connect() as conn:
run_row = conn.execute(
select(tbl_runs).where(tbl_runs.c.run_id == run_id)
).first()
if not run_row:
return None
run = dict(run_row._mapping)
io_rows = conn.execute(
select(tbl_rio).where(tbl_rio.c.run_id == run_id)
).fetchall()
run["inputs"] = []
run["outputs"] = []
for io_row in io_rows:
io = dict(io_row._mapping)
entry = {
"namespace": io["dataset_namespace"],
"name": io["dataset_name"],
"facets": _safe_parse_json(io.get("facets_json")),
}
if io["io_type"] == "INPUT":
run["inputs"].append(entry)
else:
run["outputs"].append(entry)
run["facets"] = _safe_parse_json(run.pop("facets_json", None))
return run
def prune_expired(self, retention_days: int) -> Dict[str, int]:
"""Delete events and runs older than *retention_days*.
Preserves the current-state tables (jobs, datasets, edges, symlinks)
since they represent the latest graph structure, not historical data.
Returns a dict with counts of deleted rows per table.
"""
if retention_days <= 0:
return {}
cutoff_ms = int((time.time() - retention_days * 86400) * 1000)
deleted: Dict[str, int] = {}
with self._engine.begin() as conn:
# 1. Find expired runs
tbl_runs = OL_TABLES["runs"]
expired_runs_q = select(tbl_runs.c.run_id).where(
tbl_runs.c.updated_at < cutoff_ms
)
expired_run_ids = [r[0] for r in conn.execute(expired_runs_q).fetchall()]
# 2. Delete run_io for expired runs
if expired_run_ids:
tbl_rio = OL_TABLES["run_io"]
result = conn.execute(
tbl_rio.delete().where(tbl_rio.c.run_id.in_(expired_run_ids))
)
deleted["run_io"] = result.rowcount
# 3. Delete the expired runs
result = conn.execute(
tbl_runs.delete().where(tbl_runs.c.run_id.in_(expired_run_ids))
)
deleted["runs"] = result.rowcount
else:
deleted["run_io"] = 0
deleted["runs"] = 0
# 4. Delete expired events
tbl_ev = OL_TABLES["events"]
result = conn.execute(
tbl_ev.delete().where(tbl_ev.c.created_at < cutoff_ms)
)
deleted["events"] = result.rowcount
total = sum(deleted.values())
if total > 0:
logger.info(
f"Pruned {total} expired OpenLineage rows "
f"(retention={retention_days}d): {deleted}"
)
return deleted
def get_retention_stats(self) -> Dict[str, Any]:
"""Return row counts and oldest timestamps for retention monitoring."""
stats: Dict[str, Any] = {}
with self._engine.connect() as conn:
for table_key, label in [
("events", "events"),
("runs", "runs"),
("jobs", "jobs"),
("datasets", "datasets"),
]:
tbl = OL_TABLES[table_key]
count = conn.execute(select(func.count()).select_from(tbl)).scalar()
stats[label] = {"count": count}
time_col = (
tbl.c.created_at if table_key == "events" else tbl.c.updated_at
)
oldest = conn.execute(select(func.min(time_col))).scalar()
if oldest: