Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions changelog.d/ITL-556.md
Original file line number Diff line number Diff line change
@@ -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.
18 changes: 18 additions & 0 deletions docs/dev/design_issues/ITL-556-HL1.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 2 additions & 2 deletions docs/dev/specs/itl-939-experiments/exp02_workarounds_today.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
14 changes: 7 additions & 7 deletions docs/dev/specs/itl-939-experiments/exp03_copy_tag_prototype.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -203,15 +203,15 @@ 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"
)
print(" for both rows (ResultCache keys on the input data hash only).")
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).
Expand Down
4 changes: 2 additions & 2 deletions docs/dev/specs/itl-939-experiments/exp05_hash_comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
Expand Down Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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]:
Expand Down
14 changes: 7 additions & 7 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | `"<kind part>:" + StarfixArrowHasher.hash_table(table).to_string()` | `str`, `<kind>_v<N>:<algorithm label>:<hex>` | 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_<n>`, 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 | `"<fold label>:<hex>"` `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 |
Expand Down Expand Up @@ -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 |

Expand All @@ -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(<kind>, <version>, 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`: `<kind>_v<N>:<algorithm label>:<hex>`, 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`: `<kind>_v<N>:<algorithm label>:<hex>`, 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. |

Expand Down Expand Up @@ -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. |
Expand All @@ -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:<hex>` for `Batch` (`BATCH_FOLD_LABEL`, in `batch.py`), `group_v1:<hex>` 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:<hex>` for `Batch` (`BATCH_FOLD_LABEL`, in `batch.py`), `group_v1:<hex>` 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** | `"<fold label>:<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 |
Expand Down
8 changes: 2 additions & 6 deletions scripts/hash_audit_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading