DEPosit / Scripts /pipeline_parsers /prefect_parser.py
taher-ghaleb's picture
DEPosit Dataset
031cf82
Raw
History Blame Contribute Delete
7.17 kB
"""
prefect_parser.py
~~~~~~~~~~~~~~~~~
Extracts features from Prefect flow files (both 1.x and 2.x/3.x APIs).
Prefect 1.x uses class-based flows (@task on free functions, Flow context manager).
Prefect 2.x/3.x uses @flow and @task decorators directly.
We detect both patterns via AST.
"""
import ast
import json
from typing import Any
def _decorator_names(node: ast.FunctionDef | ast.AsyncFunctionDef) -> list[str]:
names = []
for dec in node.decorator_list:
if isinstance(dec, ast.Name):
names.append(dec.id)
elif isinstance(dec, ast.Attribute):
names.append(dec.attr)
elif isinstance(dec, ast.Call):
f = dec.func
if isinstance(f, ast.Name):
names.append(f.id)
elif isinstance(f, ast.Attribute):
names.append(f.attr)
return names
def _kw_value(node: ast.Call, name: str) -> ast.expr | None:
for kw in node.keywords:
if kw.arg == name:
return kw.value
return None
def _const_int(node: ast.expr | None) -> int | None:
if isinstance(node, ast.Constant) and isinstance(node.value, int):
return node.value
return None
def _const_bool(node: ast.expr | None) -> bool | None:
if isinstance(node, ast.Constant) and isinstance(node.value, bool):
return node.value
if isinstance(node, ast.Name):
return {"True": True, "False": False}.get(node.id)
return None
class _PrefectVisitor(ast.NodeVisitor):
def __init__(self) -> None:
self.flow_count = 0
self.task_count = 0
self.max_retries = 0
self.has_retries = False
self.has_schedule = False
self.has_timeout = False
self.uses_result_caching = False
self.uses_state_handler = False
self.uses_mapped_tasks = False
self.has_deployment_block = False
self.prefect_version = "unknown"
self._imports: set[str] = set()
def visit_Import(self, node: ast.Import) -> None:
for alias in node.names:
self._imports.add(alias.name)
self.generic_visit(node)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
if node.module:
self._imports.add(node.module)
# Version detection
if node.module.startswith("prefect."):
if "deployments" in node.module or "flows" in node.module:
self.prefect_version = "2.x"
if node.module == "prefect" and any(
a.name in ("flow", "task") for a in node.names
):
self.prefect_version = "2.x"
self.generic_visit(node)
def _inspect_flow_decorator(self, dec: ast.expr) -> None:
if not isinstance(dec, ast.Call):
return
if _kw_value(dec, "schedule") is not None:
self.has_schedule = True
timeout = _kw_value(dec, "timeout_seconds")
if timeout is not None:
self.has_timeout = True
def _inspect_task_decorator(self, dec: ast.expr) -> None:
if not isinstance(dec, ast.Call):
return
retries = _kw_value(dec, "retries") or _kw_value(dec, "max_retries")
if retries is not None:
self.has_retries = True
v = _const_int(retries)
if v is not None and v > self.max_retries:
self.max_retries = v
if _kw_value(dec, "cache_key_fn") is not None:
self.uses_result_caching = True
if _kw_value(dec, "result_storage") is not None:
self.uses_result_caching = True
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
dnames = _decorator_names(node)
if "flow" in dnames:
self.flow_count += 1
for dec in node.decorator_list:
self._inspect_flow_decorator(dec)
if "task" in dnames:
self.task_count += 1
for dec in node.decorator_list:
self._inspect_task_decorator(dec)
self.generic_visit(node)
visit_AsyncFunctionDef = visit_FunctionDef
def visit_With(self, node: ast.With) -> None:
"""Prefect 1.x: with Flow(...) as flow:"""
for item in node.items:
if isinstance(item.context_expr, ast.Call):
f = item.context_expr.func
name = f.id if isinstance(f, ast.Name) else (
f.attr if isinstance(f, ast.Attribute) else ""
)
if name == "Flow":
self.flow_count += 1
self.prefect_version = "1.x"
sched = _kw_value(item.context_expr, "schedule")
if sched is not None:
self.has_schedule = True
self.generic_visit(node)
def visit_Call(self, node: ast.Call) -> None:
f = node.func
name = ""
if isinstance(f, ast.Attribute):
name = f.attr
# .map() for Prefect 1.x mapped tasks
if name == "map":
self.uses_mapped_tasks = True
# unmapped() for Prefect 2.x mapped tasks
if isinstance(f, ast.Name) and f.id == "unmapped":
self.uses_mapped_tasks = True
# Deployment block
if isinstance(f, ast.Name) and f.id in ("Deployment", "deploy"):
self.has_deployment_block = True
if isinstance(f, ast.Attribute) and f.attr in ("Deployment", "deploy"):
self.has_deployment_block = True
# State handlers (Prefect 1.x)
for kw in node.keywords:
if kw.arg == "state_handlers":
self.uses_state_handler = True
self.generic_visit(node)
def extract(content: str, file_path: str) -> dict:
"""
Parse one Prefect flow file.
Returns a feature dict for prefect_flow_features.
"""
lines = content.splitlines()
file_lines = len(lines)
try:
tree = ast.parse(content, filename=file_path)
except SyntaxError as exc:
return {"parse_error": str(exc), "file_lines": file_lines}
v = _PrefectVisitor()
try:
v.visit(tree)
except Exception as exc: # noqa: BLE001
return {"parse_error": f"visitor: {exc}", "file_lines": file_lines}
return {
"prefect_version": v.prefect_version,
"flow_count": v.flow_count,
"task_count": v.task_count,
"has_retries": int(v.has_retries),
"max_retries": v.max_retries or None,
"has_schedule": int(v.has_schedule),
"has_timeout": int(v.has_timeout),
"uses_result_caching": int(v.uses_result_caching),
"uses_state_handler": int(v.uses_state_handler),
"uses_mapped_tasks": int(v.uses_mapped_tasks),
"has_deployment_block": int(v.has_deployment_block),
"antipattern_no_retries": int(not v.has_retries),
"antipattern_no_timeout": int(not v.has_timeout),
"file_lines": file_lines,
"parse_error": None,
}