diff --git a/.zed/rules b/.zed/rules index bbd33d319..8bad0d5ae 100644 --- a/.zed/rules +++ b/.zed/rules @@ -893,7 +893,7 @@ Every pipeline element has two parallel hashes: identity. For a source it is a stable address, not a digest of its rows (developer, November 11, 2026: "sources content hash is meant to be a stable address and is not necessarily going to reflect the very data content"). A root source hashes - (class name, output schema, source_id, key columns); given a source_id, changed, added or + (class name, Arrow schema identity, source_id, key columns); given a source_id, changed, added or reordered rows leave it unchanged. The key columns are the resolved record_id_columns in key order (() for the position; a database or SpiralDB table's primary key by default): two sources that differ only in how they name their rows are two sources, with one pipeline @@ -916,9 +916,10 @@ Every pipeline element has two parallel hashes: memoized by. The node's content hash tells apart, inside a shared table, the rows of pipelines bound to different sources (__node_content_hash). 2. pipeline_hash() — schema + topology only. Ignores data content. Used for DB path scoping - so that different sources with identical schemas share database tables. + so that different sources with identical Arrow schemas share database tables. -Base case: RootSource.pipeline_identity_structure() returns (tag_schema, data_schema). +Base case: RootSource.pipeline_identity_structure() returns the Arrow schema identity of +its tag and data schemas (below, "Schemas are hashed as Arrow schemas"). Each downstream node's pipeline hash commits to its own identity plus upstream pipeline hashes, forming a Merkle chain. @@ -1066,6 +1067,51 @@ generation of hashing; rows of the current data context are the current entries. detection and automatic recomputation. - Source delegation — CSVSource, DictSource, etc. create an internal ArrowTableSource. +### Schemas are hashed as Arrow schemas + +Developer, November 18, 2026 (ITL-640; option B): a schema enters every identity as its Arrow +schema, large-normalized, hashed by the one function StarfixArrowHasher.hash_schema +(label arrow_schema_v1, ARROW_SCHEMA_HASH_LABEL), never as Python types. The places: a +source's pipeline and content identity and an input slot's +(schema_utils.arrow_schema_identity: the tag and data schemas hashed apart, as nested +ContentHash objects), the system-tag column names (compute_schema_hash, the semantic hash +of that pair, bare hex) and the output schema in a function's uri (the converter's Arrow +schema of the declared outputs, fed as a one-schema tuple, bare hex). output_schema() still +reports Python types; a function's INPUT check stays at the Python level; a function's input +types are in no schema hash. + +- Which Arrow schema: a source's or node's typed zero-row table (never computed from rows), + cached per source (RootSource.arrow_schemas); a DerivedSource takes its origin's and + refuses a stored read of another type (top-level nullability aside); a CachedSource its + source's, and refuses a cache read of another type by the same rule + (schema_utils.stored_type_mismatch); a slot made from a stream, that stream's (SourceNodeBase.arrow_schemas); a + saved job writes each slot's own Arrow types and a load rebuilds them; an unbound slot with + known Arrow types types its zero-row table from them; a loaded function node types its + zero-row output from its saved Arrow text. +- Declared Python types mean one Arrow type each, the converter's (int is int64, + datetime is timestamp[us, tz=UTC]): a hand-declared slot, an unbound SourceProxy, a + PollingSource whose impl.schema() returns a Python Schema. A source, slot or batch of + another Arrow type is refused (bind: SourceSpecMismatchError; a polled batch: + SchemaInconsistencyError before commit), never converted. The remedy is declaring in + Arrow: SourceNode(name, tag_schema=pa.schema(...), data_schema=pa.schema(...)), + impl.schema() returning a pa.Schema. Never loosen this. +- hash_schema ignores column order, large/non-large, list item field names, dictionary + encoding and field metadata other than ARROW:extension:*; it tells apart width, sign, + nullability at every depth, timestamp unit and zone, decimal precision, date types, + fixed-size against plain lists, struct fields, and a logical type's whole identifier. +- hash_schema hashes the DECLARED schema (developer, November 21, 2026, ITL-640, option + (a)): every logical type, live, in metadata (IPC) form or unregistered in the process, is + first brought to its storage form, its storage type with its identifier as + ARROW:extension:* field metadata, at any depth (canonical_form.storage_form_schema, + applied by hash_schema itself). No value-handler rewrite, no registry lookup: the + identifier pins how the values are hashed. hash_table is unchanged and a separate + procedure; never rely on hash_schema(t.schema) being the schema inside hash_table(t). + The saved-schema writer writes the storage form; an Arrow declaration and a saved schema + read back take declaration_form_schema: a top-level logical type live, a nested one + (inside a plain list, struct or map) always in the storage form, never a nested live + extension type (Arrow cannot build an empty table of one). The tests enumerate every + registered logical type from the converter (test_schema_hash_storage_form.py). + ### Arrow types Governing principle (developer, November 9, 2026): minimize convenient inference and hold to @@ -1086,8 +1132,17 @@ per-operator normalization. Names, nullability (top level and nested), field met logical (extension) types are untouched, and large and non-large variants hash identically, so no hash or default source id moves. Not covered: what is inside a library value (numpy, pandas, polars, torch) keeps its library's own distinction. list_view and large_list_view are not -supported: a source refuses them (the Arrow hasher cannot hash them) and a raw ArrowTableStream -holds them as given (ITL-1129). +supported (ITL-1129), and neither is a union (dense or sparse) or a run-end-encoded type: a +source and a raw ArrowTableStream refuse a column whose type is or contains one when they +are built (developer, November 21, 2026, ITL-640, for unions and list views; run-end-encoded +by the same rule, the coordinator the same day: one rule for every type the schema hash +rejects. A stream's identity is its Arrow schema hash, which cannot hold them; a raw stream +used to hold them as given). One rule beside the dictionary refusal, +schema_utils.schema_hash_rejected_columns with schema_hash_rejected_columns_error +(InputValidationError naming each column with its role and type), applied by +ArrowTableStream.__init__ and first by SourceStreamBuilder.build; the rejected kinds are +one constant, SCHEMA_HASH_REJECTED_KINDS, checked by a test against starfix's public schema +hash. Dictionary-encoded columns are refused, tags and data alike (developer, November 18, 2026, ITL-1264: "Say it is not currently supported in orcapod. We MAY support but not immediately in @@ -1241,14 +1296,18 @@ data. The rules: columns without a reason. SourceNodeBase.validate is the one check, used by PipelineJob.bind, the bound_source setter (and SourceJobNode.__init__) and PipelineJob.load: per column the declared Python type (structural classes of one identity - are one type, equivalent_hints), or T where the slot declares T | None; and exactly + are one type, equivalent_hints), or T where the slot declares T | None, AND the slot's + Arrow type, compared by hash_schema, with only a top-level non-null column accepted where + the slot's is nullable (nested nullability exact; ITL-640); and exactly one source-id (str) and one record-id (str) system-tag column, no other. Anything else raises SourceSpecMismatchError before anything is bound. The source's rows are given as the declared schema at one place, _DeclaredForm (nullable fields over the same arrays; the system-tag column NAMES of the declared schema hash, taken from the source's own pair by prefix, the VALUES the source's own; as a stable - convenience, not a guarantee, the declared column order, source id before record id). Limits: the check compares Python types, so a difference in Arrow width only - (int32 against int64) is not yet refused (ITL-949). A source whose system-tag columns + convenience, not a guarantee, the declared column order, source id before record id). A + difference in Arrow width only (int32 against int64) is refused (ITL-949, resolved by + ITL-640); never loosen this for timestamps or widths: a declared Python type means one + Arrow type, and the remedy is declaring the slot from the source or in Arrow. A source whose system-tag columns are not exactly one source-id and one record-id column (a joined or merged stream, a raw stream with none) is refused by the same check (developer, November 14, 2026, ITL-1126); binding one properly is ITL-1127. That includes a pipeline's input: Pipeline.compile diff --git a/CLAUDE.md b/CLAUDE.md index 7b04bb822..f1aeefe7a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -913,7 +913,7 @@ Every pipeline element has two parallel hashes: identity. For a source it is a stable *address*, not a digest of its rows (developer, November 11, 2026: "sources content hash is meant to be a stable address and is not necessarily going to reflect the very data content"). A root source hashes - `(class name, output schema, source_id, key columns)`; given a `source_id`, changed, added or + `(class name, Arrow schema identity, source_id, key columns)`; given a `source_id`, changed, added or reordered rows leave it unchanged. The key columns are the resolved `record_id_columns` in key order (`()` for the position; a database or SpiralDB table's primary key by default): two sources that differ only in how they name their rows are two sources, with one pipeline @@ -936,9 +936,10 @@ Every pipeline element has two parallel hashes: memoized by. The node's content hash tells apart, inside a shared table, the rows of pipelines bound to different sources (`__node_content_hash`). 2. **`pipeline_hash()`** — schema + topology only. Ignores data content. Used for DB path - scoping so that different sources with identical schemas share database tables. + scoping so that different sources with identical Arrow schemas share database tables. -Base case: `RootSource.pipeline_identity_structure()` returns `(tag_schema, data_schema)`. +Base case: `RootSource.pipeline_identity_structure()` returns the Arrow schema identity of +its tag and data schemas (below, "Schemas are hashed as Arrow schemas"). Each downstream node's pipeline hash commits to its own identity plus the pipeline hashes of its upstreams, forming a Merkle chain. @@ -1110,6 +1111,51 @@ and `as_table()` methods. `all_info=True` sets everything to True. - **Source delegation** — CSVSource, DictSource, etc. all create an internal `ArrowTableSource` and delegate every method to it. +### Schemas are hashed as Arrow schemas + +Developer, November 18, 2026 (ITL-640; option B): a schema enters every identity as its Arrow +schema, large-normalized, hashed by the one function `StarfixArrowHasher.hash_schema` +(label `arrow_schema_v1`, `ARROW_SCHEMA_HASH_LABEL`), never as Python types. The places: a +source's pipeline and content identity and an input slot's +(`schema_utils.arrow_schema_identity`: the tag and data schemas hashed apart, as nested +`ContentHash` objects), the system-tag column names (`compute_schema_hash`, the semantic hash +of that pair, bare hex) and the output schema in a function's `uri` (the converter's Arrow +schema of the declared outputs, fed as a one-schema tuple, bare hex). `output_schema()` still +reports Python types; a function's INPUT check stays at the Python level; a function's input +types are in no schema hash. + +- Which Arrow schema: a source's or node's typed zero-row table (never computed from rows), + cached per source (`RootSource.arrow_schemas`); a `DerivedSource` takes its origin's and + refuses a stored read of another type (top-level nullability aside); a `CachedSource` its + source's, and refuses a cache read of another type by the same rule + (`schema_utils.stored_type_mismatch`); a slot made from a stream, that stream's (`SourceNodeBase.arrow_schemas`); a + saved job writes each slot's own Arrow types and a load rebuilds them; an unbound slot with + known Arrow types types its zero-row table from them; a loaded function node types its + zero-row output from its saved Arrow text. +- Declared Python types mean one Arrow type each, the converter's (`int` is `int64`, + `datetime` is `timestamp[us, tz=UTC]`): a hand-declared slot, an unbound `SourceProxy`, a + `PollingSource` whose `impl.schema()` returns a Python `Schema`. A source, slot or batch of + another Arrow type is refused (bind: `SourceSpecMismatchError`; a polled batch: + `SchemaInconsistencyError` before commit), never converted. The remedy is declaring in + Arrow: `SourceNode(name, tag_schema=pa.schema(...), data_schema=pa.schema(...))`, + `impl.schema()` returning a `pa.Schema`. Never loosen this. +- `hash_schema` ignores column order, large/non-large, list item field names, dictionary + encoding and field metadata other than `ARROW:extension:*`; it tells apart width, sign, + nullability at every depth, timestamp unit and zone, decimal precision, date types, + fixed-size against plain lists, struct fields, and a logical type's whole identifier. +- `hash_schema` hashes the DECLARED schema (developer, November 21, 2026, ITL-640, option + (a)): every logical type, live, in metadata (IPC) form or unregistered in the process, is + first brought to its storage form, its storage type with its identifier as + `ARROW:extension:*` field metadata, at any depth (`canonical_form.storage_form_schema`, + applied by `hash_schema` itself). No value-handler rewrite, no registry lookup: the + identifier pins how the values are hashed. `hash_table` is unchanged and a separate + procedure; never rely on `hash_schema(t.schema)` being the schema inside `hash_table(t)`. + The saved-schema writer writes the storage form; an Arrow declaration and a saved schema + read back take `declaration_form_schema`: a top-level logical type live, a nested one + (inside a plain list, struct or map) always in the storage form, never a nested live + extension type (Arrow cannot build an empty table of one). The tests enumerate every + registered logical type from the converter (`test_schema_hash_storage_form.py`). + ### Arrow types Governing principle (developer, November 9, 2026): minimize convenient inference and hold to @@ -1130,8 +1176,17 @@ per-operator normalization. Names, nullability (top level and nested), field met logical (extension) types are untouched, and large and non-large variants hash identically, so no hash or default source id moves. Not covered: what is inside a library value (numpy, pandas, polars, torch) keeps its library's own distinction. `list_view` and `large_list_view` are not -supported: a source refuses them (the Arrow hasher cannot hash them) and a raw `ArrowTableStream` -holds them as given (ITL-1129). +supported (ITL-1129), and neither is a union (dense or sparse) or a run-end-encoded type: a +source and a raw `ArrowTableStream` refuse a column whose type is or contains one when they +are built (developer, November 21, 2026, ITL-640, for unions and list views; run-end-encoded +by the same rule, the coordinator the same day: one rule for every type the schema hash +rejects. A stream's identity is its Arrow schema hash, which cannot hold them; a raw stream +used to hold them as given). One rule beside the dictionary refusal, +`schema_utils.schema_hash_rejected_columns` with `schema_hash_rejected_columns_error` +(`InputValidationError` naming each column with its role and type), applied by +`ArrowTableStream.__init__` and first by `SourceStreamBuilder.build`; the rejected kinds are +one constant, `SCHEMA_HASH_REJECTED_KINDS`, checked by a test against starfix's public schema +hash. Dictionary-encoded columns are refused, tags and data alike (developer, November 18, 2026, ITL-1264: "Say it is not currently supported in orcapod. We MAY support but not immediately in @@ -1285,14 +1340,18 @@ data. The rules: columns without a reason. `SourceNodeBase.validate` is the one check, used by `PipelineJob.bind`, the `bound_source` setter (and `SourceJobNode.__init__`) and `PipelineJob.load`: per column the declared Python type (structural classes of one identity - are one type, `equivalent_hints`), or `T` where the slot declares `T | None`; and exactly + are one type, `equivalent_hints`), or `T` where the slot declares `T | None`, AND the slot's + Arrow type, compared by `hash_schema`, with only a top-level non-null column accepted where + the slot's is nullable (nested nullability exact; ITL-640); and exactly one source-id (`str`) and one record-id (`str`) system-tag column, no other. Anything else raises `SourceSpecMismatchError` before anything is bound. The source's rows are given as the declared schema at one place, `_DeclaredForm` (nullable fields over the same arrays; the system-tag column NAMES of the declared schema hash, taken from the source's own pair by prefix, the VALUES the source's own; as a stable - convenience, not a guarantee, the declared column order, source id before record id). Limits: the check compares Python types, so a difference in Arrow width only - (`int32` against `int64`) is not yet refused (ITL-949). A source whose system-tag columns + convenience, not a guarantee, the declared column order, source id before record id). A + difference in Arrow width only (`int32` against `int64`) is refused (ITL-949, resolved by + ITL-640); never loosen this for timestamps or widths: a declared Python type means one + Arrow type, and the remedy is declaring the slot from the source or in Arrow. A source whose system-tag columns are not exactly one source-id and one record-id column (a joined or merged stream, a raw stream with none) is refused by the same check (developer, November 14, 2026, ITL-1126); binding one properly is ITL-1127. That includes a pipeline's input: `Pipeline.compile` diff --git a/changelog.d/ITL-1023.md b/changelog.d/ITL-1023.md index c7e64cf66..2291c82a0 100644 --- a/changelog.d/ITL-1023.md +++ b/changelog.d/ITL-1023.md @@ -46,8 +46,7 @@ the tags stay data-tags (`FallThroughPod`). The function, its result identity and its result store are the plain pod's. `pod.process(stream)` is unchanged: its output data is the function's outputs and every output tag is plain. -- Saved job and pipeline files are at format `0.3.0`; files at `0.1.0` and `0.2.0` load - with every declared source tag plain, as they were written. +- Saved job and pipeline files state every tag binding (see below). - `Batch` works on data-tags (ITL-1017; developer decision, November 16, 2026: "Batch always simply takes anything and puts into list"). As for plain tags, every tag @@ -155,9 +154,8 @@ - Saved files of format `0.3.0` state every binding: each source config that takes the option writes `tag_only_columns` (`True` when every tag is plain), and each function - node writes `fall_through_tags` (empty for a plain pod). The format version decides - what a file means, never a missing key: a file at `0.1.0` or `0.2.0` holds only plain - tags, and a `0.3.0` file without these keys, or whose keys disagree with its saved + node writes `fall_through_tags` (empty for a plain pod). A missing key is never read + as a default: a file without these keys, or whose keys disagree with its saved schemas, is refused on load. - Errors that a data-tag causes name it and the way out; no behaviour changes. diff --git a/changelog.d/ITL-1315.md b/changelog.d/ITL-1315.md index 7f3190683..e0cf0e9a2 100644 --- a/changelog.d/ITL-1315.md +++ b/changelog.d/ITL-1315.md @@ -7,8 +7,8 @@ digits an integer, and the reloaded source had another content hash and pipeline hash under the same source id. The saved entry, `"schema"`, holds each field's Arrow type text (nested fields with their names and nullability) and the names of the nullable fields; a source - built without `schema=` saves no entry, and a configuration without one (inferred types, - or a file saved before this release) loads as before; a present entry of any other shape is + built without `schema=` saves no entry, and a configuration without one (inferred types) + loads as before; a present entry of any other shape is refused (`ValueError`; `PipelineJob.load` refuses the file). No hash changes. - An explicit schema that carries Arrow metadata (on a field at any depth, or on the schema itself) cannot be saved: `to_config()` and `PipelineJob.save` raise `ValueError` naming the diff --git a/changelog.d/ITL-640.md b/changelog.d/ITL-640.md new file mode 100644 index 000000000..16c8f7227 --- /dev/null +++ b/changelog.d/ITL-640.md @@ -0,0 +1,116 @@ +### Breaking changes and migration + +- **A schema is hashed as its Arrow schema, everywhere a schema enters an identity** (ITL-640, + ITL-949). A source's pipeline hash and content hash, an input slot's, the system-tag column + names and the output-schema part of a function's `uri` are now built from Arrow types + (`StarfixArrowHasher.hash_schema`, label `arrow_schema_v1`), no longer from Python types. Two + sources whose columns differ only in an Arrow type (`int32` and `int64`, `int8` and `uint8`, + timestamp unit or zone, decimal precision, `date32` and `date64`, list item nullability, a + struct field's type, `fixed_size_list` and `list`) now have different pipeline hashes, stored + paths and system-tag names, so they no longer write into one table. Column order, large and + non-large variants, a list's item field name, dictionary encoding and field metadata are not + part of it. Every pipeline hash, stored table path, system-tag column name and function `uri` + moves; stores written by earlier versions are not read. `output_schema()` still reports + Python types. +- **Binding compares Arrow types.** A source bound to a slot must have the slot's Arrow types; the + only difference accepted is a non-null column where the slot's is nullable. A slot made from a + source keeps that source's Arrow types. A slot declared with Python types means one Arrow type + per Python type (`int` is `int64`, `datetime` is `timestamp[us, tz=UTC]`), so a source of + another width, unit or zone is refused; declare such a slot with Arrow schemas: + `SourceNode(name, tag_schema=pa.schema([...]), data_schema=pa.schema([...]))`. +- **A `PollingSource` refuses a fetched batch whose Arrow types differ from its declared + schema** (`SchemaInconsistencyError`, before the batch is committed). `impl.schema()` may now + return a `pa.Schema`, which is then the source's schema exactly. +- **Saved job files hold each input slot's and each node's own Arrow types** (nested + nullability, units, zones, decimal precision, fixed-size widths and logical type identifiers + included), and a load rebuilds them; before, the types were re-derived from Python types, so + a type with no Python counterpart (`time64[ns]`, `duration[ns]`, `decimal128(38, 10)`, + `fixed_size_binary(3)`) was saved as `null`. One writer writes a slot's `source_config` and + every node's `output_schema`. + A logical type's identifier is written whether the field carries it as a live extension + type or as `ARROW:extension:*` field metadata (a table read back from a store), at any + depth. A map is written with its key and item as whole fields + (`map`), so the item's + name and nullability survive a save and load. A nested field name is written as it is only + when it is plain (ASCII letters, digits, `_`, `.` and `-`: `item`, `key`, `value`); + any other name (a character of the type text, whitespace, a newline, a quote, a + non-ASCII character, the empty name) is written as a JSON string + (`struct<"a:b": int8>`) and read back exactly; some such names could not be read back + before. Saved pipeline and job files are now at format 0.4.0, the only format a load + reads: a file of an earlier format (0.1.0 to 0.3.0) is refused with a message saying + so, never read in its old grammar (load and save had not been used in production; + taking older files to the current format is the migration tool's work, ITL-1048). A + file without a node's nullability record or without a node's run content hash is + malformed and refused, naming the record; it is no longer loaded with every column read + as non-null or with a guessed run hash. + A dictionary-encoded column is saved as its value type. A `decimal32` or `decimal64` + column reads back at its own width. Saving refuses, before anything is written and + naming the node and column, a type whose text would not read back as the same type + (`month_day_nano_interval`, `string_view` or `binary_view` of a slot declared in + Arrow), so no saved file is one that cannot be loaded. A loaded file whose saved + schema names a logical type this process has not registered saves again with every + node's entry unchanged (its saved type texts and saved configuration). +- **A schema hash is the hash of the declared schema** (developer decision, November 21, + 2026). Every logical type is hashed as its storage type with its identifier + (`ARROW:extension:name` and `ARROW:extension:metadata`) as field metadata, at any depth, + whether it arrives as a live extension type, in the metadata (IPC) form of a table read + back from a store, or unregistered in the process. So one logical type has one schema + hash in every form. Before, a type whose values a value handler hashes (`File`, + `Directory`, `numpy.ndarray`, torch, pandas, Polars) was hashed as `large_binary`, the form + `hash_table` uses, and the same `File` field in metadata form had another schema hash. + `hash_table` is unchanged. +- **A schema declared in Arrow with a logical type in metadata form declares that logical + type.** A field that carries its identifier as `ARROW:extension:*` metadata at the top of a + column becomes the live extension type when a `SourceNode` or a `PollingSource`'s + `impl.schema()` is declared with it, and when a saved schema is read back + (`logical_types.canonical_form.declaration_form_schema`), so a `Path` field declares `Path`, + not `str`, and accepts rows of that type. An identifier inside a plain list, struct or map + stays in the metadata form (Arrow cannot build an empty table of a nested extension type): + such a slot, a source of the same table and the slot made from that source have one + schema and one pipeline hash, before and after a save and load. +- **A raw `ArrowTableStream` can no longer hold a union, list-view or run-end-encoded + column.** A column whose Arrow type is, or contains at any depth, a union (dense or + sparse), a `list_view`, a `large_list_view` or a run-end-encoded type is refused when the + stream is built (`InputValidationError` naming each column with its role and type), as a + source already refused them: a stream's identity is its Arrow schema hash, which cannot + hold them. Cast a list view to the large list of the same items, expand a run-end-encoded + column (`pyarrow.compute.run_end_decode`), and split a union into one column per member + type. +- **An Arrow hasher must implement `hash_schema`.** It is a member of + `ArrowHasherProtocol`: every schema that enters an identity is hashed by it. A data + context whose Arrow hasher has no `hash_schema` is refused when the context is built + (`ContextValidationError`, naming the hasher's class). +- **A `CachedSource` refuses a cache read whose Arrow types are not its source's** + (`InputValidationError`, naming the column and both types), as `node.as_source()` + refuses a stored read: a Delta cache gives a `fixed_size_list` column back as + `large_list` (ITL-1275), so a `CachedSource` of such a column on Delta is refused on + read instead of presenting rows of another type under the source's identity. +- **A `PollingSource` with a declared schema refuses a fetched batch with a column the + declaration does not name** (`SchemaInconsistencyError` naming each, before anything + is committed): the rows' system-tag names would not be the declared identity's. +- **A slot declaring a column with no Arrow type is refused when it is declared** (`ValueError` + naming the slot and each such column, for example `x: int | str | None`): a slot's identity + is its Arrow schema. Before, it was refused only when a source was bound. +- The function `uri`'s output-schema component is the semantic hash of the Arrow schema hash + of the declared outputs, as the system-tag column names are the semantic hash of the source's + tag and data schema hashes: a 64-character hex digest in each case. + +### Changed + +- `node.as_source()` (`DerivedSource`) has the Arrow types of its origin's rows before and after + rows are stored, so its identity does not change when the origin runs (ITL-1280: before a + run it widened `int8`/`int32`/`uint16` to `int64` and `float16`/`float32` to `double`, gave + a timestamp of any unit or zone `timestamp[us, tz=UTC]`, and raised on a decimal); a stored read whose + type differs from the origin's (Delta reads a `fixed_size_list` back as `large_list`, + ITL-1275) is refused, naming the column and both types. +- An unbound input slot that knows its Arrow types (made from a source, or loaded from a saved + job) gives its typed zero-row table from them, so a loaded job's nodes have the stored types + before any source is bound; a loaded function node types its output from its saved types. +- A logical type a data context cannot read, in a schema, is reported with its column name. + +### Known limitations + +- The type converter writes `list[int]` and `list[int | None]` as one Arrow type (a nullable + item), so two functions that differ only in that declaration share the output-schema part of + their `uri` (ITL-1136). +- The SQLite connector database reads a non-null column back as nullable (ITL-1276). diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index bfad9305f..ec36be45d 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -406,11 +406,10 @@ print(derived.as_table().column_names) In a stream the binding is the shared name, so the marker stays with the stored table: the rows of a replay or of a derived source carry none. -A saved job or pipeline (format `0.3.0`) states every binding: each source config writes +A saved job or pipeline states every binding: each source config writes `tag_only_columns` (`True` when every tag is plain), and each function node writes -`fall_through_tags` (empty for a plain pod). The format version, never a missing -key, decides what a file means: a file at `0.1.0` or `0.2.0` holds only plain tags, and a -`0.3.0` file without these keys is refused. A loaded job keeps its hashes and bindings, and +`fall_through_tags` (empty for a plain pod). A missing key is never read as a default: a +file without these keys is refused, as is a file of an earlier format version. A loaded job keeps its hashes and bindings, and the file is checked against the stored tables when a node reads them. ## Not supported yet diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index ae7edb029..25460e959 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -1003,17 +1003,10 @@ source was configured. `PipelineJob.load(path)` reads it back, for example in a session, so that you can read the results the job stored. The file also records `orcapod_version`, the Orcapod release that wrote it (the same text as `orcapod.__version__`; a development checkout gives a development version). It is informational: loading never -depends on it. Adding the field moved the file format version from `0.1.0` to `0.2.0`, and -stating every tag binding (data-tags) moved it to `0.3.0`, the version written now. A -`0.1.0` file, written by v0.2.0, and a `0.2.0` file, written by v0.3.0, still load, with every -source tag plain as they were written, within the schema limits described below (a file with -name-only extension type text cannot be loaded); any other version is rejected. -A job saved before 0.4 names its functions `python.function.v0`; it loads read only (its -blueprint, with its tables of the older layouts reported and not read), and its functions -cannot be bound, because 0.4 runs them as `python.function.v1` -([Data function types](../reference/data-function-types.md)): rebuild the pipeline to run it. -The reverse does not hold: v0.2.0 cannot load a file saved by v0.3.0, because hashes differ -between the two releases. +depends on it. The file format version is `0.4.0`, and a load reads only that version: a +file saved by an earlier release (format `0.1.0` to `0.3.0`) is refused, with a message +saying so. Rebuild the pipeline from code and save it again; taking older files to the +current format is the work of a separate migration tool, not of `load`. For example: @@ -1093,26 +1086,22 @@ from that database, and no rows under that key is an empty result, not an error. had (a source node whose data was not saved gets its run's content hash once its source is bound). The file records which columns may be null (`T | None`), because the Arrow type text of a schema cannot say it, and the content hash of each node's run, which the stored rows - carry. Whether a file has these records is decided by the records themselves, not by the - file's format version: a file without them (format `0.1.0`, or a `0.2.0` file written - before they existed) still loads, but lossy: its schemas read every column as non-null, - and a loaded operator node cannot name its run's rows. When the database holds none under the - content hash the loaded job computes, its stored view (`as_source()`, `get_all_records()`) - raises and says why, rather than presenting stored rows as none. An empty record is - not a missing one: it says that no column may be null. Saving such a loaded job again does - not record what its file did not. Upgrading such files is left to a migration tool after - v0.3. + carry. Every saved file has these records: a file without one is malformed, and loading it + raises and names the missing record, rather than reading every column as non-null or + guessing a run's content hash. An empty record is not a missing one: it says that no column + may be null. - Sources that read files, such as `CSVSource` and `DeltaTableSource`, are rebuilt from their paths. In-memory sources (`DictSource`, `ListSource`, `ArrowTableSource`, `DataFrameSource`) keep their data only in memory, so they are not saved; loading logs this at INFO level. This does not affect reading the other nodes. To read such a source node itself, bind a source to it: `loaded.bind(sources={"mice": source})`. The source must - have the slot's tag and data columns with the same Python types, except that a column the - slot declares `T | None` may be `T` (the slot then reads it as `T | None`); `bind` refuses - any other (`SourceSpecMismatchError`, an `InputValidationError`). The pipeline determines - every node's schema: binding a source never changes a node's stored path or the schema of - any node's or stored table, only the values. The check compares Python types, so a - difference in Arrow width only (`int32` against `int64`) is not yet refused (ITL-949). A + have the slot's tag and data columns with the same Arrow types (the slot keeps the Arrow + types of the source it was saved from), except that a column the slot declares nullable + may be non-null (the slot then reads it as nullable); `bind` refuses any other + (`SourceSpecMismatchError`, an `InputValidationError`), also a difference in Arrow width + only (`int32` against `int64`). The pipeline determines every node's schema: binding a + source never changes a node's stored path or the schema of any node's or stored table, + only the values. A joined or merged stream (one pair of system-tag columns per input), or one with no system-tag columns, is refused too: make the join part of the pipeline, or store the joined stream and bind the stored source. A pipeline built directly over a raw `ArrowTableStream` @@ -1136,11 +1125,9 @@ An unknown type is reported with its node and column, and affected operators bec stubs. An incompatible identifier raises `LogicalTypeIdentifierError` instead of using a stub. Stored data independently validates its full identifier when values are read. -Older files containing name-only extension type text cannot be loaded by this reader: the -error says the file was saved by an earlier version. Use that version to read the old file, -and save a new job from the original pipeline under this version. Files with only supported -primitive schema types still load; results from pre-v0.3 table layouts remain excluded as -described below. This changes saved schema text only, not stored tables or hashes. +Only files of format `0.4.0` load, whatever their schema types: a file of an earlier format +is refused, as described above. Rebuild the pipeline from code and save it again under this +version. ### A store written by an older version diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index 9cc4376b1..3d1997b99 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -43,13 +43,15 @@ result is returned without recomputation. The pipeline hash captures the pipeline's **structure** -- schemas, function identities, and how elements are connected -- but deliberately ignores source identity. Two pipeline elements -with identical schemas and the same computational graph have the same pipeline hash, even if -they are fed by completely different sources. +with identical Arrow schemas and the same computational graph have the same pipeline hash, +even if they are fed by completely different sources. **Used for:** database scoping. Pipeline hash determines the database table path where results are stored. This means that two pipeline nodes with the same function, the same input schema and the same upstream steps share the same database table -- regardless of which source -produced the data. +produced the data. "The same input schema" means the same Arrow schema: a source whose `x` +column is `int32` and one whose `x` is `int64` both read as `int` in `output_schema()`, but +they are two schemas, with two pipeline hashes and two tables. This is a powerful feature: it means that running the same function on new data automatically benefits from results already cached for previous data with the same schema. @@ -72,8 +74,43 @@ print(source_a.pipeline_hash() == source_b.pipeline_hash()) - The content hashes differ -- different source identity - The pipeline hashes are equal -- same schema and structure -If both sources feed into the same function in a `PipelineJob`, the nodes share a database -table (same pipeline hash), but each row is stored and retrieved by its content hash. +If `source_a` and `source_b` feed into the same function in a `PipelineJob`, the nodes share +a database table (same pipeline hash), but each row is stored and retrieved by its content +hash. + +The schema in a hash is the Arrow schema, not the Python one. Two sources whose column holds +the same numbers as `int32` in one and `int64` in the other have different pipeline hashes: + +```python +import pyarrow as pa + +from orcapod.sources import ArrowTableSource + + +def source_of(int_type): + table = pa.table( + { + "subject": pa.array(["s1", "s2"], pa.large_string()), + "session": pa.array([1, 2], int_type), + "x": pa.array([0.5, 1.5]), + "y": pa.array([2, 3], int_type), + } + ) + return ArrowTableSource( + table, tag_columns=["subject", "session"], tag_only_columns=True + ) + + +narrow, wide = source_of(pa.int32()), source_of(pa.int64()) +print(narrow.output_schema() == wide.output_schema()) +# True +print(narrow.pipeline_hash() == wide.pipeline_hash()) +# False +``` + +What the schema hash ignores (column order, large and non-large variants, a list's item +field name, dictionary encoding, field metadata) and what it tells apart is listed in the +[hashing reference](../reference/hashing.md#the-arrow-schema-hash). ## The Merkle chain @@ -82,8 +119,11 @@ identity plus the pipeline hashes of all its upstream elements. ### Base case: sources -A `RootSource`'s pipeline identity is simply its `(tag_schema, data_schema)`. Sources with -the same column names and types have the same pipeline hash, regardless of their data. +A `RootSource`'s pipeline identity is the hash of its Arrow tag schema and Arrow data schema: +the types its rows have. Sources with the same column names and Arrow types have the same +pipeline hash, regardless of their data; an input slot declared with Python types stands for +one Arrow type per Python type (`int` is `int64`, `datetime` is `timestamp[us, tz=UTC]`), and +a slot can also be declared with Arrow schemas. ### Recursive case: downstream elements @@ -131,8 +171,8 @@ a different `source_id`. ### DB path scoping The pipeline hash determines the database table path. Two nodes that apply the same function -to sources with the same schema, through the same upstream steps, will write to and read from -the same table. This is intentional: it maximizes cache reuse across pipeline runs. A +to sources with the same Arrow schema, through the same upstream steps, will write to and read +from the same table; sources that differ in any Arrow type write to two tables. This is intentional: it maximizes cache reuse across pipeline runs. A schema-preserving step added upstream (a filter, say) changes the pipeline hash and so the table. This is the default `table_scope="pipeline_hash"` of a node; a node built with `table_scope="content_hash"` also adds its content hash to the path, giving each source its diff --git a/docs/concepts/logical-type-identifiers.md b/docs/concepts/logical-type-identifiers.md index e96c39302..4503148a5 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -32,8 +32,14 @@ stores it, hashes it and compares it byte for byte. - **Stored with the column.** The name and metadata are written as the column's `ARROW:extension:name` and `ARROW:extension:metadata`, in memory and in every store. +- **One identifier in every form.** A field carries it either as a live Arrow extension + type or as its storage type with those two metadata keys (a table read back from a store, + or read by a process that has not registered the type). The schema hash brings both to + the second form first, so a type has one schema hash however it arrives + ([hashing reference](../reference/hashing.md#the-arrow-schema-hash)). - **Part of the data type, so part of every hash the type takes part in.** The whole - identifier enters the type hash, the schema hash, the identity of a function whose + identifier enters the type hash, the schema hash (a schema is hashed as its Arrow schema, + whose extension name and metadata are the identifier), the identity of a function whose signature names the type, the pipeline hash, and the hash of every row that holds a value of the type. In those hashes it is written as the extension name, a `;`, and the metadata bytes in hexadecimal: @@ -125,9 +131,10 @@ a list; conceptually they are an ordinary list or set of `T`. By design: JSON as text, a logical type used inside `list[T]` or `set[T]` must have extension metadata that is valid UTF-8, for its current identifier and for every older one it declares readable. -- **In the type and schema hash it is hashed like any other generic type**, `list[int]` - included: as its origin (`list` or `set`) and its argument. The element's identifier enters - through the argument. +- **In the type hash it is hashed like any other generic type**, `list[int]` included: as its + origin (`list` or `set`) and its argument. The element's identifier enters through the + argument. In a schema hash, which hashes the Arrow schema, the container is its extension + type, whose name and metadata hold the element's identifier. - **A change to how native containers are stored or hashed is a change of Orcapod's core hashing**, recorded by the data context (the global hash version), never a change of a logical type. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 8a038e277..373fa6def 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -915,7 +915,8 @@ silent widening; convert explicitly. `large_string`), the join proceeds. Otherwise (for example `int16` and `int32`, or two timestamp units) it raises `InputValidationError` naming the column and both types; cast one input explicitly. Because `output_schema()` reports Python types, this is detected when - the join runs, not when the pipeline is built. + the join runs, not when the pipeline is built. Two such inputs already have different + pipeline hashes, since a schema enters every hash as its Arrow schema. - **Sync and async execution agree.** An operator run asynchronously (`async_execute`, as in an async pipeline) yields rows with the same Arrow types, column order, system tags and content hashes as the same operator run synchronously, whether its inputs are sources or diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 4e3d61e4c..353a5695f 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -249,9 +249,14 @@ print(job_a.nodes["bmi"].as_table().num_rows, job_b.nodes["bmi"].as_table().num_ `sources` maps a source slot's name (the `source_id` used when the blueprint was recorded) to the source to use. A source bound to a slot must have the slot's tag and data columns -with the same Python types (a column the slot declares `T | None` also accepts `T`); any -other source raises `SourceSpecMismatchError`, and an unknown slot name raises `ValueError`. -Binding a source never changes a node's schema or where its results are stored. +with the same Arrow types (a column the slot declares nullable also accepts a non-null one); +any other source raises `SourceSpecMismatchError`, and an unknown slot name raises +`ValueError`. A slot made from a source keeps that source's Arrow types, so an `int32` +column refuses an `int64` source. A slot declared with Python types (`SourceNode(name, +tag_schema=Schema({...}), data_schema=Schema({...}))`) means one Arrow type per Python type +(`int` is `int64`, `datetime` is `timestamp[us, tz=UTC]`); to accept other widths, units or +zones, declare the slot with Arrow schemas (`tag_schema=pa.schema([...])`). Binding a source +never changes a node's schema or where its results are stored. A job made without sources has **unbound** slots. It can still be run: nodes that depend on an unbound source are skipped, and `job.unbound_sources` lists what is missing. Bind later @@ -357,7 +362,10 @@ the **Nodes** table below the picture for each node's columns and status. each source was configured. `PipelineJob.load(path)` reads it back, for example in a later Python session. An `InMemoryArrowDatabase` has no location to record, so here the database is passed again; `PipelineJob.load(path, database=...)` is also how you point a loaded job -at a database that has moved. +at a database that has moved. The file records each node's own Arrow types, so saving types +every node from its inputs' types, as previewing an empty job does, and costs what that +preview costs: a pipeline whose joins keep many system-tag columns saves as slowly as it +previews. ```python job_a.save("bmi_job.json") diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index e799b8461..186185fba 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -92,8 +92,11 @@ Every source gives the large variants of string, binary and list types (`large_s a data frame, a CSV file or a database table. A `string` column you give comes back as `large_string`. Only the layout changes: names, nullability, widths (`int8` stays `int8`) and logical types are kept, and the two variants hash identically, so no hash depends on which -one you gave. The Arrow `list_view` and `large_list_view` types are not supported: a source -refuses a column of either type. +one you gave. The Arrow `list_view` and `large_list_view` types, unions (dense or sparse) and +run-end-encoded types are not supported: a source, and a stream built from an Arrow table of +your own, refuses a column whose type is or holds one, naming it (a stream's identity is its +Arrow schema hash, which cannot hold them). Cast a list view to the large list of the same +items, and expand a run-end-encoded column with `pyarrow.compute.run_end_decode`. Dictionary-encoded columns are not currently supported in Orcapod, tags and data alike. A column whose Arrow type is a `dictionary`, or holds one inside it (a list of dictionary values, diff --git a/docs/dev/design_issues/ITL-1023-RT4.md b/docs/dev/design_issues/ITL-1023-RT4.md index 8b7fdb1be..d5c35a94a 100644 --- a/docs/dev/design_issues/ITL-1023-RT4.md +++ b/docs/dev/design_issues/ITL-1023-RT4.md @@ -1,8 +1,17 @@ ## `src/orcapod/core/nodes/source_node.py` ### RT4 — A loaded job keeps a data-tag column's pending type for one role only -**Status:** open +**Status:** resolved **Severity:** medium **Issue:** ITL-1200 (found on ITL-1023, PR #342) A loaded job keeps a slot column's type as pending when it names a user class not registered in the process (`_keep_saved`), and restores it when a source of that class is bound (`_restore_pending_types`). Pending types are keyed by column name only, so for a data-tag (one name in the tag and the data schema) the data entry replaces the tag entry. After binding, the tag schema still holds the saved text as a `str`, and `_fit` can refuse a matching source with a type-mismatch message instead of the unregistered-type message. Readers to change: `_restore_pending_types`, `_take_saved_state_of`, `_pending_nullable_columns`, the `_fit` message lookup. Reported by CodeRabbit on PR #342; ITL-1200 fixes it. + +**Fix:** PR 454 (ITL-640). A loaded slot keeps no per-column pending state any more: while +unresolved, its saved Arrow type texts are the one source of its types, and one transition +(`SourceNodeBase._resolve`) derives the Arrow pair and both Python schemas, tag and data, from +them together. A data-tag column resolves in both roles at once. Test: the `datatags` layout of +`tests/test_pipeline/test_loaded_slot_unregistered_class.py` (the class column `t` and an +`int16` column `k` as data-tags; register and bind before and after saving again, by +`Pipeline.save` and `PipelineJob.save`, and reloaded; a widened `k` refused). Its ten cases +fail on 73652317 with the refusal this entry describes and pass on the fix. diff --git a/docs/dev/design_issues/ITL-1043-LJ1.md b/docs/dev/design_issues/ITL-1043-LJ1.md index 7b54b3ff6..698d84687 100644 --- a/docs/dev/design_issues/ITL-1043-LJ1.md +++ b/docs/dev/design_issues/ITL-1043-LJ1.md @@ -39,7 +39,9 @@ rows) is an empty result. A node whose file lacks the run content hash cannot na rows: with none under the hash it computes, `as_table()`/`iter_data()` raise and `head()` shows no rows with the reason. A file without the records (`0.1.0`, or a `0.2.0` file written before them) loads as before, lossy, and saving it again records nothing it did -not have. No hash, stored path or golden value of a running job changes. Facts about +not have. (Superseded by PR 454, developer, 2026-11-21: no backward compatibility for +saved files. A file of an earlier format is refused, and a file without a record is +malformed and refused, naming the record.) No hash, stored path or golden value of a running job changes. Facts about stored data stay out of the definition: the job file holds only an optional, advisory `run.expected_rows` section (rows under each node's run key at save time, written only when certain); a loaded node returns what the database holds and issues one diff --git a/docs/dev/design_issues/ITL-1112-BT1.md b/docs/dev/design_issues/ITL-1112-BT1.md index 59e10e395..26171ced6 100644 --- a/docs/dev/design_issues/ITL-1112-BT1.md +++ b/docs/dev/design_issues/ITL-1112-BT1.md @@ -35,7 +35,7 @@ form gives a stream's one system-tag pair the slot's names (taken from the strea columns by prefix), so no accepted bind changes a node's path or its columns (names, roles, types, nullable flags, system-tag names; column order is not part of that, and the form's declared order is a convenience). Two Arrow types that are one Python type (`int32` and `int64`) -are still not told apart (ITL-949). A source whose system-tag columns are not exactly one +were not told apart (ITL-949); since ITL-640 a bind compares Arrow types too (AS1). A source whose system-tag columns are not exactly one source-id and one record-id column (a joined or merged stream, a raw stream with none) is refused by the same check (developer, November 14, 2026, ITL-1126; binding one properly is ITL-1127), also as a pipeline's input: a pipeline built directly over a raw stream is diff --git a/docs/dev/design_issues/ITL-1138-LJ3.md b/docs/dev/design_issues/ITL-1138-LJ3.md index af11979ef..209bc0079 100644 --- a/docs/dev/design_issues/ITL-1138-LJ3.md +++ b/docs/dev/design_issues/ITL-1138-LJ3.md @@ -15,7 +15,8 @@ schema, so an accepted bind would have named them differently from the saving ru **Fix:** a slot rebuilt from a saved job keeps its saved pipeline hash, and its saved content hash while unbound, as loaded function and operator nodes do (`SourceNodeBase._keep_saved`). A column -whose type was not restored is kept as pending and restored when a source is bound -(`_restore_pending_types`, called by the bind check), by which time the source has registered the +whose type was not restored leaves the slot unresolved, its saved Arrow type texts the one source +of its types, and it is resolved when a source is bound (`_resolve`, called by the bind check and +every other reader of the slot's types; ITL-640), by which time the source has registered the class; a column still not restorable makes the bind raise `SourceSpecMismatchError` naming the column and the saved class. Tests: `tests/test_pipeline/test_loaded_slot_unregistered_class.py`. diff --git a/docs/dev/design_issues/ITL-1323-UC4.md b/docs/dev/design_issues/ITL-1323-UC4.md index ceb54406b..6e0d727dd 100644 --- a/docs/dev/design_issues/ITL-1323-UC4.md +++ b/docs/dev/design_issues/ITL-1323-UC4.md @@ -1,7 +1,7 @@ ## `src/orcapod/semantic_types/universal_converter.py` ### UC4 — A decimal column has no Python type: a saved job cannot rebuild its source -**Status:** open +**Status:** resolved **Severity:** medium **Issue:** ITL-1323 @@ -19,3 +19,11 @@ How a decimal is typed in Python (for example `decimal.Decimal`, with precision kept on the Arrow side) is to be decided and written down; if it moves a hash, the moved list needs the developer's approval. Related: hashing the Arrow schema instead of the Python types (ITL-640). + +**Fix:** a saved job holds each slot's and each node's own Arrow types (ITL-640, PR 454), +written from the Arrow schemas, never re-derived from Python types: the decimal column is +saved as `decimal128(10, 2)`, the slot is rebuilt with that type, and `PipelineJob.load` +binds the rebuilt `CSVSource` with the same content and pipeline hashes. The four strict +xfails in `tests/test_core/sources/test_csv_source_schema_config.py` are plain tests now. A +decimal still has no Python type (`Any` in `output_schema()`); typing it in Python is not +needed for the job round trip and is left as it is. diff --git a/docs/dev/design_issues/ITL-949-AS1.md b/docs/dev/design_issues/ITL-949-AS1.md new file mode 100644 index 000000000..75aaa944b --- /dev/null +++ b/docs/dev/design_issues/ITL-949-AS1.md @@ -0,0 +1,27 @@ +## `src/orcapod/hashing/arrow_hashers.py` — schema identity + +### AS1 — A schema was hashed as Python types: sources of different Arrow types shared paths +**Status:** resolved +**Severity:** high +**Issue:** ITL-949 (with ITL-640, ITL-1136) + +Every schema that entered an identity (a source's pipeline and content identity, an input +slot's, the system-tag column names, the output schema in a function's `uri`) was hashed as +its Python types, through `SchemaHandler`. `int32` and `int64` are both `int`, so two sources +that differed only in an Arrow type (integer or float width, signedness, timestamp unit or +zone, decimal precision, date32/date64, list item nullability, a struct field's width) had one +pipeline hash, one stored path and one set of system-tag names. Measured on November 18, 2026: +a write of the second source into the first one's table failed, a Delta operator cache cast +`uint8` into `int8` and dropped a list item's non-null flag silently, and a bind accepted a +source of another Arrow type. + +**Fix:** developer decision, November 18, 2026 (ITL-640, option B). A schema is hashed as its +Arrow schema by `StarfixArrowHasher.hash_schema` (label `arrow_schema_v1`), everywhere a schema +enters an identity (`schema_utils.arrow_schema_identity`, `compute_schema_hash`, +`DataFunctionBase.output_data_schema_hash`). Sources take their rows' types from their typed +zero-row tables, slots hold and save Arrow schemas, a bind compares Arrow types (only `T` into +`T | None` at the top level), a `PollingSource` refuses a batch of another Arrow type, and a +`DerivedSource` refuses a stored read of another type. Scripts and measurements: +`docs/dev/scripts/itl_640/`; tests: `tests/test_hashing/test_arrow_schema_identity.py`. Two +store defects it surfaced are their own issues: ITL-1275 (Delta reads `fixed_size_list` back as +`large_list`) and ITL-1276 (SQLite loses a non-null flag). diff --git a/docs/dev/scripts/itl_640/golden_proof.py b/docs/dev/scripts/itl_640/golden_proof.py new file mode 100644 index 000000000..d5f02458e --- /dev/null +++ b/docs/dev/scripts/itl_640/golden_proof.py @@ -0,0 +1,530 @@ +"""ITL-640 golden step proof: what the regenerated golden files change against a base. + +Run from the repository root: + + uv run python docs/dev/scripts/itl_640/golden_proof.py [--base REF] [--write] + +It reads the golden files of ``REF`` (default ``origin/main``) from git and the files in +the working tree, the frozen and the provisional files together, and checks: + +1. every changed, removed or added entry is one of the developer's categories: A label + only (exactly ``arrow_v1`` to ``arrow_schema_v1``, same digest), B value moved, C + renamed (an entry whose name holds a system-tag column name: paired with its new name + by the name with every digest blanked, exactly one old and one new entry per blanked + name), or one of ``ADDITIONS``; +2. the A, B and C sets equal the sets measured before the golden step + (``docs/dev/specs/itl-640/golden-moves-measured.json``); +3. the "must not move" entries are byte-identical: the semantic group, data and row + hashes, row record-id and source-id values (a renamed entry keeps its value), source + ids other than a ``derived:`` default built from a node's content hash, table hashes + (the arrow ``table``, ``extension_table`` and ``dict_order`` cases, and every + ``arrow_v1`` / ``arrow_ordered_v1`` value outside the arrow ``schema`` and + ``extension_schema`` cases, whose schema hashes carried ``arrow_v1`` before ITL-640: + those are category A) and operator identities; +4. every entry stays in its kind of file (frozen or provisional), changed or not; +5. a renamed entry whose value moved is a function pipeline table's ``record_ids``, and + its move is exactly the system-tag rename: each stored row's record-id preimage (its + tags, system tags, input data hash and recomputation index) is rebuilt from a fresh + run of the case, hashed (it must give the new pinned ids) and hashed again with every + renamed digest in the system-tag column names mapped back (it must give the old + pinned ids), so nothing but the column names moved those ids; +6. ``generate_golden_hashes.py --check`` matches. + +The base is resolved once to a full commit, which every read of the base uses. With +``--write``, the full old/new list is written to +``docs/dev/specs/itl-640/golden-moves.json``, only when every check passes (a failed run +leaves the last valid report). Exit status 0 when every check passes, 1 otherwise. +""" + +from __future__ import annotations + +import argparse +import collections +import json +import pathlib +import re +import subprocess +import sys +import warnings +from collections.abc import Iterable + +ROOT = pathlib.Path(__file__).resolve().parents[4] +GOLDEN = "tests/test_hashing/golden/data/v1" +MEASURED = ROOT / "docs/dev/specs/itl-640/golden-moves-measured.json" +OUTPUT = ROOT / "docs/dev/specs/itl-640/golden-moves.json" +HEX = re.compile(r"[0-9a-f]{64,70}") + +_FORMS = ("live", "storage") +ADDITIONS = frozenset( + { + *( + f"arrow:schema_storage_form.{label}.{form}" + for label in ("File", "Directory", "list[File]", "struct_with_Directory") + for form in _FORMS + ), + *( + f"arrow:schema_storage_form_library.{label}.{form}" + for label in ( + "numpy.ndarray", + "pandas.DataFrame", + "pandas.Series", + "polars.DataFrame", + "polars.Series", + ) + for form in _FORMS + ), + *(f"torch:schema_storage_form.torch.Tensor.{form}" for form in _FORMS), + } +) +"""The only entries the golden step adds: the canonical schema form, live and storage.""" + +DATA_KINDS = frozenset( + {"data_hash", "input_data_hashes", "tag_hash", "row_hash", "key_bits"} +) +TABLE_CASES = frozenset({"table", "extension_table", "dict_order"}) +TABLE_LABELS = ("arrow_v1:", "arrow_ordered_v1:") +# The arrow cases that pin schema hashes: before ITL-640 a schema hash carried the table +# hash's label, ``arrow_v1``; those 47 entries are category A (label only, same digest). +SCHEMA_HASH_CASES = frozenset({"schema", "extension_schema"}) + +Entry = tuple[str, str] # (group, entry name) + + +def _group_and_place(path: str) -> tuple[str, str]: + """The group and the kind of file (frozen or provisional) of a golden file path.""" + name = pathlib.PurePosixPath(path) + if name.parent.name == "provisional": + return name.stem, "provisional" + return name.stem.split("-")[0], "frozen" + + +def _base_files(ref: str) -> dict[str, str]: + """Every golden file of the commit ``ref`` (a full commit id), read from git.""" + listing = subprocess.run( + ["git", "ls-tree", "-r", "--name-only", ref, GOLDEN], + cwd=ROOT, + check=True, + capture_output=True, + text=True, + ).stdout.split() + return { + path: subprocess.run( + ["git", "show", f"{ref}:{path}"], + cwd=ROOT, + check=True, + capture_output=True, + text=True, + ).stdout + for path in listing + if path.endswith(".json") + } + + +def _head_files() -> dict[str, str]: + """Every golden file in the working tree.""" + folder = ROOT / GOLDEN + return { + str(path.relative_to(ROOT)): path.read_text() + for path in sorted(folder.rglob("*.json")) + } + + +def _entries(files: dict[str, str]) -> tuple[dict[Entry, object], dict[Entry, str]]: + """The pinned values and the kind of file of every entry in ``files``.""" + values: dict[Entry, object] = {} + places: dict[Entry, str] = {} + for path, text in files.items(): + group, place = _group_and_place(path) + for name, value in json.loads(text).items(): + key = (group, name) + if key in values: + raise SystemExit(f"{group}:{name} is pinned twice") + values[key] = value + places[key] = place + return values, places + + +def blank(name: str) -> str: + """``name`` with every digest blanked: the key a renamed entry keeps.""" + return HEX.sub("H", name) + + +def kind_of(name: str) -> str: + """The kind of value an entry pins (its last name component, digests blanked).""" + last = re.sub(r"\[[^\]]*\]", "[]", blank(name)).split(".")[-1] + if last.startswith("_tag_record_id"): + return "row record id (value)" + if last.startswith("_tag_source_id"): + return "row source id (value)" + return last + + +def label_only(old: object, new: object) -> bool: + """Whether ``old`` became ``new`` by category A: ``arrow_v1`` to ``arrow_schema_v1``, + the digest unchanged (no other label change counts).""" + if not (isinstance(old, str) and isinstance(new, str)): + return False + old_label, _, old_digest = old.partition(":") + new_label, _, new_digest = new.partition(":") + return ( + old_label == "arrow_v1" + and new_label == "arrow_schema_v1" + and old_digest == new_digest != "" + ) + + +def _text(entries: Iterable[Entry]) -> set[str]: + """Entries as ``group:name`` text.""" + return {f"{group}:{name}" for group, name in entries} + + +def _record_id_moves_unexplained( + moved: set[Entry], + renamed: dict[Entry, Entry], + old: dict[Entry, object], + new: dict[Entry, object], +) -> list[str]: + """Check 5: the failures among the renamed entries whose value moved. + + Args: + moved: The renamed entries whose value moved, by their old name. + renamed: Every renamed entry, old name to new name. + old: The base's pinned values. + new: The pinned values after the step. + + Returns: + One failure text per entry that is not a pipeline ``record_ids`` move exactly + explained by the system-tag rename. + """ + failures: list[str] = [] + record_ids = { + e for e in moved if e[0] == "pipeline" and e[1].endswith(".record_ids") + } + failures += [ + f"renamed and moved, not a record_ids entry: {g}:{n}" + for g, n in sorted(moved - record_ids) + ] + if not record_ids: + return failures + sys.path.insert(0, str(ROOT)) + warnings.simplefilter("ignore") + import pyarrow as pa + + from orcapod.contexts import get_default_context + from orcapod.databases import InMemoryArrowDatabase + from tests.test_hashing.golden import cases + + back: dict[str, str] = {} # new digest -> old digest, from every rename + for (_, old_name), (_, new_name) in renamed.items(): + for before, after in zip(HEX.findall(old_name), HEX.findall(new_name)): + if before != after: + if back.get(after, before) != before: + failures.append(f"digest {after} renamed from two digests") + back[after] = before + hasher = get_default_context().arrow_hasher + captured: list[InMemoryArrowDatabase] = [] + original_init = InMemoryArrowDatabase.__init__ + + def capturing_init( + self: InMemoryArrowDatabase, *args: object, **kwargs: object + ) -> None: + original_init(self, *args, **kwargs) # pyright: ignore[reportArgumentType] # passed through as given + captured.append(self) + + case_functions = {name: fn for name, fn, _ in cases._CASES["pipeline"]} # pyright: ignore[reportPrivateUsage] # the registered cases, as the generator reads them + InMemoryArrowDatabase.__init__ = capturing_init # pyright: ignore[reportAttributeAccessIssue] # restored below + try: + for entry in sorted(record_ids): + case_name = entry[1].partition(".table[")[0] + table_path = renamed[entry][1].partition(".table[")[2][ + : -len("].record_ids") + ] + captured.clear() + _ = case_functions[case_name]() + rebuilt_new: list[object] = [] + rebuilt_old: list[object] = [] + for database in captured: + for path in database.list_sources(): + if "/".join(path) != table_path: + continue + records = database.get_all_records( + path, record_id_column="__golden_record_id" + ) + assert records is not None + names = records.column_names + system = [c for c in names if c.startswith("_tag_")] + user = names[1 : names.index(system[0])] + for row in range(records.num_rows): + preimage = records.slice(row, 1).select( + [ + *user, + *system, + "__input_data_hash", + "__pipeline_recomputation_index", + ] + ) + preimage = preimage.cast( + pa.schema( + [ + f.with_type(pa.int32()) + if f.name == "__pipeline_recomputation_index" + else f + for f in preimage.schema + ] + ) + ) + old_names = preimage.rename_columns( + [ + HEX.sub(lambda m: back.get(m.group(0), m.group(0)), c) + for c in preimage.column_names + ] + ) + rebuilt_new.append( + cases._jsonable( + hasher.hash_table(preimage).to_prefixed_digest() + ) # pyright: ignore[reportPrivateUsage] # the generator's own value encoding + ) + rebuilt_old.append( + cases._jsonable( + hasher.hash_table(old_names).to_prefixed_digest() + ) # pyright: ignore[reportPrivateUsage] # as above + ) + if sorted(rebuilt_new, key=str) != new[renamed[entry]]: # pyright: ignore[reportCallIssue, reportArgumentType] # JSON values + failures.append( + f"record ids not rebuilt from the stored rows: {entry[1]}" + ) + elif sorted(rebuilt_old, key=str) != old[entry]: # pyright: ignore[reportCallIssue, reportArgumentType] # as above + failures.append(f"record ids moved beyond the rename: {entry[1]}") + finally: + InMemoryArrowDatabase.__init__ = original_init # pyright: ignore[reportAttributeAccessIssue] # restoring + return failures + + +def must_not_move(entry: Entry, old: object) -> str | None: + """The reason ``entry`` must keep its value, or ``None`` if it may move.""" + group, name = entry + kind = kind_of(name) + if group == "semantic": + return "semantic value" + if kind in DATA_KINDS: + return "data or row hash" + if kind in ("row record id (value)", "row source id (value)"): + return "row record-id or source-id value" + if kind == "source_id" and not ( + isinstance(old, str) and old.startswith("derived:") + ): + return "given, table-hash or location source id" + if group == "arrow" and name.split(".")[0] in TABLE_CASES: + return "table hash" + if ( + isinstance(old, str) + and old.startswith(TABLE_LABELS) + and not (group == "arrow" and name.split(".")[0] in SCHEMA_HASH_CASES) + ): + return "table hash" + if any(part.startswith("operator") for part in name.split(".")): + return "operator identity" + return None + + +def main() -> int: + """Run every check, print the report; with ``--write`` write it when all pass. + + Returns: + 0 when every check passes, 1 otherwise. + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base", default="origin/main") + parser.add_argument("--write", action="store_true") + args = parser.parse_args() + + # Resolved once: the listing and every blob read use this one commit. + base_commit = subprocess.run( + ["git", "rev-parse", "--verify", "--end-of-options", f"{args.base}^{{commit}}"], + cwd=ROOT, + check=True, + capture_output=True, + text=True, + ).stdout.strip() + old, old_place = _entries(_base_files(base_commit)) + new, new_place = _entries(_head_files()) + failures: list[str] = [] + + common = old.keys() & new.keys() + unchanged = {e for e in common if old[e] == new[e]} + changed = common - unchanged + removed = old.keys() - new.keys() + added = new.keys() - old.keys() + + a_set = {e for e in changed if label_only(old[e], new[e])} + b_set = changed - a_set + by_blank: dict[tuple[str, str], list[Entry]] = collections.defaultdict(list) + for e in added: + by_blank[(e[0], blank(e[1]))].append(e) + removed_by_blank: dict[tuple[str, str], list[Entry]] = collections.defaultdict(list) + for e in removed: + removed_by_blank[(e[0], blank(e[1]))].append(e) + renamed: dict[Entry, Entry] = {} + for e in sorted(removed): + key = (e[0], blank(e[1])) + partners = by_blank.get(key, []) + if len(partners) == 1 and len(removed_by_blank[key]) == 1: + renamed[e] = partners[0] + else: + failures.append( + f"removed with {len(partners)} new and {len(removed_by_blank[key])} " + f"removed entries of one name: {e[0]}:{e[1]}" + ) + paired_new = set(renamed.values()) + extra = {f"{g}:{n}" for g, n in added - paired_new} + c_moved = {e for e, to in renamed.items() if old[e] != new[to]} + + text = _text + measured = json.loads(MEASURED.read_text()) + for label, got, key in ( + ("A", text(a_set), "A_label_only"), + ("B", text(b_set), "B_value_moved"), + ("C", text(renamed), "C_renamed"), + ("C value moved", text(c_moved), "C_renamed_value_moved"), + ): + expected = set(measured[key]) + if got != expected: + failures.append( + f"{label}: {len(got - expected)} not measured, " + f"{len(expected - got)} measured but not changed" + ) + if extra != ADDITIONS: + failures.append( + f"additions: {sorted(extra - ADDITIONS)} not listed, " + f"{sorted(ADDITIONS - extra)} listed but not added" + ) + + for e in sorted(old): + reason = must_not_move(e, old[e]) + if reason is None: + continue + if e in renamed: + if old[e] != new[renamed[e]]: + failures.append(f"must not move ({reason}), renamed and moved: {e}") + elif e not in unchanged: + failures.append(f"must not move ({reason}): {e[0]}:{e[1]}") + for e in common: + if old_place[e] != new_place[e]: + failures.append(f"in another kind of file: {e[0]}:{e[1]}") + record_id_failures = _record_id_moves_unexplained(c_moved, renamed, old, new) + failures += record_id_failures + for e, to in renamed.items(): + if old_place[e] != new_place[to]: + failures.append(f"renamed into another file kind: {e}") + + places = collections.Counter() + for e in a_set: + places[("A", old_place[e])] += 1 + for e in b_set: + places[("B", old_place[e])] += 1 + for e in renamed: + places[("C", old_place[e])] += 1 + for g, n in added - paired_new: + places[("addition", new_place[(g, n)])] += 1 + guarded = collections.Counter( + r for e in old if (r := must_not_move(e, old[e])) is not None + ) + + check = subprocess.run( + [ + sys.executable, + "tests/test_hashing/golden/generate_golden_hashes.py", + "--check", + ], + cwd=ROOT, + capture_output=True, + text=True, + ) + check_line = (check.stdout.strip().splitlines() or [""])[-1] + if check.returncode != 0: + failures.append(f"--check failed: {check_line}") + + print( + f"base {args.base} = {base_commit[:8]}; frozen and provisional files together" + ) + print(f"entries on the base: {len(old)}; after the golden step: {len(new)}") + print(f"byte-identical: {len(unchanged)}") + print(f"A label only: {len(a_set)}") + print(f"B value moved: {len(b_set)}") + print(f"C renamed: {len(renamed)} (value moved too: {len(c_moved)})") + print(f"additions: {len(extra)} (the listed {len(ADDITIONS)})") + print( + "by file kind: " + + ", ".join(f"{c} {p} {n}" for (c, p), n in sorted(places.items())) + ) + print( + "must not move, checked: " + + ", ".join(f"{r} {n}" for r, n in sorted(guarded.items())) + ) + print(f"--check: {check_line}") + if c_moved: + # The claim is printed only when check 5 found it true (CodeRabbit on PR 454): + # a failed check is reported as failed, never beside a passing statement. + if record_id_failures: + print( + f"record ids rebuilt: {len(c_moved)} entries; " + f"{len(record_id_failures)} not explained by the system-tag names " + "(see FAIL below)" + ) + else: + print( + f"record ids rebuilt: {len(c_moved)} entries; with the system-tag " + "names mapped back they are the old pinned ids" + ) + + if args.write and not failures: + rows = [] + for e in sorted(a_set | b_set): + rows.append( + { + "category": "A" if e in a_set else "B", + "group": e[0], + "file": old_place[e], + "entry": e[1], + "old": old[e], + "new": new[e], + } + ) + for e, to in sorted(renamed.items()): + rows.append( + { + "category": "C", + "group": e[0], + "file": old_place[e], + "entry": e[1], + "new entry": to[1], + "old": old[e], + "new": new[to], + } + ) + for g, n in sorted(added - paired_new): + rows.append( + { + "category": "addition", + "group": g, + "file": new_place[(g, n)], + "entry": n, + "new": new[(g, n)], + } + ) + OUTPUT.write_text( + json.dumps( + {"base": base_commit[:8], "changes": rows}, indent=1, sort_keys=True + ) + + "\n" + ) + print(f"wrote {OUTPUT.relative_to(ROOT)} ({len(rows)} rows)") + + for failure in failures: + print("FAIL", failure) + print("OK" if not failures else f"{len(failures)} failure(s)") + return 1 if failures else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/dev/scripts/itl_640/itl_1280_as_source_types.py b/docs/dev/scripts/itl_640/itl_1280_as_source_types.py new file mode 100644 index 000000000..3b62f4fe5 --- /dev/null +++ b/docs/dev/scripts/itl_640/itl_1280_as_source_types.py @@ -0,0 +1,127 @@ +"""ITL-1280: does ``node.as_source()`` keep its origin's Arrow types? + +Run: ``uv run python docs/dev/scripts/itl_640/itl_1280_as_source_types.py`` + +For each narrow or unit-bearing Arrow type, as a tag and as a data column, over an +operator node (``map_data``, CacheMode.LOG) and a function node (tag only: a function +node's data are its declared outputs), on an in-memory and a Delta database, by the +sync and the async run: the type ``as_source()`` reports before the run (no rows) and +after it (stored rows), against the node's own type. Prints one line per case. +""" + +from __future__ import annotations + +import asyncio +import datetime as dt +import decimal +import tempfile +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode + +warnings.simplefilter("ignore") + +TS = [dt.datetime(2026, 1, 1, 0, 0, 1), dt.datetime(2026, 1, 2)] +TYPES: dict[str, pa.Array[Any]] = { + "int8": pa.array([1, 2], pa.int8()), + "int32": pa.array([1, 2], pa.int32()), + "uint16": pa.array([1, 2], pa.uint16()), + "float16": pa.array([1.5, 2.5], pa.float32()).cast(pa.float16()), + "float32": pa.array([1.5, 2.5], pa.float32()), + "ts[s]": pa.array(TS, pa.timestamp("s")), + "ts[us] naive": pa.array(TS, pa.timestamp("us")), + "ts[ms, Europe/Berlin]": pa.array(TS, pa.timestamp("ms", tz="Europe/Berlin")), + "decimal128(10,2)": pa.array( + [decimal.Decimal("1.25"), decimal.Decimal("2.50")], pa.decimal128(10, 2) + ), +} + + +@function_pod(output_keys="y") +def _plus(w: float) -> float: + return w + 1 + + +def _table(column: pa.Array[Any], role: str) -> pa.Table: + """Tags ``k`` and ``g``, data ``x`` and ``w``; the column under test is ``g`` + (tag) or ``x`` (data).""" + g = column if role == "tag" else pa.array([1, 2], pa.int64()) + x = column if role == "data" else pa.array([1, 2], pa.int64()) + schema = pa.schema( + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("g", g.type), + pa.field("x", x.type), + pa.field("w", pa.float64(), nullable=False), + ] + ) + return pa.Table.from_arrays( + [pa.array(["r1", "r2"], pa.large_string()), g, x, pa.array([0.5, 1.5])], + schema=schema, + ) + + +def measure(type_name: str, role: str, node_kind: str, db_kind: str, path: str) -> str: + column = TYPES[type_name] + folder = Path(tempfile.mkdtemp()) + database = ( + InMemoryArrowDatabase() if db_kind == "memory" else DeltaTableDatabase(folder) + ) + source = ArrowTableSource( + _table(column, role), + tag_columns=["k", "g"], + tag_only_columns=True, + source_id="s", + ) + name = "g" if role == "tag" else "z" + job = PipelineJob(name="j", database=database) + with job: + if node_kind == "operator": + source.map_data({"x": "z"}, label="node") + else: + _plus.pod(source, label="node") + node = job.nodes["node"] + if node_kind == "operator": + node.attach_databases( + pipeline_database=database.at("j"), cache_mode=CacheMode.LOG + ) + try: + before = node.as_source().as_table().schema.field(name).type + before_hash = node.as_source().pipeline_hash() + except Exception as exc: # noqa: BLE001 + return f"before: {type(exc).__name__}: {str(exc)[:120]}" + try: + job.run() if path == "sync" else asyncio.run(job.run_async()) + except Exception as exc: # noqa: BLE001 + return f"run: {type(exc).__name__}: {str(exc)[:120]}" + own = node.as_table().schema.field(name).type + try: + after = node.as_source().as_table().schema.field(name).type + after_hash = node.as_source().pipeline_hash() + except Exception as exc: # noqa: BLE001 + return f"after: {type(exc).__name__}: {str(exc)[:140]}" + ok = before == after == own == column.type and before_hash == after_hash + return ( + f"{'same' if ok else 'DIFFERS'} before {before} after {after} node {own}" + f"{'' if before_hash == after_hash else ' (pipeline hash moved)'}" + ) + + +for type_name in TYPES: + for role in ("tag", "data"): + for node_kind in ("operator", "function"): + if node_kind == "function" and role == "data": + continue + for db_kind in ("memory", "delta"): + for path in ("sync", "async"): + result = measure(type_name, role, node_kind, db_kind, path) + print( + f"{type_name:22} {role:4} {node_kind:8} {db_kind:6} {path:5} {result}" + ) diff --git a/docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py b/docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py new file mode 100644 index 000000000..67070a03c --- /dev/null +++ b/docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py @@ -0,0 +1,196 @@ +"""ITL-640 Q1/Q2: does ``StarfixArrowHasher.hash_schema`` cover a logical type's whole +identifier, and does it ignore field metadata? + +Run: ``uv run python docs/dev/scripts/itl_640/q1_q2_logical_types_and_metadata.py`` + +Q1. For every logical type a schema can hold, the field's Arrow type (from the data +context's converter) is hashed, and then the same field with only the extension +METADATA changed (name kept) and only the extension NAME changed (metadata kept): both +must hash differently from the original. + +Q2. Field metadata and schema metadata that are not ``ARROW:extension:*`` are ignored: +this script shows it, so that nothing identity-bearing may be carried only that way. +""" + +from __future__ import annotations + +import dataclasses +from typing import Any +import uuid +import warnings +from pathlib import Path + +import numpy as np +import pyarrow as pa + +import orcapod as op +from orcapod.contexts import get_default_context +from orcapod.logical_types.numpy_type import LogicalNumpyArray +from orcapod.utils.arrow_utils import normalize_extension_columns + +warnings.simplefilter("ignore") + +ctx = get_default_context() +conv = ctx.type_converter +hasher = ctx.arrow_hasher + + +@dataclasses.dataclass +class Exact: + a: int + b: str + + +@op.dataclass +class Structural: + a: int + b: str + + +@op.dataclass(name="Structural") +class StructuralOtherFields: + a: int + b: float + + +TYPES: dict[str, Any] = { + "Path": Path, + "uuid.UUID": uuid.UUID, + "File": op.File if hasattr(op, "File") else None, + "np.ndarray": np.ndarray, + "Exact (dataclass)": Exact, + "Structural (orcapod.dataclass)": Structural, + "list[Path]": list[Path], + "set[int]": set[int], + "set[Path]": set[Path], + "list[Exact]": list[Exact], +} + + +def h(schema: pa.Schema) -> str: + return hasher.hash_schema(schema).to_hex()[:16] + + +def ipc_field(field: "pa.Field[Any]") -> "pa.Field[Any]": + """The field in IPC form: storage type plus ``ARROW:extension:*`` metadata.""" + return normalize_extension_columns(pa.schema([field]).empty_table()).schema.field(0) + + +def with_ext( + field: "pa.Field[Any]", *, name: bytes | None = None, meta: bytes | None = None +) -> "pa.Field[Any]": + md: dict[bytes | str, bytes | str] = { + key: value for key, value in (field.metadata or {}).items() + } + if name is not None: + md[b"ARROW:extension:name"] = name + if meta is not None: + md[b"ARROW:extension:metadata"] = meta + return field.with_metadata(md) + + +print("Q1: logical types") +print(f"{'type':34} {'arrow type':48} {'hash':16} meta-changed name-changed") +for label, py_type in TYPES.items(): + if py_type is None: + continue + try: + # Hashing a type registers a class a factory covers (a dataclass), as a + # source or a function pod does before it converts the type. + ctx.semantic_hasher.hash_object(py_type) + arrow_type = conv.python_type_to_arrow_type(py_type) + except Exception as exc: # noqa: BLE001 + print(f"{label:34} NOT CONVERTIBLE: {type(exc).__name__}: {exc}") + continue + field = pa.field("x", arrow_type) + base = h(pa.schema([field])) + # Rebuild the field in IPC form, then change the extension metadata or name only. + ipc = ipc_field(field) + md = dict(ipc.metadata or {}) + if b"ARROW:extension:name" in md: + same_ipc = h(pa.schema([ipc])) + changed_meta = h( + pa.schema( + [with_ext(ipc, meta=md.get(b"ARROW:extension:metadata", b"") + b" ")] + ) + ) + changed_name = h( + pa.schema([with_ext(ipc, name=md[b"ARROW:extension:name"] + b"x")]) + ) + verdict = ( + f"{'DIFFERS' if changed_meta != base else 'SAME!!'} " + f"{'DIFFERS' if changed_name != base else 'SAME!!'}" + f" (ipc form hashes {'equal' if same_ipc == base else 'DIFFERENTLY'})" + ) + else: + verdict = "(no extension at top level)" + print(f"{label:34} {str(arrow_type)[:48]:48} {base} {verdict}") + +print() +print("Q1b: two numpy ignore lists (two logical types, one extension name)") +t_strict = LogicalNumpyArray().get_arrow_extension_type() +t_ignore = LogicalNumpyArray(ignore=["memory_order"]).get_arrow_extension_type() +print(" strict :", t_strict, t_strict.__arrow_ext_serialize__()) +print(" ignore :", t_ignore, t_ignore.__arrow_ext_serialize__()) +try: + print( + " hash_schema equal:", + h(pa.schema([pa.field("x", t_strict)])) + == h(pa.schema([pa.field("x", t_ignore)])), + ) +except Exception as exc: # noqa: BLE001 + # A data context reads only columns stored under its own list (CLAUDE.md). + print(f" hash_schema of the other list raises {type(exc).__name__}") + +print() +print("Q1c: structural classes, one name, other fields (identity records differ)") +ctx.semantic_hasher.hash_object(Structural) +ctx.semantic_hasher.hash_object(StructuralOtherFields) +a = conv.python_type_to_arrow_type(Structural) +b = conv.python_type_to_arrow_type(StructuralOtherFields) +print(" A:", a) +print(" B:", b) +print( + " hash_schema equal:", + h(pa.schema([pa.field("x", a)])) == h(pa.schema([pa.field("x", b)])), +) + +print() +print("Q1d: a logical type against its storage type") +for label, py_type in ( + ("Path", Path), + ("uuid.UUID", uuid.UUID), + ("set[int]", set[int]), +): + t = conv.python_type_to_arrow_type(py_type) + storage = t.storage_type if isinstance(t, pa.ExtensionType) else t + print( + f" {label}: {t} vs storage {storage}: equal =", + h(pa.schema([pa.field("x", t)])) == h(pa.schema([pa.field("x", storage)])), + ) + +print() +print("Q2: field and schema metadata (not ARROW:extension:*)") +plain = pa.schema([pa.field("x", pa.int64())]) +print( + " field metadata {'k': 'v'} ignored:", + h(plain) == h(pa.schema([pa.field("x", pa.int64(), metadata={"k": "v"})])), +) +print( + " schema metadata {'pandas': ...} ignored:", + h(plain) == h(plain.with_metadata({"pandas": "{}"})), +) +print( + " nested field metadata ignored:", + h(pa.schema([pa.field("x", pa.large_list(pa.field("item", pa.int64())))])) + == h( + pa.schema( + [ + pa.field( + "x", + pa.large_list(pa.field("item", pa.int64(), metadata={"k": "v"})), + ) + ] + ) + ), +) diff --git a/docs/dev/scripts/itl_640/q3i_storage_round_trips.py b/docs/dev/scripts/itl_640/q3i_storage_round_trips.py new file mode 100644 index 000000000..3eb3241a2 --- /dev/null +++ b/docs/dev/scripts/itl_640/q3i_storage_round_trips.py @@ -0,0 +1,174 @@ +"""ITL-640 Q3 (i): does a column read back from each database have the Arrow schema it +was written with, as ``StarfixArrowHasher.hash_schema`` sees it? + +Run: ``uv run python docs/dev/scripts/itl_640/q3i_storage_round_trips.py [tmpdir]`` + +For every database class (in-memory, Delta Lake, the connector database over SQLite) +and every column type below, one table ``(id, x)`` is written with ``add_records``, +flushed and read back with ``get_all_records``. The hash of the schema of ``x`` read +back is compared with the hash of the schema written. ``REFUSED`` means the database +refuses the type when it is written (``require_storable``), which is not a silent +change; ``READ FAILED`` means the write succeeded and the read raised. Every ``DIFFERS`` is a place where something stored and read again (a node's +stored view, ``as_source``, a cached source, a loaded job) would get another identity +than the same rows in memory. +""" + +from __future__ import annotations + +import datetime as dt +import decimal +import sys +import tempfile +import uuid +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase +from orcapod.databases.sqlite_connector import SQLiteConnector + +warnings.simplefilter("ignore") + +ctx = get_default_context() +conv = ctx.type_converter +hasher = ctx.arrow_hasher +D = decimal.Decimal +ts = [dt.datetime(2026, 1, 1, 0, 0, 1), dt.datetime(2026, 1, 2)] +tsz = [t.replace(tzinfo=dt.timezone.utc) for t in ts] +dates = [dt.date(2026, 1, 1), dt.date(2026, 1, 2)] + + +def col(values, arrow_type, nullable=True): + return pa.field("x", arrow_type, nullable=nullable), pa.array(values, arrow_type) + + +def logical_column(py_type, values): + """A logical-type column built by the converter, as a source builds it.""" + ctx.semantic_hasher.hash_object(py_type) + table = conv.python_dicts_to_arrow_table( + [{"x": v} for v in values], python_schema={"x": py_type} + ) + return table.schema.field("x"), table.column("x").combine_chunks() + + +COLUMNS = { + "int8": lambda: col([1, 2], pa.int8()), + "int16": lambda: col([1, 2], pa.int16()), + "int32": lambda: col([1, 2], pa.int32()), + "int64": lambda: col([1, 2], pa.int64()), + "uint8": lambda: col([1, 200], pa.uint8()), + "uint16": lambda: col([1, 2], pa.uint16()), + "uint32": lambda: col([1, 2], pa.uint32()), + "uint64": lambda: col([1, 2], pa.uint64()), + "float32": lambda: col([1.5, 2.5], pa.float32()), + "float64": lambda: col([1.5, 2.5], pa.float64()), + "int64 not null": lambda: col([1, 2], pa.int64(), nullable=False), + "bool": lambda: col([True, False], pa.bool_()), + "string": lambda: col(["a", "b"], pa.string()), + "binary": lambda: col([b"a", b"b"], pa.binary()), + "ts[s]": lambda: col(ts, pa.timestamp("s")), + "ts[ms]": lambda: col(ts, pa.timestamp("ms")), + "ts[us]": lambda: col(ts, pa.timestamp("us")), + "ts[ns]": lambda: col(ts, pa.timestamp("ns")), + "ts[us,UTC]": lambda: col(tsz, pa.timestamp("us", tz="UTC")), + "ts[ns,UTC]": lambda: col(tsz, pa.timestamp("ns", tz="UTC")), + "ts[us,Europe/Berlin]": lambda: col(tsz, pa.timestamp("us", tz="Europe/Berlin")), + "date32": lambda: col(dates, pa.date32()), + "date64": lambda: col(dates, pa.date64()), + "decimal(10,2)": lambda: col([D("1.25"), D("2.50")], pa.decimal128(10, 2)), + "decimal(38,4)": lambda: col([D("1.25"), D("2.50")], pa.decimal128(38, 4)), + "large_list": lambda: col( + [[1, 2], [3]], pa.large_list(pa.field("item", pa.int64())) + ), + "large_list": lambda: col( + [[1, 2], [3]], pa.large_list(pa.field("item", pa.int64(), nullable=False)) + ), + "large_list": lambda: col([[1, 2], [3]], pa.large_list(pa.int8())), + "large_list>": lambda: col( + [[[1], [2]], [[3]]], pa.large_list(pa.large_list(pa.int64())) + ), + "struct": lambda: col( + [{"a": 1, "b": "x"}, {"a": 2, "b": "y"}], + pa.struct([("a", pa.int32()), ("b", pa.string())]), + ), + "struct": lambda: col( + [{"a": 1}, {"a": 2}], pa.struct([pa.field("a", pa.int64(), nullable=False)]) + ), + "fixed_size_list[2]": lambda: col([[1, 2], [3, 4]], pa.list_(pa.int64(), 2)), + "dictionary": lambda: ( + pa.field("x", pa.dictionary(pa.int32(), pa.string())), + pa.array(["a", "b"]).dictionary_encode(), + ), + "Path": lambda: logical_column(Path, [Path("/a"), Path("/b")]), + "uuid.UUID": lambda: logical_column(uuid.UUID, [uuid.uuid4(), uuid.uuid4()]), + "list[Path]": lambda: logical_column(list[Path], [[Path("/a")], [Path("/b")]]), + "set[int]": lambda: logical_column(set[int], [{1, 2}, {3}]), + "dict[str,int]": lambda: logical_column(dict[str, int], [{"a": 1}, {"b": 2}]), +} + + +def databases(root: Path): + return { + "InMemory": InMemoryArrowDatabase(), + "Delta": DeltaTableDatabase(root / "delta"), + "SQLite": ConnectorArrowDatabase(SQLiteConnector(str(root / "store.db"))), + } + + +def describe(field: "pa.Field[Any]") -> str: + return f"{field.type}{'' if field.nullable else ' not null'}" + + +def main(root: Path) -> None: + dbs = databases(root) + ids = pa.array([b"r1", b"r2"], pa.large_binary()) + print(f"{'column':34}" + "".join(f"{name:44}" for name in dbs)) + for i, (label, make) in enumerate(COLUMNS.items()): + try: + field, values = make() + except Exception as exc: # noqa: BLE001 + print(f"{label:34}cannot build: {type(exc).__name__}: {exc}") + continue + written = pa.Table.from_arrays( + [ids, values], + schema=pa.schema( + [pa.field("id", pa.large_binary(), nullable=False), field] + ), + ) + h_written = hasher.hash_schema(pa.schema([written.schema.field("x")])) + cells = [] + for name, db in dbs.items(): + path = ("t", f"c{i}") + try: + db.add_records(path, written, record_id_column="id", flush=True) + except Exception as exc: # noqa: BLE001 + cells.append(f"REFUSED {type(exc).__name__}: {exc}"[:42]) + continue + try: + back = db.get_all_records(path, record_id_column="id") + assert back is not None + read_field = back.schema.field("x") + h_back = hasher.hash_schema(pa.schema([read_field])) + same_values = ( + back.column("x").to_pylist() == written.column("x").to_pylist() + ) + if h_back == h_written: + cells.append("same" + ("" if same_values else " (VALUES DIFFER)")) + else: + cells.append(f"DIFFERS -> {describe(read_field)}"[:42]) + except Exception as exc: # noqa: BLE001 + # Written, but the read failed: not a refusal (CodeRabbit on PR 454). + cells.append(f"READ FAILED {type(exc).__name__}: {exc}"[:42]) + print(f"{label:34}" + "".join(f"{c:44}" for c in cells)) + + +if __name__ == "__main__": + if len(sys.argv) > 1: + main(Path(sys.argv[1])) + else: + with tempfile.TemporaryDirectory() as tmp: + main(Path(tmp)) diff --git a/docs/dev/scripts/itl_640/q3ii_builders.py b/docs/dev/scripts/itl_640/q3ii_builders.py new file mode 100644 index 000000000..aca2c0b3b --- /dev/null +++ b/docs/dev/scripts/itl_640/q3ii_builders.py @@ -0,0 +1,164 @@ +"""ITL-640 Q3 (ii): the same Python data through every source builder: which Arrow +types result, column by column, and which builders would give one table two +identities under an Arrow schema hash. + +Run: ``uv run python docs/dev/scripts/itl_640/q3ii_builders.py [tmpdir]`` + +Builders: ``DictSource``, ``DataFrameSource`` over a pandas and over a polars frame, +``CSVSource`` (a CSV written from the same rows), ``ArrowTableSource`` over +``pa.Table.from_pylist`` and ``ListSource`` (one column per element value). +""" + +from __future__ import annotations + +import csv +import datetime as dt +import sys +import tempfile +import warnings +from pathlib import Path +from typing import Any + +import pandas as pd +import polars as pl +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.sources import ( + ArrowTableSource, + CSVSource, + DataFrameSource, + DictSource, + ListSource, +) + +warnings.simplefilter("ignore") + +ctx = get_default_context() + +ROWS = [ + { + "k": "a", + "i": 1, + "f": 1.5, + "s": "x", + "b": True, + "ts": dt.datetime(2026, 1, 1, 12, 0), + "tsz": dt.datetime(2026, 1, 1, 12, 0, tzinfo=dt.timezone.utc), + "d": dt.date(2026, 1, 1), + "li": [1, 2], + "n": None, + }, + { + "k": "b", + "i": 2, + "f": 2.5, + "s": "y", + "b": False, + "ts": dt.datetime(2026, 1, 2, 12, 0), + "tsz": dt.datetime(2026, 1, 2, 12, 0, tzinfo=dt.timezone.utc), + "d": dt.date(2026, 1, 2), + "li": [3], + "n": 5, + }, +] +CSV_COLUMNS = ["k", "i", "f", "s", "b", "n"] + + +def build(root: Path) -> dict[str, Any]: + kw: dict[str, Any] = { + "tag_columns": ["k"], + "tag_only_columns": True, + "source_id": "s", + } + out: dict[str, Any] = {} + for label, make in ( + ("DictSource", lambda: DictSource(ROWS, **kw)), + ("DataFrameSource(pandas)", lambda: DataFrameSource(pd.DataFrame(ROWS), **kw)), + ("DataFrameSource(polars)", lambda: DataFrameSource(pl.DataFrame(ROWS), **kw)), + ( + "ArrowTableSource(from_pylist)", + lambda: ArrowTableSource(pa.Table.from_pylist(ROWS), **kw), + ), + ): + try: + out[label] = make() + except Exception as exc: # noqa: BLE001 + out[label] = f"REFUSED {type(exc).__name__}: {exc}"[:160] + path = root / "rows.csv" + with path.open("w", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=CSV_COLUMNS) + writer.writeheader() + for row in ROWS: + writer.writerow( + {c: ("" if row[c] is None else row[c]) for c in CSV_COLUMNS} + ) + try: + out["CSVSource"] = CSVSource(str(path), **kw) + except Exception as exc: # noqa: BLE001 + out["CSVSource"] = f"REFUSED {type(exc).__name__}: {exc}"[:160] + return out + + +def field_text(f: "pa.Field[Any]") -> str: + return f"{f.type}{'' if f.nullable else ' nn'}" + + +def main(root: Path) -> None: + sources = build(root) + columns = list(ROWS[0]) + tables = {} + for label, src in sources.items(): + if isinstance(src, str): + print(f"{label}: {src}") + continue + tables[label] = src.as_table() # type: ignore[attr-defined] + labels = list(tables) + print(f"{'col':5}" + "".join(f"{lab[:30]:32}" for lab in labels)) + for c in columns: + cells = [] + for lab in labels: + t = tables[lab] + cells.append(field_text(t.schema.field(c)) if c in t.column_names else "-") + print(f"{c:5}" + "".join(f"{cell[:30]:32}" for cell in cells)) + print() + print(f"Per column, the builders whose Arrow field hashes like {labels[0]}'s:") + base = tables[labels[0]] + for c in columns: + h0 = ctx.arrow_hasher.hash_schema(pa.schema([base.schema.field(c)])) + same, diff = [], [] + for lab in labels[1:]: + t = tables[lab] + if c not in t.column_names: + continue + h = ctx.arrow_hasher.hash_schema(pa.schema([t.schema.field(c)])) + (same if h == h0 else diff).append(lab) + print(f" {c:5} same: {same} DIFFERENT: {diff}") + + print() + print("ListSource vs DictSource, one data column 'v' of Python ints / datetimes:") + utc = dt.timezone.utc + for values in ( + [1, 2], + [dt.datetime(2026, 1, 1, tzinfo=utc), dt.datetime(2026, 1, 2, tzinfo=utc)], + ): + ls = ListSource("v", values) + ds = DictSource( + [{"element_index": i, "v": v} for i, v in enumerate(values)], + tag_columns=["element_index"], + tag_only_columns=True, + ) + lf = ls.as_table().schema.field("v") + df = ds.as_table().schema.field("v") + print( + f" {type(values[0]).__name__}: ListSource {field_text(lf)} / DictSource {field_text(df)}" + f" -> hash equal: {ctx.arrow_hasher.hash_schema(pa.schema([lf])) == ctx.arrow_hasher.hash_schema(pa.schema([df]))}" + ) + + +if __name__ == "__main__": + if len(sys.argv) > 1: + main(Path(sys.argv[1])) + else: + with tempfile.TemporaryDirectory() as tmp: + main(Path(tmp)) diff --git a/docs/dev/scripts/itl_640/q3iii_operators.py b/docs/dev/scripts/itl_640/q3iii_operators.py new file mode 100644 index 000000000..323011ad7 --- /dev/null +++ b/docs/dev/scripts/itl_640/q3iii_operators.py @@ -0,0 +1,118 @@ +"""ITL-640 Q3 (iii): is every operator's Arrow schema the same in zero-row form +(``typed_zero_row_table``, ITL-912) as in its populated result, and what does the +Python prediction say about list item nullability (ITL-1136)? + +Run: ``uv run python docs/dev/scripts/itl_640/q3iii_operators.py`` + +The async path is not measured here: ``tests/test_core/operators/test_async_sync_equivalence.py`` +asserts, for every operator, that the async rows have the sync rows' Arrow types, +nullability (item level included) and column order, over int8, float32, string, +list and large_list with nullable and non-null items, a struct and a logical type. + +The inputs have two tags (``k`` str, ``g`` str) and two data columns: ``x`` int8 with a +null, ``y`` large_list. +""" + +from __future__ import annotations + +import warnings + +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.core.operators import ( + AddTags, + Batch, + DropNulls, + GroupBy, + Join, + MapData, + MergeJoin, + PolarsFilter, + SelectDataColumns, + SemiJoin, +) +from orcapod.core.streams.base import typed_zero_row_table +from orcapod.sources import ArrowTableSource + +warnings.simplefilter("ignore") +ctx = get_default_context() +NN_ITEMS = pa.large_list(pa.field("item", pa.int8(), nullable=False)) + + +def source(source_id: str, other: str = "z") -> ArrowTableSource: + table = pa.Table.from_arrays( + [ + pa.array(["r1", "r2", "r3"], pa.large_string()), + pa.array(["g1", "g1", "g2"], pa.large_string()), + pa.array([1, None, 3], pa.int8()), + pa.array([[1], [2, 3], []], NN_ITEMS), + pa.array([1.5, 2.5, 3.5], pa.float32()), + ], + schema=pa.schema( + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("g", pa.large_string(), nullable=False), + pa.field("x", pa.int8()), + pa.field("y", NN_ITEMS, nullable=False), + pa.field(other, pa.float32(), nullable=False), + ] + ), + ) + return ArrowTableSource( + table, tag_columns=["k", "g"], tag_only_columns=True, source_id=source_id + ) + + +def user(stream, schema: pa.Schema) -> pa.Schema: + tags, data = stream.keys() + return pa.schema([schema.field(n) for n in dict.fromkeys([*tags, *data])]) + + +def text(schema: pa.Schema) -> str: + return "; ".join(f"{f.name}: {f.type}{'' if f.nullable else ' nn'}" for f in schema) + + +CASES = { + "Batch()": lambda: Batch()(source("a")), + "GroupBy('g')": lambda: GroupBy("g")(source("a")), + "MergeJoin(a, b) over a null in x": lambda: MergeJoin()(source("a"), source("b")), + "MergeJoin(a, b) on y only": lambda: MergeJoin()( + SelectDataColumns(["y", "z"])(source("a")), + SelectDataColumns(["y"])(source("b", "w")), + ), + "Join(a, b')": lambda: Join()( + source("a"), source("b", "w").map_data({"x": "x2", "y": "y2"}) + ), + "SemiJoin(a, b)": lambda: SemiJoin()(source("a"), source("b")), + "SelectDataColumns(x, y)": lambda: SelectDataColumns(["y", "x"])(source("a")), + "MapData": lambda: MapData({"x": "x1", "y": "y1"})(source("a")), + "PolarsFilter": lambda: PolarsFilter(constraints={"g": "g1"})(source("a")), + "DropNulls(x)": lambda: DropNulls(["x"])(source("a")), + "AddTags": lambda: AddTags({"cohort": "A", "run": 3})(source("a")), +} + +for label, make in CASES.items(): + try: + stream = make() + populated = user(stream, stream.as_table().schema) + zero = typed_zero_row_table(stream) + zero_user = None if zero is None else user(stream, zero.schema) + equal = zero_user is not None and ctx.arrow_hasher.hash_schema( + populated + ) == ctx.arrow_hasher.hash_schema(zero_user) + print(f"== {label}: zero-row == populated: {equal}") + print(f" populated: {text(populated)}") + if not equal: + print(f" zero-row : {None if zero_user is None else text(zero_user)}") + print(f" Python : {stream.output_schema()}") + converted = ctx.type_converter.python_schema_to_arrow_schema( + stream.output_schema()[0] + stream.output_schema()[1] + ) + print( + " converter(Python) == populated:", + ctx.arrow_hasher.hash_schema(user(stream, converted)) + == ctx.arrow_hasher.hash_schema(populated), + ) + except Exception as exc: # noqa: BLE001 + print(f"== {label}: FAILED {type(exc).__name__}: {exc}") diff --git a/docs/dev/scripts/itl_640/q4_sources_without_rows.py b/docs/dev/scripts/itl_640/q4_sources_without_rows.py new file mode 100644 index 000000000..fe34117b3 --- /dev/null +++ b/docs/dev/scripts/itl_640/q4_sources_without_rows.py @@ -0,0 +1,203 @@ +"""ITL-640 Q4: where does a source's Arrow schema come from before it holds rows, and +does it equal the Arrow schema of the rows that arrive? + +Run: ``uv run python docs/dev/scripts/itl_640/q4_sources_without_rows.py [tmpdir]`` + +For each kind of source, three Arrow schemas of its (tag, data) columns are compared +with ``StarfixArrowHasher.hash_schema``: + +* ``zero-row``: ``typed_zero_row_table`` (ITL-912), before any row is read; +* ``converter``: the data context's converter applied to the declared Python schema; +* ``rows``: the schema of ``as_table()`` once rows exist. + +The source table has an ``int32`` tag ``k``, an ``int8`` data column ``x`` and a +``timestamp[ns]`` data column ``t``: three types the converter does not produce from +``int`` and ``datetime``. +""" + +from __future__ import annotations + +import datetime as dt +import sys +import tempfile +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.source_node import SourceNode +from orcapod.core.streams.base import typed_zero_row_table +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.core.sources.polling_source import PollingSource +from orcapod.types import Cursor, Schema + +warnings.simplefilter("ignore") + +TS = [dt.datetime(2026, 1, 1), dt.datetime(2026, 1, 2)] + + +def table() -> pa.Table: + return pa.Table.from_arrays( + [ + pa.array([1, 2], pa.int32()), + pa.array([1, 2], pa.int8()), + pa.array(TS, pa.timestamp("ns")), + ], + schema=pa.schema( + [ + pa.field("k", pa.int32(), nullable=False), + pa.field("x", pa.int8(), nullable=False), + pa.field("t", pa.timestamp("ns"), nullable=False), + ] + ), + ) + + +@function_pod(output_keys="y") +def double(x: int) -> int: + return x * 2 + + +def user_schema(stream: Any, arrow_schema: pa.Schema) -> pa.Schema: + tag_keys, data_keys = stream.keys() + names = [*tag_keys, *[n for n in data_keys if n not in tag_keys]] + return pa.schema([arrow_schema.field(n) for n in names]) + + +def describe(schema: pa.Schema | None) -> str: + if schema is None: + return "None" + return "; ".join( + f"{f.name}: {f.type}{'' if f.nullable else ' not null'}" for f in schema + ) + + +def schemas(stream: Any, with_rows: bool = True) -> dict[str, pa.Schema | None]: + ctx = stream.data_context + out: dict[str, pa.Schema | None] = {} + z = typed_zero_row_table(stream) + out["zero-row"] = None if z is None else user_schema(stream, z.schema) + tag, data = stream.output_schema() + out["converter"] = ctx.type_converter.python_schema_to_arrow_schema( + Schema({**dict(tag), **dict(data)}) + ) + if with_rows: + try: + t = stream.as_table() + out["rows"] = user_schema(stream, t.schema) + except Exception as exc: # noqa: BLE001 + print(f" as_table FAILED: {type(exc).__name__}: {exc}") + out["rows"] = None + return out + + +def report(label: str, stream: Any, with_rows: bool = True) -> None: + ctx = stream.data_context + found = schemas(stream, with_rows) + print(f"== {label}") + hashes = {} + for name, schema in found.items(): + print(f" {name:10} {describe(schema)}") + hashes[name] = None if schema is None else ctx.arrow_hasher.hash_schema(schema) + keys = [k for k, v in hashes.items() if v is not None] + for i, a in enumerate(keys): + for b in keys[i + 1 :]: + print(f" {a} == {b}: {hashes[a] == hashes[b]}") + + +class Impl: + """A polling implementation declaring Python types, fetching a fixed table.""" + + def __init__(self, fetched: Any) -> None: + self._fetched = fetched + + def identity(self) -> Any: + return ("q4", 1) + + def to_config(self) -> dict[str, Any] | None: + return None + + @classmethod + def from_config(cls, config: dict[str, Any]) -> "Impl": + raise NotImplementedError + + def schema(self) -> Any: + return Schema({"k": int, "x": int, "t": dt.datetime}) + + async def poll(self, cursor: Any = None) -> bool: + return cursor is None + + async def fetch(self, cursor: Any = None) -> Any: + return Cursor.now(1), self._fetched + + async def close(self) -> None: + return None + + +def main(root: Path) -> None: + source = ArrowTableSource( + table(), tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + report("ArrowTableSource (holds its table)", source) + + for kind in ("mem", "delta"): + db = ( + InMemoryArrowDatabase() + if kind == "mem" + else DeltaTableDatabase(root / kind) + ) + job = PipelineJob(name="j", database=db) + with job: + double.pod(source, label="f") + source.map_data({"x": "z"}, label="op") + f, opn = job.nodes["f"], job.nodes["op"] + report(f"[{kind}] function job node, before run", f, with_rows=False) + report(f"[{kind}] operator job node, before run", opn, with_rows=False) + report(f"[{kind}] f.as_source(), before run", f.as_source()) + report(f"[{kind}] op.as_source(), before run", opn.as_source()) + job.run() + report(f"[{kind}] function job node, after run", f) + report(f"[{kind}] operator job node, after run", opn) + report(f"[{kind}] f.as_source(), after run", f.as_source()) + report(f"[{kind}] op.as_source(), after run", opn.as_source()) + slot = job.nodes.get("s") + if slot is not None: + report(f"[{kind}] input slot of the job (bound)", slot) + cache_db = ( + InMemoryArrowDatabase() + if kind == "mem" + else DeltaTableDatabase(root / "cache") + ) + cached = CachedSource(source, cache_database=cache_db) + report(f"[{kind}] CachedSource over the ArrowTableSource", cached) + cached_derived = CachedSource(f.as_source(), cache_database=cache_db) + report(f"[{kind}] CachedSource over f.as_source()", cached_derived) + + slot = SourceNode( + name="declared", tag_schema=Schema({"k": int}), data_schema=Schema({"x": int}) + ) + report("SourceNode declared by hand (unbound)", slot, with_rows=False) + + print() + print("PollingSource: declared {k: int, x: int, t: datetime}") + for label, fetched in ( + ("pa.Table int32/int8/ts[ns]", table()), + ("Python dicts", {"k": [1, 2], "x": [1, 2], "t": TS}), + ): + p = PollingSource(Impl(fetched), tag_columns="k", record_id_columns="k") + report(f"PollingSource before poll, fetch returns {label}", p, with_rows=False) + before = p.pipeline_hash() + report(f"PollingSource after poll, fetch returned {label}", p) + print(" pipeline_hash unchanged by the poll:", before == p.pipeline_hash()) + + +if __name__ == "__main__": + if len(sys.argv) > 1: + main(Path(sys.argv[1])) + else: + with tempfile.TemporaryDirectory() as tmp: + main(Path(tmp)) diff --git a/docs/dev/scripts/itl_640/q5_saved_schema_text.py b/docs/dev/scripts/itl_640/q5_saved_schema_text.py new file mode 100644 index 000000000..56d669b74 --- /dev/null +++ b/docs/dev/scripts/itl_640/q5_saved_schema_text.py @@ -0,0 +1,85 @@ +"""ITL-640 Q5: does the saved schema text of a job rebuild the same Arrow type? + +Run: ``uv run python docs/dev/scripts/itl_640/q5_saved_schema_text.py`` + +Each Arrow type is written with the saved-job writer (``_serialize_arrow_type``) and +read with the reader (``parse_arrow_type_string``); the two are compared with +``StarfixArrowHasher.hash_schema``. Top-level nullability is saved apart, as the +``nullable`` record of a saved schema pair, so it is not part of this text. +""" + +from __future__ import annotations + +import uuid +import warnings +from pathlib import Path + +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.pipeline.serialization import ( + _serialize_arrow_type, + parse_arrow_type_string, +) + +warnings.simplefilter("ignore") +ctx = get_default_context() +conv = ctx.type_converter + + +def lt(py_type): + ctx.semantic_hasher.hash_object(py_type) + return conv.python_type_to_arrow_type(py_type) + + +TYPES = { + "int8": pa.int8(), + "uint64": pa.uint64(), + "float32": pa.float32(), + "ts[s]": pa.timestamp("s"), + "ts[ns]": pa.timestamp("ns"), + "ts[us, UTC]": pa.timestamp("us", tz="UTC"), + "ts[ms, Europe/Berlin]": pa.timestamp("ms", tz="Europe/Berlin"), + "date32": pa.date32(), + "date64": pa.date64(), + "decimal128(10,2)": pa.decimal128(10, 2), + "decimal256(50,4)": pa.decimal256(50, 4), + "large_list": pa.large_list( + pa.field("item", pa.int8(), nullable=False) + ), + "large_list>": pa.large_list( + pa.large_list(pa.field("item", pa.int64(), nullable=False)) + ), + "fixed_size_list[2]": pa.list_(pa.int64(), 2), + "struct>": pa.struct( + [ + pa.field("a", pa.int32(), nullable=False), + pa.field("b", pa.large_list(pa.timestamp("ns"))), + ] + ), + "dictionary": pa.dictionary(pa.int32(), pa.string()), + "map": pa.map_(pa.string(), pa.int64()), + "Path": lt(Path), + "uuid.UUID": lt(uuid.UUID), + "list[Path]": lt(list[Path]), + "set[int]": lt(set[int]), + "dict[str, int]": lt(dict[str, int]), +} + +for label, arrow_type in TYPES.items(): + text = _serialize_arrow_type(arrow_type) + try: + back = parse_arrow_type_string(text) + except Exception as exc: # noqa: BLE001 + print( + f"{label:52} text {text!r}: READ FAILED {type(exc).__name__}: {exc}"[:220] + ) + continue + same = ctx.arrow_hasher.hash_schema( + pa.schema([pa.field("x", arrow_type)]) + ) == ctx.arrow_hasher.hash_schema(pa.schema([pa.field("x", back)])) + print( + f"{label:52} {'same' if same else 'DIFFERS -> ' + str(back)} text {text!r}"[ + :240 + ] + ) diff --git a/docs/dev/scripts/itl_640/q9_golden_moves.py b/docs/dev/scripts/itl_640/q9_golden_moves.py new file mode 100644 index 000000000..116baa7d0 --- /dev/null +++ b/docs/dev/scripts/itl_640/q9_golden_moves.py @@ -0,0 +1,212 @@ +"""ITL-640 Q9: which golden entries move under the Arrow schema hash, by group, case +and kind of entry; which do not. Writes nothing to the golden folder. + +Run: ``uv run python docs/dev/scripts/itl_640/q9_golden_moves.py [--list]`` + +An entry whose NAME holds a system-tag column name (``row[...]._tag_source_id::``) +is renamed when the schema hash moves; such a pair (pinned name gone, computed name new) +is matched by the name with every 64-hex digest blanked, and counted as ``renamed`` +(value unchanged) or ``renamed+moved``. ``--list`` prints every changed entry. +""" + +from __future__ import annotations + +import collections +import json +import pathlib +import re +import sys +import warnings + +ROOT = pathlib.Path(__file__).resolve().parents[4] +# The cases import as ``tests.test_hashing.golden.cases``, as the generator imports them: +# fixtures hash with their module path. +sys.path.insert(0, str(ROOT)) +warnings.simplefilter("ignore") + +from tests.test_hashing.golden import cases # noqa: E402 + +GROUPS = ["semantic", "schema", "arrow", "datagram", "pipeline", "torch"] +HEX = re.compile(r"[0-9a-f]{64,70}") + + +FOLDER = ROOT / "tests" / "test_hashing" / "golden" / "data" / "v1" + + +def pinned_entries() -> dict[str, dict[str, object]]: + """Every pinned entry by group: the frozen files and the provisional files (ITL-1266).""" + out: dict[str, dict[str, object]] = collections.defaultdict(dict) + for path in sorted(FOLDER.glob("*.json")): + group = path.name.split("-")[0] + out[group].update(json.loads(path.read_text())) + for path in sorted((FOLDER / "provisional").glob("*.json")): + out[path.stem].update(json.loads(path.read_text())) + return out + + +def provisional_pins() -> set[tuple[str, str]]: + """``(group, entry)`` of every entry pinned in a provisional file.""" + return { + (path.stem, entry) + for path in sorted((FOLDER / "provisional").glob("*.json")) + for entry in json.loads(path.read_text()) + } + + +def blank(name: str) -> str: + """``name`` with every digest blanked: the key a renamed entry keeps.""" + return HEX.sub("H", name) + + +def case_of(entry: str) -> str: + """The case an entry belongs to (its first name component).""" + return entry.split(".")[0] + + +def kind_of(entry: str) -> str: + """The kind of value an entry pins (its last name component, digests blanked).""" + name = re.sub(r"\[[^\]]*\]", "[]", blank(entry)) + last = name.split(".")[-1] + if last.startswith("_tag_record_id"): + return "row record id (value)" + if last.startswith("_tag_source_id"): + return "row source id (value)" + return last + + +def label_only(old: object, new: object) -> bool: + """Whether only the label of a ``