openlakeforge-core 0.5.1a3__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.
@@ -0,0 +1,77 @@
1
+ """Canonical provider-neutral lakehouse descriptors and inventory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .descriptors import (
6
+ SOURCE_API_VERSION,
7
+ SOURCE_KIND,
8
+ LakehouseDescriptorError,
9
+ load_source_descriptor,
10
+ validate_source_descriptor,
11
+ )
12
+ from .governance import (
13
+ GOVERNANCE_API_VERSION,
14
+ GOVERNANCE_KIND,
15
+ governance_products,
16
+ load_governance_descriptor,
17
+ load_governance_lakehouse_document,
18
+ validate_governance_descriptor,
19
+ )
20
+ from .inventory import (
21
+ ArtifactPrefixes,
22
+ CatalogNamespace,
23
+ Dashboard,
24
+ Domain,
25
+ LakehouseInventory,
26
+ PhysicalInventory,
27
+ PhysicalDomainNames,
28
+ PhysicalProductNames,
29
+ Product,
30
+ FloeEntity,
31
+ ResourceLoad,
32
+ Source,
33
+ Table,
34
+ inventory_for,
35
+ load_lakehouse_inventory,
36
+ load_lakehouse_inventory_from_descriptors,
37
+ load_source,
38
+ load_transitional_lakehouse_inventory,
39
+ )
40
+ from .runs import FLOE_FULL_REFRESH_TAG, FULL_REFRESH_SCOPES, FULL_REFRESH_TAG, full_refresh_scope, full_refresh_tags
41
+
42
+ __all__ = [
43
+ "FLOE_FULL_REFRESH_TAG",
44
+ "FULL_REFRESH_SCOPES",
45
+ "FULL_REFRESH_TAG",
46
+ "GOVERNANCE_API_VERSION",
47
+ "GOVERNANCE_KIND",
48
+ "SOURCE_API_VERSION",
49
+ "SOURCE_KIND",
50
+ "ArtifactPrefixes",
51
+ "CatalogNamespace",
52
+ "Dashboard",
53
+ "Domain",
54
+ "LakehouseDescriptorError",
55
+ "LakehouseInventory",
56
+ "PhysicalInventory",
57
+ "PhysicalDomainNames",
58
+ "PhysicalProductNames",
59
+ "Product",
60
+ "FloeEntity",
61
+ "ResourceLoad",
62
+ "Source",
63
+ "Table",
64
+ "full_refresh_scope",
65
+ "full_refresh_tags",
66
+ "inventory_for",
67
+ "governance_products",
68
+ "load_governance_descriptor",
69
+ "load_governance_lakehouse_document",
70
+ "load_lakehouse_inventory",
71
+ "load_lakehouse_inventory_from_descriptors",
72
+ "load_transitional_lakehouse_inventory",
73
+ "load_source",
74
+ "load_source_descriptor",
75
+ "validate_governance_descriptor",
76
+ "validate_source_descriptor",
77
+ ]
@@ -0,0 +1,188 @@
1
+ """Versioned descriptor validation for the Source kind and the shared field checks.
2
+
3
+ The canonical model is the ``Governance`` descriptor at
4
+ ``lakehouse_code/governance.yml`` (``governance.py``) together with one ``Source``
5
+ descriptor per bronze source at ``lakehouse_code/bronze/<source>/source.yaml``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections.abc import Mapping
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import yaml
16
+
17
+ SOURCE_API_VERSION = "openlakeforge.io/v1beta1"
18
+ SOURCE_KIND = "Source"
19
+ LEGACY_SOURCE_API_VERSION = "openlakeforge.io/v1alpha3"
20
+ _PRODUCT_IDENTIFIER_PATTERN = r"[a-z][a-z0-9_]*"
21
+ _IDENTIFIER_PATTERN = re.compile(rf"^{_PRODUCT_IDENTIFIER_PATTERN}$")
22
+ # Underscore-separated words, no `_` at either end or doubled. A source that
23
+ # declares runtime keys turns its name into Kubernetes object names (`_` -> `-`,
24
+ # which may not end a name) and both into dlt variables (`__` separates dlt
25
+ # config sections), so `crm_` or `a__b` cannot be bound unambiguously.
26
+ _RUNTIME_WORDS_PATTERN = re.compile(r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$")
27
+
28
+
29
+ class LakehouseDescriptorError(ValueError):
30
+ """Raised when a lakehouse or source descriptor is invalid."""
31
+
32
+
33
+ def _identifier(value: object, *, field: str, source: str) -> str:
34
+ if not isinstance(value, str) or not _IDENTIFIER_PATTERN.fullmatch(value):
35
+ raise LakehouseDescriptorError(f"{source}: {field} must match '^[a-z][a-z0-9_]*$'")
36
+ return value
37
+
38
+
39
+ def _non_empty_string(value: object, *, field: str, source: str) -> str:
40
+ if not isinstance(value, str) or not value:
41
+ raise LakehouseDescriptorError(f"{source}: {field} must be a non-empty string")
42
+ return value
43
+
44
+
45
+ def _optional_string(value: object, *, field: str, source: str) -> None:
46
+ if value is not None and not isinstance(value, str):
47
+ raise LakehouseDescriptorError(f"{source}: {field} must be a string")
48
+
49
+
50
+ def validate_source_descriptor(document: Mapping[str, Any], *, source: str = "source.yaml") -> None:
51
+ """Validate a v1beta1 Source descriptor envelope and resource list."""
52
+ if document.get("apiVersion") == LEGACY_SOURCE_API_VERSION:
53
+ raise LakehouseDescriptorError(
54
+ f"{source}: apiVersion {LEGACY_SOURCE_API_VERSION!r} is no longer accepted; "
55
+ f"run `olf project migrate` to rewrite it as {SOURCE_API_VERSION!r}"
56
+ )
57
+ if document.get("apiVersion") != SOURCE_API_VERSION:
58
+ raise LakehouseDescriptorError(
59
+ f"{source}: unsupported apiVersion {document.get('apiVersion')!r}; expected {SOURCE_API_VERSION!r}"
60
+ )
61
+ if document.get("kind") != SOURCE_KIND:
62
+ raise LakehouseDescriptorError(f"{source}: kind must be {SOURCE_KIND!r}")
63
+ for field in ("name", "displayName", "description", "status", "resources"):
64
+ if field not in document:
65
+ raise LakehouseDescriptorError(f"{source}: missing required field {field!r}")
66
+ _identifier(document["name"], field="name", source=source)
67
+ _non_empty_string(document["displayName"], field="displayName", source=source)
68
+ _non_empty_string(document["status"], field="status", source=source)
69
+ _optional_string(document["description"], field="description", source=source)
70
+ resources = document["resources"]
71
+ if not isinstance(resources, list) or not resources:
72
+ raise LakehouseDescriptorError(f"{source}: resources must be a non-empty array")
73
+ seen: set[str] = set()
74
+ for index, resource in enumerate(resources):
75
+ if not isinstance(resource, Mapping):
76
+ raise LakehouseDescriptorError(f"{source}: resources[{index}] must be an object")
77
+ if "name" not in resource:
78
+ raise LakehouseDescriptorError(f"{source}: resources[{index}] is missing required field 'name'")
79
+ name = _identifier(resource["name"], field=f"resources[{index}].name", source=source)
80
+ if name in seen:
81
+ raise LakehouseDescriptorError(f"{source}: duplicate resource name {name!r}")
82
+ seen.add(name)
83
+ if "description" in resource and not isinstance(resource["description"], str):
84
+ raise LakehouseDescriptorError(f"{source}: resources[{index}].description must be a string")
85
+ if "load" in resource:
86
+ _validate_resource_load(resource["load"], field=f"resources[{index}].load", source=source)
87
+ unexpected = set(resource) - {"name", "description", "load"}
88
+ if unexpected:
89
+ raise LakehouseDescriptorError(
90
+ f"{source}: resources[{index}] must not contain {sorted(unexpected)!r} (provider-neutral fields only)"
91
+ )
92
+ if "runtime" in document:
93
+ if not _RUNTIME_WORDS_PATTERN.fullmatch(document["name"]):
94
+ raise LakehouseDescriptorError(
95
+ f"{source}: a source with runtime keys needs a name of underscore-separated words "
96
+ f"(no leading, trailing or doubled '_'); got {document['name']!r}"
97
+ )
98
+ _validate_source_runtime(document["runtime"], source=source)
99
+ unexpected = set(document) - {
100
+ "apiVersion",
101
+ "kind",
102
+ "name",
103
+ "displayName",
104
+ "description",
105
+ "status",
106
+ "resources",
107
+ "runtime",
108
+ }
109
+ if unexpected:
110
+ raise LakehouseDescriptorError(
111
+ f"{source}: must not contain {sorted(unexpected)!r} (provider-neutral fields only)"
112
+ )
113
+
114
+
115
+ LOAD_MODES = ("full", "incremental")
116
+
117
+
118
+ def _validate_resource_load(load: object, *, field: str, source: str) -> None:
119
+ # Column names, not values or queries: the connector owns how it reads the
120
+ # cursor, the descriptor owns which column it is and what Silver merges on.
121
+ if not isinstance(load, Mapping):
122
+ raise LakehouseDescriptorError(f"{source}: {field} must be an object")
123
+ unexpected = set(load) - {"mode", "cursor", "primary_key"}
124
+ if unexpected:
125
+ raise LakehouseDescriptorError(f"{source}: {field} must not contain {sorted(unexpected)!r}")
126
+ mode = load.get("mode")
127
+ if mode not in LOAD_MODES:
128
+ raise LakehouseDescriptorError(f"{source}: {field}.mode must be one of {list(LOAD_MODES)!r}, got {mode!r}")
129
+ if "cursor" in load:
130
+ _identifier(load["cursor"], field=f"{field}.cursor", source=source)
131
+ if "primary_key" in load:
132
+ keys = load["primary_key"]
133
+ if not isinstance(keys, list) or not keys:
134
+ raise LakehouseDescriptorError(f"{source}: {field}.primary_key must be a non-empty array of column names")
135
+ for index, key in enumerate(keys):
136
+ _identifier(key, field=f"{field}.primary_key[{index}]", source=source)
137
+ if len(set(keys)) != len(keys):
138
+ raise LakehouseDescriptorError(f"{source}: {field}.primary_key lists a column twice")
139
+ if mode == "incremental":
140
+ # Without a cursor every run is a full extract appended to the last
141
+ # one; without a key Silver cannot merge a changed row onto its old
142
+ # version.
143
+ missing = [key for key in ("cursor", "primary_key") if key not in load]
144
+ if missing:
145
+ raise LakehouseDescriptorError(f"{source}: {field} is incremental and needs {' and '.join(missing)}")
146
+ elif "cursor" in load:
147
+ raise LakehouseDescriptorError(f"{source}: {field}.cursor applies to mode 'incremental' only")
148
+
149
+
150
+ def _validate_source_runtime(runtime: object, *, source: str) -> None:
151
+ # Key names only: their values are a stage's to bind, in its own ConfigMap
152
+ # and Secret, so a revision promotes unchanged from DEV to PROD (#546).
153
+ if not isinstance(runtime, Mapping):
154
+ raise LakehouseDescriptorError(f"{source}: runtime must be an object")
155
+ unexpected = set(runtime) - {"config", "secrets"}
156
+ if unexpected:
157
+ raise LakehouseDescriptorError(
158
+ f"{source}: runtime must not contain {sorted(unexpected)!r}; it names config and secrets keys only"
159
+ )
160
+ listed: dict[str, str] = {}
161
+ for group in ("config", "secrets"):
162
+ keys = runtime.get(group, [])
163
+ if not isinstance(keys, list):
164
+ raise LakehouseDescriptorError(f"{source}: runtime.{group} must be an array of key names")
165
+ for index, key in enumerate(keys):
166
+ name = _identifier(key, field=f"runtime.{group}[{index}]", source=source)
167
+ if not _RUNTIME_WORDS_PATTERN.fullmatch(name):
168
+ raise LakehouseDescriptorError(
169
+ f"{source}: runtime.{group}[{index}] must be underscore-separated words "
170
+ f"(no leading, trailing or doubled '_'); got {name!r}"
171
+ )
172
+ if name in listed:
173
+ raise LakehouseDescriptorError(
174
+ f"{source}: runtime key {name!r} is listed twice (runtime.{listed[name]} and runtime.{group})"
175
+ )
176
+ listed[name] = group
177
+
178
+
179
+ def load_source_descriptor(path: str | Path) -> dict[str, Any]:
180
+ """Load and validate the v1beta1 Source descriptor at ``path``."""
181
+ source = str(path)
182
+ with Path(path).open(encoding="utf-8") as handle:
183
+ document = yaml.safe_load(handle)
184
+ if not isinstance(document, dict):
185
+ raise LakehouseDescriptorError(f"{source}: descriptor must contain a YAML object")
186
+ validate_source_descriptor(document, source=source)
187
+ return document
188
+
@@ -0,0 +1,143 @@
1
+ """The ``Governance`` descriptor at ``lakehouse_code/governance.yml``.
2
+
3
+ It carries business intent only: domains, and the data products nested
4
+ under them. Tables belong to a domain or product by their schema
5
+ (``<domain>_silver``, ``<product>_gold``), so no table list is declared here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import yaml
15
+
16
+ from .descriptors import LakehouseDescriptorError, _identifier, _non_empty_string, _optional_string
17
+
18
+ GOVERNANCE_API_VERSION = "openlakeforge.io/v1beta2"
19
+ GOVERNANCE_KIND = "Governance"
20
+ _LEGACY_API_VERSION = "openlakeforge.io/v1beta1"
21
+ _ENTRY_FIELDS = {"displayName", "description", "status"}
22
+
23
+
24
+ def _check_entry(entry: object, *, id_field: str, where: str, extra: set[str]) -> Mapping[str, Any]:
25
+ if not isinstance(entry, Mapping):
26
+ raise LakehouseDescriptorError(f"{where}: must be an object")
27
+ _identifier(entry.get(id_field), field=id_field, source=where)
28
+ where = f"{where[: where.rindex('[')]}[{entry[id_field]}]"
29
+ _non_empty_string(entry.get("displayName"), field="displayName", source=where)
30
+ _optional_string(entry.get("description"), field="description", source=where)
31
+ if "status" in entry:
32
+ _non_empty_string(entry["status"], field="status", source=where)
33
+ unexpected = sorted(set(entry) - _ENTRY_FIELDS - extra - {id_field})
34
+ if unexpected:
35
+ hint = ""
36
+ if "domain" in unexpected:
37
+ hint = "; a product belongs to the domain it is nested under, so `domain` is not declared"
38
+ raise LakehouseDescriptorError(f"{where}: must not contain {unexpected!r}{hint}")
39
+ return entry
40
+
41
+
42
+ def governance_products(document: Mapping[str, Any]) -> list[Mapping[str, Any]]:
43
+ """Every product of a validated document, in domain order."""
44
+ return [product for domain in document["domains"] for product in domain.get("products", [])]
45
+
46
+
47
+ def validate_governance_descriptor(document: Mapping[str, Any], *, source: str = "governance.yml") -> None:
48
+ """Validate the envelope, the domains and the products nested under them.
49
+
50
+ Product ids are unique across all domains: the ``<product>_gold`` schema
51
+ does not carry its domain.
52
+ """
53
+ api_version = document.get("apiVersion")
54
+ if api_version == _LEGACY_API_VERSION:
55
+ raise LakehouseDescriptorError(
56
+ f"{source}: apiVersion {_LEGACY_API_VERSION!r} declares a flat root `products:` list; "
57
+ f"run `olf project migrate` to nest products under their domains as {GOVERNANCE_API_VERSION!r}"
58
+ )
59
+ if api_version != GOVERNANCE_API_VERSION:
60
+ raise LakehouseDescriptorError(
61
+ f"{source}: unsupported apiVersion {api_version!r}; expected {GOVERNANCE_API_VERSION!r}"
62
+ )
63
+ if document.get("kind") != GOVERNANCE_KIND:
64
+ raise LakehouseDescriptorError(f"{source}: kind must be {GOVERNANCE_KIND!r}")
65
+ if "products" in document:
66
+ raise LakehouseDescriptorError(
67
+ f"{source}: root `products` is not part of {GOVERNANCE_API_VERSION!r}; declare each product under "
68
+ "`domains[].products`"
69
+ )
70
+ unexpected = sorted(set(document) - {"apiVersion", "kind", "domains"})
71
+ if unexpected:
72
+ raise LakehouseDescriptorError(f"{source}: must not contain {unexpected!r}")
73
+ domains = document.get("domains")
74
+ if not isinstance(domains, list) or not domains:
75
+ raise LakehouseDescriptorError(f"{source}: domains must be a non-empty array")
76
+ seen_domains: set[str] = set()
77
+ owner_of: dict[str, str] = {}
78
+ for domain in domains:
79
+ entry = _check_entry(domain, id_field="name", where=f"{source}: domains[]", extra={"products"})
80
+ name = entry["name"]
81
+ if name in seen_domains:
82
+ raise LakehouseDescriptorError(f"{source}: duplicate name {name!r} in domains")
83
+ seen_domains.add(name)
84
+ # A domain may exist before its first product (`olf domain new`).
85
+ products = entry.get("products", [])
86
+ if not isinstance(products, list):
87
+ raise LakehouseDescriptorError(f"{source}: domains[{name}].products must be an array")
88
+ for product in products:
89
+ where = f"{source}: domains[{name}].products[]"
90
+ checked = _check_entry(product, id_field="id", where=where, extra=set())
91
+ if checked["id"] in owner_of:
92
+ raise LakehouseDescriptorError(
93
+ f"{source}: duplicate id {checked['id']!r} in domains[{name}].products[{checked['id']}]; "
94
+ f"already declared under domain {owner_of[checked['id']]!r}"
95
+ )
96
+ owner_of[checked["id"]] = name
97
+
98
+
99
+ def load_governance_lakehouse_document(path: str | Path, *, allow_incomplete: bool = False) -> dict[str, Any]:
100
+ """``governance.yml`` as the document shape the inventory loader consumes.
101
+
102
+ Sources are the Bronze source directories and dashboards the Superset report
103
+ directories, so neither is declared twice. A dashboard serves the products
104
+ whose ``<product>_gold`` schema its datasets read.
105
+ """
106
+ code = Path(path).parent
107
+ # An `olf init --empty` project has no governance.yml until its first domain.
108
+ if allow_incomplete and not Path(path).is_file():
109
+ document: Mapping[str, Any] = {"domains": []}
110
+ else:
111
+ document = load_governance_descriptor(path)
112
+ products = governance_products(document)
113
+ if not products and not allow_incomplete:
114
+ raise LakehouseDescriptorError(f"{path}: governance.yml must declare at least one product")
115
+ dashboards = []
116
+ for metadata in sorted(code.glob("dashboards/superset/*/metadata.yaml")):
117
+ schemas = {
118
+ yaml.safe_load(dataset.read_text(encoding="utf-8")).get("schema")
119
+ for dataset in (metadata.parent / "datasets").rglob("*")
120
+ if dataset.suffix in {".yaml", ".yml"}
121
+ }
122
+ served = [p["id"] for p in products if f"{p['id']}_gold" in schemas]
123
+ dashboards.append({"name": metadata.parent.name, "products": served})
124
+ return {
125
+ "name": "openlakeforge",
126
+ "sources": sorted(p.parent.name for p in code.glob("bronze/*/source.yaml")),
127
+ "domains": [
128
+ {**domain, "products": [dict(p) for p in domain.get("products", [])]}
129
+ for domain in document["domains"]
130
+ ],
131
+ "dashboards": dashboards,
132
+ }
133
+
134
+
135
+ def load_governance_descriptor(path: str | Path) -> dict[str, Any]:
136
+ """Load and validate the Governance descriptor at ``path``."""
137
+ source = str(path)
138
+ with Path(path).open(encoding="utf-8") as handle:
139
+ document = yaml.safe_load(handle)
140
+ if not isinstance(document, dict):
141
+ raise LakehouseDescriptorError(f"{source}: descriptor must contain a YAML object")
142
+ validate_governance_descriptor(document, source=source)
143
+ return document
@@ -0,0 +1,553 @@
1
+ """Typed, provider-neutral inventory derived from lakehouse descriptors.
2
+
3
+ The canonical inventory is composed from the ``Governance`` descriptor at
4
+ ``lakehouse_code/governance.yml`` and one ``Source`` descriptor per bronze
5
+ source at ``lakehouse_code/bronze/<source>/source.yaml``.
6
+
7
+ Canonical identities:
8
+
9
+ * Bronze ``<source>.<resource>``
10
+ * Silver ``<domain>.<table>``
11
+ * Gold ``<product>.<table>``
12
+
13
+ with the dependency chain Source/Bronze -> Domain/Silver -> Product/Gold ->
14
+ Dashboard. The legacy v1alpha1/v1alpha2 ``Domain`` inventory loaders below are
15
+ preserved for migration diagnostics; the canonical loaders are the
16
+ ``load_lakehouse_inventory*`` functions.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from collections.abc import Mapping, Sequence
23
+ from dataclasses import dataclass
24
+ from functools import cache
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ import yaml
29
+
30
+ from .descriptors import (
31
+ LakehouseDescriptorError,
32
+ load_source_descriptor,
33
+ )
34
+ from .governance import load_governance_lakehouse_document
35
+
36
+ _IDENTIFIER_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$")
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ResourceLoad:
41
+ """How a source resource is extracted: `full` replaces Bronze, `incremental` appends past `cursor`."""
42
+
43
+ mode: str = "full"
44
+ cursor: str | None = None
45
+ primary_key: tuple[str, ...] = ()
46
+
47
+ @property
48
+ def incremental(self) -> bool:
49
+ return self.mode == "incremental"
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Table:
54
+ """A provider-neutral logical table or source resource."""
55
+
56
+ name: str
57
+ load: ResourceLoad = ResourceLoad()
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class FloeEntity:
62
+ """A domain's Silver entity as its Floe file declares it, and the Bronze resource feeding it."""
63
+
64
+ domain: str
65
+ name: str
66
+ source: str
67
+ resource: str
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class ArtifactPrefixes:
72
+ """Object-store locations derived from an owner's logical identity."""
73
+
74
+ floe_report_prefix: str
75
+ dbt_artifact_prefix: str
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class Source:
80
+ """A bronze source and the resources it owns."""
81
+
82
+ descriptor_path: Path
83
+ name: str
84
+ display_name: str
85
+ resources: tuple[Table, ...]
86
+ # Names of the settings and credentials its loader needs, never values:
87
+ # each stage binds them in the ConfigMap and Secret below.
88
+ runtime_config: tuple[str, ...] = ()
89
+ runtime_secrets: tuple[str, ...] = ()
90
+
91
+ @property
92
+ def config_map_name(self) -> str:
93
+ # Kubernetes names allow no `_` and source ids allow no `-`, so the
94
+ # mapping cannot make two sources collide.
95
+ return f"olf-source-{self.name.replace('_', '-')}"
96
+
97
+ @property
98
+ def credentials_secret_name(self) -> str:
99
+ return f"{self.config_map_name}-credentials"
100
+
101
+ def runtime_env_name(self, key: str) -> str:
102
+ """The variable dlt reads `key` from: `SOURCES__<section>__<key>`.
103
+
104
+ dlt names a source's config section after its module, and the loader
105
+ is `bronze/<source>/dlt/<source>.py`, so the section is the source id.
106
+ """
107
+ return f"SOURCES__{self.name.upper()}__{key.upper()}"
108
+
109
+ def load_of(self, resource: str) -> ResourceLoad:
110
+ for table in self.resources:
111
+ if table.name == resource:
112
+ return table.load
113
+ raise LakehouseDescriptorError(f"{self.descriptor_path}: source {self.name!r} declares no resource {resource!r}")
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class Product:
118
+ """A product and its provider-neutral derived identities.
119
+
120
+ Product identity is the product ``id`` (also the product ``name``); it is
121
+ globally unique across the lakehouse inventory. The Silver layer is
122
+ domain-aligned (``{domain}_silver``), the Gold layer is product-aligned
123
+ (``{product}_gold``).
124
+ """
125
+
126
+ domain_name: str
127
+ id: str
128
+ display_name: str
129
+
130
+ @property
131
+ def name(self) -> str:
132
+ return self.id
133
+
134
+ @property
135
+ def job_name(self) -> str:
136
+ return f"{self.id}_pipeline"
137
+
138
+ @property
139
+ def silver_namespace(self) -> str:
140
+ return f"{self.domain_name}_silver"
141
+
142
+ @property
143
+ def gold_namespace(self) -> str:
144
+ return f"{self.id}_gold"
145
+
146
+ @property
147
+ def definitions_module(self) -> str:
148
+ return f"lakehouse_code.pipelines.dagster.{self.id}"
149
+
150
+ @property
151
+ def dbt_artifact_prefix(self) -> str:
152
+ return f"run-artifacts/dbt/{self.domain_name}/{self.id}/"
153
+
154
+ @property
155
+ def dbt_project_dir(self) -> str:
156
+ return f"lakehouse_code/gold/{self.id}/dbt"
157
+
158
+ @property
159
+ def openmetadata_data_product_fqns(self) -> tuple[str, str]:
160
+ return self.id, f"{self.domain_name}.{self.id}"
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class Domain:
165
+ """A domain and its products."""
166
+
167
+ descriptor_path: Path
168
+ name: str
169
+ display_name: str
170
+ products: tuple[Product, ...]
171
+
172
+ @property
173
+ def artifact_prefixes(self) -> ArtifactPrefixes:
174
+ return ArtifactPrefixes(
175
+ floe_report_prefix=f"floe/reports/{self.name}/",
176
+ dbt_artifact_prefix="",
177
+ )
178
+
179
+ @property
180
+ def silver_namespace(self) -> str:
181
+ return f"{self.name}_silver"
182
+
183
+
184
+ @dataclass(frozen=True)
185
+ class Dashboard:
186
+ """A consumption-aligned dashboard bound to one or more products."""
187
+
188
+ name: str
189
+ products: tuple[str, ...]
190
+
191
+ @property
192
+ def report_source_dir(self) -> str:
193
+ return f"lakehouse_code/dashboards/superset/{self.name}"
194
+
195
+ @property
196
+ def superset_export_bundle_name(self) -> str:
197
+ return f"{self.name}_superset_assets_export.zip"
198
+
199
+
200
+ @dataclass(frozen=True)
201
+ class CatalogNamespace:
202
+ """A physical catalog namespace and its object-store location."""
203
+
204
+ name: str
205
+ location: str
206
+
207
+
208
+ @dataclass(frozen=True)
209
+ class PhysicalProductNames:
210
+ """Provider-specific names resolved for one logical product."""
211
+
212
+ product: str
213
+ gold_namespace: str
214
+ gold_schema_fqn: str
215
+
216
+
217
+ @dataclass(frozen=True)
218
+ class PhysicalDomainNames:
219
+ """Provider-specific names resolved for one logical Silver domain."""
220
+
221
+ domain: str
222
+ silver_namespace: str
223
+ silver_schema_fqn: str
224
+
225
+
226
+ @dataclass(frozen=True)
227
+ class PhysicalInventory:
228
+ """Physical catalog and artifact identities for a provider contract."""
229
+
230
+ catalog_namespaces: tuple[CatalogNamespace, ...]
231
+ products: tuple[PhysicalProductNames, ...]
232
+ domains: tuple[PhysicalDomainNames, ...] = ()
233
+
234
+ @property
235
+ def silver_namespaces(self) -> dict[str, str]:
236
+ return {domain.domain: domain.silver_namespace for domain in self.domains}
237
+
238
+ @property
239
+ def gold_namespaces(self) -> dict[str, str]:
240
+ return {product.product: product.gold_namespace for product in self.products}
241
+
242
+ @property
243
+ def silver_schema_fqns(self) -> dict[str, str]:
244
+ return {domain.domain: domain.silver_schema_fqn for domain in self.domains}
245
+
246
+ @property
247
+ def gold_schema_fqns(self) -> dict[str, str]:
248
+ return {product.product: product.gold_schema_fqn for product in self.products}
249
+
250
+
251
+ @dataclass(frozen=True)
252
+ class LakehouseInventory:
253
+ """All sources, domains, products, and dashboards declared in one lakehouse."""
254
+
255
+ lakehouse_root: Path
256
+ name: str
257
+ sources: tuple[Source, ...]
258
+ domains: tuple[Domain, ...]
259
+ dashboards: tuple[Dashboard, ...]
260
+
261
+ @property
262
+ def products(self) -> tuple[Product, ...]:
263
+ return tuple(product for domain in self.domains for product in domain.products)
264
+
265
+ @property
266
+ def job_names(self) -> tuple[str, ...]:
267
+ return tuple(product.job_name for product in self.products)
268
+
269
+ @property
270
+ def catalog_namespaces(self) -> tuple[str, ...]:
271
+ return tuple(
272
+ namespace
273
+ for namespace in (*self.silver_namespace_names, *self.gold_namespace_names)
274
+ )
275
+
276
+ @property
277
+ def default_product(self) -> Product:
278
+ if not self.products:
279
+ raise LakehouseDescriptorError(f"{self.lakehouse_root}: no data products were discovered")
280
+ return self.products[0]
281
+
282
+ @property
283
+ def artifact_prefixes(self) -> tuple[ArtifactPrefixes, ...]:
284
+ return tuple(domain.artifact_prefixes for domain in self.domains)
285
+
286
+ @property
287
+ def domain_names(self) -> tuple[str, ...]:
288
+ return tuple(domain.name for domain in self.domains)
289
+
290
+ @property
291
+ def source_names(self) -> tuple[str, ...]:
292
+ return tuple(source.name for source in self.sources)
293
+
294
+ @property
295
+ def openmetadata_data_products(self) -> dict[str, tuple[str, str]]:
296
+ return {product.name: product.openmetadata_data_product_fqns for product in self.products}
297
+
298
+ @property
299
+ def silver_namespace_names(self) -> frozenset[str]:
300
+ return frozenset(domain.silver_namespace for domain in self.domains)
301
+
302
+ def domain_for_product(self, product: Product) -> Domain:
303
+ return next(domain for domain in self.domains if domain.name == product.domain_name)
304
+
305
+ def floe_entities(self, domain: Domain) -> tuple[FloeEntity, ...]:
306
+ """The domain's Silver entities from its Floe files, each fed by a Bronze resource a Source declares."""
307
+ resources = {(source.name, resource.name) for source in self.sources for resource in source.resources}
308
+ entities = _read_floe_entities(self.lakehouse_root, domain.name)
309
+ for entity in entities:
310
+ if (entity.source, entity.resource) not in resources:
311
+ raise LakehouseDescriptorError(
312
+ f"{self.lakehouse_root}: Silver entity {domain.name}/{entity.name} reads unknown Bronze "
313
+ f"resource {entity.source}/{entity.resource}"
314
+ )
315
+ return entities
316
+
317
+ @property
318
+ def gold_namespace_names(self) -> frozenset[str]:
319
+ return frozenset(product.gold_namespace for product in self.products)
320
+
321
+ def resolve_physical_names(
322
+ self,
323
+ *,
324
+ catalog_database_fqn: str,
325
+ silver_bucket: str,
326
+ gold_bucket: str,
327
+ namespace_prefix: str = "",
328
+ ) -> PhysicalInventory:
329
+ """Resolve physical names from provider-contract values.
330
+
331
+ `namespace_prefix` (default: none) is prepended to every physical
332
+ database name. Every provider with its own catalog per stage (local/
333
+ Polaris, AWS/Azure custom Glue catalogs) leaves this empty - the
334
+ catalog boundary alone makes two stages' `sales_silver` collision-
335
+ free. It exists for a provider whose catalog is *not* per-stage (AWS
336
+ Glue's shared default catalog, the only kind this account's Glue
337
+ service allows creating): there, two stages' otherwise-identical
338
+ database names would collide in the one shared catalog without it.
339
+ """
340
+ namespaces: list[CatalogNamespace] = []
341
+ products: list[PhysicalProductNames] = []
342
+ domains: list[PhysicalDomainNames] = []
343
+ for domain in self.domains:
344
+ physical_name = f"{namespace_prefix}{domain.silver_namespace}"
345
+ namespaces.append(CatalogNamespace(physical_name, f"s3://{silver_bucket}/{domain.silver_namespace}/"))
346
+ domains.append(
347
+ PhysicalDomainNames(
348
+ domain=domain.name,
349
+ silver_namespace=physical_name,
350
+ silver_schema_fqn=f"{catalog_database_fqn}.{physical_name}",
351
+ )
352
+ )
353
+ for product in self.products:
354
+ physical_name = f"{namespace_prefix}{product.gold_namespace}"
355
+ namespaces.append(CatalogNamespace(physical_name, f"s3://{gold_bucket}/{product.gold_namespace}/"))
356
+ products.append(
357
+ PhysicalProductNames(
358
+ product=product.name,
359
+ gold_namespace=physical_name,
360
+ gold_schema_fqn=f"{catalog_database_fqn}.{physical_name}",
361
+ )
362
+ )
363
+ return PhysicalInventory(catalog_namespaces=tuple(namespaces), products=tuple(products), domains=tuple(domains))
364
+
365
+
366
+ def _lakehouse_root(path: Path) -> Path:
367
+ candidate = path.resolve()
368
+ return candidate / "lakehouse_code" if (candidate / "lakehouse_code").is_dir() else candidate
369
+
370
+
371
+ def _source_table_names(source: Mapping[str, Any]) -> set[str]:
372
+ resources = source.get("resources")
373
+ if not isinstance(resources, list):
374
+ return set()
375
+ return {resource["name"] for resource in resources if isinstance(resource, Mapping) and "name" in resource}
376
+
377
+
378
+ def _product(path: Path, domain_name: str, product: Mapping[str, Any], index: int) -> Product:
379
+ label = product.get("id") or f"products[{index}]"
380
+ product_id = product.get("id")
381
+ if not isinstance(product_id, str) or not _IDENTIFIER_PATTERN.fullmatch(product_id):
382
+ raise LakehouseDescriptorError(f"{path}: product {label!r}: id must match '^[a-z][a-z0-9_]*$'")
383
+ display_name = product.get("displayName")
384
+ if not isinstance(display_name, str) or not display_name:
385
+ raise LakehouseDescriptorError(f"{path}: product {label!r}: displayName is required and must be a non-empty string")
386
+ return Product(domain_name=domain_name, id=product_id, display_name=display_name)
387
+
388
+
389
+ def _resource_load(load: Mapping[str, Any] | None) -> ResourceLoad:
390
+ if not load:
391
+ return ResourceLoad()
392
+ return ResourceLoad(mode=load["mode"], cursor=load.get("cursor"), primary_key=tuple(load.get("primary_key", ())))
393
+
394
+
395
+ def _read_floe_entities(lakehouse_root: Path, domain: str) -> tuple[FloeEntity, ...]:
396
+ entity_dir = lakehouse_root / "silver" / domain / "contracts" / "floe"
397
+ entities = []
398
+ for path in sorted(entity_dir.glob("*.yml")):
399
+ if path.name == "_domain.yml":
400
+ continue
401
+ document = yaml.safe_load(path.read_text(encoding="utf-8"))
402
+ try:
403
+ entities.append(
404
+ FloeEntity(domain, document["name"], document["source"]["ref"], document["source"]["resource"])
405
+ )
406
+ except (KeyError, TypeError) as exc:
407
+ raise LakehouseDescriptorError(f"{path}: entity must declare name and source.ref/resource") from exc
408
+ return tuple(entities)
409
+
410
+
411
+ def _validate_inventory_identities(
412
+ lakehouse_root: Path,
413
+ sources: tuple[Source, ...],
414
+ domains: tuple[Domain, ...],
415
+ dashboards: tuple[Dashboard, ...],
416
+ ) -> None:
417
+ seen_sources: set[str] = set()
418
+ for source in sources:
419
+ if source.name in seen_sources:
420
+ raise LakehouseDescriptorError(f"{source.descriptor_path}: duplicate source name {source.name!r}")
421
+ seen_sources.add(source.name)
422
+ seen_domains: set[str] = set()
423
+ seen_product_ids: set[str] = set()
424
+ for domain in domains:
425
+ if domain.name in seen_domains:
426
+ raise LakehouseDescriptorError(f"{domain.descriptor_path}: duplicate domain name {domain.name!r}")
427
+ seen_domains.add(domain.name)
428
+ for product in domain.products:
429
+ if product.id in seen_product_ids:
430
+ raise LakehouseDescriptorError(
431
+ f"{domain.descriptor_path}: product {product.id!r}: id must be globally unique across the lakehouse"
432
+ )
433
+ seen_product_ids.add(product.id)
434
+ seen_dashboards: set[str] = set()
435
+ for dashboard in dashboards:
436
+ if dashboard.name in seen_dashboards:
437
+ raise LakehouseDescriptorError(f"{lakehouse_root}: duplicate dashboard name {dashboard.name!r}")
438
+ seen_dashboards.add(dashboard.name)
439
+ unknown_products = sorted(set(dashboard.products) - seen_product_ids)
440
+ if unknown_products:
441
+ raise LakehouseDescriptorError(
442
+ f"{lakehouse_root}: dashboard {dashboard.name!r}: products {unknown_products!r} must reference declared products"
443
+ )
444
+
445
+
446
+ def load_source(source_path: str | Path) -> Source:
447
+ """Load and validate one `bronze/<source>/source.yaml`, without the rest of the inventory."""
448
+ document = load_source_descriptor(source_path)
449
+ name = document["name"]
450
+ if name != Path(source_path).parent.name:
451
+ raise LakehouseDescriptorError(
452
+ f"{source_path}: name {name!r} must match source directory {Path(source_path).parent.name!r}"
453
+ )
454
+ return Source(
455
+ descriptor_path=Path(source_path),
456
+ name=name,
457
+ display_name=document["displayName"],
458
+ resources=tuple(
459
+ Table(name=resource["name"], load=_resource_load(resource.get("load")))
460
+ for resource in document["resources"]
461
+ if isinstance(resource, Mapping) and "name" in resource
462
+ ),
463
+ runtime_config=tuple(document.get("runtime", {}).get("config", ())),
464
+ runtime_secrets=tuple(document.get("runtime", {}).get("secrets", ())),
465
+ )
466
+
467
+
468
+ def load_lakehouse_inventory_from_descriptors(
469
+ lakehouse_path: str | Path,
470
+ source_paths: Sequence[str | Path],
471
+ *,
472
+ source_label: str | Path | None = None,
473
+ allow_incomplete: bool = False,
474
+ ) -> LakehouseInventory:
475
+ """Load and validate one Lakehouse descriptor plus its Source descriptors."""
476
+ lakehouse_document = load_governance_lakehouse_document(lakehouse_path, allow_incomplete=allow_incomplete)
477
+ sources = [load_source(source_path) for source_path in source_paths]
478
+ declared_sources = set(lakehouse_document["sources"])
479
+ discovered_sources = {source.name for source in sources}
480
+ if declared_sources != discovered_sources:
481
+ raise LakehouseDescriptorError(
482
+ f"{lakehouse_path}: lakehouse sources {sorted(declared_sources)!r} must match discovered "
483
+ f"source descriptors {sorted(discovered_sources)!r} under lakehouse_code/bronze/*/source.yaml"
484
+ )
485
+ domains: list[Domain] = []
486
+ for index, domain in enumerate(lakehouse_document["domains"]):
487
+ if not isinstance(domain, Mapping):
488
+ raise LakehouseDescriptorError(f"{lakehouse_path}: domains[{index}] must be an object")
489
+ domain_name = domain["name"]
490
+ products = tuple(
491
+ _product(lakehouse_path, domain_name, product, product_index)
492
+ for product_index, product in enumerate(domain["products"])
493
+ if isinstance(product, Mapping)
494
+ )
495
+ domains.append(
496
+ Domain(
497
+ descriptor_path=Path(lakehouse_path),
498
+ name=domain_name,
499
+ display_name=domain["displayName"],
500
+ products=products,
501
+ )
502
+ )
503
+ dashboards = tuple(
504
+ Dashboard(
505
+ name=dashboard["name"],
506
+ products=tuple(dashboard["products"]),
507
+ )
508
+ for dashboard in lakehouse_document["dashboards"]
509
+ if isinstance(dashboard, Mapping)
510
+ )
511
+ inventory = LakehouseInventory(
512
+ lakehouse_root=Path(source_label) if source_label is not None else Path(lakehouse_path).parent,
513
+ name=lakehouse_document["name"],
514
+ sources=tuple(sources),
515
+ domains=tuple(domains),
516
+ dashboards=dashboards,
517
+ )
518
+ _validate_inventory_identities(inventory.lakehouse_root, inventory.sources, inventory.domains, inventory.dashboards)
519
+ return inventory
520
+
521
+
522
+ def load_lakehouse_inventory(path: str | Path, *, allow_incomplete: bool = False) -> LakehouseInventory:
523
+ """Load and validate ``lakehouse_code/governance.yml`` plus every source."""
524
+ lakehouse_root = _lakehouse_root(Path(path))
525
+ lakehouse_descriptor = lakehouse_root / "governance.yml"
526
+ if not lakehouse_descriptor.is_file() and not allow_incomplete:
527
+ raise LakehouseDescriptorError(f"{lakehouse_root}: no governance.yml found")
528
+ source_descriptors = sorted(lakehouse_root.glob("bronze/*/source.yaml"))
529
+ if not source_descriptors and not allow_incomplete:
530
+ raise LakehouseDescriptorError(f"{lakehouse_root}: no source descriptors found at bronze/*/source.yaml")
531
+ return load_lakehouse_inventory_from_descriptors(
532
+ lakehouse_descriptor, source_descriptors, source_label=lakehouse_root, allow_incomplete=allow_incomplete
533
+ )
534
+
535
+
536
+ def load_transitional_lakehouse_inventory(path: str | Path) -> LakehouseInventory:
537
+ """Load an `olf init --empty` project while it has no runnable product.
538
+
539
+ This is intentionally limited to scaffold planning. Deployment and
540
+ ordinary descriptor validation retain the strict descriptor contract.
541
+ """
542
+ return load_lakehouse_inventory(path, allow_incomplete=True)
543
+
544
+
545
+ @cache
546
+ def _cached_lakehouse_inventory(resolved_path: str) -> LakehouseInventory:
547
+ return load_lakehouse_inventory(resolved_path)
548
+
549
+
550
+ def inventory_for(repo_root: str | Path) -> LakehouseInventory:
551
+ """Load and cache the canonical lakehouse inventory for a repository root."""
552
+ return _cached_lakehouse_inventory(str(Path(repo_root).resolve()))
553
+
File without changes
@@ -0,0 +1,47 @@
1
+ """The run-launch contract `olf` and the project-code runtime share."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # A Dagster run tag rather than run config: a tag reaches every asset of the
6
+ # job (Bronze, Floe's own Silver assets, dbt) without each one declaring a
7
+ # config schema, and the launchpad and `olf infra product run` set it the same way.
8
+ FULL_REFRESH_TAG = "openlakeforge/full_refresh"
9
+
10
+ # `bronze` re-ingests from Bronze: Silver is rebuilt from every Bronze file
11
+ # already landed, then Gold from Silver. Nothing is extracted again, so the
12
+ # sources and their cursors are untouched. `gold` rebuilds Gold alone and
13
+ # leaves Silver as it is.
14
+ FULL_REFRESH_SCOPES = ("bronze", "gold")
15
+
16
+ # dagster-floe's own tag (0.5.0): it runs the job's Floe entities with
17
+ # `floe run --full-refresh`, which reads every input rather than the pending
18
+ # ones. A `bronze` refresh must carry it, or Silver would not be rebuilt.
19
+ FLOE_FULL_REFRESH_TAG = "floe/full_refresh"
20
+
21
+
22
+ def full_refresh_tags(scope: str) -> dict[str, str]:
23
+ """The run tags that ask one run for a full refresh of `scope`."""
24
+ if scope not in FULL_REFRESH_SCOPES:
25
+ raise ValueError(f"full refresh scope {scope!r} must be one of {list(FULL_REFRESH_SCOPES)!r}")
26
+ tags = {FULL_REFRESH_TAG: scope}
27
+ if scope == "bronze":
28
+ tags[FLOE_FULL_REFRESH_TAG] = "true"
29
+ return tags
30
+
31
+
32
+ def full_refresh_scope(tags: dict[str, str] | None) -> str | None:
33
+ """The full-refresh scope a run's tags ask for, or None for an incremental run."""
34
+ tags = tags or {}
35
+ scope = tags.get(FULL_REFRESH_TAG)
36
+ if scope is None:
37
+ return None
38
+ if scope not in FULL_REFRESH_SCOPES:
39
+ raise ValueError(f"run tag {FULL_REFRESH_TAG}={scope!r} must be one of {list(FULL_REFRESH_SCOPES)!r}")
40
+ # Checked before Bronze drops anything, so a run launched with only one of
41
+ # the two tags fails instead of leaving Silver unrebuilt.
42
+ if scope == "bronze" and tags.get(FLOE_FULL_REFRESH_TAG) != "true":
43
+ raise ValueError(
44
+ f"run tag {FULL_REFRESH_TAG}=bronze needs {FLOE_FULL_REFRESH_TAG}=true too, so Floe rebuilds Silver; "
45
+ "`olf infra product run --full-refresh bronze` sets both"
46
+ )
47
+ return scope
@@ -0,0 +1,6 @@
1
+ Metadata-Version: 2.4
2
+ Name: openlakeforge-core
3
+ Version: 0.5.1a3
4
+ Summary: Canonical provider-neutral domain model for OpenLakeForge
5
+ Requires-Python: >=3.12
6
+ Requires-Dist: PyYAML<7,>=6.0
@@ -0,0 +1,10 @@
1
+ openlakeforge_core/__init__.py,sha256=-GzmEGdPOFdyqWbPZ25LR2M3EmV3GNd_DWu_kxiW-Yw,1929
2
+ openlakeforge_core/descriptors.py,sha256=iwpFa9KepF33KrAav-Y74OREayj-xuSd6BbyRDC-mdM,9204
3
+ openlakeforge_core/governance.py,sha256=QnilU4Xx93PT5SDp4sDEGfkU6e_6XljukH4VI7kS6Hk,6822
4
+ openlakeforge_core/inventory.py,sha256=h0k22rAQQcn6aK4PrVSCl-QL1joW7akNtDlnabRI5Yk,20419
5
+ openlakeforge_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ openlakeforge_core/runs.py,sha256=ktGZxAwLOQHfJWYDxjwBE_kaj0AheTERqwYVA72o9mA,2210
7
+ openlakeforge_core-0.5.1a3.dist-info/METADATA,sha256=AQkR1TVCNLqolkD8xS8GZpiCKyXIKHbACqI30OtsLpE,185
8
+ openlakeforge_core-0.5.1a3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ openlakeforge_core-0.5.1a3.dist-info/top_level.txt,sha256=ACAw0HJqOFo1NvdPkLbmeDexCSqFRe4QzW6v7iHxEQg,19
10
+ openlakeforge_core-0.5.1a3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ openlakeforge_core