masoora 0.1.0__tar.gz
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.
- masoora-0.1.0/LICENSE +21 -0
- masoora-0.1.0/PKG-INFO +125 -0
- masoora-0.1.0/README.md +97 -0
- masoora-0.1.0/pyproject.toml +61 -0
- masoora-0.1.0/src/masoora/__init__.py +31 -0
- masoora-0.1.0/src/masoora/builder.py +87 -0
- masoora-0.1.0/src/masoora/catalog.py +38 -0
- masoora-0.1.0/src/masoora/context.py +18 -0
- masoora-0.1.0/src/masoora/errors.py +31 -0
- masoora-0.1.0/src/masoora/graph.py +117 -0
- masoora-0.1.0/src/masoora/pipeline.py +213 -0
- masoora-0.1.0/src/masoora/py.typed +0 -0
- masoora-0.1.0/src/masoora/steps.py +84 -0
- masoora-0.1.0/src/masoora/testing.py +59 -0
masoora-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ahmed Osman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
masoora-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: masoora
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fluent builder for testable ETL pipelines
|
|
5
|
+
Keywords: etl,pipeline,dag,data-engineering,builder,testing
|
|
6
|
+
Author: Ahmed Osman
|
|
7
|
+
Author-email: Ahmed Osman <79141373+ahmedtilal@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Dist: pydantic>=2.13.4
|
|
21
|
+
Requires-Dist: pytest>=9.0 ; extra == 'pytest'
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Project-URL: Homepage, https://github.com/ahmedtilal/masoora
|
|
24
|
+
Project-URL: Issues, https://github.com/ahmedtilal/masoora/issues
|
|
25
|
+
Project-URL: Repository, https://github.com/ahmedtilal/masoora
|
|
26
|
+
Provides-Extra: pytest
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# masoora
|
|
30
|
+
|
|
31
|
+
Fluent builder for testable ETL pipelines in Python.
|
|
32
|
+
|
|
33
|
+
- **Fluent chaining**: `.with_read_step()` / `.with_transform_step()` / `.with_write_step()`
|
|
34
|
+
- **Pydantic context**: typed configuration passed to every step
|
|
35
|
+
- **Data catalog**: in-memory key → dataset store (polars/pandas/spark/dicts — anything)
|
|
36
|
+
- **DAG resolution**: declare steps in any order; cycles and missing inputs fail at `build()`
|
|
37
|
+
- **Testable**: mock reads/writes and assert on the catalog with a pytest fixture
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from masoora import PipelineBuilder, PipelineContext
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class MyContext(PipelineContext):
|
|
46
|
+
source_url: str
|
|
47
|
+
min_score: float = 0.5
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def read_events(ctx: MyContext): ...
|
|
51
|
+
def score(ctx: MyContext, events): ...
|
|
52
|
+
def filter_top(ctx: MyContext, scored): ...
|
|
53
|
+
def write_db(ctx: MyContext, top): ...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
pipeline = (
|
|
57
|
+
PipelineBuilder[MyContext]()
|
|
58
|
+
.with_read_step(read_events, output="events")
|
|
59
|
+
.with_transform_step(score, inputs=["events"], output="scored")
|
|
60
|
+
.with_transform_step(filter_top, inputs=["scored"], output="top")
|
|
61
|
+
.with_write_step(write_db, inputs=["top"])
|
|
62
|
+
.build()
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
catalog = pipeline.run(MyContext(source_url="https://..."))
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Step signatures:
|
|
69
|
+
|
|
70
|
+
| Step kind | Signature | Effect |
|
|
71
|
+
|---|---|---|
|
|
72
|
+
| read | `fn(ctx) -> dataset` | `catalog[output] = result` |
|
|
73
|
+
| transform | `fn(ctx, *inputs) -> dataset` | `catalog[output] = result` |
|
|
74
|
+
| write | `fn(ctx, *inputs) -> None` | terminal |
|
|
75
|
+
|
|
76
|
+
Steps may be declared in any order — `build()` topo-sorts them. Run only what's
|
|
77
|
+
needed for one output with `pipeline.run(ctx, target="top")`. Pre-populated
|
|
78
|
+
catalog keys are declared with `.with_seed(key)`.
|
|
79
|
+
|
|
80
|
+
## Parallel execution
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
pipeline.run(ctx, parallel=True) # thread pool, os.cpu_count() workers
|
|
84
|
+
pipeline.run(ctx, parallel=4) # explicit worker count
|
|
85
|
+
pipeline.run(ctx, executor=pool) # your Executor (not shut down by masoora)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Steps run concurrently in a `ThreadPoolExecutor` with dependency-driven
|
|
89
|
+
scheduling: each step starts the instant its own dependencies finish — there
|
|
90
|
+
is no level barrier, so unrelated slow steps never delay a ready branch.
|
|
91
|
+
Fail-fast: the first step error cancels queued work and raises
|
|
92
|
+
`StepExecutionError` immediately; already-running siblings finish in the
|
|
93
|
+
background.
|
|
94
|
+
|
|
95
|
+
Contract: steps must only read their declared input keys, write their own
|
|
96
|
+
output key, and treat the context as read-only. Under this contract parallel
|
|
97
|
+
results are identical to sequential.
|
|
98
|
+
|
|
99
|
+
## Testing
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from masoora import TestRunResult, make_pipeline_fixture
|
|
103
|
+
|
|
104
|
+
run_pipeline = make_pipeline_fixture(
|
|
105
|
+
pipeline,
|
|
106
|
+
MyContext(source_url="test"),
|
|
107
|
+
reads={"events": fake_events}, # read step is replaced, real source untouched
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_top_events(run_pipeline: TestRunResult[MyContext]) -> None:
|
|
112
|
+
assert run_pipeline.catalog["top"] == expected
|
|
113
|
+
assert run_pipeline.written["top"] == expected # write step captured, not executed
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Or without pytest: `pipeline.to_testable(reads={...}).run(ctx)` → `TestRunResult`.
|
|
117
|
+
|
|
118
|
+
## Development
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
uv sync
|
|
122
|
+
uv run pytest
|
|
123
|
+
uv run ruff check .
|
|
124
|
+
uv run mypy src tests
|
|
125
|
+
```
|
masoora-0.1.0/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# masoora
|
|
2
|
+
|
|
3
|
+
Fluent builder for testable ETL pipelines in Python.
|
|
4
|
+
|
|
5
|
+
- **Fluent chaining**: `.with_read_step()` / `.with_transform_step()` / `.with_write_step()`
|
|
6
|
+
- **Pydantic context**: typed configuration passed to every step
|
|
7
|
+
- **Data catalog**: in-memory key → dataset store (polars/pandas/spark/dicts — anything)
|
|
8
|
+
- **DAG resolution**: declare steps in any order; cycles and missing inputs fail at `build()`
|
|
9
|
+
- **Testable**: mock reads/writes and assert on the catalog with a pytest fixture
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from masoora import PipelineBuilder, PipelineContext
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MyContext(PipelineContext):
|
|
18
|
+
source_url: str
|
|
19
|
+
min_score: float = 0.5
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def read_events(ctx: MyContext): ...
|
|
23
|
+
def score(ctx: MyContext, events): ...
|
|
24
|
+
def filter_top(ctx: MyContext, scored): ...
|
|
25
|
+
def write_db(ctx: MyContext, top): ...
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
pipeline = (
|
|
29
|
+
PipelineBuilder[MyContext]()
|
|
30
|
+
.with_read_step(read_events, output="events")
|
|
31
|
+
.with_transform_step(score, inputs=["events"], output="scored")
|
|
32
|
+
.with_transform_step(filter_top, inputs=["scored"], output="top")
|
|
33
|
+
.with_write_step(write_db, inputs=["top"])
|
|
34
|
+
.build()
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
catalog = pipeline.run(MyContext(source_url="https://..."))
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Step signatures:
|
|
41
|
+
|
|
42
|
+
| Step kind | Signature | Effect |
|
|
43
|
+
|---|---|---|
|
|
44
|
+
| read | `fn(ctx) -> dataset` | `catalog[output] = result` |
|
|
45
|
+
| transform | `fn(ctx, *inputs) -> dataset` | `catalog[output] = result` |
|
|
46
|
+
| write | `fn(ctx, *inputs) -> None` | terminal |
|
|
47
|
+
|
|
48
|
+
Steps may be declared in any order — `build()` topo-sorts them. Run only what's
|
|
49
|
+
needed for one output with `pipeline.run(ctx, target="top")`. Pre-populated
|
|
50
|
+
catalog keys are declared with `.with_seed(key)`.
|
|
51
|
+
|
|
52
|
+
## Parallel execution
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
pipeline.run(ctx, parallel=True) # thread pool, os.cpu_count() workers
|
|
56
|
+
pipeline.run(ctx, parallel=4) # explicit worker count
|
|
57
|
+
pipeline.run(ctx, executor=pool) # your Executor (not shut down by masoora)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Steps run concurrently in a `ThreadPoolExecutor` with dependency-driven
|
|
61
|
+
scheduling: each step starts the instant its own dependencies finish — there
|
|
62
|
+
is no level barrier, so unrelated slow steps never delay a ready branch.
|
|
63
|
+
Fail-fast: the first step error cancels queued work and raises
|
|
64
|
+
`StepExecutionError` immediately; already-running siblings finish in the
|
|
65
|
+
background.
|
|
66
|
+
|
|
67
|
+
Contract: steps must only read their declared input keys, write their own
|
|
68
|
+
output key, and treat the context as read-only. Under this contract parallel
|
|
69
|
+
results are identical to sequential.
|
|
70
|
+
|
|
71
|
+
## Testing
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from masoora import TestRunResult, make_pipeline_fixture
|
|
75
|
+
|
|
76
|
+
run_pipeline = make_pipeline_fixture(
|
|
77
|
+
pipeline,
|
|
78
|
+
MyContext(source_url="test"),
|
|
79
|
+
reads={"events": fake_events}, # read step is replaced, real source untouched
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_top_events(run_pipeline: TestRunResult[MyContext]) -> None:
|
|
84
|
+
assert run_pipeline.catalog["top"] == expected
|
|
85
|
+
assert run_pipeline.written["top"] == expected # write step captured, not executed
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Or without pytest: `pipeline.to_testable(reads={...}).run(ctx)` → `TestRunResult`.
|
|
89
|
+
|
|
90
|
+
## Development
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
uv sync
|
|
94
|
+
uv run pytest
|
|
95
|
+
uv run ruff check .
|
|
96
|
+
uv run mypy src tests
|
|
97
|
+
```
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "masoora"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Fluent builder for testable ETL pipelines"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Ahmed Osman", email = "79141373+ahmedtilal@users.noreply.github.com" }
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
keywords = ["etl", "pipeline", "dag", "data-engineering", "builder", "testing"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Programming Language :: Python :: 3.14",
|
|
22
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
23
|
+
"Typing :: Typed",
|
|
24
|
+
]
|
|
25
|
+
dependencies = [
|
|
26
|
+
"pydantic>=2.13.4",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/ahmedtilal/masoora"
|
|
31
|
+
Repository = "https://github.com/ahmedtilal/masoora"
|
|
32
|
+
Issues = "https://github.com/ahmedtilal/masoora/issues"
|
|
33
|
+
|
|
34
|
+
[build-system]
|
|
35
|
+
requires = ["uv_build>=0.8.8,<0.9.0"]
|
|
36
|
+
build-backend = "uv_build"
|
|
37
|
+
|
|
38
|
+
[dependency-groups]
|
|
39
|
+
dev = [
|
|
40
|
+
"mypy>=2.3.1",
|
|
41
|
+
"pytest>=9.1.1",
|
|
42
|
+
"ruff>=0.16.3",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
[project.optional-dependencies]
|
|
46
|
+
pytest = ["pytest>=9.0"]
|
|
47
|
+
|
|
48
|
+
[tool.ruff]
|
|
49
|
+
line-length = 100
|
|
50
|
+
target-version = "py310"
|
|
51
|
+
|
|
52
|
+
[tool.ruff.lint]
|
|
53
|
+
select = ["E", "F", "I", "UP", "B", "SIM"]
|
|
54
|
+
|
|
55
|
+
[tool.mypy]
|
|
56
|
+
strict = true
|
|
57
|
+
disallow_untyped_defs = true
|
|
58
|
+
|
|
59
|
+
[tool.pytest.ini_options]
|
|
60
|
+
testpaths = ["tests"]
|
|
61
|
+
addopts = "-p no:cacheprovider"
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""masoora: fluent builder for testable ETL pipelines."""
|
|
2
|
+
|
|
3
|
+
from masoora.builder import PipelineBuilder
|
|
4
|
+
from masoora.catalog import DataCatalog
|
|
5
|
+
from masoora.context import PipelineContext
|
|
6
|
+
from masoora.errors import (
|
|
7
|
+
PipelineCycleError,
|
|
8
|
+
PipelineError,
|
|
9
|
+
PipelineValidationError,
|
|
10
|
+
StepExecutionError,
|
|
11
|
+
)
|
|
12
|
+
from masoora.pipeline import Pipeline, TestablePipeline
|
|
13
|
+
from masoora.steps import ReadStep, TransformStep, WriteStep
|
|
14
|
+
from masoora.testing import TestRunResult, make_pipeline_fixture
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"DataCatalog",
|
|
18
|
+
"Pipeline",
|
|
19
|
+
"PipelineBuilder",
|
|
20
|
+
"PipelineContext",
|
|
21
|
+
"PipelineCycleError",
|
|
22
|
+
"PipelineError",
|
|
23
|
+
"PipelineValidationError",
|
|
24
|
+
"ReadStep",
|
|
25
|
+
"StepExecutionError",
|
|
26
|
+
"TestRunResult",
|
|
27
|
+
"TestablePipeline",
|
|
28
|
+
"TransformStep",
|
|
29
|
+
"WriteStep",
|
|
30
|
+
"make_pipeline_fixture",
|
|
31
|
+
]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Fluent builder for pipelines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
7
|
+
|
|
8
|
+
from masoora.errors import PipelineValidationError
|
|
9
|
+
from masoora.graph import topo_sort
|
|
10
|
+
from masoora.pipeline import Pipeline
|
|
11
|
+
from masoora.steps import ReadStep, Step, TransformStep, WriteStep
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from typing_extensions import Self
|
|
15
|
+
|
|
16
|
+
from masoora.context import PipelineContext
|
|
17
|
+
|
|
18
|
+
ContextT = TypeVar("ContextT", bound="PipelineContext")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PipelineBuilder(Generic[ContextT]):
|
|
22
|
+
"""Chain read/transform/write steps, then build() a validated Pipeline.
|
|
23
|
+
|
|
24
|
+
Steps may be declared in any order; build() resolves dependencies
|
|
25
|
+
(DAG topo-sort) and fails fast on unknown inputs, duplicate outputs,
|
|
26
|
+
or cycles.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self) -> None:
|
|
30
|
+
self._steps: list[Step[ContextT]] = []
|
|
31
|
+
self._seeds: set[str] = set()
|
|
32
|
+
|
|
33
|
+
def with_read_step(self, fn: Callable[[ContextT], Any], *, output: str) -> Self:
|
|
34
|
+
"""fn(context) -> dataset, stored at catalog[output]."""
|
|
35
|
+
self._steps.append(ReadStep(fn=fn, output=output))
|
|
36
|
+
return self
|
|
37
|
+
|
|
38
|
+
def with_transform_step(
|
|
39
|
+
self, fn: Callable[..., Any], *, inputs: Sequence[str], output: str
|
|
40
|
+
) -> Self:
|
|
41
|
+
"""fn(context, *inputs) -> dataset, stored at catalog[output]."""
|
|
42
|
+
self._steps.append(TransformStep(fn=fn, inputs=inputs, output=output))
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
def with_write_step(self, fn: Callable[..., None], *, inputs: Sequence[str]) -> Self:
|
|
46
|
+
"""fn(context, *inputs) -> None; terminal step."""
|
|
47
|
+
self._steps.append(WriteStep(fn=fn, inputs=inputs))
|
|
48
|
+
return self
|
|
49
|
+
|
|
50
|
+
def with_seed(self, key: str) -> Self:
|
|
51
|
+
"""Declare a catalog key that will be pre-populated before run()."""
|
|
52
|
+
self._seeds.add(key)
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def build(self) -> Pipeline[ContextT]:
|
|
56
|
+
"""Validate and topo-sort the steps into an executable Pipeline."""
|
|
57
|
+
self._validate()
|
|
58
|
+
return Pipeline(steps=topo_sort(self._steps))
|
|
59
|
+
|
|
60
|
+
def _validate(self) -> None:
|
|
61
|
+
produced: dict[str, str] = {}
|
|
62
|
+
for step in self._steps:
|
|
63
|
+
for key in step.outputs:
|
|
64
|
+
if key in produced:
|
|
65
|
+
raise PipelineValidationError(
|
|
66
|
+
f"Duplicate output key {key!r}: produced by both "
|
|
67
|
+
f"{produced[key]!r} and {step.name!r}"
|
|
68
|
+
)
|
|
69
|
+
produced[key] = step.name
|
|
70
|
+
|
|
71
|
+
unknown: dict[str, list[str]] = {}
|
|
72
|
+
for step in self._steps:
|
|
73
|
+
for key in step.inputs:
|
|
74
|
+
if key not in produced and key not in self._seeds:
|
|
75
|
+
unknown.setdefault(key, []).append(step.name)
|
|
76
|
+
if unknown:
|
|
77
|
+
details = "; ".join(
|
|
78
|
+
f"{key!r} (needed by {', '.join(names)})" for key, names in unknown.items()
|
|
79
|
+
)
|
|
80
|
+
raise PipelineValidationError(
|
|
81
|
+
f"Input keys not produced by any step and not seeded: {details}. "
|
|
82
|
+
"Add a producing step or declare .with_seed(key)."
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
for step in self._steps:
|
|
86
|
+
if isinstance(step, WriteStep) and not step.inputs:
|
|
87
|
+
raise PipelineValidationError(f"Write step {step.name!r} has no inputs")
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""In-memory data catalog: keys mapped to datasets of any type."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator, Mapping, MutableMapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class DataCatalog(MutableMapping[str, Any]):
|
|
10
|
+
"""Holds datasets produced and consumed by pipeline steps.
|
|
11
|
+
|
|
12
|
+
Values are unconstrained: polars/pandas/spark dataframes, dicts, models, etc.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, initial: Mapping[str, Any] | None = None) -> None:
|
|
16
|
+
self._data: dict[str, Any] = dict(initial) if initial else {}
|
|
17
|
+
|
|
18
|
+
def __getitem__(self, key: str) -> Any:
|
|
19
|
+
return self._data[key]
|
|
20
|
+
|
|
21
|
+
def __setitem__(self, key: str, value: Any) -> None:
|
|
22
|
+
self._data[key] = value
|
|
23
|
+
|
|
24
|
+
def __delitem__(self, key: str) -> None:
|
|
25
|
+
del self._data[key]
|
|
26
|
+
|
|
27
|
+
def __iter__(self) -> Iterator[str]:
|
|
28
|
+
return iter(self._data)
|
|
29
|
+
|
|
30
|
+
def __len__(self) -> int:
|
|
31
|
+
return len(self._data)
|
|
32
|
+
|
|
33
|
+
def __repr__(self) -> str:
|
|
34
|
+
return f"DataCatalog(keys={list(self._data)})"
|
|
35
|
+
|
|
36
|
+
def snapshot(self) -> dict[str, Any]:
|
|
37
|
+
"""Return a shallow copy of the catalog contents."""
|
|
38
|
+
return dict(self._data)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Base class for pipeline contexts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PipelineContext(BaseModel):
|
|
9
|
+
"""Holds all variables/configuration a pipeline needs.
|
|
10
|
+
|
|
11
|
+
Users subclass this and declare their own fields:
|
|
12
|
+
|
|
13
|
+
class MyContext(PipelineContext):
|
|
14
|
+
source_url: str
|
|
15
|
+
batch_size: int = 100
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Errors raised by masoora."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PipelineError(Exception):
|
|
7
|
+
"""Base class for all masoora errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PipelineValidationError(PipelineError):
|
|
11
|
+
"""Raised at build time when the pipeline definition is invalid."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PipelineCycleError(PipelineValidationError):
|
|
15
|
+
"""Raised at build time when steps form a dependency cycle."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, cycle: list[str]) -> None:
|
|
18
|
+
self.cycle = cycle
|
|
19
|
+
super().__init__(f"Pipeline contains a dependency cycle: {' -> '.join(cycle)}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class StepExecutionError(PipelineError):
|
|
23
|
+
"""Raised when a step fails during run()."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, step_index: int, step_name: str, original: Exception) -> None:
|
|
26
|
+
self.step_index = step_index
|
|
27
|
+
self.step_name = step_name
|
|
28
|
+
self.original = original
|
|
29
|
+
super().__init__(
|
|
30
|
+
f"Step {step_index} ({step_name!r}) failed: {type(original).__name__}: {original}"
|
|
31
|
+
)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Dependency graph resolution for pipeline steps.
|
|
2
|
+
|
|
3
|
+
Steps are nodes; catalog keys are edges: a step depends on the step that
|
|
4
|
+
produces each of its input keys. Keys not produced by any step are seeds
|
|
5
|
+
(pre-populated catalog entries) and create no edges.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import heapq
|
|
11
|
+
from typing import TYPE_CHECKING, TypeVar
|
|
12
|
+
|
|
13
|
+
from masoora.errors import PipelineCycleError, PipelineValidationError
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from masoora.context import PipelineContext
|
|
17
|
+
from masoora.steps import Step
|
|
18
|
+
|
|
19
|
+
ContextT = TypeVar("ContextT", bound="PipelineContext")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _dependencies(steps: list[Step[ContextT]]) -> list[set[int]]:
|
|
23
|
+
"""deps[i] = indices of steps that must run before steps[i]."""
|
|
24
|
+
producer: dict[str, int] = {}
|
|
25
|
+
for idx, step in enumerate(steps):
|
|
26
|
+
for key in step.outputs:
|
|
27
|
+
producer[key] = idx
|
|
28
|
+
deps: list[set[int]] = [set() for _ in steps]
|
|
29
|
+
for idx, step in enumerate(steps):
|
|
30
|
+
for key in step.inputs:
|
|
31
|
+
if key in producer:
|
|
32
|
+
deps[idx].add(producer[key])
|
|
33
|
+
return deps
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def topo_sort(steps: list[Step[ContextT]]) -> list[Step[ContextT]]:
|
|
37
|
+
"""Kahn's algorithm; declaration order breaks ties (deterministic)."""
|
|
38
|
+
steps = list(steps)
|
|
39
|
+
deps = _dependencies(steps)
|
|
40
|
+
dependents: list[list[int]] = [[] for _ in steps]
|
|
41
|
+
indegree = [0] * len(steps)
|
|
42
|
+
for idx, dep_set in enumerate(deps):
|
|
43
|
+
indegree[idx] = len(dep_set)
|
|
44
|
+
for dep in dep_set:
|
|
45
|
+
dependents[dep].append(idx)
|
|
46
|
+
|
|
47
|
+
heap = [idx for idx in range(len(steps)) if indegree[idx] == 0]
|
|
48
|
+
heapq.heapify(heap)
|
|
49
|
+
order: list[Step[ContextT]] = []
|
|
50
|
+
while heap:
|
|
51
|
+
idx = heapq.heappop(heap)
|
|
52
|
+
order.append(steps[idx])
|
|
53
|
+
for dependent in dependents[idx]:
|
|
54
|
+
indegree[dependent] -= 1
|
|
55
|
+
if indegree[dependent] == 0:
|
|
56
|
+
heapq.heappush(heap, dependent)
|
|
57
|
+
|
|
58
|
+
if len(order) != len(steps):
|
|
59
|
+
raise PipelineCycleError(_find_cycle(steps, deps))
|
|
60
|
+
return order
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _find_cycle(steps: list[Step[ContextT]], deps: list[set[int]]) -> list[str]:
|
|
64
|
+
"""Extract one cycle (as step names) from the unresolved subgraph."""
|
|
65
|
+
unresolved = {idx for idx, dep_set in enumerate(deps) if dep_set}
|
|
66
|
+
# Follow unresolved predecessors until we revisit a node.
|
|
67
|
+
path: list[int] = []
|
|
68
|
+
current = next(iter(unresolved))
|
|
69
|
+
seen: dict[int, int] = {}
|
|
70
|
+
while current not in seen:
|
|
71
|
+
seen[current] = len(path)
|
|
72
|
+
path.append(current)
|
|
73
|
+
current = next(idx for idx in deps[current] if idx in unresolved)
|
|
74
|
+
cycle = path[seen[current] :]
|
|
75
|
+
names = [steps[idx].name for idx in cycle]
|
|
76
|
+
return [*names, steps[current].name]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def dependency_edges(
|
|
80
|
+
steps: list[Step[ContextT]],
|
|
81
|
+
) -> tuple[list[set[int]], list[list[int]]]:
|
|
82
|
+
"""Return (deps, dependents): deps[i] = indices that must finish before
|
|
83
|
+
steps[i]; dependents[i] = indices that depend on steps[i]."""
|
|
84
|
+
deps = _dependencies(steps)
|
|
85
|
+
dependents: list[list[int]] = [[] for _ in steps]
|
|
86
|
+
for idx, dep_set in enumerate(deps):
|
|
87
|
+
for dep in dep_set:
|
|
88
|
+
dependents[dep].append(idx)
|
|
89
|
+
return deps, dependents
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def ancestors_of_target(steps: list[Step[ContextT]], target: str) -> list[Step[ContextT]]:
|
|
93
|
+
"""Return the topo-ordered subset of steps needed to produce `target`.
|
|
94
|
+
|
|
95
|
+
`steps` must already be topo-sorted. Raises if no step produces `target`.
|
|
96
|
+
"""
|
|
97
|
+
steps = list(steps)
|
|
98
|
+
deps = _dependencies(steps)
|
|
99
|
+
producer: dict[str, int] = {}
|
|
100
|
+
for idx, step in enumerate(steps):
|
|
101
|
+
for key in step.outputs:
|
|
102
|
+
producer[key] = idx
|
|
103
|
+
if target not in producer:
|
|
104
|
+
available = sorted(producer)
|
|
105
|
+
raise PipelineValidationError(
|
|
106
|
+
f"Target {target!r} is not produced by any step. Available: {available}"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
needed: set[int] = set()
|
|
110
|
+
stack = [producer[target]]
|
|
111
|
+
while stack:
|
|
112
|
+
idx = stack.pop()
|
|
113
|
+
if idx in needed:
|
|
114
|
+
continue
|
|
115
|
+
needed.add(idx)
|
|
116
|
+
stack.extend(deps[idx])
|
|
117
|
+
return [step for idx, step in enumerate(steps) if idx in needed]
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Pipeline: an ordered, executable sequence of steps."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections import deque
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from concurrent.futures import FIRST_COMPLETED, Executor, Future, ThreadPoolExecutor, wait
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
10
|
+
|
|
11
|
+
from masoora.catalog import DataCatalog
|
|
12
|
+
from masoora.errors import StepExecutionError
|
|
13
|
+
from masoora.graph import ancestors_of_target, dependency_edges
|
|
14
|
+
from masoora.steps import ReadStep, Step, WriteStep
|
|
15
|
+
from masoora.testing import TestRunResult
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from masoora.context import PipelineContext
|
|
19
|
+
|
|
20
|
+
ContextT = TypeVar("ContextT", bound="PipelineContext")
|
|
21
|
+
|
|
22
|
+
#: parallel=False -> sequential; True -> os.cpu_count() workers; int -> N workers
|
|
23
|
+
ParallelMode = bool | int
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _execute_steps(
|
|
27
|
+
steps: Sequence[Step[ContextT]], context: ContextT, catalog: DataCatalog
|
|
28
|
+
) -> None:
|
|
29
|
+
for index, step in enumerate(steps):
|
|
30
|
+
try:
|
|
31
|
+
step.execute(context, catalog)
|
|
32
|
+
except Exception as exc:
|
|
33
|
+
raise StepExecutionError(index, step.name, exc) from exc
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _execute_parallel(
|
|
37
|
+
steps: Sequence[Step[ContextT]],
|
|
38
|
+
context: ContextT,
|
|
39
|
+
catalog: DataCatalog,
|
|
40
|
+
parallel: ParallelMode,
|
|
41
|
+
executor: Executor | None,
|
|
42
|
+
) -> None:
|
|
43
|
+
"""Dependency-driven scheduling; fail-fast on the first error.
|
|
44
|
+
|
|
45
|
+
Each step is submitted the instant its own dependencies complete (no
|
|
46
|
+
level barrier). Correct under the masoora step contract: steps only read
|
|
47
|
+
declared input keys and write their own output key, and treat context as
|
|
48
|
+
read-only.
|
|
49
|
+
"""
|
|
50
|
+
steps = list(steps)
|
|
51
|
+
n = len(steps)
|
|
52
|
+
deps, dependents = dependency_edges(steps)
|
|
53
|
+
remaining = [len(dep_set) for dep_set in deps]
|
|
54
|
+
ready: deque[int] = deque(idx for idx in range(n) if remaining[idx] == 0)
|
|
55
|
+
futures: dict[Future[None], int] = {}
|
|
56
|
+
completed = 0
|
|
57
|
+
|
|
58
|
+
pool: Executor
|
|
59
|
+
if executor is not None:
|
|
60
|
+
pool = executor
|
|
61
|
+
owns_pool = False
|
|
62
|
+
else:
|
|
63
|
+
workers = None
|
|
64
|
+
if parallel is True:
|
|
65
|
+
workers = os.cpu_count()
|
|
66
|
+
elif isinstance(parallel, int) and parallel > 0:
|
|
67
|
+
workers = parallel
|
|
68
|
+
pool = ThreadPoolExecutor(max_workers=workers)
|
|
69
|
+
owns_pool = True
|
|
70
|
+
|
|
71
|
+
error: tuple[int, str, BaseException] | None = None
|
|
72
|
+
try:
|
|
73
|
+
while completed < n:
|
|
74
|
+
while ready and error is None:
|
|
75
|
+
idx = ready.popleft()
|
|
76
|
+
futures[pool.submit(steps[idx].execute, context, catalog)] = idx
|
|
77
|
+
if not futures:
|
|
78
|
+
break
|
|
79
|
+
finished, _ = wait(set(futures), return_when=FIRST_COMPLETED)
|
|
80
|
+
for future in finished:
|
|
81
|
+
idx = futures.pop(future)
|
|
82
|
+
completed += 1
|
|
83
|
+
exc = future.exception()
|
|
84
|
+
if exc is not None:
|
|
85
|
+
if error is None:
|
|
86
|
+
error = (idx, steps[idx].name, exc)
|
|
87
|
+
elif error is None:
|
|
88
|
+
for nxt in dependents[idx]:
|
|
89
|
+
remaining[nxt] -= 1
|
|
90
|
+
if remaining[nxt] == 0:
|
|
91
|
+
ready.append(nxt)
|
|
92
|
+
if error is not None:
|
|
93
|
+
for future in futures:
|
|
94
|
+
future.cancel()
|
|
95
|
+
break
|
|
96
|
+
finally:
|
|
97
|
+
if owns_pool:
|
|
98
|
+
# On failure return promptly: cancel queued work, don't wait for
|
|
99
|
+
# running steps (they only touch their own catalog keys).
|
|
100
|
+
pool.shutdown(wait=error is None, cancel_futures=error is not None)
|
|
101
|
+
|
|
102
|
+
if error is not None:
|
|
103
|
+
index, name, exc = error
|
|
104
|
+
if isinstance(exc, Exception):
|
|
105
|
+
raise StepExecutionError(index, name, exc) from exc
|
|
106
|
+
raise exc # KeyboardInterrupt & co. propagate unwrapped
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _dispatch(
|
|
110
|
+
steps: Sequence[Step[ContextT]],
|
|
111
|
+
context: ContextT,
|
|
112
|
+
catalog: DataCatalog,
|
|
113
|
+
parallel: ParallelMode,
|
|
114
|
+
executor: Executor | None,
|
|
115
|
+
) -> None:
|
|
116
|
+
if executor is None and not parallel:
|
|
117
|
+
_execute_steps(steps, context, catalog)
|
|
118
|
+
else:
|
|
119
|
+
_execute_parallel(steps, context, catalog, parallel, executor)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Pipeline(Generic[ContextT]):
|
|
123
|
+
"""A topo-sorted sequence of steps. Built via PipelineBuilder."""
|
|
124
|
+
|
|
125
|
+
def __init__(self, steps: Sequence[Step[ContextT]]) -> None:
|
|
126
|
+
self._steps: tuple[Step[ContextT], ...] = tuple(steps)
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def steps(self) -> tuple[Step[ContextT], ...]:
|
|
130
|
+
return self._steps
|
|
131
|
+
|
|
132
|
+
def run(
|
|
133
|
+
self,
|
|
134
|
+
context: ContextT,
|
|
135
|
+
catalog: DataCatalog | None = None,
|
|
136
|
+
target: str | None = None,
|
|
137
|
+
parallel: ParallelMode = False,
|
|
138
|
+
executor: Executor | None = None,
|
|
139
|
+
) -> DataCatalog:
|
|
140
|
+
"""Execute all steps (or only those needed for `target`) in topo order.
|
|
141
|
+
|
|
142
|
+
parallel: False (default) runs sequentially; True uses a thread pool
|
|
143
|
+
with os.cpu_count() workers; an int sets the worker count. Steps run
|
|
144
|
+
concurrently, each starting the instant its own dependencies finish
|
|
145
|
+
(dependency-driven scheduling, no level barrier).
|
|
146
|
+
executor: caller-provided Executor; wins over `parallel` and is NOT
|
|
147
|
+
shut down by the pipeline.
|
|
148
|
+
"""
|
|
149
|
+
steps = self._select(target)
|
|
150
|
+
cat = catalog if catalog is not None else DataCatalog()
|
|
151
|
+
_dispatch(steps, context, cat, parallel, executor)
|
|
152
|
+
return cat
|
|
153
|
+
|
|
154
|
+
def to_testable(
|
|
155
|
+
self,
|
|
156
|
+
reads: Mapping[str, Any] | None = None,
|
|
157
|
+
*,
|
|
158
|
+
mock_writes: bool = True,
|
|
159
|
+
target: str | None = None,
|
|
160
|
+
) -> TestablePipeline[ContextT]:
|
|
161
|
+
"""Return a copy with read steps replaced by fixture data and,
|
|
162
|
+
optionally, write steps captured instead of executed."""
|
|
163
|
+
read_fixtures = dict(reads) if reads else {}
|
|
164
|
+
mocked: list[Step[ContextT]] = []
|
|
165
|
+
for step in self._select(target):
|
|
166
|
+
if isinstance(step, ReadStep) and step.output in read_fixtures:
|
|
167
|
+
value = read_fixtures[step.output]
|
|
168
|
+
|
|
169
|
+
def constant_read(_ctx: ContextT, v: Any = value) -> Any:
|
|
170
|
+
return v
|
|
171
|
+
|
|
172
|
+
mocked.append(ReadStep(fn=constant_read, output=step.output))
|
|
173
|
+
elif isinstance(step, WriteStep) and mock_writes:
|
|
174
|
+
mocked.append(step) # capture happens in TestablePipeline.run
|
|
175
|
+
else:
|
|
176
|
+
mocked.append(step)
|
|
177
|
+
return TestablePipeline(steps=mocked, mock_writes=mock_writes)
|
|
178
|
+
|
|
179
|
+
def _select(self, target: str | None) -> list[Step[ContextT]]:
|
|
180
|
+
if target is None:
|
|
181
|
+
return list(self._steps)
|
|
182
|
+
return ancestors_of_target(list(self._steps), target)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class TestablePipeline(Generic[ContextT]):
|
|
186
|
+
"""A pipeline with mocked reads/writes; run() returns a TestRunResult."""
|
|
187
|
+
|
|
188
|
+
def __init__(self, steps: Sequence[Step[ContextT]], *, mock_writes: bool) -> None:
|
|
189
|
+
self._steps: tuple[Step[ContextT], ...] = tuple(steps)
|
|
190
|
+
self._mock_writes = mock_writes
|
|
191
|
+
|
|
192
|
+
def run(
|
|
193
|
+
self,
|
|
194
|
+
context: ContextT,
|
|
195
|
+
catalog: DataCatalog | None = None,
|
|
196
|
+
parallel: ParallelMode = False,
|
|
197
|
+
executor: Executor | None = None,
|
|
198
|
+
) -> TestRunResult[ContextT]:
|
|
199
|
+
cat = catalog if catalog is not None else DataCatalog()
|
|
200
|
+
written: dict[str, Any] = {}
|
|
201
|
+
steps: list[Step[ContextT]] = []
|
|
202
|
+
for step in self._steps:
|
|
203
|
+
if isinstance(step, WriteStep) and self._mock_writes:
|
|
204
|
+
keys = step.inputs
|
|
205
|
+
|
|
206
|
+
def capture(_ctx: ContextT, *datasets: Any, keys: tuple[str, ...] = keys) -> None:
|
|
207
|
+
written.update(dict(zip(keys, datasets, strict=True)))
|
|
208
|
+
|
|
209
|
+
steps.append(WriteStep(fn=capture, inputs=step.inputs))
|
|
210
|
+
else:
|
|
211
|
+
steps.append(step)
|
|
212
|
+
_dispatch(steps, context, cat, parallel, executor)
|
|
213
|
+
return TestRunResult(catalog=cat, written=written)
|
|
File without changes
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Pipeline steps: read, transform, write."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from masoora.catalog import DataCatalog
|
|
11
|
+
from masoora.context import PipelineContext
|
|
12
|
+
|
|
13
|
+
ContextT = TypeVar("ContextT", bound="PipelineContext")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class ReadStep(Generic[ContextT]):
|
|
18
|
+
"""fn(context) -> dataset, stored at catalog[output]."""
|
|
19
|
+
|
|
20
|
+
fn: Callable[[ContextT], Any]
|
|
21
|
+
output: str
|
|
22
|
+
inputs: tuple[str, ...] = field(default_factory=tuple, init=False)
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def name(self) -> str:
|
|
26
|
+
return getattr(self.fn, "__name__", repr(self.fn))
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def outputs(self) -> tuple[str, ...]:
|
|
30
|
+
return (self.output,)
|
|
31
|
+
|
|
32
|
+
def execute(self, context: ContextT, catalog: DataCatalog) -> None:
|
|
33
|
+
catalog[self.output] = self.fn(context)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class TransformStep(Generic[ContextT]):
|
|
38
|
+
"""fn(context, *inputs) -> dataset, stored at catalog[output]."""
|
|
39
|
+
|
|
40
|
+
fn: Callable[..., Any]
|
|
41
|
+
inputs: tuple[str, ...]
|
|
42
|
+
output: str
|
|
43
|
+
|
|
44
|
+
def __init__(self, fn: Callable[..., Any], inputs: Sequence[str], output: str) -> None:
|
|
45
|
+
object.__setattr__(self, "fn", fn)
|
|
46
|
+
object.__setattr__(self, "inputs", tuple(inputs))
|
|
47
|
+
object.__setattr__(self, "output", output)
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def name(self) -> str:
|
|
51
|
+
return getattr(self.fn, "__name__", repr(self.fn))
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def outputs(self) -> tuple[str, ...]:
|
|
55
|
+
return (self.output,)
|
|
56
|
+
|
|
57
|
+
def execute(self, context: ContextT, catalog: DataCatalog) -> None:
|
|
58
|
+
catalog[self.output] = self.fn(context, *(catalog[key] for key in self.inputs))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class WriteStep(Generic[ContextT]):
|
|
63
|
+
"""fn(context, *inputs) -> None; produces no catalog output."""
|
|
64
|
+
|
|
65
|
+
fn: Callable[..., None]
|
|
66
|
+
inputs: tuple[str, ...]
|
|
67
|
+
|
|
68
|
+
def __init__(self, fn: Callable[..., None], inputs: Sequence[str]) -> None:
|
|
69
|
+
object.__setattr__(self, "fn", fn)
|
|
70
|
+
object.__setattr__(self, "inputs", tuple(inputs))
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def name(self) -> str:
|
|
74
|
+
return getattr(self.fn, "__name__", repr(self.fn))
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def outputs(self) -> tuple[str, ...]:
|
|
78
|
+
return ()
|
|
79
|
+
|
|
80
|
+
def execute(self, context: ContextT, catalog: DataCatalog) -> None:
|
|
81
|
+
self.fn(context, *(catalog[key] for key in self.inputs))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
Step = ReadStep[ContextT] | TransformStep[ContextT] | WriteStep[ContextT]
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Testing helpers: run pipelines with mocked reads/writes under pytest."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from masoora.catalog import DataCatalog
|
|
11
|
+
from masoora.context import PipelineContext
|
|
12
|
+
from masoora.pipeline import Pipeline
|
|
13
|
+
|
|
14
|
+
ContextT = TypeVar("ContextT", bound="PipelineContext")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class TestRunResult(Generic[ContextT]):
|
|
19
|
+
"""Result of running a TestablePipeline.
|
|
20
|
+
|
|
21
|
+
catalog: full data catalog after the run (assert on any key).
|
|
22
|
+
written: input key -> dataset for every mocked write step.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
catalog: DataCatalog
|
|
26
|
+
written: dict[str, Any] = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
__test__ = False # not a pytest test class
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def make_pipeline_fixture(
|
|
32
|
+
pipeline: Pipeline[ContextT],
|
|
33
|
+
context: ContextT | Callable[[], ContextT],
|
|
34
|
+
reads: Mapping[str, Any] | None = None,
|
|
35
|
+
*,
|
|
36
|
+
mock_writes: bool = True,
|
|
37
|
+
target: str | None = None,
|
|
38
|
+
) -> Callable[[], TestRunResult[ContextT]]:
|
|
39
|
+
"""Create a pytest fixture that runs the pipeline with mocked IO.
|
|
40
|
+
|
|
41
|
+
Usage:
|
|
42
|
+
run_pipeline = make_pipeline_fixture(
|
|
43
|
+
my_pipeline, MyContext(url="test"), reads={"raw": fake_df}
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
def test_output(run_pipeline: TestRunResult[MyContext]) -> None:
|
|
47
|
+
assert "clean" in run_pipeline.catalog
|
|
48
|
+
"""
|
|
49
|
+
try:
|
|
50
|
+
import pytest
|
|
51
|
+
except ImportError as exc: # pragma: no cover
|
|
52
|
+
raise ImportError("make_pipeline_fixture requires pytest; install masoora[pytest]") from exc
|
|
53
|
+
|
|
54
|
+
@pytest.fixture
|
|
55
|
+
def _fixture() -> TestRunResult[ContextT]:
|
|
56
|
+
ctx = context() if callable(context) else context
|
|
57
|
+
return pipeline.to_testable(reads=reads, mock_writes=mock_writes, target=target).run(ctx)
|
|
58
|
+
|
|
59
|
+
return _fixture
|