Metadata-Version: 2.4
Name: lakehouse-plumber
Version: 0.8.7
Summary: A framework for building and managing enterprise Lakeflow Spark Declaritive Pipelines
Author-email: Mehdi Modarressi <modarressi.mehdi@gmail.com>
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
        "License" shall mean the terms and conditions for use, reproduction,
        and distribution as defined by Sections 1 through 9 of this document.
        
        "Licensor" shall mean the copyright owner or entity granting the License.
        
        "Legal Entity" shall mean the union of the acting entity and all
        other entities that control, are controlled by, or are under common
        control with that entity. For the purposes of this definition,
        "control" means (i) the power, direct or indirect, to cause the
        direction or management of such entity, whether by contract or
        otherwise, or (ii) ownership of fifty percent (50%) or more of the
        outstanding shares, or (iii) beneficial ownership of such entity.
        
        "You" (or "Your") shall mean an individual or Legal Entity
        exercising permissions granted by this License.
        
        "Source" form shall mean the preferred form for making modifications,
        including but not limited to software source code, documentation
        source, and configuration files.
        
        "Object" form shall mean any form resulting from mechanical
        transformation or translation of a Source form, including but
        not limited to compiled object code, generated documentation,
        and conversions to other media types.
        
        "Work" shall mean the work of authorship, whether in Source or
        Object form, made available under the License, as indicated by a
        copyright notice that is included in or attached to the work
        (which shall not include communication on electronic mailing
        lists, announcements on electronic bulletin boards, and
        similar communications).
        
        "Derivative Works" shall mean any work, whether in Source or Object
        form, that is based upon (or derived from) the Work and for which the
        editorial revisions, annotations, elaborations, or other modifications
        represent, as a whole, an original work of authorship. For the purposes
        of this License, Derivative Works shall not include works that remain
        separable from, or merely link (or bind by name) to the interfaces of,
        the Work and derivative works thereof.
        
        "Contribution" shall mean any work of authorship, including
        the original version of the Work and any modifications or additions
        to that Work or Derivative Works thereof, that is intentionally
        submitted to Licensor for inclusion in the Work by the copyright owner
        or by an individual or Legal Entity authorized to submit on behalf of
        the copyright owner. For the purposes of this definition, "submitted"
        means any form of electronic, verbal, or written communication sent
        to the Licensor or its representatives, including but not limited to
        communication on electronic mailing lists, source code control
        systems, and issue tracking systems that are managed by, or on behalf
        of, the Licensor for the purpose of discussing and improving the Work,
        but excluding communication that is conspicuously marked or otherwise
        designated in writing by the copyright owner as "Not a Contribution."
        
        "Contributor" shall mean Licensor and any individual or Legal Entity
        on behalf of whom a Contribution has been received by Licensor and
        subsequently incorporated within the Work.
        
        2. Grant of Copyright License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        copyright license to use, reproduce, modify, merge, publish,
        distribute, sublicense, and/or sell copies of the Work, and to
        permit persons to whom the Work is furnished to do so, subject to
        the following conditions:
        
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Work.
        
        3. Grant of Patent License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        (except as stated in this section) patent license to make, have made,
        use, offer to sell, sell, import, and otherwise transfer the Work,
        where such license applies only to those patent claims licensable
        by such Contributor that are necessarily infringed by their
        Contribution(s) alone or by combination of their Contribution(s)
        with the Work to which such Contribution(s) was submitted. If You
        institute patent litigation against any entity (including a
        cross-claim or counterclaim in a lawsuit) alleging that the Work
        or a Contribution incorporated within the Work constitutes direct
        or contributory patent infringement, then any patent licenses
        granted to You under this License for that Work shall terminate
        as of the date such litigation is filed.
        
        4. Redistribution. You may reproduce and distribute copies of the
        Work or Derivative Works thereof in any medium, with or without
        modifications, and in Source or Object form, provided that You
        meet the following conditions:
        
        (a) You must give any other recipients of the Work or
        Derivative Works a copy of this License; and
        
        (b) You must cause any modified files to carry prominent notices
        stating that You changed the files; and
        
        (c) You must retain, in the Source form of any Derivative Works
        that You distribute, all copyright, patent, trademark, and
        attribution notices from the Source form of the Work,
        excluding those notices that do not pertain to any part of
        the Derivative Works; and
        
        (d) If the Work includes a "NOTICE" text file as part of its
        distribution, then any Derivative Works that You distribute must
        include a readable copy of the attribution notices contained
        within such NOTICE file, excluding those notices that do not
        pertain to any part of the Derivative Works, in at least one
        of the following places: within a NOTICE text file distributed
        as part of the Derivative Works; within the Source form or
        documentation, if provided along with the Derivative Works; or,
        within a display generated by the Derivative Works, if and
        wherever such third-party notices normally appear. The contents
        of the NOTICE file are for informational purposes only and
        do not modify the License. You may add Your own attribution
        notices within Derivative Works that You distribute, alongside
        or as an addendum to the NOTICE text from the Work, provided
        that such additional attribution notices cannot be construed
        as modifying the License.
        
        You may add Your own copyright notice to Your modifications and
        may provide additional or different license terms and conditions
        for use, reproduction, or distribution of Your modifications, or
        for any such Derivative Works as a whole, provided Your use,
        reproduction, and distribution of the Work otherwise complies with
        the conditions stated in this License.
        
        5. Submission of Contributions. Unless You explicitly state otherwise,
        any Contribution intentionally submitted for inclusion in the Work
        by You to the Licensor shall be under the terms and conditions of
        this License, without any additional terms or conditions.
        Notwithstanding the above, nothing herein shall supersede or modify
        the terms of any separate license agreement you may have executed
        with Licensor regarding such Contributions.
        
        6. Trademarks. This License does not grant permission to use the trade
        names, trademarks, service marks, or product names of the Licensor,
        except as required for reasonable and customary use in describing the
        origin of the Work and reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty. Unless required by applicable law or
        agreed to in writing, Licensor provides the Work (and each
        Contributor provides its Contributions) on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        implied, including, without limitation, any warranties or conditions
        of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        PARTICULAR PURPOSE. You are solely responsible for determining the
        appropriateness of using or redistributing the Work and assume any
        risks associated with Your exercise of permissions under this License.
        
        8. Limitation of Liability. In no event and under no legal theory,
        whether in tort (including negligence), contract, or otherwise,
        unless required by applicable law (such as deliberate and grossly
        negligent acts) or agreed to in writing, shall any Contributor be
        liable to You for damages, including any direct, indirect, special,
        incidental, or consequential damages of any character arising as a
        result of this License or out of the use or inability to use the
        Work (including but not limited to damages for loss of goodwill,
        work stoppage, computer failure or malfunction, or any and all
        other commercial damages or losses), even if such Contributor
        has been advised of the possibility of such damages.
        
        9. Accepting Warranty or Support. You may choose to offer, and to
        charge a fee for, warranty, support, indemnity or other liability
        obligations and/or rights consistent with this License. However, in
        accepting such obligations, You may act only on Your own behalf and on
        Your sole responsibility, not on behalf of any other Contributor, and
        only if You agree to indemnify, defend, and hold each Contributor
        harmless for any liability incurred by, or claims asserted against,
        such Contributor by reason of your accepting any such warranty or support.
        
        END OF TERMS AND CONDITIONS
        
        APPENDIX: How to apply the Apache License to your work.
        
        To apply the Apache License to your work, attach the following
        boilerplate notice, with the fields enclosed by brackets "[]"
        replaced with your own identifying information. (Don't include
        the brackets!)  The text should be enclosed in the appropriate
        comment syntax for the file format. We also recommend that a
        file or class name and description of purpose be included on the
        same page as the copyright notice for easier identification within
        third-party archives.
        
        Copyright 2024 Mehdi Modarressi
        
        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
        
            http://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. 
