openlakeforge-runtime 0.5.1a3__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.
Files changed (27) hide show
  1. openlakeforge_runtime-0.5.1a3/PKG-INFO +6 -0
  2. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/__init__.py +13 -0
  3. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/bronze_csv.py +96 -0
  4. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/bronze_dlt.py +138 -0
  5. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/bronze_incremental.py +125 -0
  6. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/dbt/__init__.py +1 -0
  7. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/dbt/openlakeforge_dbt/dbt_project.yml +5 -0
  8. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/dbt/openlakeforge_dbt/macros/generate_schema_name.sql +7 -0
  9. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/dbt/profiles/trino.yml +28 -0
  10. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/dbt/render_profiles.py +180 -0
  11. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/duckdb_extensions.py +107 -0
  12. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/floe_profile.py +247 -0
  13. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/gold_maintenance.py +125 -0
  14. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/k8s_log_archive.py +107 -0
  15. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/openlakeforge_logging.py +22 -0
  16. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/polaris_token.py +49 -0
  17. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/product_dagster.py +538 -0
  18. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/py.typed +0 -0
  19. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/s3_artifacts.py +62 -0
  20. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime/source_bindings.py +52 -0
  21. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime.egg-info/PKG-INFO +6 -0
  22. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime.egg-info/SOURCES.txt +25 -0
  23. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime.egg-info/dependency_links.txt +1 -0
  24. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime.egg-info/requires.txt +1 -0
  25. openlakeforge_runtime-0.5.1a3/openlakeforge_runtime.egg-info/top_level.txt +1 -0
  26. openlakeforge_runtime-0.5.1a3/pyproject.toml +18 -0
  27. openlakeforge_runtime-0.5.1a3/setup.cfg +4 -0
