skifer-engine 4.2.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.
- skifer/core/interpreter.py +609 -0
- skifer/core/loaders.py +123 -0
- skifer/core/rule_executor.py +172 -0
- skifer/core/spark_backend.py +1523 -0
- skifer/core/writer.py +174 -0
- skifer/spark_factory.py +144 -0
- skifer_engine-4.2.0.dist-info/METADATA +766 -0
- skifer_engine-4.2.0.dist-info/RECORD +10 -0
- skifer_engine-4.2.0.dist-info/WHEEL +4 -0
- skifer_engine-4.2.0.dist-info/licenses/LICENSE +21 -0
skifer/core/loaders.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Generic Data Loaders registered via the RuleRegistry.
|
|
3
|
+
|
|
4
|
+
Breaking change (v1.0): the legacy ``spark`` positional parameter has been removed.
|
|
5
|
+
Loaders now receive the backend via ``backend=`` keyword argument injected by the engine.
|
|
6
|
+
|
|
7
|
+
``load_generic_explode_union`` uses PySpark F.explode and therefore requires a backend
|
|
8
|
+
with a ``.spark`` attribute (i.e. SparkBackend). Passing any other backend will raise
|
|
9
|
+
a ``RuntimeError``.
|
|
10
|
+
"""
|
|
11
|
+
from .registry import RuleRegistry
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@RuleRegistry.register_loader(name="load_and_union_tables")
|
|
15
|
+
def load_and_union_tables(config, table_fqns, **kwargs):
|
|
16
|
+
"""
|
|
17
|
+
Loads a list of tables using their FQNs and performs a unionByName.
|
|
18
|
+
Missing columns are filled with nulls.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
config (dict): The configuration dictionary.
|
|
22
|
+
table_fqns (list[str]): FQNs of tables to load.
|
|
23
|
+
backend: Backend instance injected by the engine (required).
|
|
24
|
+
|
|
25
|
+
Raises:
|
|
26
|
+
ValueError: If none of the provided tables could be loaded.
|
|
27
|
+
RuntimeError: If no backend is provided.
|
|
28
|
+
"""
|
|
29
|
+
backend = kwargs.get("backend")
|
|
30
|
+
if backend is None:
|
|
31
|
+
raise RuntimeError(
|
|
32
|
+
"[load_and_union_tables] A backend is required. "
|
|
33
|
+
"The legacy spark positional argument was removed in v1.0."
|
|
34
|
+
)
|
|
35
|
+
print(f" -> [Data Loader] Loading and Unioning {len(table_fqns)} tables...")
|
|
36
|
+
list_of_dfs = []
|
|
37
|
+
for table in table_fqns:
|
|
38
|
+
try:
|
|
39
|
+
list_of_dfs.append(backend.read_table(table))
|
|
40
|
+
except Exception as e:
|
|
41
|
+
print(f" [WARNING] Could not load {table}. Skipping. ({e})")
|
|
42
|
+
|
|
43
|
+
if not list_of_dfs:
|
|
44
|
+
raise ValueError("No tables loaded successfully.")
|
|
45
|
+
|
|
46
|
+
return backend.union_by_name(list_of_dfs)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@RuleRegistry.register_loader()
|
|
50
|
+
def load_generic_explode_union(config, source_fqn, filter_expr=None, union_config=None, **kwargs):
|
|
51
|
+
"""
|
|
52
|
+
Loads a source table, explodes multiple array columns, and unions branches.
|
|
53
|
+
Requires a SparkBackend (uses PySpark F.explode internally).
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
config (dict): The configuration dictionary.
|
|
57
|
+
source_fqn (str): FQN of the source table.
|
|
58
|
+
filter_expr (str, optional): SQL filter to apply before exploding.
|
|
59
|
+
union_config (dict): Branch configuration.
|
|
60
|
+
backend: SparkBackend instance injected by the engine (required).
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
ValueError: If 'union_config' is not provided.
|
|
64
|
+
RuntimeError: If no backend or backend has no .spark attribute.
|
|
65
|
+
"""
|
|
66
|
+
from pyspark.sql import functions as F
|
|
67
|
+
|
|
68
|
+
backend = kwargs.get("backend")
|
|
69
|
+
if backend is None:
|
|
70
|
+
raise RuntimeError(
|
|
71
|
+
"[load_generic_explode_union] A backend is required. "
|
|
72
|
+
"The legacy spark positional argument was removed in v1.0."
|
|
73
|
+
)
|
|
74
|
+
if getattr(backend, 'spark', None) is None:
|
|
75
|
+
raise RuntimeError(
|
|
76
|
+
f"[load_generic_explode_union] Requires a SparkBackend (.spark attribute). "
|
|
77
|
+
f"Got: {type(backend).__name__}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
print(f" [Loader] Generic Explode & Union on {source_fqn}")
|
|
81
|
+
|
|
82
|
+
df_source = backend.read_table(source_fqn)
|
|
83
|
+
if filter_expr:
|
|
84
|
+
df_source = backend.filter(df_source, backend.expr(filter_expr))
|
|
85
|
+
|
|
86
|
+
if not union_config:
|
|
87
|
+
raise ValueError("[Loader] 'union_config' is required for load_generic_explode_union")
|
|
88
|
+
|
|
89
|
+
common_cols = union_config.get("common_cols", [])
|
|
90
|
+
branches = union_config.get("branches", [])
|
|
91
|
+
dfs_to_union = []
|
|
92
|
+
|
|
93
|
+
for i, branch_conf in enumerate(branches):
|
|
94
|
+
explode_col = branch_conf["explode_col"]
|
|
95
|
+
item_alias = branch_conf.get("item_alias", "item")
|
|
96
|
+
mappings = branch_conf.get("mappings", {})
|
|
97
|
+
defaults = branch_conf.get("defaults", {})
|
|
98
|
+
|
|
99
|
+
print(f" -> Processing branch {i+1}: {explode_col} (alias: {item_alias})")
|
|
100
|
+
|
|
101
|
+
df_branch = df_source.withColumn(item_alias, F.explode(F.col(explode_col)))
|
|
102
|
+
select_exprs = [F.col(c) for c in common_cols]
|
|
103
|
+
mapped_col_names = []
|
|
104
|
+
for target_col, source_path in mappings.items():
|
|
105
|
+
select_exprs.append(F.col(source_path).alias(target_col))
|
|
106
|
+
mapped_col_names.append(target_col)
|
|
107
|
+
for target_col, default_val in defaults.items():
|
|
108
|
+
if target_col not in mapped_col_names:
|
|
109
|
+
if isinstance(default_val, float):
|
|
110
|
+
select_exprs.append(F.lit(default_val).cast("double").alias(target_col))
|
|
111
|
+
elif isinstance(default_val, int):
|
|
112
|
+
select_exprs.append(F.lit(default_val).cast("int").alias(target_col))
|
|
113
|
+
else:
|
|
114
|
+
select_exprs.append(F.lit(default_val).alias(target_col))
|
|
115
|
+
df_branch = df_branch.select(*select_exprs)
|
|
116
|
+
dfs_to_union.append(df_branch)
|
|
117
|
+
|
|
118
|
+
if not dfs_to_union:
|
|
119
|
+
print(" [Warning] No branches processed. Returning empty DF.")
|
|
120
|
+
return backend.limit(df_source, 0)
|
|
121
|
+
|
|
122
|
+
print(f" [Union] Merging {len(dfs_to_union)} branches...")
|
|
123
|
+
return backend.union_by_name(dfs_to_union)
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""
|
|
2
|
+
RuleExecutor — executes a list of :class:`~skifer.core.rule_planner.RuleStage`
|
|
3
|
+
objects produced by :class:`~skifer.core.rule_planner.RulePlanner`.
|
|
4
|
+
|
|
5
|
+
Fusion strategies
|
|
6
|
+
-----------------
|
|
7
|
+
* **projection** stage: calls every rule function (which returns
|
|
8
|
+
``dict[str, Column]``), collects all column definitions, and applies them in
|
|
9
|
+
a **single** ``select(*existing_cols, *new_cols)`` call. This avoids the
|
|
10
|
+
O(N²) Catalyst plan re-traversal caused by chained ``withColumn()`` calls.
|
|
11
|
+
* **aggregation** stage with multiple rules sharing the same ``groupBy`` keys:
|
|
12
|
+
merges all ``agg(...)`` expressions into a single ``groupBy(...).agg(...)``
|
|
13
|
+
call. Requires the rule function to carry an ``agg_keys`` attribute
|
|
14
|
+
(set via the ``kind="aggregation"`` decorator convention).
|
|
15
|
+
* **transform** stage: applies each rule function sequentially (legacy
|
|
16
|
+
``df → df`` contract, no fusion).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
from typing import TYPE_CHECKING
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from pyspark.sql import DataFrame
|
|
26
|
+
from skifer.core.rule_planner import RuleStage
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RuleExecutor:
|
|
32
|
+
"""
|
|
33
|
+
Applies an ordered list of :class:`RuleStage` objects to a DataFrame.
|
|
34
|
+
|
|
35
|
+
Usage::
|
|
36
|
+
|
|
37
|
+
planner = RulePlanner()
|
|
38
|
+
executor = RuleExecutor()
|
|
39
|
+
stages = planner.plan(rule_names)
|
|
40
|
+
df = executor.execute(df, stages)
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def execute(self, df: "DataFrame", stages: list["RuleStage"]) -> "DataFrame":
|
|
44
|
+
"""
|
|
45
|
+
Execute all stages sequentially, applying fusion where possible.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
df: Input DataFrame.
|
|
49
|
+
stages: Ordered list of :class:`RuleStage` produced by
|
|
50
|
+
:class:`RulePlanner`.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
Transformed DataFrame.
|
|
54
|
+
"""
|
|
55
|
+
for stage in stages:
|
|
56
|
+
if stage.kind == "projection":
|
|
57
|
+
df = self._execute_projection_stage(df, stage)
|
|
58
|
+
elif stage.kind == "aggregation":
|
|
59
|
+
df = self._execute_aggregation_stage(df, stage)
|
|
60
|
+
else:
|
|
61
|
+
df = self._execute_transform_stage(df, stage)
|
|
62
|
+
return df
|
|
63
|
+
|
|
64
|
+
# ------------------------------------------------------------------
|
|
65
|
+
# Stage executors
|
|
66
|
+
# ------------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
def _execute_projection_stage(self, df: "DataFrame", stage: "RuleStage") -> "DataFrame":
|
|
69
|
+
"""
|
|
70
|
+
Fuse all projection rules into a single ``select()`` call.
|
|
71
|
+
|
|
72
|
+
Each rule returns ``dict[str, Column]``. Brand-new columns are appended
|
|
73
|
+
to the existing schema in topological order (already sorted by the
|
|
74
|
+
planner). Duplicate column names produced by different rules are
|
|
75
|
+
de-duplicated: the last rule's expression wins (consistent with
|
|
76
|
+
sequential semantics).
|
|
77
|
+
|
|
78
|
+
A rule may also produce a column whose name already exists in the input
|
|
79
|
+
DataFrame (e.g. ``{"x": F.upper(F.col("x"))}``). Such columns *replace*
|
|
80
|
+
the input column in place — keeping their original position — exactly
|
|
81
|
+
like a sequential ``withColumn``. This avoids emitting two homonymous
|
|
82
|
+
columns in the fused ``select()`` (which would raise
|
|
83
|
+
``AMBIGUOUS_REFERENCE``).
|
|
84
|
+
"""
|
|
85
|
+
from pyspark.sql import functions as F
|
|
86
|
+
|
|
87
|
+
rule_names = [s.name for s in stage.rules]
|
|
88
|
+
logger.debug("[Executor] Fusing %d projection rules: %s", len(stage.rules), rule_names)
|
|
89
|
+
|
|
90
|
+
# Collect all new column definitions (ordered, last-writer wins for dupes)
|
|
91
|
+
new_cols: dict[str, object] = {}
|
|
92
|
+
for spec in stage.rules:
|
|
93
|
+
result = spec.func(df)
|
|
94
|
+
if not isinstance(result, dict):
|
|
95
|
+
raise TypeError(
|
|
96
|
+
f"Rule '{spec.name}' is declared as kind='projection' but returned "
|
|
97
|
+
f"{type(result).__name__} instead of dict[str, Column]. "
|
|
98
|
+
"Either return a dict or change kind to 'transform'."
|
|
99
|
+
)
|
|
100
|
+
new_cols.update(result)
|
|
101
|
+
|
|
102
|
+
if not new_cols:
|
|
103
|
+
return df
|
|
104
|
+
|
|
105
|
+
# Build the select expression. Columns rewritten by a rule replace the
|
|
106
|
+
# input column in place (preserving position); brand-new columns are
|
|
107
|
+
# appended. Keeping a rewritten column out of `existing` avoids two
|
|
108
|
+
# homonymous columns in the select (AMBIGUOUS_REFERENCE).
|
|
109
|
+
select_exprs = [
|
|
110
|
+
new_cols[c].alias(c) if c in new_cols else F.col(c)
|
|
111
|
+
for c in df.columns
|
|
112
|
+
]
|
|
113
|
+
select_exprs += [
|
|
114
|
+
col_expr.alias(col_name)
|
|
115
|
+
for col_name, col_expr in new_cols.items()
|
|
116
|
+
if col_name not in df.columns
|
|
117
|
+
]
|
|
118
|
+
return df.select(*select_exprs)
|
|
119
|
+
|
|
120
|
+
def _execute_aggregation_stage(self, df: "DataFrame", stage: "RuleStage") -> "DataFrame":
|
|
121
|
+
"""
|
|
122
|
+
Execute aggregation rules.
|
|
123
|
+
|
|
124
|
+
When all rules in the stage share the same ``groupBy`` keys (declared
|
|
125
|
+
via the ``agg_keys`` attribute on the rule function), they are merged
|
|
126
|
+
into a single ``groupBy(...).agg(...)`` call.
|
|
127
|
+
|
|
128
|
+
Each aggregation rule must return a tuple
|
|
129
|
+
``(group_keys: list[str], agg_exprs: dict[str, Column])`` when the
|
|
130
|
+
``agg_keys`` attribute is set; otherwise it must return a ``DataFrame``
|
|
131
|
+
(legacy transform-style fallback).
|
|
132
|
+
"""
|
|
133
|
+
if not stage.rules:
|
|
134
|
+
return df
|
|
135
|
+
|
|
136
|
+
# Check if all rules declare agg_keys and share the same keys
|
|
137
|
+
all_keys = [getattr(spec.func, "agg_keys", None) for spec in stage.rules]
|
|
138
|
+
all_exprs_available = all(k is not None for k in all_keys)
|
|
139
|
+
|
|
140
|
+
if all_exprs_available and len(set(tuple(sorted(k)) for k in all_keys)) == 1:
|
|
141
|
+
# Fused path: merge all agg exprs
|
|
142
|
+
group_keys = list(all_keys[0])
|
|
143
|
+
logger.debug(
|
|
144
|
+
"[Executor] Fusing %d aggregation rules on keys %s",
|
|
145
|
+
len(stage.rules),
|
|
146
|
+
group_keys,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
merged_agg: dict[str, object] = {}
|
|
150
|
+
for spec in stage.rules:
|
|
151
|
+
_, agg_exprs = spec.func(df)
|
|
152
|
+
merged_agg.update(agg_exprs)
|
|
153
|
+
|
|
154
|
+
agg_cols = [col_expr.alias(col_name) for col_name, col_expr in merged_agg.items()]
|
|
155
|
+
return df.groupBy(*group_keys).agg(*agg_cols)
|
|
156
|
+
else:
|
|
157
|
+
# Sequential fallback
|
|
158
|
+
for spec in stage.rules:
|
|
159
|
+
result = spec.func(df)
|
|
160
|
+
if isinstance(result, tuple):
|
|
161
|
+
group_keys, agg_exprs = result
|
|
162
|
+
agg_cols = [col_expr.alias(col_name) for col_name, col_expr in agg_exprs.items()]
|
|
163
|
+
df = df.groupBy(*group_keys).agg(*agg_cols)
|
|
164
|
+
else:
|
|
165
|
+
df = result
|
|
166
|
+
return df
|
|
167
|
+
|
|
168
|
+
def _execute_transform_stage(self, df: "DataFrame", stage: "RuleStage") -> "DataFrame":
|
|
169
|
+
"""Execute transform rules sequentially (legacy ``df → df`` contract)."""
|
|
170
|
+
for spec in stage.rules:
|
|
171
|
+
df = spec.func(df)
|
|
172
|
+
return df
|