Project-URL: Homepage, https://github.com/Mmodarre/Lakehouse_Plumber
Project-URL: Documentation, https://lakehouse-plumber.readthedocs.io/
Project-URL: Repository, https://github.com/Mmodarre/Lakehouse_Plumber.git
Project-URL: Bug Tracker, https://github.com/Mmodarre/Lakehouse_Plumber/issues
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.3.0
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: ruamel.yaml>=0.19.0
Requires-Dist: jinja2>=3.0.0
Requires-Dist: pydantic>=2.12.0
Requires-Dist: jsonschema>=4.26.0
Requires-Dist: packaging>=23.2
Requires-Dist: black==26.3.1
Requires-Dist: networkx>=3.6.0
Provides-Extra: dev
Requires-Dist: pytest>=9.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
Requires-Dist: flake8>=6.0.0; extra == "dev"
Requires-Dist: black==26.3.1; extra == "dev"
Requires-Dist: isort>=5.12.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: requests>=2.32.0; extra == "dev"
Requires-Dist: pip-audit>=2.7.0; extra == "dev"
Requires-Dist: bandit[sarif]>=1.7.0; extra == "dev"
Requires-Dist: liccheck>=0.9.0; extra == "dev"
Requires-Dist: pre-commit>=3.0.0; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Dynamic: license-file