@@ -0,0 +1,6 @@
1
+ Metadata-Version: 2.4
2
+ Name: openlakeforge-runtime
3
+ Version: 0.5.1a3
4
+ Summary: OpenLakeForge project-code runtime: Dagster, dlt, dbt and Floe glue imported by lakehouse code
5
+ Requires-Python: >=3.12
6
+ Requires-Dist: openlakeforge-core==0.5.1a3
@@ -0,0 +1,13 @@
1
+ """OpenLakeForge project-code runtime.
2
+
3
+ Customer code imports only the modules in `PUBLIC_MODULES`, and from each only
4
+ the names in its `__all__`. Every other module and name is private and may
5
+ change in any release. `docs/reference/runtime-api.md` states the promise.
6
+ """
7
+
8
+ PUBLIC_MODULES = (
9
+ "openlakeforge_runtime.bronze_csv",
10
+ "openlakeforge_runtime.bronze_dlt",
11
+ "openlakeforge_runtime.bronze_incremental",
12
+ "openlakeforge_runtime.product_dagster",
13
+ )
@@ -0,0 +1,96 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import os
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ import boto3
9
+ from botocore.client import Config
10
+
11
+ __all__ = [
12
+ "BronzeLoadResult",
13
+ "load_entities_to_bronze",
14
+ "load_entity_to_bronze",
15
+ ]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class BronzeLoadResult:
20
+ entity: str
21
+ rows: int
22
+ uri: str
23
+ source_file: str
24
+
25
+
26
+ def load_entities_to_bronze(
27
+ *,
28
+ entities: tuple[str, ...],
29
+ raw_dir: Path,
30
+ bronze_prefix: str,
31
+ ) -> dict[str, BronzeLoadResult]:
32
+ return {
33
+ entity: load_entity_to_bronze(
34
+ entity=entity,
35
+ raw_dir=raw_dir,
36
+ bronze_prefix=bronze_prefix,
37
+ allowed_entities=entities,
38
+ )
39
+ for entity in entities
40
+ }
41
+
42
+
43
+ def load_entity_to_bronze(
44
+ *,
45
+ entity: str,
46
+ raw_dir: Path,
47
+ bronze_prefix: str,
48
+ allowed_entities: tuple[str, ...],
49
+ ) -> BronzeLoadResult:
50
+ if entity not in allowed_entities:
51
+ raise ValueError(f"unsupported entity for Bronze load: {entity}")
52
+
53
+ source_file = raw_dir / f"{entity}.csv"
54
+ rows = _count_data_rows(source_file)
55
+ if not rows:
56
+ raise ValueError(f"{source_file} did not produce any rows")
57
+
58
+ bucket = _required_env("OPENLAKEFORGE_STORAGE_BRONZE_BUCKET")
59
+ key = f"{bronze_prefix}/{entity}/{entity}.csv"
60
+ # upload_file streams in managed multipart chunks, so memory stays flat
61
+ # whatever the file size.
62
+ _s3_client().upload_file(str(source_file), bucket, key, ExtraArgs={"ContentType": "text/csv"})
63
+
64
+ return BronzeLoadResult(
65
+ entity=entity,
66
+ rows=rows,
67
+ uri=f"s3://{bucket}/{key}",
68
+ source_file=str(source_file),
69
+ )
70
+
71
+
72
+ def _count_data_rows(source_file: Path) -> int:
73
+ # The csv module, not line counting: quoted fields may contain newlines.
74
+ # Blank lines are skipped and the header is excluded, as csv.DictReader did.
75
+ with source_file.open(newline="", encoding="utf-8") as handle:
76
+ records = sum(1 for row in csv.reader(handle) if row)
77
+ return max(records - 1, 0)
78
+
79
+
80
+ def _s3_client():
81
+ region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or "us-east-1"
82
+ endpoint_url = os.environ.get("AWS_ENDPOINT_URL_S3")
83
+ force_path_style = os.environ.get("AWS_S3_FORCE_PATH_STYLE", "true").lower() == "true"
84
+ return boto3.client(
85
+ "s3",
86
+ endpoint_url=endpoint_url,
87
+ region_name=region,
88
+ config=Config(s3={"addressing_style": "path" if force_path_style else "virtual"}),
89
+ )
90
+
91
+
92
+ def _required_env(name: str, *, default: str | None = None) -> str:
93
+ value = os.environ.get(name, default)
94
+ if not value:
95
+ raise RuntimeError(f"required environment variable {name} is not set")
96
+ return value
@@ -0,0 +1,138 @@
1
+ """A dlt pipeline that loads one source into the stage's own Bronze bucket.
2
+
3
+ For sources that are real dlt sources (an API, a database) rather than the
4
+ CSV fixtures `openlakeforge_runtime.bronze_csv` uploads. dlt keeps a pipeline's incremental
5
+ state in its destination, so state lives in the stage's own bucket under a
6
+ stage-named pipeline: a DEV run can never move PROD's cursor (#546). The
7
+ working directory is fresh on every run; the state is restored from the
8
+ bucket, not from a pod's disk.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import inspect
14
+ import os
15
+ import tempfile
16
+ from collections.abc import Mapping, Sequence
17
+ from importlib import import_module
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import dlt
22
+ from openlakeforge_core import load_source
23
+
24
+ from openlakeforge_runtime.bronze_csv import BronzeLoadResult
25
+
26
+ __all__ = ["load_dlt_source"]
27
+
28
+
29
+ def _declared_cursor(resource: Any) -> str | None:
30
+ wrapper = resource.incremental
31
+ if wrapper is None:
32
+ return None
33
+ if wrapper.incremental is not None:
34
+ return wrapper.incremental.cursor_path
35
+ # dlt binds a cursor declared as the resource function's default argument,
36
+ # its usual idiom, only when the resource runs; before that the signature
37
+ # is the only place it is visible.
38
+ argument = wrapper.get_incremental_arg(inspect.signature(resource._pipe.gen))
39
+ return argument.default.cursor_path if argument is not None else None
40
+
41
+
42
+ def bronze_pipeline(
43
+ source: str, *, environ: Mapping[str, str] | None = None, bucket_url: str | None = None
44
+ ) -> Any:
45
+ """The source's pipeline; files land at `<bucket>/<source>/<resource>/`, where Floe reads Bronze.
46
+
47
+ `bucket_url` replaces the stage's bucket, for a run against another
48
+ filesystem; the stage still names the pipeline and so its state.
49
+ """
50
+ env = os.environ if environ is None else environ
51
+
52
+ def required(name: str) -> str:
53
+ value = env.get(name, "").strip()
54
+ if not value:
55
+ raise RuntimeError(f"{name} is not set; the stage activation must provide it for Bronze loads.")
56
+ return value
57
+
58
+ stage = required("OPENLAKEFORGE_STAGE")
59
+ destination = bucket_url or f"s3://{required('OPENLAKEFORGE_STORAGE_BRONZE_BUCKET')}"
60
+ # Only what the stage sets: unset keys leave dlt on the pod's default AWS
61
+ # credential chain, which is how a cloud workload identity is picked up.
62
+ credentials = {
63
+ field: value
64
+ for field, name in (
65
+ ("endpoint_url", "AWS_ENDPOINT_URL_S3"),
66
+ ("region_name", "OPENLAKEFORGE_STORAGE_REGION"),
67
+ ("aws_access_key_id", "AWS_ACCESS_KEY_ID"),
68
+ ("aws_secret_access_key", "AWS_SECRET_ACCESS_KEY"),
69
+ )
70
+ if (value := env.get(name, "").strip())
71
+ }
72
+ # dlt's default layout, `<resource>/<load_id>.<file_id>.<ext>`, sorts batches
73
+ # oldest first. Floe orders pending files by URI and, for a key that repeats
74
+ # across them, merges the latest file's row, so a layout must keep that order.
75
+ return dlt.pipeline(
76
+ pipeline_name=f"{stage}__{source}",
77
+ pipelines_dir=tempfile.mkdtemp(prefix=f"olf-dlt-{source}-"),
78
+ destination=dlt.destinations.filesystem(
79
+ bucket_url=destination,
80
+ credentials=credentials if destination.startswith("s3://") else None,
81
+ ),
82
+ dataset_name=source,
83
+ )
84
+
85
+
86
+ def load_dlt_source(
87
+ source: str,
88
+ dlt_source: Any,
89
+ resources: Sequence[str],
90
+ *,
91
+ environ: Mapping[str, str] | None = None,
92
+ bucket_url: str | None = None,
93
+ lakehouse_root: Path | None = None,
94
+ ) -> dict[str, BronzeLoadResult]:
95
+ """Load `resources` of `dlt_source` into Bronze as `source.yaml` declares them.
96
+
97
+ A `full` resource replaces its Bronze files on every run. An `incremental`
98
+ one appends the rows past its cursor's last value as new files; the
99
+ connector declares the cursor with `dlt.sources.incremental`, on the column
100
+ the descriptor names. Nothing here drops Bronze: a full refresh rebuilds
101
+ Silver and Gold from the batches already landed, so the cursor and every
102
+ file survive it.
103
+
104
+ The loader contract is `load_<source>_entities_to_bronze(resources)`.
105
+ """
106
+ # The project imported as `lakehouse_code`: beside openlakeforge_runtime/ in the image, but a
107
+ # separate root when olf checks a customer project against the distribution.
108
+ root = lakehouse_root or Path(import_module("lakehouse_code").__file__).resolve().parent
109
+ declared = load_source(root / "bronze" / source / "source.yaml")
110
+ selected = dlt_source.with_resources(*resources)
111
+ for name in resources:
112
+ load = declared.load_of(name)
113
+ resource = selected.resources[name]
114
+ if not load.incremental:
115
+ resource.apply_hints(write_disposition="replace")
116
+ continue
117
+ cursor = _declared_cursor(resource)
118
+ if cursor != load.cursor:
119
+ raise RuntimeError(
120
+ f"{source}/{name} is incremental on {load.cursor!r} in source.yaml, but the connector's "
121
+ f"dlt.sources.incremental cursor is {cursor!r}"
122
+ )
123
+ resource.apply_hints(write_disposition="append", primary_key=list(load.primary_key))
124
+
125
+ pipeline = bronze_pipeline(source, environ=environ, bucket_url=bucket_url)
126
+ info = pipeline.run(selected, loader_file_format="parquet")
127
+ row_counts = pipeline.last_trace.last_normalize_info.row_counts
128
+ destination = pipeline.destination_client().config.bucket_url.rstrip("/")
129
+ load_id = info.loads_ids[-1] if info.loads_ids else "none"
130
+ return {
131
+ name: BronzeLoadResult(
132
+ entity=name,
133
+ rows=row_counts.get(name, 0),
134
+ uri=f"{destination}/{source}/{name}/",
135
+ source_file=f"{pipeline.pipeline_name} load {load_id}",
136
+ )
137
+ for name in resources
138
+ }
@@ -0,0 +1,125 @@
1
+ """Building blocks for incremental dlt connectors (#342).
2
+
3
+ A connector reads its source, and `openlakeforge_runtime.bronze_dlt.load_dlt_source` lands
4
+ what it reads in Bronze as `source.yaml` declares. These helpers cover the two
5
+ read patterns most sources fit, so a connector keeps only what is specific to
6
+ its source: the request or query, and the row shape.
7
+
8
+ - `newest_first_pages`: an API that can sort by modification time but not
9
+ filter on it. Read newest first, stop at the cursor.
10
+ - `keyset_batches`: a SQL table with a monotonically increasing key. Read past
11
+ the cursor in key order, a bounded number of rows a run.
12
+ - `sql_engine`: a SQLAlchemy engine from a source's stage bindings.
13
+
14
+ Each takes the resource's `dlt.sources.incremental` argument as `cursor`; the
15
+ connector still declares it, on the column `source.yaml` names, because
16
+ `load_dlt_source` checks the two match.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import time
22
+ from collections.abc import Callable, Iterator, Mapping, Sequence
23
+ from typing import Any
24
+
25
+ __all__ = ["CursorNotReached", "keyset_batches", "newest_first_pages", "sql_engine"]
26
+
27
+
28
+ class CursorNotReached(RuntimeError):
29
+ """The page budget ran out before the source reached the cursor."""
30
+
31
+
32
+ def _has_cursor(cursor: Any) -> bool:
33
+ # dlt starts a resource that has never loaded, or whose state a reload
34
+ # dropped, from its declared initial value.
35
+ return cursor.start_value != cursor.initial_value
36
+
37
+
38
+ def newest_first_pages(
39
+ fetch_page: Callable[[int], Sequence[Mapping[str, Any]]],
40
+ cursor: Any,
41
+ *,
42
+ cursor_field: str,
43
+ key: str,
44
+ page_size: int,
45
+ max_pages: int,
46
+ interval_seconds: float = 0.0,
47
+ sleep: Callable[[float], None] = time.sleep,
48
+ ) -> Iterator[list[Mapping[str, Any]]]:
49
+ """Pages of items, newest first, until the first item at or before the cursor.
50
+
51
+ `fetch_page(n)` returns page `n` (from 1) of items sorted by `cursor_field`,
52
+ newest first, at most `page_size` of them. An item modified while paging
53
+ moves to page 1 and pushes the rest down, so it can come back on a later
54
+ page: only its first, newer, read is yielded (`key` identifies it).
55
+
56
+ The page budget is `max_pages`, with `interval_seconds` between requests
57
+ for an API's rate limit. With a cursor, running out of budget before
58
+ reaching it raises `CursorNotReached`: stopping would move the cursor past
59
+ items never read. With no cursor yet, the budget's pages are the backfill
60
+ and the generator stops there, so a first run loads the newest items even
61
+ when nothing changed recently.
62
+ """
63
+ seen: set[Any] = set()
64
+ for page in range(1, max_pages + 1):
65
+ if page > 1 and interval_seconds:
66
+ sleep(interval_seconds)
67
+ items = fetch_page(page)
68
+ fresh = [item for item in items if item[key] not in seen]
69
+ seen.update(item[key] for item in fresh)
70
+ if fresh:
71
+ yield fresh
72
+ if len(items) < page_size or (items and items[-1][cursor_field] <= cursor.start_value):
73
+ return
74
+ if _has_cursor(cursor):
75
+ raise CursorNotReached(
76
+ f"{max_pages} pages of {page_size} did not reach the cursor {cursor_field}={cursor.start_value}; "
77
+ "raise the page budget or narrow the query"
78
+ )
79
+
80
+
81
+ def keyset_batches(
82
+ connection: Any,
83
+ query: Any,
84
+ cursor: Any,
85
+ *,
86
+ cursor_field: str,
87
+ batch_size: int,
88
+ max_rows: int,
89
+ params: Mapping[str, Any] | None = None,
90
+ ) -> Iterator[list[dict[str, Any]]]:
91
+ """Rows past the cursor in `cursor_field` order, in batches, at most `max_rows` a run.
92
+
93
+ `query` is a SQLAlchemy statement with the bind parameters `:last` and
94
+ `:limit`, of the form `... where <cursor_field> > :last order by
95
+ <cursor_field> limit :limit`; `params` adds the query's own. A run reads up
96
+ to `max_rows`, so a large table backfills one slice per run, and dlt saves
97
+ the cursor only once a batch is loaded, so a killed run resumes from the
98
+ last loaded key.
99
+ """
100
+ last, loaded = cursor.start_value, 0
101
+ while loaded < max_rows:
102
+ limit = min(batch_size, max_rows - loaded)
103
+ result = connection.execute(query, {**(params or {}), "last": last, "limit": limit})
104
+ rows = [dict(row) for row in result.mappings()]
105
+ if not rows:
106
+ return
107
+ yield rows
108
+ last, loaded = rows[-1][cursor_field], loaded + len(rows)
109
+ if len(rows) < limit:
110
+ return
111
+
112
+
113
+ def sql_engine(drivername: str, binding: Mapping[str, Any], *, connect_args: Mapping[str, Any] | None = None) -> Any:
114
+ """A SQLAlchemy engine for a database source from its bound `host`, `port`, `database`, `username`, `password`.
115
+
116
+ `binding` holds the source's `runtime.config` and `runtime.secrets` values,
117
+ as dlt resolved them; keys outside those five are ignored, and absent ones
118
+ are left out of the URL. `connect_args` goes to the driver as is, e.g.
119
+ `{"connect_timeout": 30}` for psycopg2.
120
+ """
121
+ import sqlalchemy as sa
122
+
123
+ keys = ("host", "port", "database", "username", "password")
124
+ url = sa.URL.create(drivername, **{name: binding[name] for name in keys if name in binding})
125
+ return sa.create_engine(url, connect_args=dict(connect_args or {}))
@@ -0,0 +1 @@
1
+ """Shared dbt runtime helpers and profile templates for OpenLakeForge."""
@@ -0,0 +1,5 @@
1
+ name: openlakeforge_dbt
2
+ version: "1.0.0"
3
+ config-version: 2
4
+
5
+ macro-paths: ["macros"]
@@ -0,0 +1,7 @@
1
+ {% macro generate_schema_name(custom_schema_name, node) -%}
2
+ {%- if custom_schema_name is none -%}
3
+ {{ target.schema }}
4
+ {%- else -%}
5
+ {{ custom_schema_name | trim }}
6
+ {%- endif -%}
7
+ {%- endmacro %}
@@ -0,0 +1,28 @@
1
+ {{PROFILE_NAME}}:
2
+ target: runtime
3
+ outputs:
4
+ runtime:
5
+ type: trino
6
+ method: "{{ env_var('OPENLAKEFORGE_DBT_TRINO_METHOD', 'none') }}"
7
+ host: "{{ env_var('OPENLAKEFORGE_QUERY_TRINO_HOST') }}"
8
+ port: "{{ (env_var('OPENLAKEFORGE_QUERY_TRINO_TLS_PORT') if env_var('OPENLAKEFORGE_QUERY_TRINO_HTTP_SCHEME', 'http') == 'https' else env_var('OPENLAKEFORGE_QUERY_TRINO_PORT')) | int }}"
9
+ user: "{{ env_var('OPENLAKEFORGE_DBT_TRINO_USER') }}"
10
+ password: "{{ env_var('OPENLAKEFORGE_DBT_TRINO_PASSWORD', '') or none }}"
11
+ http_scheme: "{{ env_var('OPENLAKEFORGE_QUERY_TRINO_HTTP_SCHEME', 'http') }}"
12
+ cert: "{{ env_var('OPENLAKEFORGE_QUERY_TRINO_CA', '') or none }}"
13
+ database: "{{ env_var('OPENLAKEFORGE_CATALOG_NAME') }}"
14
+ schema: "{{ env_var('OPENLAKEFORGE_CATALOG_SCHEMA_PREFIX', '') }}{{GOLD_SCHEMA}}"
15
+ # One model at a time unless the stage says otherwise. Slim's Trino has a 2G heap whose usable 70% (1.4G)
16
+ # is smaller than two queries at the 1GB query.max-memory-per-node cap, and a single 41M-row Gold
17
+ # rebuild already OOM-killed its coordinator (#755); see release/query-sizes.yaml. Raising it trades
18
+ # concurrent query memory for wall time, so it is set per stage once a benchmark shows the Trino fits.
19
+ threads: "{{ env_var('OPENLAKEFORGE_DBT_THREADS', '1') | int }}"
20
+ # The stage's Polaris token for a keyless catalog (#967); a keyed catalog ignores it, and it
21
+ # is empty where the catalog has no token endpoint.
22
+ http_headers:
23
+ X-Trino-Extra-Credential: "token={{ env_var('OPENLAKEFORGE_POLARIS_TOKEN', '') }}"
24
+ # A Gold query reads about two stages per table, and Trino's default of
25
+ # 150 refused a 75-table union (#706). Matches max_stage_count in
26
+ # release/query-sizes.yaml; a lower server value still wins.
27
+ session_properties:
28
+ query_max_stage_count: 300
@@ -0,0 +1,180 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ import re
6
+ import subprocess
7
+ from collections.abc import Iterable
8
+ from pathlib import Path
9
+
10
+ # The project root is an input, never derived from where this module is installed.
11
+ PROJECT_ROOT_ENV = "OPENLAKEFORGE_PROJECT_ROOT"
12
+ PROFILE_TEMPLATE_DIR = Path(__file__).resolve().parent / "profiles"
13
+ # Where the image bakes the profile and the code location reads it: outside
14
+ # lakehouse_code/, so it never enters a project revision (#546).
15
+ BAKED_PROFILES_SUBDIR = Path("generated") / "dbt-profiles"
16
+ # A check of a customer project renders that project's profiles elsewhere:
17
+ # the distribution's baked file names only the products it was built with.
18
+ PROFILES_DIR_ENV = "OPENLAKEFORGE_DBT_PROFILES_DIR"
19
+ # Each product's packages.yml names the shared openlakeforge_dbt package
20
+ # through this variable, because a path relative to the product cannot name
21
+ # the installed distribution from a customer repository (#627). Every dbt
22
+ # command renders packages.yml, so whatever runs dbt sets it to this
23
+ # distribution's own.
24
+ PACKAGES_DIR_ENV = "OPENLAKEFORGE_DBT_PACKAGES_DIR"
25
+ DBT_PACKAGES_DIR = Path(__file__).resolve().parent
26
+ # A template per query engine. Trino is the only one; a second engine (#547)
27
+ # adds a template here, while the stage values stay env_var() references.
28
+ DEFAULT_ADAPTER = "trino"
29
+
30
+ # The bake parse never connects, but the profile reads these with no
31
+ # default, so it needs values. They are deliberately no stage's: the image
32
+ # serves every stage, and each run re-parses with its pod's own values
33
+ # (dagster-dbt gives every invocation a fresh target path).
34
+ PARSE_PLACEHOLDERS = {
35
+ "OPENLAKEFORGE_QUERY_TRINO_HOST": "stage-query-host",
36
+ "OPENLAKEFORGE_QUERY_TRINO_PORT": "8080",
37
+ "OPENLAKEFORGE_DBT_TRINO_USER": "stage-query-user",
38
+ "OPENLAKEFORGE_CATALOG_NAME": "stage_catalog",
39
+ "OPENLAKEFORGE_CATALOG_SCHEMA_PREFIX": "",
40
+ }
41
+
42
+
43
+ def project_root() -> Path:
44
+ """The directory holding `lakehouse_code/`: `OPENLAKEFORGE_PROJECT_ROOT`, else the working directory."""
45
+ return Path(os.environ.get(PROJECT_ROOT_ENV) or Path.cwd())
46
+
47
+
48
+ def baked_profiles_dir() -> Path:
49
+ return project_root() / BAKED_PROFILES_SUBDIR
50
+
51
+
52
+ def resolve_profiles_dir() -> Path:
53
+ return Path(os.environ.get(PROFILES_DIR_ENV) or baked_profiles_dir())
54
+
55
+
56
+ def dbt_environment() -> dict[str, str]:
57
+ """The variables a dbt invocation needs to resolve the distribution's package."""
58
+ return {PACKAGES_DIR_ENV: str(DBT_PACKAGES_DIR)}
59
+
60
+
61
+ def discover_project_dirs(gold_root: Path) -> list[Path]:
62
+ return sorted(path.parent for path in gold_root.glob("*/dbt/dbt_project.yml"))
63
+
64
+
65
+ def profile_name(project_dir: Path) -> str:
66
+ dbt_project = project_dir / "dbt_project.yml"
67
+ name = _read_dbt_project_field(dbt_project, "profile") or _read_dbt_project_field(dbt_project, "name")
68
+ if not name:
69
+ raise ValueError(f"Cannot determine dbt profile name from {dbt_project}")
70
+ return name
71
+
72
+
73
+ def render_profile(project_dir: Path, adapter: str = DEFAULT_ADAPTER) -> str:
74
+ project_dir = project_dir.resolve()
75
+ template_path = PROFILE_TEMPLATE_DIR / f"{adapter}.yml"
76
+ if not template_path.is_file():
77
+ supported = ", ".join(sorted(path.stem for path in PROFILE_TEMPLATE_DIR.glob("*.yml")))
78
+ raise ValueError(f"Unsupported dbt adapter {adapter!r}. Supported: {supported}.")
79
+
80
+ replacements = {
81
+ "{{PROFILE_NAME}}": profile_name(project_dir),
82
+ "{{GOLD_SCHEMA}}": f"{project_dir.parent.name}_gold",
83
+ }
84
+ rendered = template_path.read_text(encoding="utf-8")
85
+ for placeholder, value in replacements.items():
86
+ rendered = rendered.replace(placeholder, value)
87
+ return rendered
88
+
89
+
90
+ def write_profiles(project_dirs: Iterable[Path], output_dir: Path, adapter: str = DEFAULT_ADAPTER) -> Path:
91
+ """Write one profiles.yml holding every product's profile."""
92
+ project_dirs = list(project_dirs)
93
+ # Each product's profile carries its own Gold schema. In one shared file a
94
+ # repeated name would be a duplicate YAML key, and the last product's
95
+ # schema would silently win for both.
96
+ names = [profile_name(project_dir) for project_dir in project_dirs]
97
+ shared = sorted({name for name in names if names.count(name) > 1})
98
+ if shared:
99
+ raise ValueError(f"dbt products must use distinct profile names; shared: {', '.join(shared)}")
100
+ output_dir.mkdir(parents=True, exist_ok=True)
101
+ profile_path = output_dir / "profiles.yml"
102
+ profile_path.write_text(
103
+ "".join(render_profile(project_dir, adapter=adapter) for project_dir in project_dirs), encoding="utf-8"
104
+ )
105
+ return profile_path
106
+
107
+
108
+ def write_profile(project_dir: Path, output_dir: Path, adapter: str = DEFAULT_ADAPTER) -> Path:
109
+ return write_profiles([project_dir], output_dir, adapter=adapter)
110
+
111
+
112
+ def bake_manifest(project_dir: Path, profiles_dir: Path, dbt: str = "dbt") -> Path:
113
+ """Parse a stage-neutral manifest into the project's target/."""
114
+ env = {**dbt_environment(), **os.environ, **PARSE_PLACEHOLDERS}
115
+ subprocess.run([dbt, "deps", "--project-dir", str(project_dir)], check=True, env=env)
116
+ subprocess.run(
117
+ [dbt, "parse", "--project-dir", str(project_dir), "--profiles-dir", str(profiles_dir), "--no-partial-parse"],
118
+ check=True,
119
+ env=env,
120
+ )
121
+ # dagster-dbt seeds each run's target path with this file, and a partial
122
+ # parse could keep placeholder relations; without it every run parses
123
+ # in full with its own stage's values. --no-partial-parse above likewise
124
+ # keeps a target/ copied in from a workstation from steering the bake.
125
+ (project_dir / "target" / "partial_parse.msgpack").unlink(missing_ok=True)
126
+ return project_dir / "target" / "manifest.json"
127
+
128
+
129
+ def ensure_baked_manifest(project_dir: Path, profiles_dir: Path | None = None) -> Path:
130
+ """Return the image's manifest, baking one where none was (a checkout).
131
+
132
+ The profile is ensured either way: runs read it from `profiles_dir`, and a
133
+ checkout can hold a manifest from `olf check dbt` without one.
134
+ """
135
+ profiles_dir = profiles_dir or resolve_profiles_dir()
136
+ if not (profiles_dir / "profiles.yml").is_file():
137
+ write_profiles(discover_project_dirs(project_dir.parents[1]), profiles_dir)
138
+ manifest_path = project_dir / "target" / "manifest.json"
139
+ if manifest_path.is_file():
140
+ return manifest_path
141
+ return bake_manifest(project_dir, profiles_dir)
142
+
143
+
144
+ def _read_dbt_project_field(path: Path, field: str) -> str | None:
145
+ pattern = re.compile(rf"^\s*{re.escape(field)}\s*:\s*[\"']?([^\"'#]+)[\"']?\s*(?:#.*)?$")
146
+ for line in path.read_text(encoding="utf-8").splitlines():
147
+ match = pattern.match(line)
148
+ if match:
149
+ return match.group(1).strip()
150
+ return None
151
+
152
+
153
+ def main() -> None:
154
+ parser = argparse.ArgumentParser(description="Render the OpenLakeForge dbt profiles and bake product manifests.")
155
+ parser.add_argument("--adapter", default=DEFAULT_ADAPTER)
156
+ parser.add_argument("--project-dir", action="append", type=Path, default=[])
157
+ parser.add_argument("--root", type=Path, help=f"Project root; default ${PROJECT_ROOT_ENV}, else the working dir.")
158
+ parser.add_argument("--output-dir", type=Path)
159
+ parser.add_argument("--bake", action="store_true", help="Also resolve and parse each project's manifest.")
160
+ args = parser.parse_args()
161
+
162
+ root = args.root.resolve() if args.root else project_root()
163
+ output_dir = args.output_dir or root / BAKED_PROFILES_SUBDIR
164
+ project_dirs = (
165
+ [path.resolve() for path in args.project_dir]
166
+ if args.project_dir
167
+ else discover_project_dirs(root / "lakehouse_code" / "gold")
168
+ )
169
+ if not project_dirs:
170
+ raise SystemExit("ERROR: no product dbt projects found.")
171
+
172
+ profile_path = write_profiles(project_dirs, output_dir, adapter=args.adapter)
173
+ print(f"Rendered {profile_path}")
174
+ if args.bake:
175
+ for project_dir in project_dirs:
176
+ print(f"dbt manifest baked at {bake_manifest(project_dir, output_dir)}")
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()