-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Milestone 8 — render/bundle layer and end-to-end Generator.generate() #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+1,181
−26
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d5adc5b
feat: Milestone 8 — render/bundle layer and end-to-end Generator.gene…
shaypal5 e750de5
fix: address self-review on PR #13 render/bundle layer
shaypal5 47dc5e2
fix: second self-review pass on PR #13
shaypal5 42e4ae1
fix: address Copilot review comments on PR #13
shaypal5 5629f12
fix: address Copilot round-2 review on PR #13
shaypal5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| """Bundle writer — assembles and serialises the full output bundle. | ||
|
|
||
| :func:`write_bundle` is called by :meth:`WorldBundle.save` and orchestrates | ||
| all rendering steps: | ||
|
|
||
| 1. Write relational Parquet tables (``tables/``). | ||
| 2. Build the lead snapshot and write task splits (``tasks/``). | ||
| 3. Write ``dataset_card.md`` and ``feature_dictionary.csv``. | ||
| 4. Build and write ``manifest.json``. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from pathlib import Path | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from leadforge.narrative.dataset_card import render_dataset_card | ||
| from leadforge.render.manifests import build_manifest, write_manifest | ||
| from leadforge.render.relational import to_dataframes | ||
| from leadforge.render.snapshots import build_snapshot | ||
| from leadforge.render.tasks import write_task_splits | ||
| from leadforge.schema.dictionaries import write_feature_dictionary | ||
| from leadforge.schema.tables import write_parquet | ||
| from leadforge.schema.tasks import CONVERTED_WITHIN_90_DAYS | ||
|
|
||
| if TYPE_CHECKING: | ||
| from leadforge.core.models import WorldBundle | ||
|
|
||
|
|
||
| def write_bundle(bundle: WorldBundle, path: str) -> None: | ||
| """Write *bundle* to disk at *path*. | ||
|
|
||
| Args: | ||
| bundle: Fully populated :class:`~leadforge.core.models.WorldBundle`. | ||
| path: Destination directory (created if absent). | ||
|
|
||
| Raises: | ||
| RuntimeError: if any of ``bundle.simulation_result``, | ||
| ``bundle.population``, or ``bundle.world_graph`` are ``None``. | ||
| """ | ||
| if bundle.simulation_result is None or bundle.population is None or bundle.world_graph is None: | ||
| raise RuntimeError("WorldBundle is not fully populated. Call Generator.generate() first.") | ||
|
|
||
| root = Path(path) | ||
| root.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| config = bundle.spec.config | ||
| result = bundle.simulation_result | ||
| population = bundle.population | ||
| world_graph = bundle.world_graph | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # 1. Relational tables → tables/ | ||
| # ------------------------------------------------------------------ | ||
| tables_dir = root / "tables" | ||
| tables_dir.mkdir(exist_ok=True) | ||
|
|
||
| dfs = to_dataframes(result, population) | ||
| table_row_counts: dict[str, int] = {} | ||
| for table_name, df in dfs.items(): | ||
| write_parquet(df, tables_dir / f"{table_name}.parquet") | ||
| table_row_counts[table_name] = len(df) | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # 2. Snapshot + task splits → tasks/ | ||
| # ------------------------------------------------------------------ | ||
| snapshot = build_snapshot(result, population, horizon_days=config.horizon_days) | ||
| task_row_counts = write_task_splits(snapshot, root / "tasks", seed=config.seed) | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # 3. Dataset card and feature dictionary | ||
| # ------------------------------------------------------------------ | ||
| (root / "dataset_card.md").write_text(render_dataset_card(bundle.spec)) | ||
| write_feature_dictionary(root / "feature_dictionary.csv") | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # 4. Manifest | ||
| # ------------------------------------------------------------------ | ||
| manifest = build_manifest( | ||
| config=config, | ||
| world_graph=world_graph, | ||
| table_row_counts=table_row_counts, | ||
| task_row_counts={CONVERTED_WITHIN_90_DAYS.task_id: task_row_counts}, | ||
| bundle_root=root, | ||
| ) | ||
| write_manifest(manifest, root) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| """Bundle manifest builder. | ||
|
|
||
| :func:`build_manifest` constructs the ``manifest.json`` dict that is written | ||
| at the root of every output bundle. The manifest records provenance (recipe, | ||
| seed, version, generation timestamp) and integrity metadata (row counts and | ||
| SHA-256 hashes) for the Parquet data files: relational tables and task splits. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import hashlib | ||
| import json | ||
| from datetime import UTC, datetime | ||
| from pathlib import Path | ||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| if TYPE_CHECKING: | ||
| from leadforge.core.models import GenerationConfig | ||
| from leadforge.structure.graph import WorldGraph | ||
|
|
||
| # Bump this whenever the bundle layout or manifest schema changes. | ||
| BUNDLE_SCHEMA_VERSION = "1" | ||
|
|
||
|
|
||
| def build_manifest( | ||
| config: GenerationConfig, | ||
| world_graph: WorldGraph, | ||
| table_row_counts: dict[str, int], | ||
| task_row_counts: dict[str, dict[str, int]], | ||
| bundle_root: Path, | ||
| generation_timestamp: str | None = None, | ||
| ) -> dict[str, Any]: | ||
| """Build the bundle manifest dict. | ||
|
|
||
| SHA-256 hashes are computed by reading the written Parquet files from | ||
| *bundle_root*, so all table and task files must already exist on disk | ||
| before calling this function. | ||
|
|
||
| Args: | ||
| config: The resolved generation configuration. | ||
| world_graph: The sampled hidden world graph (provides motif_family). | ||
| table_row_counts: Mapping of table name → row count. | ||
| task_row_counts: Mapping of task_id → {split_name → row count}. | ||
| bundle_root: Root directory of the written bundle. | ||
| generation_timestamp: ISO-8601 UTC timestamp string. Defaults to now. | ||
|
|
||
| Returns: | ||
| A JSON-serialisable dict ready to be written as ``manifest.json``. | ||
| """ | ||
| if generation_timestamp is None: | ||
| generation_timestamp = datetime.now(UTC).isoformat(timespec="seconds") | ||
|
|
||
| # Build table entries with row counts and file hashes. | ||
| tables: dict[str, Any] = {} | ||
| for table_name, row_count in table_row_counts.items(): | ||
| rel_path = f"tables/{table_name}.parquet" | ||
| abs_path = bundle_root / rel_path | ||
| sha = _sha256(abs_path) | ||
| tables[table_name] = {"row_count": row_count, "file": rel_path, "sha256": sha} | ||
|
|
||
| # Build task entries. | ||
| tasks: dict[str, Any] = {} | ||
| for task_id, split_counts in task_row_counts.items(): | ||
| entry: dict[str, Any] = {} | ||
| for split_name, row_count in split_counts.items(): | ||
| rel_path = f"tasks/{task_id}/{split_name}.parquet" | ||
| abs_path = bundle_root / rel_path | ||
| sha = _sha256(abs_path) | ||
| entry[f"{split_name}_rows"] = row_count | ||
| entry[f"{split_name}_sha256"] = sha | ||
| tasks[task_id] = entry | ||
|
|
||
| return { | ||
| "bundle_schema_version": BUNDLE_SCHEMA_VERSION, | ||
| "package_version": config.package_version, | ||
| "recipe_id": config.recipe_id, | ||
| "seed": config.seed, | ||
| "generation_timestamp": generation_timestamp, | ||
| "exposure_mode": config.exposure_mode.value, | ||
| "difficulty": config.difficulty.value, | ||
| "n_accounts": config.n_accounts, | ||
| "n_contacts": config.n_contacts, | ||
| "n_leads": config.n_leads, | ||
| "horizon_days": config.horizon_days, | ||
| "motif_family": world_graph.motif_family, | ||
| "tables": tables, | ||
| "tasks": tasks, | ||
| } | ||
|
|
||
|
|
||
| def write_manifest(manifest: dict[str, Any], bundle_root: Path) -> Path: | ||
| """Serialise *manifest* to ``bundle_root/manifest.json`` and return the path.""" | ||
| path = bundle_root / "manifest.json" | ||
| path.write_text(json.dumps(manifest, indent=2)) | ||
| return path | ||
|
|
||
|
|
||
| def _sha256(path: Path) -> str: | ||
| """Return the hex-encoded SHA-256 digest of *path*.""" | ||
| h = hashlib.sha256() | ||
| with path.open("rb") as fh: | ||
| for chunk in iter(lambda: fh.read(65536), b""): | ||
| h.update(chunk) | ||
| return h.hexdigest() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.