<div align="center">
  <img src="https://raw.githubusercontent.com/Mmodarre/Lakehouse_Plumber/main/lhp_colour.png" alt="LakehousePlumber Logo" width="50%">
</div>

# Lakehouse Plumber

*Because every Lakehouse needs a good plumber to keep the flows running smoothly* 🚰

**Generate readable, debuggable Python for Databricks Lakeflow Declarative Pipelines (formerly DLT) from concise YAML.** LHP is a code generator, not a runtime framework — the Python it produces is exactly what executes in your workspace, with no `import lhp` and no metadata-interpretation layer.

<div align="center">

[![PyPI version](https://badge.fury.io/py/lakehouse-plumber.svg?icon=si%3Apython)](https://badge.fury.io/py/lakehouse-plumber)
[![Tests](https://github.com/Mmodarre/Lakehouse_Plumber/actions/workflows/python_ci.yml/badge.svg)](https://github.com/Mmodarre/Lakehouse_Plumber/actions/workflows/python_ci.yml)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![codecov](https://codecov.io/gh/Mmodarre/Lakehouse_Plumber/branch/main/graph/badge.svg?token=80IBHIFAQY)](https://codecov.io/gh/Mmodarre/Lakehouse_Plumber)
[![Documentation](https://img.shields.io/badge/docs-available-brightgreen.svg)](https://lakehouse-plumber.readthedocs.io/)
[![Databricks](https://img.shields.io/badge/Databricks-Lakeflow-%23FF3621?logo=databricks)](https://www.databricks.com/product/data-engineering)
[![PyPI Downloads](https://static.pepy.tech/badge/lakehouse-plumber/month)](https://pepy.tech/projects/lakehouse-plumber)

</div>

## What it looks like

This 10-line FlowGroup, plus a reusable 51-line ingestion template, generates 81 lines of production Python:

<table>
<tr>
<th>Input — <code>part_ingestion.yaml</code> (10 lines)</th>
<th>Output — <code>part_ingestion.py</code> (81 lines, abridged)</th>
</tr>
<tr>
<td valign="top">

```yaml
pipeline: acmi_edw_raw
flowgroup: part_ingestion

use_template: json_ingestion_template
template_parameters:
  table_name: part_raw
  landing_folder: part
  schema_file: part_schema
```

</td>
<td valign="top">

```python
from pyspark.sql import functions as F
from pyspark import pipelines as dp

part_cloudfiles_schema_hints = """
    p_partkey BIGINT NOT NULL, p_name STRING NOT NULL,
    p_mfgr STRING NOT NULL, ...
""".strip().replace("\n", " ")

@dp.temporary_view()
def v_part_raw_cloudfiles():
    df = (spark.readStream.format("cloudFiles")
        .option("cloudFiles.format", "json")
        .option("cloudFiles.schemaHints", ...)
        .load("/Volumes/.../part/*.json"))
    df = df.withColumn("_processing_timestamp", F.current_timestamp())
    return df

dp.create_streaming_table(name="...part_raw", ...)

@dp.append_flow(target="...part_raw", name="f_part_raw_cloudfiles")
def f_part_raw_cloudfiles():
    return spark.readStream.table("v_part_raw_cloudfiles")
```

</td>
</tr>
</table>

**Measured ratio: ~8x per FlowGroup**, with the 51-line template amortized across every JSON ingestion in the project. Ten new tables of the same shape cost ~100 lines of YAML; you still get 810 lines of production-grade Python with schema hints, append-flow registration, and operational metadata columns. *(Numbers measured from `tests/e2e/fixtures/testing_project/`.)*

## When to use LHP vs. alternatives

| If you are doing this... | Use | Why |
|---|---|---|
| Hand-writing repetitive DLT Python across many bronze/silver tables | **LHP** | LHP generates the boilerplate; you keep the readable output |
| Using **dlt-meta** | LHP — if you value static, debuggable Python in your repo | dlt-meta interprets metadata at *runtime* inside the DLT pipeline; LHP generates static Python *before* deployment. You read the code that runs, debug it in the IDE, and Databricks Assistant sees normal Python |
| Using **dbt** for gold/semantic models | **Both** — LHP for bronze/silver ingestion + CDC, dbt for SQL transformations on top | dbt does not handle streaming, Auto Loader, CDC apply-changes, or SCD — LHP does. They compose; they don't compete |
| Hand-writing raw **Lakeflow Declarative Pipelines (DLT)** | **LHP** if you have >10 similar tables | At low scale raw DLT is simpler. Past a dozen tables, the boilerplate is the problem LHP exists to solve |
| Using **Databricks Asset Bundles (DABs)** for deployment | **Both** — they compose | DABs deploys; LHP generates the Python that DABs deploys. `lhp init` produces a DAB-ready project by default |

LHP is **not** a runtime framework. There is no `import lhp` in any generated file, no agent process, no metadata table interpreted at pipeline-startup. The output is the same Python you would have written by hand — just with the boilerplate removed.

## Install and ship your first pipeline

```bash
pip install lakehouse-plumber
lhp init my_project              # bundle-ready by default; --no-bundle to opt out
cd my_project
lhp generate --env dev           # YAML in, Python out
```

That's it. Edit YAML files under `pipelines/`, point your Databricks Asset Bundle at the generated Python, and deploy with `databricks bundle deploy --target dev`.

> Optional: open the project in VS Code. `lhp init` wires `.vscode/settings.json` to seven JSON schemas, so you get IntelliSense, hover docs, and inline validation for every YAML file out of the box.

## The two things LHP does that nothing else does

### 1. Blueprint fan-out: one pipeline shape, many sites

The pattern that breaks every other metadata framework: stamp out the same bronze→silver→gold shape across 50 regional sites, tenants, or domains, without hand-maintaining 50 pipelines.

A Blueprint is a parameterised *shape* — multiple FlowGroups, their relationships, and the per-instance variables. An Instance file invokes the blueprint with a 4-line declaration:

```yaml
# pipelines/sites/site_alpha.yaml — 4 lines
use_blueprint: medallion_demo
parameters:
  site_name: site_alpha
  domain_id: ALPHA001
```

Two 4-line instance files × one 94-line blueprint = **6 generated Python files across 3 pipeline directories**, all sharing one source of truth. Add a 4-line `site_charlie.yaml` and you get three more generated files — no copy-paste, no fork-and-edit. (Verified in `src/lhp/core/services/blueprint_expander.py` and `tests/e2e/fixtures/testing_project/pipelines/10_blueprint_demo/`.)

### 2. Single pane of glass monitoring across every pipeline

Every Lakeflow / DLT pipeline emits an event log. Stitching those event logs together across an entire project — to feed a dashboard or an AI/BI metric — is a side project everyone starts and nobody finishes.

LHP ships it as a first-class output. Enable `event_log` in `lhp.yaml`, run `lhp generate`, and you get a deployable dashboard like this on day one:

<div align="center">
  <img src="https://raw.githubusercontent.com/Mmodarre/Lakehouse_Plumber/main/lhp_monitoring_dashboard.png" alt="LHP Operations Dashboard — pipeline activity, health by domain, freshness, and reliability across all pipelines" width="95%">
</div>

Under the hood, `lhp generate` emits:

- One **union notebook** with N independent streaming queries — one per event-log-enabled pipeline, each with its own checkpoint
- One **MVs-only DLT FlowGroup** with a pre-built `pipeline_run_summary` materialized view: pipeline name, run ID, status, duration, row metrics
- Optional **Databricks Jobs correlation** (state, start/end, duration) when `enable_job_monitoring: true`

Plug those into an AI/BI dashboard and you have project-wide observability — pipeline activity, health by domain, freshness, daily reliability — without writing the aggregation logic yourself. dlt-meta gives you per-pipeline event logs; LHP gives you the cross-pipeline rollup. (Logic in `src/lhp/core/services/monitoring_pipeline_builder.py`.)

Every `lhp generate` regenerates all flowgroups; state-file caching has been removed in version 0.10.0.

## Core workflow

Every FlowGroup is a sequence of typed actions:

```mermaid
graph LR
    A[Load] --> B{0..N Transform}
    B --> C[Write]
```

The action sub-types cover everything Lakeflow SDP exposes:

| Action | Sub-types |
|---|---|
| **Load** | CloudFiles (Auto Loader), Delta (with CDF), JDBC, SQL, custom Python |
| **Transform** | SQL, Python, data-quality expectations, schema mapping, temp tables |
| **Write** | Streaming Table, Materialized View, Append Flow (multi-source fan-in), CDC (SCD Type 1 and 2), Snapshot CDC, Sink (Delta, Kafka, JDBC, REST) |
| **Test** | Row count, uniqueness, referential integrity, completeness, range, schema match, lookup validity, custom SQL, custom expectations |

The full action reference is in [the docs](https://lakehouse-plumber.readthedocs.io/en/latest/actions/index.html).

## Substitutions and secrets

LHP composes four substitution layers, in order:

```
%{local_var}  →  {{ template_param }}  →  ${env_token}  →  ${secret:scope/key}
```

`local_var` is per-FlowGroup. `template_param` is per-template-invocation. `env_token` comes from `substitutions/<env>.yaml` (one per environment — `dev.yaml`, `staging.yaml`, `prod.yaml`). `secret:scope/key` is compiled into a `dbutils.secrets.get()` call in the generated Python — **secret values never appear in YAML, never appear in generated source, and are resolved at pipeline runtime by Databricks**.

You can chain layers: an `env_token` can expand to a string containing a `secret:` reference. The substitution processor lives in `src/lhp/core/services/flowgroup_processor.py`.

## A real bronze ingestion FlowGroup

```yaml
pipeline: bronze_ingestion
flowgroup: customers
presets: [bronze_layer_defaults]

actions:
  - name: load_customers_autoloader
    type: load
    source:
      type: cloudfiles
      path: "${landing_path}/customers/*.parquet"
      schema_evolution_mode: addNewColumns
    target: v_customers_raw

  - name: write_customers_bronze
    type: write
    source: v_customers_raw
    write_target:
      type: streaming_table
      database: "${catalog}.${bronze_schema}"
      table: customers
      cluster_columns: [market_segment]
```

The `bronze_layer_defaults` preset injects table properties, comment templates, and operational metadata columns shared across every bronze table. The `${landing_path}`, `${catalog}`, and `${bronze_schema}` tokens come from `substitutions/dev.yaml`. Run `lhp generate --env dev`, get production-ready Python with Auto Loader options, schema hints, append-flow registration, and Delta table properties — all configured per your preset.

The [docs](https://lakehouse-plumber.readthedocs.io/) cover silver transforms (CDC, SCD Type 2, multi-source append flows), gold materialized views, and the full test-action catalog with examples.

## Project layout

```
my_project/
├── lhp.yaml                    # project config (catalog, monitoring, defaults)
├── pipelines/                  # FlowGroups grouped by pipeline directory
│   ├── bronze_ingestion/
│   │   ├── customers.yaml
│   │   └── orders.yaml
│   └── silver_transforms/
│       └── customer_dimension.yaml
├── templates/                  # parameterised action patterns (reused across FlowGroups)
├── presets/                    # standardisation snippets (bronze defaults, audit columns, …)
├── blueprints/                 # parameterised pipeline shapes (multi-site / multi-tenant)
├── substitutions/              # per-environment variable values
│   ├── dev.yaml
│   └── prod.yaml
├── schemas/                    # JSON / SQL schemas referenced by Auto Loader
├── expectations/               # JSON expectation files for data-quality transforms
├── .vscode/                    # IntelliSense settings (auto-generated by `lhp init`)
└── generated/                  # output — checked in, version-controlled, debuggable
```

## What's new

- **Lakeflow SDP migration** — generated code now uses `from pyspark import pipelines as dp` (Lakeflow Spark Declarative Pipelines API) instead of the legacy `import dlt` decorators
- **Sink writes** — Delta tables, Kafka, JDBC, REST APIs as terminal write targets
- **Multi-FlowGroup files** — one YAML can declare multiple FlowGroups under shared settings, cutting file count for large templated projects
- **Cross-pipeline monitoring** — event-log aggregation + run-summary MV + optional Jobs correlation, dashboard-ready
- **Pipeline & Job config** — per-environment overrides for compute, runtime, scheduling, notifications, permissions

The full [changelog](https://lakehouse-plumber.readthedocs.io/en/latest/changelog.html) follows Keep a Changelog.

## Documentation and community

- **[Quickstart](https://lakehouse-plumber.readthedocs.io/en/latest/quickstart.html)** — ship your first pipeline in 10 minutes
- **[Migrating from raw DLT](https://lakehouse-plumber.readthedocs.io/en/latest/migrate_from_dlt.html)** — what to port first, how presets map to your existing patterns
- **[Architecture](https://lakehouse-plumber.readthedocs.io/en/latest/architecture.html)** — execution model, the six reuse primitives, the generation pipeline
- **[Full docs](https://lakehouse-plumber.readthedocs.io/)** — every action, every YAML key, every error code

[Issues](https://github.com/Mmodarre/Lakehouse_Plumber/issues) for bugs and feature requests. [Discussions](https://github.com/Mmodarre/Lakehouse_Plumber/discussions) for design questions and best-practice exchange.

## License

Apache 2.0 — see [LICENSE](LICENSE).

<div align="center">

Built for Lakeflow Spark Declarative Pipelines.

</div>
