diff --git a/changelog.d/ITL-1948.md b/changelog.d/ITL-1948.md new file mode 100644 index 000000000..57432c5c9 --- /dev/null +++ b/changelog.d/ITL-1948.md @@ -0,0 +1,3 @@ +### Added + +- Discover stored function pod results in a database and open them as read-only derived sources with `orcapod.discover_function_results()`. diff --git a/docs/api/sources.md b/docs/api/sources.md index 1f03bea82..080766f5a 100644 --- a/docs/api/sources.md +++ b/docs/api/sources.md @@ -35,6 +35,8 @@ source id and hashes are not frozen with data context v1 (`PROVISIONAL_SOURCES`) ::: orcapod.core.sources.DerivedSource +::: orcapod.discover_function_results + ::: orcapod.core.sources.CachedSource ::: orcapod.core.sources.SourceProxy diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index ffde56c6a..9609ee8a2 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1191,6 +1191,65 @@ With the default lineage-based record IDs, a `CachedSourceChangedRowError` if a newer stored result changes a lineage the cache already holds, so use a new cache path for the updated results. +**Discovering results in a database.** Use `discover_function_results(database)` when +you have the database and want to find its stored function results. Each entry identifies +the pipeline, function and node content hash, and exposes the stored table paths and +tag and data Arrow schemas. Opening an entry returns a provisional `DerivedSource` you can pass to another +job. Discovery reads the current layout and data context. It needs access to both the +pipeline records and the function results and performs no writes or computation. +Discovery recovers the pipeline name relative to the database view. A job named +`"daily"` written through `database.at("shared")` is named `daily` from that view +and `shared/daily` from the root. Use the same database view as the job to recover +the identity of `node.as_source()`. Pass `entry.as_source(pipeline_name="alias")` +to open it under a surrogate name. A surrogate changes the source ID, content hash +and provenance values that contain the source ID. A job with no enclosing pipeline +folder is listed with `pipeline_name=None` and needs a surrogate to open. +For a job that used a separate result store, pass its `result_database=` as well. +Discovery relies on the stored field declarations, including Arrow types, nullability +and data-tag markers. It uses exact table paths from in-memory, Delta on POSIX or +cloud storage, SQLite, PostgreSQL, and writable keyed SpiralDB databases. Discovery +refuses connectors whose listing only exposes sanitized names. +The original job's database must also support writing its result schema. +A discovered source shows the rows committed when it is first read. To see rows the +original job commits after that first read, call `discover_function_results` again and +open a new source from the returned entry. + +```python +from tempfile import TemporaryDirectory + +from orcapod import PipelineJob, discover_function_results, function_pod +from orcapod.databases import DeltaTableDatabase +from orcapod.sources import DictSource + + +@function_pod(output_keys=["meters", "kilograms"]) +def to_metric(centimeters: int, grams: int) -> tuple[float, float]: + return centimeters / 100, grams / 1000 + + +with TemporaryDirectory() as directory: + job = PipelineJob(name="measurements", database=DeltaTableDatabase(directory)) + readings = DictSource( + [ + {"site": "north", "sample": "a", "centimeters": 160, "grams": 900}, + {"site": "south", "sample": "b", "centimeters": 180, "grams": 1200}, + ], + tag_columns=["site", "sample"], + tag_only_columns=True, + source_id="readings", + ) + with job: + to_metric.pod(readings) + job.run() + + (entry,) = discover_function_results(DeltaTableDatabase(directory)) + print(entry.function_name) + rows = entry.as_source().as_table().sort_by([("site", "ascending"), ("sample", "ascending")]) + print(rows.to_pylist()) +# to_metric +# [{'site': 'north', 'sample': 'a', 'meters': 1.6, 'kilograms': 0.9}, {'site': 'south', 'sample': 'b', 'meters': 1.8, 'kilograms': 1.2}] +``` + **Using a tag value as an input to a computation.** Tags identify a row and data is what a function computes on. A data-tag (the default for a declared tag) is both: a function reads it through its data role, under the same name (see diff --git a/docs/dev/scripts/itl_1948/inspect_stored_job.py b/docs/dev/scripts/itl_1948/inspect_stored_job.py new file mode 100644 index 000000000..4a9f18144 --- /dev/null +++ b/docs/dev/scripts/itl_1948/inspect_stored_job.py @@ -0,0 +1,329 @@ +"""Compare a live derived source with the database left by its job. + +Run with `uv run python docs/dev/scripts/itl_1948/inspect_stored_job.py`. +""" + +from __future__ import annotations + +from collections.abc import Callable +from tempfile import TemporaryDirectory +from typing import cast + +import pyarrow as pa + +from orcapod import ( + FunctionPod, + Path, + PipelineJob, + discover_function_results, + function_pod, +) +from orcapod.core.data_tags import stored_data_tags, without_tag_kind_marks +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.protocols.core_protocols import FunctionPodProtocol, StreamProtocol +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.sources import ArrowTableSource +from orcapod.system_constants import ( + PIPELINE_DB_SCHEMA_VERSION, + RESULT_DB_SCHEMA_VERSION, + constants, +) +from orcapod.types import ContentHash + + +@function_pod(output_keys=["score", "note", "artifact"]) +def summarize(run_key: int, value: float) -> tuple[float, str | None, Path]: + """Return a mix of numeric, nullable large-string, and logical output.""" + return value * 2, "ok" if run_key % 2 else None, Path(f"artifact-{run_key}") + + +class InstanceScopedNode(FunctionJobNode): + """Use the supported per-content storage layout for the probe.""" + + def __init__( + self, + function_pod: FunctionPodProtocol, + input_stream: StreamProtocol, + label: str | None, + ) -> None: + super().__init__( + function_pod, input_stream, label=label, table_scope="content_hash" + ) + + +class InstanceScopedJob(PipelineJob): + """Run actual compiled nodes with the per-content path suffix.""" + + function_node_class = InstanceScopedNode + + +def write_job( + database: ArrowDatabaseProtocol, + name: str | tuple[str, ...], + *, + reverse_tags: bool = False, + result_database: ArrowDatabaseProtocol | None = None, + job_class: type[PipelineJob] = PipelineJob, +) -> tuple[str, str, str, tuple[pa.Schema, pa.Schema], pa.Table]: + """Write two nodes sharing a pipeline table and retain one node's reference.""" + job = job_class(name=name, database=database, result_database=result_database) + with job: + for cohort in ("first", "second"): + summarize.pod(input_source(cohort, reverse_tags=reverse_tags), label=cohort) + job.run() + node = cast(FunctionJobNode, job.nodes["first"]) + source = node.as_source(source_id=None if name else "explicit") + return ( + node.content_hash().to_string(), + source.source_id, + source.pipeline_hash().to_hex(), + source.arrow_schemas, + source.as_table(columns={"system_tags": True, "source": True}), + ) + + +def input_source(cohort: str, *, reverse_tags: bool = False) -> ArrowTableSource: + """Build the shared synthetic input used for each path case.""" + table = pa.Table.from_arrays( + [ + pa.array([cohort, cohort], type=pa.large_string()), + pa.array([1, 2], type=pa.int32()), + pa.array([3.5, 4.5], type=pa.float64()), + ], + schema=pa.schema( + [ + pa.field("cohort", pa.large_string(), nullable=False), + pa.field("run_key", pa.int32(), nullable=False), + pa.field("value", pa.float64(), nullable=False), + ] + ), + ) + return ArrowTableSource( + table, + tag_columns=["run_key", "cohort"] if reverse_tags else ["cohort", "run_key"], + tag_only_columns=["cohort"], + source_id=cohort, + ) + + +def inspect_database( + database: ArrowDatabaseProtocol, +) -> tuple[tuple[pa.Schema, pa.Schema], dict[str, list[int]]]: + """Inspect the stored paths, schemas and result links without a node.""" + paths = database.list_table_paths() + (pipeline_path,) = (p for p in paths if p[-1] == PIPELINE_DB_SCHEMA_VERSION) + (result_path,) = (p for p in paths if p[-1] == RESULT_DB_SCHEMA_VERSION) + pipeline = database.get_all_records(pipeline_path) + result = database.get_all_records( + result_path, record_id_column=constants.DATA_RECORD_ID + ) + assert pipeline is not None and result is not None + print("pipeline path:", "/".join(pipeline_path)) + print("result path:", "/".join(result_path)) + print("pipeline fields:", pipeline.column_names) + print("result fields:", result.column_names) + print("stored data-tags:", stored_data_tags(pipeline.schema)) + print( + "stored __data_context:", + pipeline[constants.DATA_CONTEXT_COL].unique().to_pylist(), + ) + + tags = [name for name in pipeline.column_names if not name.startswith("_")] + from_results = [name for name in result.column_names if not name.startswith("_")] + data_tags = [name for name in tags if name in stored_data_tags(pipeline.schema)] + unmarked = without_tag_kind_marks(pipeline).schema + schemas = ( + pa.schema([unmarked.field(name) for name in tags]), + pa.schema( + [unmarked.field(name) for name in data_tags] + + [result.schema.field(name) for name in from_results] + ), + ) + output_ids = set(result[constants.DATA_RECORD_ID].to_pylist()) + by_node: dict[str, list[int]] = {} + for node_hash, result_id, run_key in zip( + pipeline[constants.NODE_CONTENT_HASH_COL].to_pylist(), + pipeline[constants.DATA_RECORD_ID].to_pylist(), + pipeline["run_key"].to_pylist(), + strict=True, + ): + assert result_id in output_ids + assert isinstance(node_hash, bytes) + assert isinstance(run_key, int) + digest = ContentHash.from_prefixed_digest(node_hash).to_string() + by_node.setdefault(digest, []).append(run_key) + print("node groups:", sorted(sorted(keys) for keys in by_node.values())) + print("pipeline/result row counts:", pipeline.num_rows, result.num_rows) + return schemas, by_node + + +def demonstrate( + database: ArrowDatabaseProtocol, + read_database: ArrowDatabaseProtocol | None = None, +) -> None: + """Establish both recoverable fields and ambiguity in the stored identity.""" + reference = write_job(database, ("outer", "inner")) + if read_database is None: + read_database = database + schemas, by_node = inspect_database(read_database) + node_hash, source_id, pipeline_hash, declared_schemas, table = reference + assert sorted(by_node[node_hash]) == [1, 2] + print("reference source id:", source_id) + print("reference source pipeline hash:", pipeline_hash) + print("declared tag and data schemas:", *declared_schemas, sep="\n") + print("stored tag and data schemas:", *schemas, sep="\n") + print( + "declared and stored schemas equal (including field metadata):", + [ + left.equals(right, check_metadata=True) + for left, right in zip(declared_schemas, schemas, strict=True) + ], + ) + print("derived columns:", table.column_names) + print( + "derived record ids:", + sorted( + record + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_RECORD_ID_PREFIX) + for record in cast(list[str], table[name].to_pylist()) + ), + ) + + paths_before = read_database.list_table_paths() + alias_hash, alias_id, alias_pipeline_hash, alias_schemas, _ = write_job( + database.at("outer"), "inner", reverse_tags=True + ) + assert paths_before == read_database.list_table_paths() + assert alias_hash == node_hash + assert alias_pipeline_hash == pipeline_hash + assert alias_id != source_id + assert alias_schemas[0].names == list(reversed(declared_schemas[0].names)) + for path in paths_before: + table_after = read_database.get_all_records(path) + assert table_after is not None + expected_rows = 4 if path[-1] == PIPELINE_DB_SCHEMA_VERSION else 2 + assert table_after.num_rows == expected_rows + print("same path and node hash, second default source id:", alias_id) + print("second declared tag order:", alias_schemas[0].names) + + +def show_case( + title: str, + database: ArrowDatabaseProtocol, + names: set[tuple[str, ...] | None], + *, + name: str | None = None, + result_database: ArrowDatabaseProtocol | None = None, +) -> None: + """Print the listed paths and confirm the names they support.""" + print(f"--- {title} (view {database.base_path!r}) ---") + for path in database.list_table_paths(): + print("/".join(path)) + entries = discover_function_results(database, result_database=result_database) + discovered = {entry.pipeline_name for entry in entries} + assert discovered == names + if name is not None: + assert entries + for entry in entries: + source = entry.as_source(pipeline_name=name) + assert source.as_table().num_rows > 0 + print("opened source:", source.source_id) + print("discovered names:", sorted(discovered, key=repr)) + + +def demonstrate_names(open_store: Callable[[str], ArrowDatabaseProtocol]) -> None: + """Exercise job folders, database view prefixes and result store placement.""" + root = open_store("default") + write_job(root, "daily") + show_case("default", root, {("daily",)}) + + root = open_store("scoped") + write_job(root.at("shared"), "daily") + show_case("explicit pipeline prefix", root, {("shared", "daily")}) + show_case( + "reader scoped to the database supplied to the job", + root.at("shared"), + {("daily",)}, + ) + show_case( + "reader scoped to the job folder", + root.at("shared", "daily"), + {None}, + ) + + root = open_store("explicit") + write_job(root, "daily", result_database=root.at("result_pool")) + show_case("explicit result view in the same store", root, {("daily",)}) + show_case("result view alone", root.at("result_pool"), set()) + + root = open_store("separate-pipeline") + result_store = open_store("separate-result") + write_job(root, "daily", result_database=result_store) + show_case("separate stores, pipeline view", root, set()) + show_case("separate stores, result view", result_store, set()) + show_case( + "separate stores, both views supplied", + root, + {("daily",)}, + name="daily", + result_database=result_store, + ) + + root = open_store("shared-root") + write_job(root, "daily") + write_job(root, "weekly") + show_case("two named jobs sharing the root", root, {("daily",), ("weekly",)}) + + root = open_store("empty-name") + write_job(root, ()) + show_case("job with an empty name", root, {None}) + show_case( + "job with an empty name and a surrogate", + root, + {None}, + name="recovered", + ) + + root = open_store("standalone") + node = FunctionJobNode( + FunctionPod(data_function=summarize.pod.data_function), + input_source("first"), + pipeline_database=root, + ) + node.run() + show_case("standalone root node", root, {None}) + + root = open_store("instance") + write_job(root, "daily", job_class=InstanceScopedJob) + show_case("content-hash table scope", root, {("daily",)}) + + +def main() -> None: + """Run the inspection on in-memory and Delta databases.""" + print("=== In memory ===") + demonstrate(InMemoryArrowDatabase()) + demonstrate_names(lambda _: InMemoryArrowDatabase()) + print("=== Delta ===") + with TemporaryDirectory() as directory: + root = Path(directory) + demonstrate( + DeltaTableDatabase(root / "schema"), DeltaTableDatabase(root / "schema") + ) + demonstrate_names(lambda name: DeltaTableDatabase(root / name)) + scoped_root = root / "scoped" / "shared" + show_case( + "independent reader rooted at the physical prefix directory", + DeltaTableDatabase(scoped_root), + {("daily",)}, + ) + show_case( + "independent reader rooted at the physical job directory", + DeltaTableDatabase(scoped_root / "daily"), + {None}, + ) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1948-discover-stored-results.md b/docs/dev/specs/itl-1948-discover-stored-results.md new file mode 100644 index 000000000..5aced7526 --- /dev/null +++ b/docs/dev/specs/itl-1948-discover-stored-results.md @@ -0,0 +1,215 @@ +# ITL-1948 Discover stored function results + +## Public API + +`orcapod.discover_function_results(database, *, result_database=None) -> tuple[StoredFunctionResult, ...]` +lists committed function results for the current default data context in the supplied +database view. An entry exposes `pipeline_name` (the name relative to the supplied database, or `None`), +exact `pipeline_path` and `result_path` relative to their database views, `function_name`, +`function_major` (integer), `function_type` (full type ID), `node_content_hash` +(labelled `ContentHash`), and `arrow_schemas` (the tag and data schema pair). An optional +`pipeline_record_count` counts persistent pipeline records for that node and context when +already available from the listing read. This can include earlier revisions of an input. +`entry.as_source(*, pipeline_name=None) -> DerivedSource` opens the result as a root source. The listing is +ordered by pipeline name, function path and node content hash. A result table without +pipeline records cannot identify which inputs a job processed, so it cannot yield a source +entry. Pass the same `result_database` view when the job wrote results in a different +store or outside the supplied database view. + +`Pipeline(name=...)` names a blueprint and has no database argument. Both it and +`PipelineJob(name=..., database=..., result_database=...)` normalize a string or +tuple name to a tuple in `pipeline/base.py:AbstractPipelineBase.__init__`. A +standalone `PipelineJob` chooses its own name, defaulting to `"pipeline"`. +`PipelineJob.from_pipeline` copies +the blueprint name through `from_invocations(..., name=pipeline._name)` and has +no name override. `job.as_pipeline()` likewise uses the job name. A separate job +created with `PipelineJob.from_invocations(..., name=...)` can choose a different +name. The store path is always scoped by +the running job's name and its database view. `PipelineJob._database_views` calls +`database.at(*name)` for the pipeline tables, then `.at("_result")` for results +unless `result_database` is supplied. An explicit result database is used as given. + +Discovery takes the same database view the job was given and recovers the name from +the stored folder relative to that view. Different pipelines can use identical +relative function table paths within their respective job folders. The enclosing +job folder distinguishes them. A job named `daily` written through +`database.at("shared")` is named `daily` from that view and `shared/daily` from the +root. Opening from the original writer view with the default name reproduces the +live source exactly. A caller can use `entry.as_source(pipeline_name=...)` for a +surrogate. A root entry with `pipeline_name=None` requires a surrogate to open. + +## Find and read the stored tables + +Use `ArrowDatabaseProtocol.list_exact_table_paths()`, relative to the database supplied. Parse +positioned path components from the right, preserving arbitrary namespace depth and any +optional `instance:` component. Both public paths are the exact listed +tuples. In-memory and supported Delta paths round-trip directly. The SQLite and +PostgreSQL catalogs store path components as registered, and the writable keyed +SpiralDB store returns the original paths from table identity records. These +capabilities preserve names containing `-`, `.` and `__`. Discovery rejects a +backend that cannot enumerate exact paths. This includes connector fallback +listings based on sanitized table names and local Windows Delta listings whose +directory encoding cannot distinguish literal exclamation marks from escaped +colons. Each database's existing ability to store the required Arrow fields +still applies. The ordinary shapes are: + +```text +///v//schema:[/instance:]/pdb_v2 +/_result///v//rev/rdb_v1 +``` + +Match the function URI components from the listed paths. The function name is the +`` component and the function major, type major, result revision and table +layout each have their own components. Validate the type and its current result +revision through `declaration_for`. For an explicitly scoped result table inside the +supplied view or explicitly supplied result store, accept only a unique result +table containing every current result ID referenced by the node. A partial +intersection is insufficient. Report competing complete matches or a missing pairing. The context-taking function +path has a `side_effect_function` component and the result URI shape described by +`core/result_cache.py:context_result_path`. Apply its own grammar if it has a readable +pair. Side-effect logs are outside discovery. + +The read-only setup already exists in +`core/nodes/function_node.py:FunctionJobNode.from_descriptor`, called by +`pipeline/job.py:PipelineJob.load`. Factor its read-only setup to take the validated +listed paths and resolved Arrow schema pair directly. The file loader keeps its saved +descriptor and source bindings. The discovery caller has neither a function nor +an upstream stream. Both use the same `_ResultDatabaseReader`, `get_all_records` and +`_fetch_joined_records`. Supply the stored node content hash so the read is filtered +to that node. In the content-hash-scoped case also verify that the row hash agrees +with the path's `instance:` component. Discovery passes a listed path through the +setup and never computes one from the identity of a reconstructed node. + +The pipeline table stores user tags, including data-tags marked by +`core/data_tags.py:stored_data_tags`, and input system tags (`_tag_`). Columns +`_input_source_*` hold input provenance. They do not establish membership in the tag +or data schema. The other fields are `__data_id`, `__node_content_hash`, input and +output data hashes, context, computed and ephemeral flags, pipeline instance, +record and run IDs, and `__recorded_at`. Function outputs are the result table's user +columns, plus a corresponding `_source_*` token. The result cache owns the common +bookkeeping, and the data function type declaration owns the variation and execution +fields. The current Python function type also records `__pf_var_output_keys` on new +result rows. The data schema consists of fall-through data-tags in tag order followed +by result outputs. A data-tag is one column in the row and a field in both schemas. + +Read committed rows through the required `ArrowDatabaseProtocol.get_committed_records()` +method. Pending writes +remain in the backend's queue throughout discovery and source reads. Both tables are filtered +through `keep_rows_of_data_context` and skipped contexts are reported. Report stale +function layouts by listed name using `contexts/stored.CURRENT_LAYOUTS`, including +older result revisions. They are never read as current. Validate the expected +bookkeeping, a unique and coherent column layout, recoverable data-tag marks, registered +logical types and complete lineage. If the backend cannot establish a role or type, +report the affected path and field and refuse the entry. A list operation failure +propagates `TableListingNotSupportedError`. For a known entry, `as_source()` reports an +`InputValidationError` when it cannot validate the data, or the existing database read +error when the store cannot serve it. A declared function output schema can also be +checked against the output schema digest present in the listed URI using the existing +schema hash recipe. No new stored column roles or types are needed. + +The join uses the pipeline row's `__data_id` and the result ID exposed by the backend +under that column name. Result rows are shared across nodes, and neither the input +hash nor the pipeline record ID is a substitute for the result ID. The shared joins +take user arrays by Arrow row number to preserve types and values. Discovery can +read committed results reachable in its view. A process-local ephemeral result that +has disappeared supplies no output row, as with a loaded job. Report unreachable +persistent results through the existing reader. + +## Identity and schema equivalence + +Discovery calls the read-only stub's ordinary `as_source()`. This returns the same +provisional `DerivedSource` class and exercises its existing warning, schema logic, +lineage selection and provenance builder. Both construction and identity reads remain +covered by the existing `PROVISIONAL_SOURCES` rules. + +| Attribute | Source and recoverability | +| --- | --- | +| Function and node information | Function name, declared output schema digest, function major and function type ID are in both paths. The node content hash is labelled binary in `__node_content_hash` and decoded by `ContentHash.from_prefixed_digest`. The job's step label is display information and is unnecessary for a source. | +| `source_id` | `DerivedSource.source_name` calls `derived_source_name(job_name, node_content_hash)`, and `RootSource.source_id` adds the versioned derived kind. The job name is supplied by `PipelineJob._compile_job` or the saved job loader. Discovery passes the pipeline folder relative to the supplied view, or the explicitly supplied surrogate to the same naming code. The boundary between a database prefix and the original job name is ambiguous in the stored path. | +| `content_hash` | `RootSource.identity_structure` hashes the full source ID, the pair of labelled Arrow schema hashes and empty key tuple. `DerivedSource.identity_structure` adds its default lineage-fold policy. Recover the schema inputs by reading the validated, typed tables. Use the shared identity code and the selected pipeline name. | +| `pipeline_hash` | A root source hashes its tag and data schema pair only. The path's `schema:` component belongs to the original function node and its upstream topology. It is available for stub setup but does not become the source hash. | +| Arrow schemas and roles | For a live node, `DerivedSource._empty_origin_table` gets the node's typed zero-row output. That takes tag fields from the input stream, result fields from the declared outputs, and the fall-through data-tag fields from the tags. For discovery use the same fields from the typed pipeline/result read and the stored marker for shared roles. Preserve the backend's reconstructed logical types, nested fields and large variants. Avoid inferring types from Python row values. | +| Nullability | Live source identity uses the zero-row schema's field flags. For displayed rows, `_fetch_joined_records` restores stored field flags and `DerivedSource._require_origin_types` compares all schema-hashed type details except top-level nullability. Therefore the example's stored flags give the same identity, while a store that lost the declared flags can be unsuitable for discovery even if a live job with the declarations could still read it. Never infer a required field from the absence of null values. | +| System-tag column names | `schema_utils.compute_schema_hash` derives the suffix from the Arrow schema pair and current context. `SourceStreamBuilder._attach_provenance` builds a new source and record system-tag pair. The original pipeline system-tag columns are inputs to the lineage instead. | +| Record IDs and result rows | `DerivedSource._read_lineage` reads the sorted, paired upstream system-tag columns and their values. `_select_origin_rows` selects the latest joined record per lineage by `__recorded_at` then result ID, rejecting unresolved ties. The derived record ID is the existing labelled lineage fold. Values and IDs are independent of the discovered pipeline name. | + +When the discovered pipeline name and origin job name differ, the differing source attributes are +`source_name`, `source_id`, and `content_hash`. In the emitted tables the values of +the generated source-ID system tag and source-info tokens differ because they embed +that ID. Downstream node content hashes and stored entry, instance and record IDs +can consequently differ. `pipeline_hash`, system-tag column names, the generated +record-ID system tag and its values, user schema types and roles, user row values and +the data datagram's payload content hash remain equal. When the names match, the +provenance values and source content hash also match. + +Exact live declaration order is not always recoverable from storage. Keep the stored row +presentation order and compare declared schema fields by name when the same shared table +was reused with a different live declaration order. Arrow schema hashing already follows +this rule. The evidence below reproduces the case. When backing table declarations have +lost schema information necessary for identity, report that loss instead of emitting a +source based on guesses. + +## Recover the pipeline folder from the table path + +The folder is the prefix before the function URI in the listed pipeline table path, +relative to the database supplied. The special `side_effect_function` component +belongs to the URI when the matched result uses the context-function layout. The +database view's base path can locate that marker when it lies at the view boundary; +it contributes nothing to the recovered name. Function-table layout versions, node +hashes and record keys stay the same. When the prefix is empty, discovery lists +the entry with `pipeline_name=None` and opening requires a surrogate. + +The probe verified these cases on InMemory and Delta. `U` below denotes the existing +four-component function URI, `S` is the existing `schema:` component and +`I` is the optional `instance:` component. + +| Job or store configuration | Pipeline table path from the store root | Result table placement | Recoverable name and availability | +| --- | --- | --- | --- | +| `PipelineJob(name="daily", database=db)` on the root | `daily/U/S/pdb_v2` | `daily/_result/U/rev1/rdb_v1` | The folder is `daily`, which equals the job name. | +| Job `daily` through `db.at("shared")` | `shared/daily/U/S/pdb_v2` | `shared/daily/_result/U/rev1/rdb_v1` | The root recovers `shared/daily`. `db.at("shared")` recovers `daily` and matches the live source. `db.at("shared", "daily")` lists an unnamed entry. | +| Explicit result view in the same root | `daily/U/S/pdb_v2` | `result_pool/U/rev1/rdb_v1` | The pipeline folder is `daily`. The root can see both tables, and the result view alone cannot find the job. | +| Explicit result database in a different store | `daily/U/S/pdb_v2` | `U/rev1/rdb_v1` in the separate store | The pipeline store contains `daily`. The result-only store contains no job name. Pass both original views as `database` and `result_database` to open it. | +| Named jobs sharing the root database | `daily/U/S/pdb_v2` and `weekly/U/S/pdb_v2` | `/_result/U/rev1/rdb_v1` | Job names still scope all pipeline tables, even with no common prefix. | +| `PipelineJob(name=())` or a standalone `FunctionJobNode` attached to the root | `U/S/pdb_v2` | `_result/U/rev1/rdb_v1` | The pipeline folder is absent. The entry is listed and needs `as_source(pipeline_name=...)`. The live node needs an explicit source ID. | +| Named job with legacy `table_scope="content_hash"` | `daily/U/S/I/pdb_v2` | `daily/_result/U/rev1/rdb_v1` | The folder is still `daily`. The `instance:` suffix holds the node content digest; it carries no additional naming information. | + +Unlike `database.at(...)`, opening a Delta database directly at a physical +subdirectory makes that directory the database root. The probe then recovers +`daily` when opened at the physical `shared` directory. When opened at the physical +`shared/daily` directory, no pipeline folder remains in the listed paths. +Discovery lists the latter entry as unnamed. + +Listing and opening a source perform only reads. The read-only stub never resolves +or imports the original function. The end-to-end test compares every function node +of an ordinary pipeline and reads the same identities, rows, and provenance in a +fresh process after removing the pod module. User docs show a named job, a fresh +database reader and a listing/open example. + +## Evidence + +Run [the inspection script](../scripts/itl_1948/inspect_stored_job.py) with +`uv run python docs/dev/scripts/itl_1948/inspect_stored_job.py`. It executes a real job +on in-memory and Delta, then its database-only reader enumerates paths, inspects field +metadata and matches IDs. Delta is read through a separately opened handle. There are +four pipeline rows, two per node content hash, and two shared result rows. Both +backends returned required `large_string` and `int32` tags, a required `double` output, +a nullable `large_string` output and a required `orcapod.path` output. The stored +data-tag marker identified `run_key`; after removing the marker and splitting the +fields, both schemas equaled the reference source's identity schemas including field +metadata. The function node path's `schema:` digest began `8faf4964`; the derived +source's pipeline hash and the suffix of its system-tag names began `f912231a`. + +On both stores, a job named `("outer", "inner")` over the root database and a job named +`"inner"` over `database.at("outer")` had the same node content hash, same stored paths +and unchanged row counts, while their default derived IDs began +`derived_v1:outer/inner:` and `derived_v1:inner:` respectively. The second job used +reversed tag declaration order. Its source's declared tag schema was reversed, while +both sources' pipeline hashes matched and the shared stored table stayed in the first +order. + +With the equivalence harness, compare both names-equal and names-differ cases. Exercise +sync and async jobs, in-memory, Delta and the fake SpiralDB SDK, two node hashes in one +table, nontrivial schemas and data-tags, stale layouts and contexts, missing or invalid +metadata and missing IDs. Verify discovery through an instrumented read-only database +and compare sorted rows with generated provenance, allowing only the named ID-bearing +values to differ. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e4ad91dcf..80befc851 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -413,7 +413,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | Location | Hash consumed | Into | Form | Call sites | |---|---|---|---|---| | nested hash in a structure | any nested hash: types, schemas, upstream streams, value hashes | the enclosing structure hash | `{"__type__": "hash", "label": ..., "digest": ...}` | `hashing/semantic_hashing/semantic_hasher.py:nested_hash` | -| schema identity | the `arrow_schema_v1` hashes of a source's or slot's Arrow tag and data schemas, or of a function's output Arrow schema | a source's content and pipeline identity, system-tag column names, the function `uri` | the `ContentHash` objects, nested | `utils/schema_utils.py:arrow_schema_identity`, `utils/schema_utils.py:compute_schema_hash`, `core/data_function.py:DataFunctionBase.output_data_schema_hash` | +| schema identity | the `arrow_schema_v1` hashes of a source's or slot's Arrow tag and data schemas, or of a function's output Arrow schema | a source's content and pipeline identity, system-tag column names, the function `uri` | the `ContentHash` objects, nested | `utils/schema_utils.py:arrow_schema_identity`, `utils/schema_utils.py:compute_schema_hash`, `core/data_function.py:function_output_schema_hash` | | union and generic alias arguments | argument type hashes, sorted by digest, then label (ordering only) | the type hash, via the nested form | as above | `hashing/semantic_hashing/builtin_handlers.py:_sorted_hashes`, `hashing/semantic_hashing/builtin_handlers.py:_sorted_hashes..` | | logical type identifier | the type's extension name and metadata, including its declared `value_hash` | type, annotation, schema and table hashes | Arrow extension field metadata or `;` | `logical_types/identifier.py:LogicalTypeIdentifier.text`, `logical_types/canonical_form.py:storage_form_schema` | | logical-type cell, scalar and container | a value-hashed cell's value hash | the Arrow table hash | `::