diff --git a/changelog.d/ITL-556.md b/changelog.d/ITL-556.md new file mode 100644 index 000000000..e068e175d --- /dev/null +++ b/changelog.d/ITL-556.md @@ -0,0 +1,10 @@ +### Breaking changes and migration + +- Orcapod uses full hash digests in system-tag column names and logical table + paths. Remove `system_tag_n_char`, `schema_n_char`, and `path_n_char` from your + hashing configuration. Programmatic configs reject these fields, and pipeline saves + omit them. Config files and saved pipelines that specify a value for a removed + setting raise an error naming it. Older saved pipelines may contain `null` for + unset settings and still load. Rebuild any stores written with shortened + system-tag names using the full digests. `ContentHash.to_hex(char_count=...)` + still supports shortening a digest for display. diff --git a/docs/dev/design_issues/ITL-556-HL1.md b/docs/dev/design_issues/ITL-556-HL1.md new file mode 100644 index 000000000..f2ce497bf --- /dev/null +++ b/docs/dev/design_issues/ITL-556-HL1.md @@ -0,0 +1,18 @@ +## `src/orcapod/config.py` — hash lengths in stored names + +### HL1 — Hash truncation changed stored provenance column names and entry ids +**Status:** resolved +**Severity:** critical +**Issue:** ITL-556 + +The same job could write different system-tag column names and entry ids to the same +table paths when `schema_n_char` or `system_tag_n_char` shortened a digest. Short schema +digests could also collide and silently combine columns for distinct provenance. +The `path_n_char` setting had no callers. + +**Fix:** Removed all three length settings and used full digests in system-tag +column names and logical table paths. Programmatic configurations refuse the +removed fields in typed objects and mappings. Loaders identify removed settings +in both tables and arrays of tables. Pipeline saves omit the fields, and the +loader accepts the null defaults older writers included automatically. The public +mapping parser rejects the removed keys even when their values are null. diff --git a/docs/dev/specs/itl-939-experiments/exp02_workarounds_today.py b/docs/dev/specs/itl-939-experiments/exp02_workarounds_today.py index d5c80a359..e6c4659ab 100644 --- a/docs/dev/specs/itl-939-experiments/exp02_workarounds_today.py +++ b/docs/dev/specs/itl-939-experiments/exp02_workarounds_today.py @@ -98,8 +98,8 @@ def show(label: str, stream) -> None: c for c in stream.as_table(all_info=True).column_names if c.startswith("_tag_") ] print("system tag columns:", sys_cols) - print("pipeline_hash:", stream.pipeline_hash().to_hex(16)) - print("content_hash: ", stream.content_hash().to_hex(16)) + print("pipeline_hash:", stream.pipeline_hash().to_hex()[:16]) + print("content_hash: ", stream.content_hash().to_hex()[:16]) def rows(stream, cols: list[str]) -> None: diff --git a/docs/dev/specs/itl-939-experiments/exp03_copy_tag_prototype.py b/docs/dev/specs/itl-939-experiments/exp03_copy_tag_prototype.py index 15142e03f..46563cc8c 100644 --- a/docs/dev/specs/itl-939-experiments/exp03_copy_tag_prototype.py +++ b/docs/dev/specs/itl-939-experiments/exp03_copy_tag_prototype.py @@ -174,17 +174,17 @@ def section(title: str) -> None: section("3. data content hashes: copy operator vs W2 recipe") w2_in = fx.w2_src.select_data_columns(["session_start", "experiment_start_timestamp"]) c_in = copied.select_data_columns(["session_start", "experiment_start_timestamp"]) -w2_hashes = [d.content_hash().to_hex(16) for _, d in w2_in.iter_data()] -c_hashes = [d.content_hash().to_hex(16) for _, d in c_in.iter_data()] +w2_hashes = [d.content_hash().to_hex()[:16] for _, d in w2_in.iter_data()] +c_hashes = [d.content_hash().to_hex()[:16] for _, d in c_in.iter_data()] print("W2 :", w2_hashes) print("copy :", c_hashes) print("per-row data hashes equal (so pod result caches agree):", w2_hashes == c_hashes) print( "pipeline_hash experiment (unchanged by the feature):", - experiment.pipeline_hash().to_hex(16), + experiment.pipeline_hash().to_hex()[:16], ) -print("pipeline_hash after copy:", copied.pipeline_hash().to_hex(16)) -print("pipeline_hash W2 source :", fx.w2_src.pipeline_hash().to_hex(16)) +print("pipeline_hash after copy:", copied.pipeline_hash().to_hex()[:16]) +print("pipeline_hash W2 source :", fx.w2_src.pipeline_hash().to_hex()[:16]) # 4. Why design D (pods read tags directly) is unsafe with today's result cache. section("4. two rows, same data, different tags -> same input data hash") @@ -203,7 +203,7 @@ def section(title: str) -> None: source_id="d", infer_nullable=True, ) -print("data hashes:", [d.content_hash().to_hex(16) for _, d in s.iter_data()]) +print("data hashes:", [d.content_hash().to_hex()[:16] for _, d in s.iter_data()]) print( "-> a pod that read session_start_datetime from the TAG would get one cached result" ) @@ -211,7 +211,7 @@ def section(title: str) -> None: s_c = CopyTagsToData({"session_start_datetime": "session_start"})(s) print( "with the copy, data hashes:", - [d.content_hash().to_hex(16) for _, d in s_c.iter_data()], + [d.content_hash().to_hex()[:16] for _, d in s_c.iter_data()], ) # 5. Nullable keys (every EDI key column is nullable in the DB schema). diff --git a/docs/dev/specs/itl-939-experiments/exp05_hash_comparison.py b/docs/dev/specs/itl-939-experiments/exp05_hash_comparison.py index 6eca90da1..923040045 100644 --- a/docs/dev/specs/itl-939-experiments/exp05_hash_comparison.py +++ b/docs/dev/specs/itl-939-experiments/exp05_hash_comparison.py @@ -43,7 +43,7 @@ def h(x) -> str: """Return the first 16 hex characters of a ``ContentHash``.""" - return x.to_hex(16) + return x.to_hex()[:16] print("=== per-row input data content_hash (the pod's result-cache key)") @@ -96,7 +96,7 @@ def h(x) -> str: f"input_data_hash=...{vals['__input_data_hash'].hex()[-16:]}", ) # How FunctionNode.compute_base_entry_id hashes the preimage. - entry = contexts.get_default_context().arrow_hasher.hash_table(pre).to_hex(16) + entry = contexts.get_default_context().arrow_hasher.hash_table(pre).to_hex()[:16] print(f"{name:5s} base entry id (arrow hash of the preimage): {entry}") print("\n=== divergence: the copy is ordinary data once created") diff --git a/docs/dev/specs/itl-939-experiments/exp06_derived_source_today.py b/docs/dev/specs/itl-939-experiments/exp06_derived_source_today.py index 4f9cd37d8..35c3db3ee 100644 --- a/docs/dev/specs/itl-939-experiments/exp06_derived_source_today.py +++ b/docs/dev/specs/itl-939-experiments/exp06_derived_source_today.py @@ -110,10 +110,10 @@ def task_upper(task_id: str) -> str: print("derived _source_task_upper[0]:", der_t["_source_task_upper"][0].as_py()) print("\n=== 5. identity") -print("origin content_hash :", node.content_hash().to_hex(16)) -print("derived content_hash :", derived.content_hash().to_hex(16)) -print("origin pipeline_hash:", node.pipeline_hash().to_hex(16)) -print("derived pipeline_hash:", derived.pipeline_hash().to_hex(16)) +print("origin content_hash :", node.content_hash().to_hex()[:16]) +print("derived content_hash :", derived.content_hash().to_hex()[:16]) +print("origin pipeline_hash:", node.pipeline_hash().to_hex()[:16]) +print("derived pipeline_hash:", derived.pipeline_hash().to_hex()[:16]) print("derived.upstreams:", derived.upstreams, "| producer:", derived.producer) diff --git a/docs/dev/specs/itl-939-experiments/exp07_derived_source_prototype.py b/docs/dev/specs/itl-939-experiments/exp07_derived_source_prototype.py index 3dd3fdcd5..6b3fac03f 100644 --- a/docs/dev/specs/itl-939-experiments/exp07_derived_source_prototype.py +++ b/docs/dev/specs/itl-939-experiments/exp07_derived_source_prototype.py @@ -96,7 +96,7 @@ def __init__( table = table.append_column( pa.field(name, field.type, nullable=field.nullable), table[tag] ) - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) # The builder takes the name and the kind part apart since ITL-1425. self._stream = builder.build( table, @@ -139,7 +139,7 @@ def from_config( def h(x: Any) -> str: """Return the first 16 hex characters of a ``ContentHash``.""" - return x.to_hex(16) + return x.to_hex()[:16] def prov(table: pa.Table) -> list[str]: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index bd752c850..497b22489 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -22,10 +22,10 @@ appended, because it is a variant of the same system tag mechanism.) |---|------|-----------|---------------|--------------------| | 1 | `content_hash()` | `SemanticAwarePythonHasher` → JSON + SHA-256 | `ContentHash` | Unique per semantic content of the object; data-inclusive | | 2 | `pipeline_hash()` | `SemanticAwarePythonHasher` → JSON + SHA-256 | `ContentHash` | Unique per pipeline topology + schema; data-exclusive | -| 3 | Schema hash (system tag column naming) | `SemanticAwarePythonHasher.hash_object((hash_schema(tag), hash_schema(data))).to_hex(n)` over the Arrow schemas | Truncated hex `str` | Unique per Arrow `(tag, data)` schema pair; embedded in system tag column names | +| 3 | Schema hash (system tag column naming) | `SemanticAwarePythonHasher.hash_object((hash_schema(tag), hash_schema(data))).to_hex()` over the Arrow schemas | Full hex digest (`str`) | Unique per Arrow `(tag, data)` schema pair; embedded in system tag column names | | 4 | Default `source_id` of an in-memory source | `":" + StarfixArrowHasher.hash_table(table).to_string()` | `str`, `_v::` | Unique per kind, implementation version and raw table content; the hash is the source's name when none is given | | 5 | Per-row `record_id` (system tag value) | the row identifier itself: `row_`, or the canonical JSON of the key columns (`key_row_identifier`) | `str` (`large_string`) | Names the row within its source; stable as long as its position or its key is | -| 6 | Join system tag suffix | `stream.pipeline_hash().to_hex(n)` + `:{idx}` appended to column name | Column name suffix | Unique per `(input topology, canonical join position)`; encodes full join lineage in column name | +| 6 | Join system tag suffix | `stream.pipeline_hash().to_hex()` + `:{idx}` appended to column name | Column name suffix | Unique per `(input topology, canonical join position)`; encodes full join lineage in column name | | 6b | Aggregating operator system tag fold | SHA-256 of the canonical JSON list of member values, after the operation's label, for both system tags | `":"` `str`, plus a column name suffix | Deterministic per ordered member set; keeps system tags scalar through a many-to-one reduction | | 7 | Entry id (`row_ids.entry_id`) | `StarfixArrowHasher.hash_table(tags + system_tags + INPUT_DATA_HASH_COL)` | `ContentHash`; stored as `bytes` (`b"method:digest"`) | Unique per `(tag lineage, input_data content)`: an entry of the pipeline table | | 8 | Instance id (`row_ids.instance_id`) | `StarfixArrowHasher.hash_table(entry id + source-info tokens in name order)` | `ContentHash`; stored as `bytes` | Unique per `(entry, provenance of the input)`: one arrival of an entry; the pipeline table's lookup column | @@ -1089,8 +1089,8 @@ topology suffix, encoding the full join lineage into each column name. | Field | Value | |---|---| | **Inputs** | the Arrow tag schema and data schema (a data-tag in both) of the source's table, or of a slot | -| **Algorithm** | `SemanticAwarePythonHasher.hash_object((hash_schema(tag), hash_schema(data))).to_hex(schema_n_char)` (`schema_utils.compute_schema_hash`), where `schema_n_char = OrcapodConfig.hashing.schema_n_char` | -| **Output format** | Truncated hex `str` (length = `schema_n_char`; `None` = full digest) | +| **Algorithm** | `SemanticAwarePythonHasher.hash_object((hash_schema(tag), hash_schema(data))).to_hex()` (`schema_utils.compute_schema_hash`) | +| **Output format** | Full hex digest (`str`) | | **Uniqueness guarantee** | Unique per Arrow schema pair; two sources whose Arrow schemas are equal (as "The Arrow schema hash" compares them) produce identically-named system tag columns, and two that differ in any Arrow type (`int32` and `int64`) do not | | **Known exclusions** | No data content; no source identity; purely structural | @@ -1102,7 +1102,7 @@ topology suffix, encoding the full join lineage into each column name. |---|---| | **Inputs** | Full raw Arrow table (all columns, before any system tag injection), its rows in the order given, or sorted by the key columns in key order with `hash_in_key_order=True` (`arrow_utils.key_row_order`, ITL-1272) | | **Algorithm** | `build_source_id(, , hash_source_name(StarfixArrowHasher.hash_table(table)))`, at full length — the table hash is starfix hash format 2: the 3-byte format number `00 00 02` followed by a SHA-256 digest (`starfix` 0.6.0 or newer, with the float rule, §9) | -| **Output format** | `str`: `_v::`, for example `dict_v1:arrow_v1:000002fe…`. The kind is the class's config type key (`SOURCE_KIND`: `arrow_table`, `dict`, `list`, `data_frame`) and `N` its `SOURCE_VERSION`; the label is the one the hash carries. Nothing is shortened: the hex is the full digest whatever `hashing.path_n_char` says (a default source id is a name; developer, November 16, 2026). The parts hold no `:`, so the id never contains the `::` that separates the parts of a source-info value | +| **Output format** | `str`: `_v::`, for example `dict_v1:arrow_v1:000002fe…`. The kind is the class's config type key (`SOURCE_KIND`: `arrow_table`, `dict`, `list`, `data_frame`) and `N` its `SOURCE_VERSION`; the label is the one the hash carries. The hex is the full digest. The parts hold no `:`, so the id never contains the `::` that separates the parts of a source-info value | | **Uniqueness guarantee** | Unique per kind, implementation version and raw table content; changes if any cell value changes or the rows are reordered, except with `hash_in_key_order=True`, where a reorder changes nothing and a change of the key columns' order changes the id only when it sorts the table differently (it always changes the content hash, which holds the key columns in key order) | | **Known exclusions** | Used **only** as a fallback when no explicit `source_id` is provided. With a user-supplied `source_id` the builder still computes the table hash (it returns it as `table_hash`), but the hash enters neither the id nor the source's identity. | @@ -1149,7 +1149,7 @@ print(first_row["_source_age"]) | Field | Value | |---|---| | **Inputs** | `stream.pipeline_hash()` of each canonically-ordered input stream + its 0-based canonical position index `idx` | -| **Algorithm** | Streams are first sorted by `stream.pipeline_hash().to_hex()` for determinism. For each input at canonical position `idx`, every existing system tag column name has `{BLOCK_SEPARATOR}{stream.pipeline_hash().to_hex(system_tag_n_char)}:{idx}` appended via `arrow_utils.append_to_system_tags()`. (`system_tag_n_char` from `OrcapodConfig.hashing`; default `None` = full digest.) | +| **Algorithm** | Streams are first sorted by `stream.pipeline_hash().to_hex()` for determinism. For each input at canonical position `idx`, every existing system tag column name has `{BLOCK_SEPARATOR}{stream.pipeline_hash().to_hex()}:{idx}` appended via `arrow_utils.append_to_system_tags()`. | | **Output format** | Column name suffix; no separate value is stored | | **Uniqueness guarantee** | Each post-join system tag column name uniquely identifies `(original schema, input topology, canonical join position)`; no collision even when joining streams with identical schemas | | **Known exclusions** | `SemiJoin` passes system tags through unchanged. Aggregating operators (`Batch`, `GroupBy`) use the fold described in site 6b instead. | @@ -1167,7 +1167,7 @@ tag columns too, so those calls are as wide as the joins make them (ITL-1132). | Field | Value | |---|---| | **Inputs** | The ordered list of a group's member values for one system tag column, and the operation's label | -| **Algorithm** | `arrow_utils.fold_system_tag_values(values, label=...)`, one helper for both system tags: SHA-256 of the canonical JSON array of the members in order (`json.dumps([None if v is None else str(v) for v in values], separators=(",", ":"), ensure_ascii=False)`, UTF-8), as 64 hex characters after the operation's label: `batch_v1:` for `Batch` (`BATCH_FOLD_LABEL`, in `batch.py`), `group_v1:` for `GroupBy` (`GROUP_BY_FOLD_LABEL`, in `group_by.py`). The label names the operation; each operation's procedure may change on its own (ITL-1154). The array marks where each member ends, so `["ab", "c"]` and `["a", "bc"]` fold differently, and a `None` member (`null`) differs from `""` (ITL-942). The folded column name then gains `{BLOCK_SEPARATOR}{stream.pipeline_hash().to_hex(system_tag_n_char)}` via `arrow_utils.append_to_system_tags()`. | +| **Algorithm** | `arrow_utils.fold_system_tag_values(values, label=...)`, one helper for both system tags: SHA-256 of the canonical JSON array of the members in order (`json.dumps([None if v is None else str(v) for v in values], separators=(",", ":"), ensure_ascii=False)`, UTF-8), as 64 hex characters after the operation's label: `batch_v1:` for `Batch` (`BATCH_FOLD_LABEL`, in `batch.py`), `group_v1:` for `GroupBy` (`GROUP_BY_FOLD_LABEL`, in `group_by.py`). The label names the operation; each operation's procedure may change on its own (ITL-1154). The array marks where each member ends, so `["ab", "c"]` and `["a", "bc"]` fold differently, and a `None` member (`null`) differs from `""` (ITL-942). The folded column name then gains `{BLOCK_SEPARATOR}{stream.pipeline_hash().to_hex()}` via `arrow_utils.append_to_system_tags()`. | | **Output format** | `":<64 hex>"` `str` for the source id and the record id alike: **scalar**, matching the input column's type | | **Uniqueness guarantee** | Deterministic per ordered member set, and stable across processes (both primitives are SHA-based). `Batch` and `GroupBy` both order their members deterministically before folding, so an unchanged member set always folds to the same digest | | **Known exclusions** | Member order is significant; a permuted member set folds differently. This is why `GroupBy` sorts members by their non-key tag values with `record_id` as a tiebreaker rather than relying on upstream emission order | diff --git a/scripts/hash_audit_example.py b/scripts/hash_audit_example.py index eea141a38..8e4fd6013 100644 --- a/scripts/hash_audit_example.py +++ b/scripts/hash_audit_example.py @@ -13,7 +13,6 @@ import hashlib -from orcapod.config import DEFAULT_CONFIG from orcapod.contexts import resolve_context from orcapod.core import row_ids from orcapod.core.function_pod import function_pod @@ -48,7 +47,6 @@ def sub(title: str) -> None: def main() -> None: ctx = resolve_context() - schema_n_char = DEFAULT_CONFIG.hashing.schema_n_char # ------------------------------------------------------------------ # Build the example pipeline (deterministic source_id values) @@ -117,11 +115,9 @@ def grade(math: int, days: int) -> float: tag_schema, data_schema = scores.output_schema() # The schema hash is built from the Arrow schemas of the source's rows (ITL-640). arrow_tag, arrow_data = scores.arrow_schemas - schema_hash = compute_schema_hash( - arrow_tag, arrow_data, scores.data_context, schema_n_char - ) + schema_hash = compute_schema_hash(arrow_tag, arrow_data, scores.data_context) print(f" (tag_schema, data_schema) = ({tag_schema!r}, {data_schema!r})") - print(f" schema_hash (char_count={schema_n_char!r}) = {schema_hash!r}") + print(f" schema_hash = {schema_hash!r}") sub("Site 4 — Default source_id (explicit in this example → no hash computed)") print( diff --git a/src/orcapod/config.py b/src/orcapod/config.py index cdc1deca5..bf57a747d 100644 --- a/src/orcapod/config.py +++ b/src/orcapod/config.py @@ -2,13 +2,54 @@ from __future__ import annotations import logging -from collections.abc import Mapping -from dataclasses import dataclass, field, replace +from collections.abc import Iterable, Mapping +from dataclasses import asdict, dataclass, field, replace from pathlib import Path from typing import Any, Literal, Self logger = logging.getLogger(__name__) +_REMOVED_HASHING_SETTINGS = frozenset( + {"system_tag_n_char", "schema_n_char", "path_n_char"} +) + + +def _reject_removed_hashing_keys(keys: Iterable[str]) -> None: + removed = sorted(_REMOVED_HASHING_SETTINGS.intersection(keys)) + if removed: + settings = ", ".join(f"hashing.{key}" for key in removed) + raise ValueError(f"Removed hash-length settings: {settings}. Use full digests.") + + +def _hashing_setting_keys(section: object, *, allow_null: bool) -> Iterable[str]: + """Read setting names from a table or an array of tables.""" + if isinstance(section, Mapping): + yield from ( + key for key, value in section.items() if value is not None or not allow_null + ) + elif isinstance(section, (list, tuple)): + for table in section: + yield from _hashing_setting_keys(table, allow_null=allow_null) + + +def validate_descriptor_config(config: object) -> None: + """Refuse non-null removed hash-length settings in a saved descriptor. + + Older saved descriptors included null for each unset setting whenever + another section was customized. + + Args: + config: Parsed configuration, possibly absent or malformed. + + Raises: + ValueError: If a removed setting has a non-null value. + """ + if not isinstance(config, Mapping): + return + _reject_removed_hashing_keys( + _hashing_setting_keys(config.get("hashing"), allow_null=True) + ) + @dataclass(frozen=True) class _SectionConfig: @@ -71,16 +112,7 @@ class DatetimeConfig(_SectionConfig): @dataclass(frozen=True) class HashingConfig(_SectionConfig): - """Hash length settings for system-tag column names, schema hashes, and path scoping. - - All fields default to ``None``, which means full-length hashes are used everywhere. - Set a field to a positive integer to truncate hashes to that many hex characters - (e.g. for backwards compatibility with existing stored data). - """ - - system_tag_n_char: int | None = None - schema_n_char: int | None = None - path_n_char: int | None = None + """Hashing configuration. System-tag names and logical paths use full digests.""" @dataclass(frozen=True) @@ -111,6 +143,15 @@ class OrcapodConfig: display: DisplayConfig = field(default_factory=DisplayConfig) datetime: DatetimeConfig = field(default_factory=DatetimeConfig) + def __post_init__(self) -> None: + """Refuse removed settings supplied through a programmatic hashing section.""" + _reject_removed_hashing_keys( + _hashing_setting_keys(self.hashing, allow_null=False) + ) + _reject_removed_hashing_keys( + key for key in _REMOVED_HASHING_SETTINGS if hasattr(self.hashing, key) + ) + def with_updates(self, **kwargs: Any) -> Self: """Create a new ``OrcapodConfig`` with updated section values. @@ -168,7 +209,35 @@ def from_dict( Returns: ``OrcapodConfig`` populated from ``data``; missing sections and fields fall back to built-in defaults. + + Raises: + ValueError: If a removed hash-length setting is present. """ + try: + _reject_removed_hashing_keys( + _hashing_setting_keys(data.get("hashing"), allow_null=False) + ) + except ValueError as exc: + if source_path is not None: + exc.add_note(f"Loading configuration from {source_path}") + raise + + return cls._parse_dict(data, source_path) + + @staticmethod + def from_node_descriptor(descriptor: Mapping[str, Any]) -> OrcapodConfig: + """Restore a saved node's config, accepting old null hash-length defaults.""" + data = descriptor.get("config") + if data is None: + return DEFAULT_CONFIG + validate_descriptor_config(data) + return OrcapodConfig._parse_dict(data) + + @classmethod + def _parse_dict( + cls, data: Mapping[str, Any], source_path: Path | str | None = None + ) -> OrcapodConfig: + """Parse a configuration after checking for removed hash-length settings.""" known_sections = {"hashing", "display", "datetime"} path_str = f" in {source_path}" if source_path is not None else "" @@ -177,20 +246,16 @@ def from_dict( logger.warning("Unknown config section %r%s — ignored", key, path_str) hashing_dict = data.get("hashing", {}) - known_hashing = set(HashingConfig.__dataclass_fields__) if not isinstance(hashing_dict, Mapping): logger.warning( "Config section [hashing]%s is not a table — ignored", path_str ) hashing_dict = {} for key in hashing_dict: - if key not in known_hashing: + if key not in _REMOVED_HASHING_SETTINGS: logger.warning( "Unknown field %r in [hashing]%s — ignored", key, path_str ) - hashing = HashingConfig( - **{k: v for k, v in hashing_dict.items() if k in known_hashing} - ) display_dict = data.get("display", {}) known_display = set(DisplayConfig.__dataclass_fields__) @@ -224,13 +289,27 @@ def from_dict( **{k: v for k, v in datetime_dict.items() if k in known_datetime} ) - return cls(hashing=hashing, display=display, datetime=datetime_config) + return cls(display=display, datetime=datetime_config) # Module-level default config — created at import time. DEFAULT_CONFIG = OrcapodConfig() +def config_for_save(config: OrcapodConfig) -> dict[str, Any] | None: + """Serialize a node's config without removed hashing settings. + + Return ``None`` for the default config so loading uses the current defaults. + """ + if config == DEFAULT_CONFIG: + return None + + saved = asdict(config) + for key in _REMOVED_HASHING_SETTINGS: + saved["hashing"].pop(key, None) + return saved + + def load_config( project_config_path: Path | str | None = None, user_config_path: Path | str | None = None, @@ -255,7 +334,8 @@ def load_config( Merged ``OrcapodConfig`` with all applicable overrides applied. Raises: - ValueError: If a config file exists but contains invalid TOML. + ValueError: If a config file contains invalid TOML or a removed hash-length + setting. """ import tomllib @@ -270,7 +350,6 @@ def load_config( else Path.cwd() / "orcapod_config.toml" ) - known_hashing = set(HashingConfig.__dataclass_fields__) known_display = set(DisplayConfig.__dataclass_fields__) known_datetime = set(DatetimeConfig.__dataclass_fields__) @@ -284,6 +363,12 @@ def load_config( data = tomllib.load(f) except tomllib.TOMLDecodeError as e: raise ValueError(f"Malformed TOML in {path}: {e}") from e + try: + _reject_removed_hashing_keys( + _hashing_setting_keys(data.get("hashing"), allow_null=False) + ) + except ValueError as exc: + raise ValueError(f"{path}: {exc}") from exc # Warn on unknown top-level sections. for key in data: @@ -298,14 +383,11 @@ def load_config( logger.warning( "Config section [hashing] in %s is not a table — ignored", path ) - hashing_data = {} else: for key in hashing_data: - if key not in known_hashing: - logger.warning( - "Unknown field %r in [hashing] in %s — ignored", key, path - ) - hashing_updates = {k: v for k, v in hashing_data.items() if k in known_hashing} + logger.warning( + "Unknown field %r in [hashing] in %s — ignored", key, path + ) display_data = data.get("display", {}) if not isinstance(display_data, dict): @@ -337,10 +419,6 @@ def load_config( k: v for k, v in datetime_data.items() if k in known_datetime } - if hashing_updates: - config = config.with_updates( - hashing=replace(config.hashing, **hashing_updates) - ) if display_updates: config = config.with_updates( display=replace(config.display, **display_updates) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9809760af..354b2972b 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -1095,14 +1095,7 @@ def from_descriptor( node._data_context = contexts.resolve_saved_context( descriptor.get("data_context_key") ) - from orcapod.config import DEFAULT_CONFIG, OrcapodConfig - - config_dict = descriptor.get("config") - node._orcapod_config = ( - OrcapodConfig.from_dict(config_dict) - if config_dict is not None - else DEFAULT_CONFIG - ) + node._orcapod_config = OrcapodConfig.from_node_descriptor(descriptor) # From ContentIdentifiableBase node._content_hash_cache = {} @@ -1831,7 +1824,6 @@ def from_descriptor( A ``FunctionJobNode`` in read-only stub mode (``load_status=UNAVAILABLE``). """ - from orcapod.config import DEFAULT_CONFIG, OrcapodConfig from orcapod.pipeline.serialization import LoadStatus if "table_scope" not in descriptor: @@ -1856,12 +1848,7 @@ def from_descriptor( node._data_context = contexts.resolve_saved_context( descriptor.get("data_context_key") ) - config_dict = descriptor.get("config") - node._orcapod_config = ( - OrcapodConfig.from_dict(config_dict) - if config_dict is not None - else DEFAULT_CONFIG - ) + node._orcapod_config = OrcapodConfig.from_node_descriptor(descriptor) # From ContentIdentifiableBase node._content_hash_cache = {} diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 4f4632f3d..560511f00 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -757,17 +757,10 @@ def from_descriptor( node._label = descriptor.get("label") # From DataContextMixin - from orcapod.config import DEFAULT_CONFIG, OrcapodConfig - node._data_context = contexts.resolve_saved_context( descriptor.get("data_context_key") ) - config_dict = descriptor.get("config") - node._orcapod_config = ( - OrcapodConfig.from_dict(config_dict) - if config_dict is not None - else DEFAULT_CONFIG - ) + node._orcapod_config = OrcapodConfig.from_node_descriptor(descriptor) # From ContentIdentifiableBase node._content_hash_cache = {} @@ -1147,17 +1140,10 @@ def from_descriptor( node._label = descriptor.get("label") # From DataContextMixin - from orcapod.config import DEFAULT_CONFIG, OrcapodConfig - node._data_context = contexts.resolve_saved_context( descriptor.get("data_context_key") ) - config_dict = descriptor.get("config") - node._orcapod_config = ( - OrcapodConfig.from_dict(config_dict) - if config_dict is not None - else DEFAULT_CONFIG - ) + node._orcapod_config = OrcapodConfig.from_node_descriptor(descriptor) # From ContentIdentifiableBase node._content_hash_cache = {} diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5b69d510d..82ad5390f 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -60,7 +60,7 @@ from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.utils.schema_utils import ( arrow_schema_identity, - compute_source_schema_hash, + compute_schema_hash, declared_arrow_schema, ) @@ -881,14 +881,9 @@ def _schema_hash_str(self) -> str: # The saved type text stands in until the class is registered (ITL-1138). return self.data_context.semantic_hasher.hash_object( (self._tag_schema, self._data_schema) - ).to_hex(char_count=self.orcapod_config.hashing.schema_n_char) + ).to_hex() tag_schema, data_schema = self.arrow_schemas - return compute_source_schema_hash( - tag_schema, - data_schema, - self.data_context, - self.orcapod_config, - ) + return compute_schema_hash(tag_schema, data_schema, self.data_context) @property def node_uri(self) -> tuple[str, ...]: diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e7a1969f8..9d9153c74 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -193,9 +193,8 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: arrays.append(arrow_utils.aggregated_list_array(column, offsets, list_type)) batched_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) - n_char = self.orcapod_config.hashing.system_tag_n_char batched_table = arrow_utils.append_to_system_tags( - batched_table, stream.pipeline_hash().to_hex(n_char) + batched_table, stream.pipeline_hash().to_hex() ) # A data-tag stays a data-tag: the same list in both roles. @@ -228,8 +227,7 @@ def unary_output_schema( A ``(tag_schema, data_schema)`` tuple. """ tag_types, data_types = stream.output_schema(columns=columns, all_info=all_info) - n_char = self.orcapod_config.hashing.system_tag_n_char - suffix = stream.pipeline_hash().to_hex(n_char) + suffix = stream.pipeline_hash().to_hex() batched_tag_types: dict[str, Any] = {} for name, col_type in tag_types.items(): diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index acce7333c..c5b03cbd6 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -550,9 +550,8 @@ def folded(c: str) -> pa.Array[Any]: arrays.append(emitted(c) if c in self.by else folded(c)) grouped_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) - n_char = self.orcapod_config.hashing.system_tag_n_char grouped_table = arrow_utils.append_to_system_tags( - grouped_table, stream.pipeline_hash().to_hex(n_char) + grouped_table, stream.pipeline_hash().to_hex() ) # The keys, in the input's tag order rather than the order of `by`. A @@ -727,8 +726,7 @@ def unary_output_schema( data-tag key stays scalar. """ tag_types, data_types = stream.output_schema(columns=columns, all_info=all_info) - n_char = self.orcapod_config.hashing.system_tag_n_char - suffix = stream.pipeline_hash().to_hex(n_char) + suffix = stream.pipeline_hash().to_hex() out_tag_types: dict[str, Any] = {} for name, col_type in tag_types.items(): diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index d9f199509..0ad0fe26f 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -432,7 +432,6 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema: appending ::{pipeline_hash}:{canonical_position}. This method computes those output column names without performing the join. """ - n_char = self.orcapod_config.hashing.system_tag_n_char ordered_streams = self.order_input_streams(*streams) system_tag_fields: dict[str, DataType] = {} @@ -442,7 +441,7 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema: if col_name.startswith(constants.SYSTEM_TAG_PREFIX): new_name = ( f"{col_name}{constants.BLOCK_SEPARATOR}" - f"{stream.pipeline_hash().to_hex(n_char)}:{idx}" + f"{stream.pipeline_hash().to_hex()}:{idx}" ) system_tag_fields[new_name] = col_type nullable = arrow_utils.sorted_system_tag_nullability( @@ -479,8 +478,6 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: # data column (meta columns are dropped, so they never collide). tag_schema, data_schema = self._joined_user_schemas(*streams) - n_char = self.orcapod_config.hashing.system_tag_n_char - stream = ordered_streams[0] tag_keys, _ = [set(k) for k in stream.keys()] @@ -495,7 +492,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: table = _with_common_key(table) table = arrow_utils.append_to_system_tags( table, - f"{stream.pipeline_hash().to_hex(n_char)}:0", + f"{stream.pipeline_hash().to_hex()}:0", ) for idx, next_stream in enumerate(ordered_streams[1:], start=1): @@ -506,7 +503,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: ) next_table = arrow_utils.append_to_system_tags( next_table, - f"{next_stream.pipeline_hash().to_hex(n_char)}:{idx}", + f"{next_stream.pipeline_hash().to_hex()}:{idx}", ) # trick to ensure that there will always be at least one shared key # this ensure that no overlap in keys lead to full caretesian product @@ -690,7 +687,7 @@ def _compute_system_tag_suffixes( ) -> list[str]: """Compute per-input system-tag suffixes from pipeline hashes. - Each suffix is ``{truncated_hash}:{canonical_position}`` where + Each suffix is ``{pipeline_hash}:{canonical_position}`` where canonical position is determined by sorting the hashes (matching the deterministic ordering used by ``static_process``). @@ -701,7 +698,6 @@ def _compute_system_tag_suffixes( Returns: List of suffix strings, one per input position. """ - n_char = self.orcapod_config.hashing.system_tag_n_char hex_strings = [h.to_hex() for h in input_pipeline_hashes] # Canonical order: sorted by full hex (same as order_input_streams). @@ -713,11 +709,10 @@ def _compute_system_tag_suffixes( for canon_idx, orig_idx in enumerate(ranked): canon_position[orig_idx] = canon_idx - suffixes: list[str] = [] - for orig_idx in range(len(hex_strings)): - truncated = input_pipeline_hashes[orig_idx].to_hex(n_char) - suffixes.append(f"{truncated}:{canon_position[orig_idx]}") - return suffixes + return [ + f"{hex_digest}:{position}" + for hex_digest, position in zip(hex_strings, canon_position, strict=True) + ] async def async_execute( self, diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 8e49d0728..4b3cb7c74 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -350,8 +350,7 @@ def _system_tag_suffix(self, stream: StreamProtocol, position: int) -> str: ``position`` is the input's argument index (0 for the first, 1 for the second): MergeJoin is ordered, so its inputs are never reordered. """ - n_char = self.orcapod_config.hashing.system_tag_n_char - return f"{stream.pipeline_hash().to_hex(n_char)}:{position}" + return f"{stream.pipeline_hash().to_hex()}:{position}" def _predict_system_tag_schema( self, left_stream: StreamProtocol, right_stream: StreamProtocol diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index fae5beed5..75d0ea2a1 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -687,9 +687,8 @@ def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: def _suffix(self, input_index: int, position: int) -> str: """What an input's system-tag column names gain: ``{pipeline hash}:{position}``.""" - n_char = self.operator.orcapod_config.hashing.system_tag_n_char pipeline_hash = self.inputs[input_index].pipeline_hash() - return f"{pipeline_hash.to_hex(n_char)}:{position}" + return f"{pipeline_hash.to_hex()}:{position}" class StreamingJoin(StreamingJoinKernel): diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index c31370727..1b03e0509 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -118,7 +118,7 @@ def __init__( table = table.cast(arrow_utils.infer_schema_nullable(table)) # else: schema is trusted as-is. - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) result = builder.build( table, tag_columns=tag_columns, diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index e6d087c68..e44f9c189 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -367,7 +367,7 @@ def _read_table(self) -> pa.Table: def _build(self, table: pa.Table) -> SourceStreamResult: """Enrich ``table`` as this source's stream (source info, system tags).""" - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) return builder.build( table, tag_columns=self._tag_columns, diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 54a563f88..fc1eff7fb 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -103,7 +103,7 @@ def __init__( ) self._key_columns = normalize_record_id_columns(record_id_columns) or () - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) result = builder.build( arrow_table, tag_columns=tag_columns, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 55f0c82b7..e49199372 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -252,7 +252,7 @@ def _read_table( def _build(self, table: pa.Table) -> SourceStreamResult: """Enrich ``table`` as this source's stream (source info, system tags).""" - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) return builder.build( table, tag_columns=self._tag_columns, diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 239c00191..8a9b272f1 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -114,7 +114,7 @@ def _read_table(self) -> "pa.Table": def _build(self, table: "pa.Table") -> SourceStreamResult: """Enrich ``table`` as this source's stream (source info, system tags).""" - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) return builder.build( table, tag_columns=self._tag_columns, diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index aeef4bfd5..122d46cab 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -616,7 +616,7 @@ def _derive_from( table = table.append_column( table.schema.field(tag).with_name(name), table.column(tag) ) - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) result = builder.build( table, tag_columns=self._origin.keys()[0], diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index d45d68a92..ef08b5895 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -84,7 +84,7 @@ def __init__( ) self._key_columns = normalize_record_id_columns(record_id_columns) or () - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) result = builder.build( arrow_table, tag_columns=tag_columns, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f18da3433..6bac10c39 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -121,7 +121,7 @@ def __init__( ) self._key_columns = normalize_record_id_columns(record_id_columns) or () - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) result = builder.build( arrow_table, tag_columns=tag_columns, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 3b4f65398..107a42328 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -50,7 +50,7 @@ from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.utils.schema_utils import ( _normalize_column_list, - compute_source_schema_hash, + compute_schema_hash, declared_arrow_schema, ) @@ -384,14 +384,14 @@ def _declared_schema_hash(self) -> str | None: _tag_source_id:: → source-ID column (large_string) _tag_record_id:: → record-ID column (large_string) - where ```` is produced by ``compute_source_schema_hash(tag_schema, - data_schema, data_context, config)``. + where ```` is produced by ``compute_schema_hash(tag_schema, + data_schema, data_context)``. Callers such as ``FunctionJobNode.async_execute`` ask for these column names up-front (via ``output_schema(columns={"system_tags": True})`` / ``keys(columns={"system_tags": True})``) before any data has been fetched. ``_declared_schema_hash`` computes this hash from the schemas - declared by ``impl.schema()`` via the shared ``compute_source_schema_hash`` + declared by ``impl.schema()`` via the shared ``compute_schema_hash`` helper, so those callers can get the correct column names and Arrow types without triggering a poll+fetch cycle. @@ -402,9 +402,7 @@ def _declared_schema_hash(self) -> str | None: declared = self._declared_arrow_pair() if declared is None: return None - return compute_source_schema_hash( - *declared, self.data_context, self.orcapod_config - ) + return compute_schema_hash(*declared, self.data_context) def _declared_arrow_pair(self) -> "tuple[pa.Schema, pa.Schema] | None": """The declared tag and data Arrow schemas, or ``None`` with none declared.""" @@ -943,7 +941,7 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: arrow_table = arrow_table.cast(target_schema) self._require_declared_types(arrow_table) - builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + builder = SourceStreamBuilder(self.data_context) result = builder.build( arrow_table, tag_columns=self._tag_columns, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index dcce1443f..ded72d556 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -422,7 +422,7 @@ def __init__( self._data_tags = source_data_tags(resolved_tags, tag_only_columns) # A zero-row stream with the table's columns answers every schema question. - self._builder = SourceStreamBuilder(self.data_context, self.orcapod_config) + self._builder = SourceStreamBuilder(self.data_context) try: template = self._builder.build( schema.empty_table(), diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 22736f37f..29cf32b9b 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -28,10 +28,9 @@ from orcapod.system_constants import constants from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.schema_utils import compute_source_schema_hash +from orcapod.utils.schema_utils import compute_schema_hash if TYPE_CHECKING: - from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext from orcapod.protocols.hashing_protocols import ArrowHasherProtocol @@ -449,12 +448,10 @@ class SourceStreamBuilder: Args: data_context: Provides type_converter, semantic_hasher, arrow_hasher. - config: Orcapod config (controls hash character counts). """ - def __init__(self, data_context: DataContext, config: OrcapodConfig) -> None: + def __init__(self, data_context: DataContext) -> None: self._data_context = data_context - self._config = config def build( self, @@ -591,11 +588,10 @@ def build( tag_schema = non_sys.select(list(tag_columns_tuple)).schema data_schema = non_sys.drop(list(tag_only_tuple)).schema try: - schema_hash = compute_source_schema_hash( + schema_hash = compute_schema_hash( tag_schema, data_schema, self._data_context, - self._config, ) except ValueError as exc: # A type the Arrow hasher cannot hash fails here first, at its schema diff --git a/src/orcapod/hashing/semantic_hashing/content_identifiable_mixin.py b/src/orcapod/hashing/semantic_hashing/content_identifiable_mixin.py index 8f7d8a796..2b9529991 100644 --- a/src/orcapod/hashing/semantic_hashing/content_identifiable_mixin.py +++ b/src/orcapod/hashing/semantic_hashing/content_identifiable_mixin.py @@ -256,7 +256,7 @@ def __repr__(self) -> str: encouraged to override this if they need a more informative repr. """ try: - short_hash = self.content_hash().to_hex(char_count=8) + short_hash = self.content_hash().to_hex()[:8] except Exception: short_hash = "" return f"{type(self).__name__}(content_hash={short_hash!r})" diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 0b58b8f37..92465b14b 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any import orcapod +from orcapod.config import config_for_save, validate_descriptor_config from orcapod.contexts import resolve_saved_context from orcapod.core.nodes import ( FunctionNode, @@ -188,16 +189,7 @@ def save(self, path: str | Path) -> None: _dc = getattr(node, "_data_context", None) data_context_key = _dc.context_key if _dc is not None else None - import dataclasses - - from orcapod.config import DEFAULT_CONFIG as _DEFAULT_CONFIG - - # Save None when the config matches DEFAULT_CONFIG so that future - # changes to the default are picked up on load (forward-compatible). - # See ENG-544 for the tradeoff discussion (reproducibility vs. - # forward-compatibility). - _cfg = node.orcapod_config - config_val = None if _cfg == _DEFAULT_CONFIG else dataclasses.asdict(_cfg) + config_val = config_for_save(node.orcapod_config) try: output_schema: dict[str, Any] = ( @@ -321,7 +313,7 @@ def load(cls, path: str | Path) -> "Pipeline": Raises: ValueError: If the file's format version is not the one this Orcapod - writes (an earlier format is refused, never migrated). + writes or a node specifies a removed hash-length setting. """ import json as _json from orcapod.pipeline.serialization import ( @@ -387,6 +379,7 @@ def load(cls, path: str | Path) -> "Pipeline": # Every node records its nullability (ITL-1043), and every function node # names its data-tags (ITL-1019). try: + validate_descriptor_config(descriptor.get("config")) require_nullability_records(descriptor) if descriptor.get("node_type") == "function": descriptor[FALL_THROUGH_TAGS_KEY] = list( diff --git a/src/orcapod/pipeline/loaded_side_effects.py b/src/orcapod/pipeline/loaded_side_effects.py index aa5182742..0c767aa4a 100644 --- a/src/orcapod/pipeline/loaded_side_effects.py +++ b/src/orcapod/pipeline/loaded_side_effects.py @@ -46,7 +46,7 @@ class SavedSideEffectNode: """ def __init__(self, descriptor: dict[str, Any]) -> None: - from orcapod.config import DEFAULT_CONFIG, OrcapodConfig + from orcapod.config import OrcapodConfig from orcapod.contexts import resolve_saved_context from orcapod.types import ContentHash @@ -72,11 +72,8 @@ def __init__(self, descriptor: dict[str, Any]) -> None: self.data_context: DataContext = resolve_saved_context( descriptor.get("data_context_key") ) - config_dict = descriptor.get("config") - self.orcapod_config: OrcapodConfig = ( - OrcapodConfig.from_dict(config_dict) - if config_dict is not None - else DEFAULT_CONFIG + self.orcapod_config: OrcapodConfig = OrcapodConfig.from_node_descriptor( + descriptor ) diff --git a/src/orcapod/types/__init__.py b/src/orcapod/types/__init__.py index f74d8a529..7907c07b0 100644 --- a/src/orcapod/types/__init__.py +++ b/src/orcapod/types/__init__.py @@ -646,16 +646,17 @@ class ContentHash: method: str digest: bytes - # TODO: make the default char count configurable def to_hex(self, char_count: int | None = None) -> str: """Convert the digest to a hexadecimal string. + System-tag column names and logical storage paths use the full digest. + Args: - char_count: If given, truncate the hex string to this many - characters. + char_count: Optional slice length for display. ``None`` or zero + returns the full digest. Returns: - The full (or truncated) hex representation of the digest. + The full or shortened hex representation of the digest. """ hex_str = self.digest.hex() return hex_str[:char_count] if char_count else hex_str diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 0ca064757..37be8b8aa 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -639,7 +639,6 @@ def compute_schema_hash( tag_schema: "pa.Schema", data_schema: "pa.Schema", data_context: Any, - char_count: int | None, ) -> str: """Compute the schema hash used for system-tag column naming. @@ -653,45 +652,12 @@ def compute_schema_hash( tag_schema: The Arrow schema of the tag columns. data_schema: The Arrow schema of the data columns (data-tags included). data_context: The active ``DataContext``. - char_count: Number of hex characters to include. ``None`` returns the full - hex digest. Returns: - Hex string: the full digest when ``char_count`` is ``None``, otherwise - truncated to ``char_count`` characters. + The full hex digest of the schema hash. """ identity = arrow_schema_identity(tag_schema, data_schema, data_context) - return data_context.semantic_hasher.hash_object(identity).to_hex( - char_count=char_count - ) - - -def compute_source_schema_hash( - tag_schema: "pa.Schema", - data_schema: "pa.Schema", - data_context: Any, - config: Any, -) -> str: - """Compute the schema hash for system-tag column naming from a ``DataContext`` and config. - - This is the canonical single entry-point used by ``SourceStreamBuilder``, - ``SourceNodeBase``, and ``PollingSource`` so the truncation by - ``config.hashing.schema_n_char`` is not replicated at every call site. - - Args: - tag_schema: The Arrow schema of the tag columns. - data_schema: The Arrow schema of the data columns (data-tags included). - data_context: The active ``DataContext``. - config: Active ``OrcapodConfig`` — ``config.hashing.schema_n_char`` - controls hash truncation. - - Returns: - Hex string schema hash, truncated to ``config.hashing.schema_n_char`` - characters. - """ - return compute_schema_hash( - tag_schema, data_schema, data_context, config.hashing.schema_n_char - ) + return data_context.semantic_hasher.hash_object(identity).to_hex() def column_names(columns: str | Iterable[str]) -> tuple[str, ...]: diff --git a/test-specification/property/test_hash_properties.py b/test-specification/property/test_hash_properties.py index e84cb3abf..bb6646753 100644 --- a/test-specification/property/test_hash_properties.py +++ b/test-specification/property/test_hash_properties.py @@ -69,14 +69,12 @@ def test_roundtrip(self, h): class TestContentHashHexConsistency: - """to_hex() truncation should be consistent.""" + """Hex conversion preserves the entire digest.""" - @given(content_hashes, st.integers(min_value=1, max_value=64)) + @given(content_hashes) @settings(max_examples=50) - def test_truncation_is_prefix(self, h, length): - full_hex = h.to_hex() - truncated = h.to_hex(length) - assert full_hex.startswith(truncated) + def test_hex_round_trip(self, h): + assert bytes.fromhex(h.to_hex()) == h.digest class TestContentHashEquality: diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 1376833e0..e8e4f0a49 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -1153,9 +1153,8 @@ def test_reducing_operator_names_system_tags_after_its_input( input. The input here is an operator's output, whose pipeline hash is not the schema-only hash of its rows. """ - op = make_op() stream = after_operator(source_a()) - suffix = stream.pipeline_hash().to_hex(op.orcapod_config.hashing.system_tag_n_char) + suffix = stream.pipeline_hash().to_hex() for rows in (sync_rows(make_op(), stream), async_rows(make_op(), stream)): for tag, _ in rows: names = list(tag.system_tags()) diff --git a/tests/test_core/operators/test_merge_join.py b/tests/test_core/operators/test_merge_join.py index 3f3203787..ce69dccfb 100644 --- a/tests/test_core/operators/test_merge_join.py +++ b/tests/test_core/operators/test_merge_join.py @@ -337,7 +337,6 @@ def test_system_tag_positions_are_argument_indices(self, left_source, right_sour from orcapod.system_constants import constants op = MergeJoin() - n_char = op.orcapod_config.hashing.system_tag_n_char for order in ((left_source, right_source), (right_source, left_source)): table = op.static_process(*order).as_table(columns={"system_tags": True}) sys_cols = [ @@ -346,7 +345,7 @@ def test_system_tag_positions_are_argument_indices(self, left_source, right_sour if c.startswith(constants.SYSTEM_TAG_PREFIX) ] for index, stream in enumerate(order): - suffix = f"{stream.pipeline_hash().to_hex(n_char)}:{index}" + suffix = f"{stream.pipeline_hash().to_hex()}:{index}" assert sum(c.endswith(suffix) for c in sys_cols) == 2, suffix def test_system_tag_values_same_pipeline_hash_follow_argument_order(self): @@ -632,11 +631,8 @@ def test_two_system_tag_columns_produced(self, left_source, right_source): def test_system_tag_positions_are_argument_indices(self, left_source, right_source): """System tag columns carry each input's argument index (ITL-1281).""" - from orcapod.config import OrcapodConfig from orcapod.system_constants import constants - n_char = OrcapodConfig().hashing.system_tag_n_char - op = MergeJoin() result = op.static_process(left_source, right_source) result_table = result.as_table(columns={"system_tags": True}) @@ -654,8 +650,8 @@ def test_system_tag_positions_are_argument_indices(self, left_source, right_sour ) positions[index_str] = stream_hash assert positions == { - "0": left_source.pipeline_hash().to_hex(n_char), - "1": right_source.pipeline_hash().to_hex(n_char), + "0": left_source.pipeline_hash().to_hex(), + "1": right_source.pipeline_hash().to_hex(), } def test_same_schema_inputs_distinguished_by_argument_position(self): diff --git a/tests/test_core/operators/test_operators.py b/tests/test_core/operators/test_operators.py index 7b766e7ac..ab4db2c5b 100644 --- a/tests/test_core/operators/test_operators.py +++ b/tests/test_core/operators/test_operators.py @@ -1393,7 +1393,7 @@ def test_source_schema_hash_matches_pipeline_hash(self): table, tag_columns=["id"], tag_only_columns=True, infer_nullable=True ) schema_hash = source._schema_hash - pipeline_hash_hex = source.pipeline_hash().to_hex(char_count=len(schema_hash)) + pipeline_hash_hex = source.pipeline_hash().to_hex() assert schema_hash == pipeline_hash_hex @@ -1488,11 +1488,9 @@ def test_system_tag_position_maps_to_correct_source(self, three_sources): - schema_hash matching the original source's schema_hash - stream_hash matching the input stream's pipeline_hash - canonical index matching the position""" - from orcapod.config import OrcapodConfig from orcapod.system_constants import constants src_a, src_b, src_c = three_sources - n_char = OrcapodConfig().hashing.system_tag_n_char # Independently determine expected position → source mapping sources = [src_a, src_b, src_c] @@ -1519,7 +1517,7 @@ def test_system_tag_position_maps_to_correct_source(self, three_sources): f"{expected_source._schema_hash!r}, got {schema_hash!r}" ) # For direct source→join, stream_hash == source's pipeline_hash - expected_stream_hash = expected_source.pipeline_hash().to_hex(n_char) + expected_stream_hash = expected_source.pipeline_hash().to_hex() assert stream_hash == expected_stream_hash, ( f"Position {expected_idx}: expected stream_hash " f"{expected_stream_hash!r}, got {stream_hash!r}" @@ -1595,12 +1593,9 @@ def test_intermediate_operators_produce_different_stream_hash(self): With an intermediate MapData, stream_hash comes from the DynamicPodStream which has a different pipeline_hash than the original source.""" - from orcapod.config import OrcapodConfig from orcapod.core.sources.arrow_table_source import ArrowTableSource from orcapod.system_constants import constants - n_char = OrcapodConfig().hashing.system_tag_n_char - src_a = ArrowTableSource( pa.table( { @@ -1686,7 +1681,7 @@ def test_intermediate_operators_produce_different_stream_hash(self): # stream_hash should match the intermediate stream's pipeline_hash # (different from schema_hash due to the MapData operator) - expected_stream_hash = expected_stream.pipeline_hash().to_hex(n_char) + expected_stream_hash = expected_stream.pipeline_hash().to_hex() assert stream_hash == expected_stream_hash, ( f"Position {expected_idx}: expected stream_hash " f"{expected_stream_hash!r}, got {stream_hash!r}" diff --git a/tests/test_core/sources/test_default_source_ids.py b/tests/test_core/sources/test_default_source_ids.py index 75e5a2a89..aa71e0c7a 100644 --- a/tests/test_core/sources/test_default_source_ids.py +++ b/tests/test_core/sources/test_default_source_ids.py @@ -16,7 +16,6 @@ import pyarrow as pa import pytest -from orcapod.config import HashingConfig, OrcapodConfig from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode @@ -162,14 +161,6 @@ def test_given_name_is_never_changed(self, cls, kind, make, data_column, given): sep = constants.BLOCK_SEPARATOR assert info == [f"{full}{sep}row_{i}{sep}{data_column}" for i in range(3)] - def test_default_is_full_length_whatever_path_n_char( - self, cls, kind, make, data_column - ): - """A default source id is a name, never shortened (developer, November 16, 2026).""" - full = make().source_id - config = OrcapodConfig(hashing=HashingConfig(path_n_char=12)) - assert make(config=config).source_id == full - class TestArrowTableDefaultIsTheLabelledTableHash: def test_default_is_kind_plus_the_table_hash_string(self): diff --git a/tests/test_core/sources/test_keyed_default_source_id.py b/tests/test_core/sources/test_keyed_default_source_id.py index 1e2e4f1d5..03ffa33ee 100644 --- a/tests/test_core/sources/test_keyed_default_source_id.py +++ b/tests/test_core/sources/test_keyed_default_source_id.py @@ -554,11 +554,10 @@ def test_as_given_two_row_orders_are_two_nodes(self, kind: str, role: str) -> No def test_build_takes_hash_in_key_order_by_keyword_only() -> None: """``SourceStreamBuilder.build`` refuses ``hash_in_key_order`` given by position.""" - from orcapod import DEFAULT_CONFIG from orcapod.contexts import get_default_context from orcapod.core.sources.stream_builder import SourceStreamBuilder - builder = SourceStreamBuilder(get_default_context(), DEFAULT_CONFIG) + builder = SourceStreamBuilder(get_default_context()) table = pa.Table.from_pylist(ROWS, schema=SCHEMA) positional: Any = builder.build # the signature refuses this; call it untyped with pytest.raises(TypeError): diff --git a/tests/test_core/sources/test_source_id_review_findings.py b/tests/test_core/sources/test_source_id_review_findings.py index 6efd2ea36..98c08b60a 100644 --- a/tests/test_core/sources/test_source_id_review_findings.py +++ b/tests/test_core/sources/test_source_id_review_findings.py @@ -345,23 +345,17 @@ def test_a_legacy_config_nested_in_a_cached_source_is_refused( class TestFinding5OneBuilderOneParser: @pytest.mark.parametrize("bad", ["wrong", "csv", "csv_v0", "Csv_v1", "csv_v1:x"]) def test_the_stream_builder_refuses_a_malformed_kind_part(self, bad): - from orcapod.config import DEFAULT_CONFIG from orcapod.contexts import resolve_context - builder = SourceStreamBuilder( - data_context=resolve_context(None), config=DEFAULT_CONFIG - ) + builder = SourceStreamBuilder(data_context=resolve_context(None)) table = pa.Table.from_pylist(ROWS, schema=SCHEMA) with pytest.raises(ValueError, match="kind part"): builder.build(table, tag_columns=KEY, source_name="x", kind_part=bad) def test_the_stream_builder_builds_a_valid_kind_part(self): - from orcapod.config import DEFAULT_CONFIG from orcapod.contexts import resolve_context - builder = SourceStreamBuilder( - data_context=resolve_context(None), config=DEFAULT_CONFIG - ) + builder = SourceStreamBuilder(data_context=resolve_context(None)) table = pa.Table.from_pylist(ROWS, schema=SCHEMA) result = builder.build( table, tag_columns=KEY, source_name="a:b", kind_part="csv_v1" diff --git a/tests/test_core/sources/test_stream_builder.py b/tests/test_core/sources/test_stream_builder.py index ce96a7fe0..4bdd53335 100644 --- a/tests/test_core/sources/test_stream_builder.py +++ b/tests/test_core/sources/test_stream_builder.py @@ -16,10 +16,9 @@ class TestSourceStreamBuilder: @pytest.fixture def builder(self): from orcapod.contexts import resolve_context - from orcapod.config import DEFAULT_CONFIG ctx = resolve_context(None) - return SourceStreamBuilder(data_context=ctx, config=DEFAULT_CONFIG) + return SourceStreamBuilder(data_context=ctx) def test_build_returns_source_stream_result(self, builder): table = pa.table({"id": pa.array([1, 2]), "x": pa.array([10, 20])}) @@ -115,10 +114,9 @@ class TestSourceStreamBuilderRespectsSchema: @pytest.fixture def builder(self): from orcapod.contexts import resolve_context - from orcapod.config import DEFAULT_CONFIG ctx = resolve_context(None) - return SourceStreamBuilder(data_context=ctx, config=DEFAULT_CONFIG) + return SourceStreamBuilder(data_context=ctx) def test_nullable_true_schema_preserved(self, builder): """build() preserves nullable=True from incoming schema.""" diff --git a/tests/test_core/streams/test_streams.py b/tests/test_core/streams/test_streams.py index 45eb020cb..5e7b96852 100644 --- a/tests/test_core/streams/test_streams.py +++ b/tests/test_core/streams/test_streams.py @@ -515,13 +515,12 @@ def test_non_nullable_fields_yield_plain_type_in_output_schema(self): def test_infer_schema_nullable_before_build_produces_plain_type(self): """Applying infer_schema_nullable() before build() gives plain T for null-free columns.""" - from orcapod.config import DEFAULT_CONFIG from orcapod.contexts import resolve_context from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.utils import arrow_utils ctx = resolve_context(None) - builder = SourceStreamBuilder(data_context=ctx, config=DEFAULT_CONFIG) + builder = SourceStreamBuilder(data_context=ctx) # Raw Arrow table with nullable=True (the default) table = pa.table( diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index 9335098ea..2dfe4277c 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -936,23 +936,21 @@ def schema_compute_schema_hash() -> dict[str, Any]: from orcapod.utils.schema_utils import compute_schema_hash tag_schema, data_schema = _tag_data_arrow_schemas() - ctx = _ctx() + full = compute_schema_hash(tag_schema, data_schema, _ctx()) return { - "full": compute_schema_hash(tag_schema, data_schema, ctx, None), - "chars_16": compute_schema_hash(tag_schema, data_schema, ctx, 16), + "full": full, + # Preserve the existing golden projection of the full digest. + "chars_16": full[:16], } @case("schema", "source_schema_hash") def schema_source_schema_hash() -> dict[str, Any]: - from orcapod import DEFAULT_CONFIG from orcapod.utils.arrow_utils import system_tag_column_names - from orcapod.utils.schema_utils import compute_source_schema_hash + from orcapod.utils.schema_utils import compute_schema_hash tag_schema, data_schema = _tag_data_arrow_schemas() - schema_hash = compute_source_schema_hash( - tag_schema, data_schema, _ctx(), DEFAULT_CONFIG - ) + schema_hash = compute_schema_hash(tag_schema, data_schema, _ctx()) source_id_col, record_id_col = system_tag_column_names(schema_hash) return { "schema_hash": schema_hash, @@ -981,10 +979,9 @@ def _builder_table() -> pa.Table: @case("schema", "source_stream_builder") def schema_source_stream_builder() -> dict[str, Any]: # SourceStreamBuilder is not public API; the issue names it as a pinned call site. - from orcapod import DEFAULT_CONFIG from orcapod.core.sources.stream_builder import SourceStreamBuilder - builder = SourceStreamBuilder(_ctx(), DEFAULT_CONFIG) + builder = SourceStreamBuilder(_ctx()) out: dict[str, Any] = {} variants: dict[str, dict[str, Any]] = { # Every source id has a kind part (ITL-1425): the builder takes it and a name. @@ -1091,7 +1088,6 @@ def schema_hash_in_key_order() -> dict[str, Any]: Returns: Each variant's source id, content hash and table hash. """ - from orcapod import DEFAULT_CONFIG from orcapod.core.sources import ( ArrowTableSource, DataFrameSource, @@ -1172,7 +1168,7 @@ def build(kind: str, rows: list[dict[str, Any]], **kw: Any) -> Any: prefix = f"{kind}.aligned.{key_name}" out[f"{prefix}.source_id"] = source.source_id out[f"{prefix}.content_hash"] = source.content_hash().to_string() - builder = SourceStreamBuilder(_ctx(), DEFAULT_CONFIG) + builder = SourceStreamBuilder(_ctx()) for variant, kwargs in variants.items(): for order, rows in row_orders.items(): result = builder.build( diff --git a/tests/test_hashing/test_semantic_hasher.py b/tests/test_hashing/test_semantic_hasher.py index 18604fa05..95673a11a 100644 --- a/tests/test_hashing/test_semantic_hasher.py +++ b/tests/test_hashing/test_semantic_hasher.py @@ -372,6 +372,25 @@ def test_different_uuids_differ(self, hasher): # --------------------------------------------------------------------------- +@pytest.mark.parametrize( + ("char_count", "expected"), + [ + (None, "deadbeef"), + (0, "deadbeef"), + (4, "dead"), + (20, "deadbeef"), + (-1, "deadbee"), + ], +) +def test_content_hash_to_hex_display_length( + char_count: int | None, expected: str +) -> None: + content_hash = ContentHash("test_v1", bytes.fromhex("deadbeef")) + + assert content_hash.to_hex() == "deadbeef" + assert content_hash.to_hex(char_count=char_count) == expected + + class TestContentHashTerminal: def test_content_hash_returned_as_is(self, hasher): """hash_object(ContentHash) must return the same object unchanged.""" @@ -1073,8 +1092,8 @@ def test_content_hash_conversion_methods(self): assert isinstance(ch.to_hex(), str) assert len(ch.to_hex()) == 64 assert isinstance(ch.to_int(), int) - assert isinstance(ch.to_hex(16), str) - assert len(ch.to_hex(16)) == 16 + assert ch.to_int(hexdigits=16) == int(ch.to_hex()[:16], 16) + assert ch.to_string(prefix_method=False, hexdigits=16) == ch.to_hex()[:16] def test_get_default_arrow_hasher_returns_protocol_instance(self): """get_default_arrow_hasher() returns the arrow hasher from the default context.""" diff --git a/tests/test_orcapod_config.py b/tests/test_orcapod_config.py index fb1fe7c17..90c471ba5 100644 --- a/tests/test_orcapod_config.py +++ b/tests/test_orcapod_config.py @@ -2,43 +2,75 @@ from __future__ import annotations +from collections import UserDict +from dataclasses import make_dataclass +from typing import Any -class TestHashingConfig: - def test_defaults(self): - from orcapod.config import HashingConfig +import pytest - cfg = HashingConfig() - assert cfg.system_tag_n_char is None - assert cfg.schema_n_char is None - assert cfg.path_n_char is None - def test_is_frozen(self): - import dataclasses +REMOVED_HASHING_FIELDS = ("system_tag_n_char", "schema_n_char", "path_n_char") - import pytest - from orcapod.config import HashingConfig +@pytest.mark.parametrize("key", REMOVED_HASHING_FIELDS) +def test_removed_hashing_constructor_field_is_refused(key: str) -> None: + from orcapod.config import HashingConfig - cfg = HashingConfig() - with pytest.raises(dataclasses.FrozenInstanceError): - cfg.system_tag_n_char = 99 # type: ignore[misc] + with pytest.raises(TypeError, match=key): + HashingConfig(**{key: 6}) - def test_merge_non_default_wins(self): - from orcapod.config import HashingConfig - base = HashingConfig() - other = HashingConfig(system_tag_n_char=8) - merged = base.merge(other) - assert merged.system_tag_n_char == 8 - assert merged.schema_n_char is None # unchanged +@pytest.mark.parametrize("key", REMOVED_HASHING_FIELDS) +@pytest.mark.parametrize("value", [6, 0, None]) +def test_removed_hashing_subclass_field_is_refused(key: str, value: int | None) -> None: + from orcapod.config import HashingConfig, OrcapodConfig - def test_merge_default_does_not_override(self): - from orcapod.config import HashingConfig + legacy_type = make_dataclass( + "LegacyHashingConfig", [(key, int | None)], bases=(HashingConfig,), frozen=True + ) + with pytest.raises(ValueError, match=rf"hashing\.{key}"): + OrcapodConfig(hashing=legacy_type(value)) - base = HashingConfig(system_tag_n_char=6) - other = HashingConfig() # all defaults - merged = base.merge(other) - assert merged.system_tag_n_char == 6 # base value preserved + +@pytest.mark.parametrize("key", REMOVED_HASHING_FIELDS) +@pytest.mark.parametrize("value", [0, None]) +@pytest.mark.parametrize("entry_point", ["constructor", "with_updates"]) +def test_removed_programmatic_hashing_mapping_field_is_refused( + key: str, value: int | None, entry_point: str +) -> None: + from orcapod.config import DEFAULT_CONFIG, OrcapodConfig + + # Exercise a runtime input beyond the constructor's annotated HashingConfig. + hashing: Any = UserDict({key: value}) + factory = ( + OrcapodConfig if entry_point == "constructor" else DEFAULT_CONFIG.with_updates + ) + with pytest.raises(ValueError, match=rf"hashing\.{key}"): + factory(hashing=hashing) + + +@pytest.mark.parametrize("key", REMOVED_HASHING_FIELDS) +@pytest.mark.parametrize("value", [6, 0, None]) +def test_removed_hashing_mapping_field_is_refused(key: str, value: int | None) -> None: + from orcapod.config import OrcapodConfig + + with pytest.raises(ValueError, match=rf"hashing\.{key}"): + OrcapodConfig.from_dict({"hashing": {key: value}}) + + +@pytest.mark.parametrize("key", REMOVED_HASHING_FIELDS) +@pytest.mark.parametrize( + "toml", + ["[hashing]\n{key} = 6\n", "[[hashing]]\n[[hashing]]\n{key} = 6\n"], + ids=["table", "array-of-tables"], +) +def test_removed_hashing_toml_field_is_refused(key: str, toml: str, tmp_path) -> None: + from orcapod.config import load_config + + project_cfg = tmp_path / "orcapod_config.toml" + project_cfg.write_text(toml.format(key=key)) + with pytest.raises(ValueError, match=rf"hashing\.{key}"): + load_config(project_cfg, tmp_path / "missing.toml") class TestDisplayConfig: @@ -95,14 +127,6 @@ def test_default_config_is_orcapod_config_instance(self): assert isinstance(DEFAULT_CONFIG, OrcapodConfig) - def test_with_updates_hashing_section(self): - from orcapod.config import HashingConfig, OrcapodConfig - - cfg = OrcapodConfig() - updated = cfg.with_updates(hashing=HashingConfig(system_tag_n_char=8)) - assert updated.hashing.system_tag_n_char == 8 - assert cfg.hashing.system_tag_n_char is None # original unchanged - def test_with_updates_display_section(self): from orcapod.config import DisplayConfig, OrcapodConfig @@ -111,22 +135,6 @@ def test_with_updates_display_section(self): assert updated.display.max_rows == 50 assert cfg.display.max_rows is None # original unchanged - def test_merge_hashing_non_default_wins(self): - from orcapod.config import HashingConfig, OrcapodConfig - - base = OrcapodConfig() - other = OrcapodConfig(hashing=HashingConfig(system_tag_n_char=8)) - merged = base.merge(other) - assert merged.hashing.system_tag_n_char == 8 - - def test_merge_hashing_default_does_not_override(self): - from orcapod.config import HashingConfig, OrcapodConfig - - base = OrcapodConfig(hashing=HashingConfig(system_tag_n_char=6)) - other = OrcapodConfig() - merged = base.merge(other) - assert merged.hashing.system_tag_n_char == 6 - def test_merge_display_non_default_wins(self): from orcapod.config import DisplayConfig, OrcapodConfig @@ -151,24 +159,16 @@ def test_empty_dict_returns_default(self): assert OrcapodConfig.from_dict({}) == DEFAULT_CONFIG - def test_partial_hashing_section(self): - from orcapod.config import OrcapodConfig - - cfg = OrcapodConfig.from_dict({"hashing": {"system_tag_n_char": 8}}) - assert cfg.hashing.system_tag_n_char == 8 - assert cfg.hashing.schema_n_char is None # default preserved - def test_full_sections_round_trip(self): from orcapod.config import OrcapodConfig data = { - "hashing": {"system_tag_n_char": 8, "schema_n_char": 6, "path_n_char": 16}, + "hashing": {}, + "datetime": {"timezone_policy": "coerce_utc"}, "display": {"max_rows": 100, "show_source_columns": True}, } cfg = OrcapodConfig.from_dict(data) - assert cfg.hashing.system_tag_n_char == 8 - assert cfg.hashing.schema_n_char == 6 - assert cfg.hashing.path_n_char == 16 + assert cfg.datetime.timezone_policy == "coerce_utc" assert cfg.display.max_rows == 100 assert cfg.display.show_source_columns is True @@ -210,7 +210,7 @@ def test_non_dict_hashing_section_warns_and_uses_defaults(self, caplog): with caplog.at_level(logging.WARNING, logger="orcapod.config"): cfg = OrcapodConfig.from_dict({"hashing": "not-a-table"}) assert "hashing" in caplog.text - assert cfg.hashing.system_tag_n_char is None # falls back to default + assert cfg == OrcapodConfig() def test_non_dict_display_section_warns_and_uses_defaults(self, caplog): import logging @@ -237,12 +237,12 @@ def test_user_global_config_applied(self, tmp_path): from orcapod.config import load_config user_cfg = tmp_path / "config.toml" - user_cfg.write_text("[hashing]\nsystem_tag_n_char = 8\n") + user_cfg.write_text("[display]\nmax_rows = 8\n") result = load_config( user_config_path=user_cfg, project_config_path=tmp_path / "nonexistent.toml", ) - assert result.hashing.system_tag_n_char == 8 + assert result.display.max_rows == 8 def test_project_local_config_applied(self, tmp_path): from orcapod.config import load_config @@ -259,28 +259,11 @@ def test_project_local_wins_over_user_global(self, tmp_path): from orcapod.config import load_config user_cfg = tmp_path / "user.toml" - user_cfg.write_text("[hashing]\nsystem_tag_n_char = 6\n") - project_cfg = tmp_path / "project.toml" - project_cfg.write_text("[hashing]\nsystem_tag_n_char = 10\n") - result = load_config(user_config_path=user_cfg, project_config_path=project_cfg) - assert result.hashing.system_tag_n_char == 10 - - def test_project_local_wins_over_user_global_with_explicit_value(self, tmp_path): - """Project-local file wins over user-global file when both set an explicit value. - - The built-in default is now ``None``, which cannot be expressed in TOML, so - this test verifies the simpler (and still meaningful) case: project value 12 - beats user value 6. - """ - from orcapod.config import load_config - - user_cfg = tmp_path / "user.toml" - user_cfg.write_text("[hashing]\nsystem_tag_n_char = 6\n") + user_cfg.write_text("[display]\nmax_rows = 6\n") project_cfg = tmp_path / "project.toml" - # Project sets 12 (a non-default value) — should win over user's 6. - project_cfg.write_text("[hashing]\nsystem_tag_n_char = 12\n") + project_cfg.write_text("[display]\nmax_rows = 10\n") result = load_config(user_config_path=user_cfg, project_config_path=project_cfg) - assert result.hashing.system_tag_n_char == 12 + assert result.display.max_rows == 10 def test_malformed_toml_raises_value_error(self, tmp_path): import pytest diff --git a/tests/test_pipeline/test_serialization.py b/tests/test_pipeline/test_serialization.py index 72662c5e2..0cc9ac3a0 100644 --- a/tests/test_pipeline/test_serialization.py +++ b/tests/test_pipeline/test_serialization.py @@ -2,12 +2,14 @@ from __future__ import annotations +import dataclasses import json import pyarrow as pa import pytest import orcapod +from orcapod.config import DEFAULT_CONFIG, DisplayConfig, HashingConfig, OrcapodConfig from orcapod.core.nodes import SourceNode from orcapod.core.operators import Join from orcapod.core.sources import ArrowTableSource @@ -15,6 +17,7 @@ from orcapod.pipeline import Pipeline from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.serialization import PIPELINE_FORMAT_VERSION +from orcapod.types import Schema @pytest.fixture @@ -47,6 +50,107 @@ def _src(tag, data): return pipeline, tmp_path +@pytest.fixture(params=[False, True], ids=["forward", "reverse"]) +def hashing_settings_pipeline(request): + """Build the same join with two tag, data and operand arrangements.""" + + def build(left_config: OrcapodConfig = DEFAULT_CONFIG) -> Pipeline: + def schema(*names: str) -> Schema: + order = names[::-1] if request.param else names + return Schema({name: int for name in order}) + + left = SourceNode( + name="left", + tag_schema=schema("k1", "k2", "k3"), + data_schema=schema("a", "b", "c"), + config=left_config, + ) + right = SourceNode( + name="right", + tag_schema=schema("k1", "k2", "k3"), + data_schema=schema("d", "e", "f"), + ) + inputs = (right, left) if request.param else (left, right) + with Pipeline(name="hashing_settings") as pipeline: + Join()(*inputs, label="joiner") + return pipeline + + return build + + +def test_saved_pipeline_accepts_old_default_hashing_settings( + hashing_settings_pipeline, tmp_path +) -> None: + pipeline = hashing_settings_pipeline() + path = tmp_path / "pipeline.json" + pipeline.save(path) + saved = json.loads(path.read_text()) + operator = next(n for n in saved["nodes"].values() if n["node_type"] == "operator") + # A read-only node restores its display settings directly from the descriptor. + del operator["operator_config"] + # The old writer serialized all dataclass defaults alongside a display override. + operator["config"] = dataclasses.asdict( + DEFAULT_CONFIG.with_updates(display=DisplayConfig(max_rows=17)) + ) + operator["config"]["hashing"] = { + "system_tag_n_char": None, + "schema_n_char": None, + "path_n_char": None, + } + path.write_text(json.dumps(saved)) + + loaded = Pipeline.load(path) + assert loaded.nodes["joiner"].orcapod_config.display.max_rows == 17 + loaded.save(path) + resaved = json.loads(path.read_text()) + operator = next( + n for n in resaved["nodes"].values() if n["node_type"] == "operator" + ) + assert operator["config"]["hashing"] == {} + + +def test_pipeline_save_omits_removed_hashing_settings( + hashing_settings_pipeline, tmp_path +) -> None: + @dataclasses.dataclass(frozen=True) + class LegacyHashingConfig(HashingConfig): + system_tag_n_char: int = 6 + schema_n_char: int = 0 + path_n_char: int | None = None + + config = OrcapodConfig(display=DisplayConfig(max_rows=17)) + # Simulate a legacy typed object reaching save without constructor validation. + object.__setattr__(config, "hashing", LegacyHashingConfig()) + pipeline = hashing_settings_pipeline(config) + + path = tmp_path / "pipeline.json" + pipeline.save(path) + saved = json.loads(path.read_text()) + descriptor = next(n for n in saved["nodes"].values() if n["label"] == "left") + assert descriptor["config"]["hashing"] == {} + assert descriptor["config"]["display"]["max_rows"] == 17 + assert "left" in Pipeline.load(path).nodes + + +@pytest.mark.parametrize("node_type", ["source", "operator"]) +@pytest.mark.parametrize("key", ["system_tag_n_char", "schema_n_char", "path_n_char"]) +@pytest.mark.parametrize("as_array", [False, True], ids=["object", "array"]) +def test_saved_pipeline_refuses_removed_hashing_settings( + hashing_settings_pipeline, tmp_path, node_type: str, key: str, as_array: bool +) -> None: + pipeline = hashing_settings_pipeline() + path = tmp_path / "pipeline.json" + pipeline.save(path) + saved = json.loads(path.read_text()) + node = next(n for n in saved["nodes"].values() if n["node_type"] == node_type) + fields = {key: 6} + node["config"] = {"hashing": [{}, fields] if as_array else fields} + path.write_text(json.dumps(saved)) + + with pytest.raises(ValueError, match=rf"hashing\.{key}"): + Pipeline.load(path) + + class TestPipelineBlueprintSave: def test_save_creates_file(self, spec_pipeline): pipeline, tmp_path = spec_pipeline diff --git a/tests/test_utils/test_schema_utils.py b/tests/test_utils/test_schema_utils.py index c6f51608e..0c1256f8b 100644 --- a/tests/test_utils/test_schema_utils.py +++ b/tests/test_utils/test_schema_utils.py @@ -46,7 +46,7 @@ class TestComputeSchemaHash: def test_returns_full_hex_digest(self, ctx): from orcapod.utils.schema_utils import compute_schema_hash - result = compute_schema_hash(TAG, DATA, ctx, None) + result = compute_schema_hash(TAG, DATA, ctx) assert isinstance(result, str) # SHA-256 digest is 32 bytes = 64 hex characters, no label. assert len(result) == 64 @@ -55,15 +55,10 @@ def test_returns_full_hex_digest(self, ctx): def test_deterministic(self, ctx): from orcapod.utils.schema_utils import compute_schema_hash - assert compute_schema_hash(TAG, DATA, ctx, None) == compute_schema_hash( - TAG, DATA, ctx, None + assert compute_schema_hash(TAG, DATA, ctx) == compute_schema_hash( + TAG, DATA, ctx ) - def test_length_equals_char_count_when_explicit(self, ctx): - from orcapod.utils.schema_utils import compute_schema_hash - - assert len(compute_schema_hash(TAG, DATA, ctx, 12)) == 12 - @pytest.mark.parametrize( "other", [ @@ -78,8 +73,8 @@ def test_an_arrow_type_difference_is_another_hash(self, ctx, other): from orcapod.utils.schema_utils import compute_schema_hash changed = pa.schema([DATA.field("value"), other]) - assert compute_schema_hash(TAG, DATA, ctx, None) != compute_schema_hash( - TAG, changed, ctx, None + assert compute_schema_hash(TAG, DATA, ctx) != compute_schema_hash( + TAG, changed, ctx ) def test_column_order_and_large_variants_are_not_part_of_it(self, ctx): @@ -91,9 +86,9 @@ def test_column_order_and_large_variants_are_not_part_of_it(self, ctx): plain_tag = pa.schema( [TAG.field("id"), pa.field("site", pa.string())] ) # string, not large_string - expected = compute_schema_hash(TAG, DATA, ctx, None) - assert compute_schema_hash(reordered_tag, reordered_data, ctx, None) == expected - assert compute_schema_hash(plain_tag, DATA, ctx, None) == expected + expected = compute_schema_hash(TAG, DATA, ctx) + assert compute_schema_hash(reordered_tag, reordered_data, ctx) == expected + assert compute_schema_hash(plain_tag, DATA, ctx) == expected @dataclasses.dataclass