From 79dba63a89a5a5997677c38c0326f01c4e8b33eb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 19:02:41 -0800 Subject: [PATCH 01/11] test(sources): add stored result discovery equivalence harness --- .../sources/test_discovered_results.py | 329 ++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 tests/test_core/sources/test_discovered_results.py diff --git a/tests/test_core/sources/test_discovered_results.py b/tests/test_core/sources/test_discovered_results.py new file mode 100644 index 000000000..0dd7cd7c1 --- /dev/null +++ b/tests/test_core/sources/test_discovered_results.py @@ -0,0 +1,329 @@ +"""Discover function pod results without the job that wrote them.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Literal + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.contexts.stored import CURRENT_LAYOUTS +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SpiralDBConnector, +) +from orcapod.errors import ProvisionalHashWarning +from orcapod.protocols.core_protocols.sources import SourceProtocol +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.sources import ArrowTableSource +from orcapod.utils.provisional import reset_provisional_use_warnings +from tests.test_databases import fake_spiral_sdk + + +# Pending developer approval. Pin every difference attributable to the source name. +EXPECTED_DIFFERENCES = { + "source_id", + "content_hash", + "system_tag_source_id", + "source_info_tokens", +} + + +def _discover(_database: ArrowDatabaseProtocol) -> list[tuple[str, SourceProtocol]]: + """List the discovery labels and open their stored sources.""" + pytest.skip("ITL-1948 API not wired yet") + + +def _open_discovered( + _database: ArrowDatabaseProtocol, _node: FunctionJobNode +) -> SourceProtocol: + """Select and open the stored content for this reference node.""" + pytest.skip("ITL-1948 API not wired yet") + + +_TAGS = ("unit", "trial") +_OUTPUTS = ("artifact", "ratio") +_ROW_ID = "__rid" +_CALLS: list[tuple[int, int]] = [] + + +@function_pod(output_keys=_OUTPUTS) +def summarize(x: int, y: int) -> tuple[Path, float | None]: + """Return both a logical value and a nullable value.""" + _CALLS.append((x, y)) + return Path("artifacts") / f"{x + y}.txt", x / y if y else None + + +@pytest.fixture(autouse=True) +def _fresh_warnings_and_calls() -> Iterator[None]: + """Reset the process-wide warning deduplication and the call log.""" + reset_provisional_use_warnings() + _CALLS.clear() + yield + reset_provisional_use_warnings() + _CALLS.clear() + + +@pytest.fixture(params=["memory", "delta", "spiral"]) +def open_database( + request: pytest.FixtureRequest, tmp_path: Path +) -> Iterator[Callable[[], ArrowDatabaseProtocol]]: + """Open a fresh reader on the same store after each run.""" + if request.param == "memory": + database = InMemoryArrowDatabase() + yield lambda: database + elif request.param == "delta": + yield lambda: DeltaTableDatabase(tmp_path / "results") + else: + with fake_spiral_sdk.install(tmp_path): + yield lambda: ConnectorArrowDatabase( + SpiralDBConnector("p", "d", writable=True) + ) + + +def _input( + name: str, start: int, *, size: int = 2, interleaved: bool = False +) -> ArrowTableSource: + """Construct keyed, deliberately unsorted input with two tags and two values.""" + schema = pa.schema( + [ + pa.field("unit", pa.large_string(), nullable=False), + pa.field("trial", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("y", pa.int64(), nullable=False), + ] + ) + table = pa.table( + { + "unit": [name] * size, + "trial": list(range(size, 0, -1)), + "x": [start + i for i in range(size, 0, -1)], + "y": [i % 2 for i in range(size, 0, -1)], + }, + schema=schema, + ) + if interleaved: + table = table.select(["y", "trial", "x", "unit"]) + return ArrowTableSource( + table, + tag_columns=_TAGS[::-1] if interleaved else _TAGS, + tag_only_columns=True, + record_id_columns=_TAGS, + source_id=name, + ) + + +def _job( + database: ArrowDatabaseProtocol, *sources: ArrowTableSource +) -> tuple[PipelineJob, tuple[FunctionJobNode, ...]]: + """Attach the same pod to each input in one job.""" + job = PipelineJob(name=("examples", "summaries"), database=database) + labels = [f"summary_{index}" for index in range(len(sources))] + with job: + for label, source in zip(labels, sources, strict=True): + _ = summarize.pod(source, label=label) + nodes: list[FunctionJobNode] = [] + for label in labels: + node = job.nodes[label] + assert isinstance(node, FunctionJobNode) + nodes.append(node) + return job, tuple(nodes) + + +def _run(job: PipelineJob, asynchronous: bool) -> None: + """Exercise the job's synchronous or asynchronous entry point.""" + if asynchronous: + _ = asyncio.run(job.run_async()) + else: + _ = job.run() + + +def _stored_tables(database: ArrowDatabaseProtocol) -> dict[tuple[str, ...], pa.Table]: + """Snapshot all stored paths, schemas and records including the storage key.""" + tables: dict[tuple[str, ...], pa.Table] = {} + for path in database.list_table_paths(): + records = database.get_all_records(path, record_id_column=_ROW_ID) + assert records is not None, path + tables[path] = records.sort_by([(_ROW_ID, "ascending")]) + return tables + + +def _assert_unchanged( + before: dict[tuple[str, ...], pa.Table], database: ArrowDatabaseProtocol +) -> None: + """Check that opening and reading sources leaves every stored table unchanged.""" + after = _stored_tables(database) + assert after.keys() == before.keys() + for path, records in before.items(): + assert after[path].equals(records, check_metadata=True), path + + +def _assert_equivalent( + actual: SourceProtocol, node: FunctionJobNode, *, rows: int +) -> None: + """Compare with the default source and verify every value under the new name.""" + expected = node.as_source() + _, _, source_name = actual.source_id.partition(":") + renamed = node.as_source(source_id=source_name) + assert actual.source_id == renamed.source_id + assert actual.content_hash() == renamed.content_hash() + assert actual.pipeline_hash() == renamed.pipeline_hash() == expected.pipeline_hash() + differences: set[str] = set() + if actual.source_id != expected.source_id: + differences.add("source_id") + if actual.content_hash() != expected.content_hash(): + differences.add("content_hash") + + for source in (expected, renamed, actual): + tags, data = source.keys() + assert set(tags) == set(_TAGS) + assert set(data) == set(_OUTPUTS) + assert actual.output_schema() == renamed.output_schema() == expected.output_schema() + + system_tags, _ = expected.keys(columns={"system_tags": True}) + assert set(system_tags) - set(_TAGS) + actual_system_tags, _ = actual.keys(columns={"system_tags": True}) + assert actual_system_tags == system_tags + + sort_keys: list[tuple[str, Literal["ascending", "descending"]]] = [ + (name, "ascending") for name in _TAGS + ] + for columns in ({}, {"all_info": True}): + reference = expected.as_table(columns=columns).sort_by(sort_keys) + renamed_table = renamed.as_table(columns=columns).sort_by(sort_keys) + found = actual.as_table(columns=columns).sort_by(sort_keys) + assert found.schema.equals(reference.schema, check_metadata=True) + assert found.equals(renamed_table, check_metadata=True) + assert found.num_rows == reference.num_rows == rows + assert reference.schema.field("ratio").nullable + assert reference["ratio"].null_count == 1 + assert isinstance(reference.schema.field("artifact").type, pa.BaseExtensionType) + for name in reference.column_names: + if not found[name].equals(reference[name]): + if name.startswith("_tag_source_id::"): + differences.add("system_tag_source_id") + elif name in {f"_source_{key}" for key in _OUTPUTS}: + differences.add("source_info_tokens") + else: + differences.add(name) + assert differences == EXPECTED_DIFFERENCES + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("interleaved", [False, True], ids=["grouped", "interleaved"]) +def test_discovered_sources_match_two_nodes_in_one_pipeline_table( + open_database: Callable[[], ArrowDatabaseProtocol], + asynchronous: bool, + interleaved: bool, +) -> None: + """A shared physical pipeline table has separate stored content for each node.""" + job, nodes = _job( + open_database(), + _input("alpha", 10, interleaved=interleaved), + _input("beta", 20, interleaved=interleaved), + ) + _run(job, asynchronous) + reader = open_database() + before = _stored_tables(reader) + (pipeline,) = [table for path, table in before.items() if path[-1] == "pdb_v2"] + assert pipeline.num_rows == 4 + assert set(pipeline["__node_content_hash"].to_pylist()) == { + node.content_hash().to_prefixed_digest() for node in nodes + } + + calls = list(_CALLS) + assert len(calls) == 4 + with pytest.warns(ProvisionalHashWarning): + listing = _discover(reader) + opened = [_open_discovered(reader, node) for node in nodes] + + expected_ids = {source.source_id for source in opened} + assert len(expected_ids) == len(listing) == 2 + assert all(label for label, _ in listing) + assert {source.source_id for _, source in listing} == expected_ids + listed_by_id = {source.source_id: source for _, source in listing} + for node, source in zip(nodes, opened, strict=True): + _assert_equivalent(source, node, rows=2) + _assert_equivalent(listed_by_id[source.source_id], node, rows=2) + assert _CALLS == calls + _assert_unchanged(before, open_database()) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_discovery_reads_rows_added_by_a_rerun( + open_database: Callable[[], ArrowDatabaseProtocol], asynchronous: bool +) -> None: + """A later run of the same content adds a new input instance.""" + job, (node,) = _job(open_database(), _input("alpha", 10)) + _run(job, asynchronous) + first = _open_discovered(open_database(), node) + assert first.as_table().num_rows == 2 + + # Bind a new snapshot of the same keyed source, retaining both original rows. + job.bind({"alpha": _input("alpha", 10, size=3)}) + _run(job, asynchronous) + reader = open_database() + after = _open_discovered(reader, node) + assert after.source_id == first.source_id + _assert_equivalent(after, node, rows=3) + assert len(_CALLS) == 3 + + +def _copy_stale_tables( + source: ArrowDatabaseProtocol, + target: ArrowDatabaseProtocol, + *, + old_layout: bool, +) -> None: + """Copy stored records using an earlier layout or a foreign data context.""" + for path, rows in _stored_tables(source).items(): + if old_layout: + if path[-1] == "rdb_v1": + path = (*path[:-2], "rdb_v2") + else: + assert path[-1] == "pdb_v2" + path = (*path[:-1], "pdb_v1") + assert path[-1] not in CURRENT_LAYOUTS + rows = rows.drop(["__data_context"]) + else: + index = rows.schema.get_field_index("__data_context") + field = rows.schema.field(index) + contexts = pa.array(["std:v0.9:other"] * rows.num_rows, type=field.type) + rows = rows.set_column(index, field, contexts) + target.add_records(path, rows, record_id_column=_ROW_ID) + target.flush() + + +@pytest.mark.parametrize( + "old_layout", [False, True], ids=["other-context", "old-layout"] +) +def test_stale_records_are_not_offered_as_current(old_layout: bool) -> None: + """Only the current node is discoverable alongside stale function pod records.""" + written = InMemoryArrowDatabase() + job, (historical, matching) = _job( + written, _input("historical", 50), _input("current", 100, size=3) + ) + _run(job, asynchronous=False) + + database = InMemoryArrowDatabase() + _copy_stale_tables(written, database, old_layout=old_layout) + stale = _stored_tables(database) + assert len(stale) == 2 + assert _discover(database) == [] + _assert_unchanged(stale, database) + + job, (node,) = _job(database, _input("current", 10)) + _run(job, asynchronous=False) + assert node.content_hash() == matching.content_hash() + assert node.content_hash() != historical.content_hash() + before = _stored_tables(database) + ((_, source),) = _discover(database) + _assert_equivalent(source, node, rows=2) + _assert_unchanged(before, database) From 8c41e0c007d43eb88039596fe0247704ba9daac6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 19:23:15 -0800 Subject: [PATCH 02/11] feat(sources): discover stored function results (ITL-1948) --- changelog.d/ITL-1948.md | 3 + docs/concepts/sources.md | 40 ++ .../scripts/itl_1948/inspect_stored_job.py | 189 ++++++++ .../specs/itl-1948-discover-stored-results.md | 172 +++++++ docs/reference/hashing.md | 7 +- src/orcapod/__init__.py | 2 + src/orcapod/core/data_function.py | 17 +- src/orcapod/core/nodes/function_node.py | 77 ++- src/orcapod/core/result_cache.py | 13 +- src/orcapod/core/sources/discovery.py | 452 ++++++++++++++++++ .../sources/test_discovered_results.py | 123 ++++- 11 files changed, 1060 insertions(+), 35 deletions(-) create mode 100644 changelog.d/ITL-1948.md create mode 100644 docs/dev/scripts/itl_1948/inspect_stored_job.py create mode 100644 docs/dev/specs/itl-1948-discover-stored-results.md create mode 100644 src/orcapod/core/sources/discovery.py 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/concepts/sources.md b/docs/concepts/sources.md index ffde56c6a..8aaf8d401 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1191,6 +1191,46 @@ 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 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. +List the database again to find results from later runs. + +```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") +def to_meters(centimeters: int) -> float: + return centimeters / 100 + + +with TemporaryDirectory() as directory: + job = PipelineJob(name="measurements", database=DeltaTableDatabase(directory)) + readings = DictSource( + [{"sample": "a", "centimeters": 160}, {"sample": "b", "centimeters": 180}], + tag_columns=["sample"], + tag_only_columns=True, + source_id="readings", + ) + with job: + to_meters.pod(readings) + job.run() + + (entry,) = discover_function_results(DeltaTableDatabase(directory)) + print(entry.function_name) + print(entry.as_source().as_table().sort_by("sample").to_pylist()) +# to_meters +# [{'sample': 'a', 'meters': 1.6}, {'sample': 'b', 'meters': 1.8}] +``` + **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..eebe0a56d --- /dev/null +++ b/docs/dev/scripts/itl_1948/inspect_stored_job.py @@ -0,0 +1,189 @@ +"""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 tempfile import TemporaryDirectory +from typing import cast + +import pyarrow as pa + +from orcapod import Path, PipelineJob, 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.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}") + + +def write_job( + database: ArrowDatabaseProtocol, + name: str | tuple[str, ...], + *, + reverse_tags: bool = False, +) -> 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 = PipelineJob(name=name, database=database) + with job: + for cohort in ("first", "second"): + 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), + ] + ), + ) + tags = ["run_key", "cohort"] if reverse_tags else ["cohort", "run_key"] + source = ArrowTableSource( + table, + tag_columns=tags, + tag_only_columns=["cohort"], + source_id=cohort, + ) + summarize.pod(source, label=cohort) + job.run() + node = cast(FunctionJobNode, job.nodes["first"]) + source = node.as_source() + 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 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 main() -> None: + """Run the inspection on in-memory and Delta databases.""" + print("=== In memory ===") + demonstrate(InMemoryArrowDatabase()) + print("=== Delta ===") + with TemporaryDirectory() as directory: + demonstrate(DeltaTableDatabase(directory), DeltaTableDatabase(directory)) + + +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..f9051271b --- /dev/null +++ b/docs/dev/specs/itl-1948-discover-stored-results.md @@ -0,0 +1,172 @@ +# ITL-1948 Discover stored function results + +## Public API + +`orcapod.discover_function_results(database: ArrowDatabaseProtocol) -> tuple[StoredFunctionResult, ...]` +lists committed function results for the current default data context in the supplied +database view. An entry exposes `pipeline_name` (the team name), `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() -> 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. The first API takes one database view and can pair tables within it. A separate +result store that the view cannot see is reported as unavailable. + +For naming, use the existing `PipelineJob.name` as the team name by default. An optional +keyword-only `PipelineJob(team_name=...)` would let teams keep their existing job paths +while giving discovery one common name. Validate that the selected name can be used with +`derived_source_job_path`, the same grammar that names an ordinary derived source. Store +the name on the write path described below. It affects the discovered source ID without +changing the job's namespace or the stored function node's identity. + +## Find and read the stored tables + +Use `ArrowDatabaseProtocol.list_table_paths()`, relative to the database supplied. Parse +positioned path components from the right, preserving arbitrary namespace depth and any +optional `instance:` component. 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, accept a uniquely matching listed table reachable by the pipeline's +exact result IDs. Report ambiguity 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 and validate through the existing stored-table rules. 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. The actual name is ambiguous in a scoped view. Discovery supplies the stored pipeline/team name to that same naming code. | +| `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 recorded team 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 team name. | + +When the team 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. + +## Small stored record for the pipeline name + +Put one name record beside the function pipeline table by replacing its layout suffix +with `fnd_v1`. This keeps the same maximum path depth and needs no change to +`PIPELINE_DB_SCHEMA_VERSION` or `RESULT_DB_SCHEMA_VERSION`. Add +`FUNCTION_DISCOVERY_DB_SCHEMA_VERSION` to `CURRENT_LAYOUTS`. Store +`__data_context`, `__node_content_hash` and the team/pipeline name. The companion +record's own key is the context, node hash and team name, scoped to its table. This +supports multiple named uses of one physical pipeline table even when the pipeline row +was deduplicated. Existing node IDs, pipeline record keys and paths stay as they are. +Putting the name on every pipeline row would require a pipeline layout change and would +still lose the second name on deduplication. + +Queue the name from the shared pipeline-record write/commit path, including cache hits, +and flush it after committing its pipeline rows. A failed or absent name write leaves +the ordinary node result readable and the discovery entry unavailable until a successful +retry. Readers ignore an orphan name record and report current pipeline records without a +name record. Listing and opening a source never create or backfill records, flush, +download missing results from a different database, or execute a function. User docs +show a job with a team name, 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 | `::