From d474e2e104ddd051d82fadab84fbec0155b88f51 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 23:01:27 -0800 Subject: [PATCH 01/13] docs(pipeline): specify versioned job repositories --- .../dev/specs/itl-1965-pipeline-repository.md | 173 ++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 docs/dev/specs/itl-1965-pipeline-repository.md diff --git a/docs/dev/specs/itl-1965-pipeline-repository.md b/docs/dev/specs/itl-1965-pipeline-repository.md new file mode 100644 index 000000000..96641b93c --- /dev/null +++ b/docs/dev/specs/itl-1965-pipeline-repository.md @@ -0,0 +1,173 @@ +# Pipeline repository (ITL-1965) + +A pipeline repository publishes and retrieves saved `PipelineJob` snapshots using +any record-storing `ArrowDatabaseProtocol` implementation. The repository database +holds the saved job text and publication metadata. The job's own database bindings +still determine where its node results live. + +## Public API + +Define `PipelineRepository` and the immutable `PipelinePublication` dataclass in +`orcapod.pipeline.repository`. Export both from `orcapod.pipeline` and `orcapod`, +alongside `PipelineJob`. + +```python +@dataclass(frozen=True) +class PipelinePublication: + name: tuple[str, ...] + version: int + published_at: datetime + +class PipelineRepository: + def __init__(self, database: ArrowDatabaseProtocol) -> None: ... + def publish(self, job: PipelineJob) -> PipelinePublication: ... + def list_pipelines(self) -> list[PipelinePublication]: ... + def list_versions(self, name: str | tuple[str, ...]) -> list[PipelinePublication]: ... + def load( + self, + name: str | tuple[str, ...], + database: ArrowDatabaseProtocol | None = None, + *, + version: int | None = None, + result_database: ArrowDatabaseProtocol | None = None, + ) -> PipelineJob: ... +``` + +- `publish(job)` uses the job's current `name`. It raises `ValueError` if the + name has no components or an empty component. The usual default `("pipeline",)` + is a name. Save errors propagate and leave the repository untouched. A database + that explicitly discards records is refused on publication. +- `list_pipelines()` returns each name once, with its highest version and that + publication's UTC timestamp. It sorts by name tuple and returns `[]` for an + empty repository. `list_versions(name)` returns that name's publications in + ascending version order, or `[]` if the name is unknown. +- `load(name)` loads the highest version. `load(name, version=N)` loads that + version. An unknown name or version raises `KeyError` identifying the requested + name and version where applicable. An explicit version must be a positive + integer. Invalid names and version arguments raise `ValueError`. +- `load` uses the same database overrides, binding rules and validation as + `PipelineJob.load`. Pass the original in-memory results database or the + appropriate connector database explicitly when needed. Loaded jobs read stored + results and may run only with `load_only=True`. + +## Stored table + +Use one table at `("_pipeline_repository", "prdb_v1")` relative to the supplied +database view. Callers can use `database.at(...)` for separate repositories. Declare +`PIPELINE_REPOSITORY_SCHEMA_VERSION = "prdb_v1"` in `system_constants.py` and register +it in `contexts.stored.CURRENT_LAYOUTS`. Open only the current layout path. + +| Column | Arrow type | Meaning | +| --- | --- | --- | +| `__record_id` | `large_binary` | Database key for one publication | +| `pipeline_name` | `large_string` | Canonical JSON array of name components | +| `version` | `int64` | Version, starting at 1 for each name in the current data context | +| `published_at` | `timestamp[us, tz=UTC]` | UTC time recorded when publishing | +| `saved_job` | `large_string` | Full text produced by `PipelineJob.save` | +| `__data_context` | `large_string` | Repository writer's current default data context key | + +Every field is non-nullable. Use `contexts.stored.with_data_context` to add the +context column. A string name is one component, so `"sales"` and `("sales",)` +identify the same name. `"sales/daily"` and `("sales", "daily")` identify distinct +names. Encode the tuple as compact, ASCII-escaped JSON. Preserve case, component +order and whitespace. Names are values in the table and never become table path +components. The record id is the UTF-8 encoding of a compact, ASCII-escaped JSON +array `[context_key, name_components, version]`, where `name_components` is a +nested array. The context in the key lets rows from different contexts coexist. + +Refresh the table before looking up publications. Metadata reads filter by +`__data_context` and, for one name, by `pipeline_name`. They request only the +metadata columns. An exact load uses the database record key and checks the row's +context. Listing and loading use read-only database operations, including when the +table has never been created. They perform no flush, table creation, or metadata +write, so a repository can be read through a viewer grant. The table is created +by the first successful insert. Publish reads the +highest version for the name, adds one row through the database protocol, and +flushes it before returning. Version order determines the latest publication even +when publication clocks tie or move backwards. + +Each name has a single publisher at a time. Concurrent publication of the same +name is outside the first version of this API. The database protocol allocates +no atomic per-name sequence. + +## Shared saved-job format + +`PipelineJob.save` currently writes indented JSON. Store that exact text, which +is also valid YAML 1.2, in `saved_job`. Extract the existing job text writer and +reader into private shared code. File save writes the same text the repository +stores, and both file load and repository load pass their text through the same +parser and reconstruction logic. Keep the public file signatures and file format +as they are. The repository adds publication metadata outside the saved text and +stores no copies of source data or node results. Read-only database opening and +sharing are outside this spec. + +## Duplicate publication decision + +| Option | Consequences | +| --- | --- | +| Refuse a repeated name | Uses the existing insert semantics, but callers need to choose a new name each time they publish an update. | +| Replace the previous row | Keeps one row per name and bounds storage. A portable replacement would require a new operation on `ArrowDatabaseProtocol`. Previous publications would be lost. | +| Append a version | Uses the existing insert operation. A name stays stable across updates, previous publications stay available, and storage grows with every publication. | + +The developer selected append when the job differs from the name's latest +publication. Publishing the same job as the latest publication returns the +existing metadata, including its original timestamp, without writing or +flushing. A job that matches only an older publication gets a new version. +Earlier versions remain available by number. + +## Whole-job hash proposal + +The existing run snapshot hashes the sorted content hashes of sink nodes in the +execution DAG and uses the first 16 hex characters in the run URI. It represents +the selected sinks' lineage and data state. It omits job and database configuration, +and node content hashes omit the name chain that distinguishes node labels. Node +hashes include the name chain and pipeline definition but omit bound input data. +Neither recipe covers the whole saved job. The saved form carries the graph and +labels, per-node identities and configuration, source bindings and their recorded +identities, database bindings, and saved run state. + +Recommend hashing the canonical saved document. Parse the same JSON text stored in +`saved_job`, remove `orcapod_version` at the job and embedded blueprint levels, and +remove `run.run_id` and `run.expected_rows`. Retain both file format versions, the +rest of the blueprint and bindings, and `run.status`, `run.unbound_sources` and +`run.node_job_content_hashes`. Sort the blueprint's edge pairs, which describe +connectivity. Preserve arrays carrying declared argument, schema or key order. +Use `hashing.labelled_hash.canonical_json` so mapping insertion order and JSON +formatting do not affect the digest. Existing embedded hashes keep their labels. + +Two saves of the same unchanged job in the same environment are expected to write +identical bytes. A save creates no timestamp or run id. A fresh run generates a +random run id, and its expected row counts are advisory. Save writes source +bindings in name order and writes the already-compiled graph's order. The file is +not a canonical encoding across independently built jobs. Source and database +paths are serialized as the existing bindings report them, so their saved path +text may differ across environments. The proposed hash preserves that text. + +Changing a node label, saved source binding, or saved job or result database +binding should create a version because the loaded job may expose different nodes +or read different data. This includes changed bound content when its source or +node identity is present in the saved form. Switching between in-memory database +objects with identical saved configurations is indistinguishable to the saved +form. Changes confined to the advisory fields above, runtime-only state outside +the file, or the timestamp the repository assigns should leave the version alone. + +Proposed algorithm `PIPELINE_JOB_PUBLICATION_HASH_LABEL = "pipeline_job_publication_v1"` +in `orcapod.pipeline.repository`, beside `_publication_hash`. Its digest is +SHA-256 of the canonical UTF-8 JSON bytes of the document defined above. Store +`ContentHash.to_string()` in a new non-null `job_hash: large_string` column, with +the same `prdb_v1` layout because it has never shipped. Add a label and a producing +site entry to the inventory in `docs/reference/hashing.md`, identifying this as +the saved-job publication hash, and list `PipelineRepository.publish` as the +labelled-value write site. This recipe awaits approval. + +## Verification + +Through the public API, run and publish multiple named jobs on in-memory, Delta +Lake, SQLite and fake SpiralDB databases. Use fresh repository objects to check +listing, exact and latest version loads, and persisted node results. Include both +name forms, names that would collide if joined with a delimiter, repeated +publication, and unknown names and versions. Compare the stored text and load +behavior with the existing file API, including the `load_only=True` requirement. +Cover PostgreSQL if its existing fixtures support the same test with little setup. +On fake SpiralDB, record mutating calls and verify that listing and loading never +make any, both when the repository is empty and when it holds publications. From 47f43f183e3eed81fde8f295d7cc0dcc5a6c2ee3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 23:03:47 -0800 Subject: [PATCH 02/13] docs(pipeline): assess publication metadata and access requirements --- docs/dev/specs/itl-1965-pipeline-repository.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/docs/dev/specs/itl-1965-pipeline-repository.md b/docs/dev/specs/itl-1965-pipeline-repository.md index 96641b93c..518ff7f80 100644 --- a/docs/dev/specs/itl-1965-pipeline-repository.md +++ b/docs/dev/specs/itl-1965-pipeline-repository.md @@ -62,7 +62,7 @@ it in `contexts.stored.CURRENT_LAYOUTS`. Open only the current layout path. | `__record_id` | `large_binary` | Database key for one publication | | `pipeline_name` | `large_string` | Canonical JSON array of name components | | `version` | `int64` | Version, starting at 1 for each name in the current data context | -| `published_at` | `timestamp[us, tz=UTC]` | UTC time recorded when publishing | +| `published_at` | `large_string` | UTC time in ISO 8601 with microseconds and `+00:00`, decoded as a timezone-aware `datetime` | | `saved_job` | `large_string` | Full text produced by `PipelineJob.save` | | `__data_context` | `large_string` | Repository writer's current default data context key | @@ -74,6 +74,7 @@ order and whitespace. Names are values in the table and never become table path components. The record id is the UTF-8 encoding of a compact, ASCII-escaped JSON array `[context_key, name_components, version]`, where `name_components` is a nested array. The context in the key lets rows from different contexts coexist. +Use plain timestamp text because SQLite cannot store an Arrow timestamp. Refresh the table before looking up publications. Metadata reads filter by `__data_context` and, for one name, by `pipeline_name`. They request only the @@ -160,6 +161,20 @@ site entry to the inventory in `docs/reference/hashing.md`, identifying this as the saved-job publication hash, and list `PipelineRepository.publish` as the labelled-value write site. This recipe awaits approval. +## Requested capabilities + +| Request | Recommendation | Reason and cost | +| --- | --- | --- | +| Read a published job's stored results without the publisher's function modules | v1 | `Pipeline.load` reconstructs function descriptors with `function_pod=None`, and the job loader attaches their saved result bindings. Exercise a published graph in a fresh subprocess after deleting the pod module. The same file-load rules still apply to in-memory source data, uncached operators, side-effect rows and unavailable custom types. | +| Let a viewer identity list and load with no writable flag | v1 for viewer access, later for flag-free opening | Today use `SpiralDBConnector(..., writable=True)` to select Orcapod's keyed-table format. Listing and loading only call read operations even with that flag. ITL-1961 covers opening the keyed format explicitly for read-only use. | +| Cheap listing of name, version, date, hash, function names and output schemas | v1 for publication metadata, later for node summaries | Project name, version and date from the repository table. Exposing the already-stored labelled hash as `PipelinePublication.job_hash: str` would add one projected column and requires approval. Function names and output schemas would duplicate blueprint data and require a catalogue schema with type and compatibility rules. | +| Keep tuple names and filter by component prefix | v1 for tuples, later for filtering | Return tuple names now. Callers can filter the returned metadata by tuple slicing. A backend-side component-prefix query needs a capability beyond the protocol's equality predicates or an extra index. | +| Record the verified publishing identity | later | PostgreSQL can identify its current database role and SpiralDB authenticates its service principal. The Arrow database protocol exposes neither. SQLite and in-memory stores have no authenticated publisher, and Delta local storage has none while remote storage credentials belong to the storage provider. A future identity capability should store a nullable identity for backends where it is unknown. | +| Allocate distinct versions to concurrent publishers and make the identical-hash no-op race-safe | later | In-memory stores share queues within a handle family, SQLite and PostgreSQL can ignore a conflicting primary key, Delta can merge on the record id, and keyed SpiralDB uses a single writer. None of those operations atomically couples the latest hash check with sequence allocation through `ArrowDatabaseProtocol`. This requires a new concurrency contract and backend-specific support. | +| Pin by version or select the latest as of a time | v1 for exact version, later for time lookup | Exact version uses the record key. Time lookup adds decisions about ties, clock skew and backdated publications. Callers can inspect recorded times through `list_versions`. | +| Show an optional publication description in listings | later | Adds a metadata field and public API input. The field's effect on identical-job republishing would need a decision. | +| Unpublish or retire a version | later | Keep earlier versions by default. Removal needs a portable delete capability or a retirement marker and rules for latest-version selection and existing pins. | + ## Verification Through the public API, run and publish multiple named jobs on in-memory, Delta From e6fe7becadd533cabbe652233c315a726d8979c8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 23:08:19 -0800 Subject: [PATCH 03/13] docs(pipeline): record repository v1 scope --- .../dev/specs/itl-1965-pipeline-repository.md | 52 +++++++++++++------ 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/docs/dev/specs/itl-1965-pipeline-repository.md b/docs/dev/specs/itl-1965-pipeline-repository.md index 518ff7f80..7d495af8c 100644 --- a/docs/dev/specs/itl-1965-pipeline-repository.md +++ b/docs/dev/specs/itl-1965-pipeline-repository.md @@ -17,11 +17,19 @@ class PipelinePublication: name: tuple[str, ...] version: int published_at: datetime + job_hash: str + function_nodes: tuple[str, ...] + publisher: str | None + description: str | None class PipelineRepository: def __init__(self, database: ArrowDatabaseProtocol) -> None: ... - def publish(self, job: PipelineJob) -> PipelinePublication: ... - def list_pipelines(self) -> list[PipelinePublication]: ... + def publish( + self, job: PipelineJob, *, description: str | None = None + ) -> PipelinePublication: ... + def list_pipelines( + self, *, prefix: str | tuple[str, ...] = () + ) -> list[PipelinePublication]: ... def list_versions(self, name: str | tuple[str, ...]) -> list[PipelinePublication]: ... def load( self, @@ -39,8 +47,10 @@ class PipelineRepository: that explicitly discards records is refused on publication. - `list_pipelines()` returns each name once, with its highest version and that publication's UTC timestamp. It sorts by name tuple and returns `[]` for an - empty repository. `list_versions(name)` returns that name's publications in - ascending version order, or `[]` if the name is unknown. + empty repository. A prefix matches whole leading components. `prefix="sales"` + matches `("sales", "daily")` and `("sales",)`. The empty tuple lists all names. + `list_versions(name)` returns that name's publications in ascending version + order, or `[]` if the name is unknown. - `load(name)` loads the highest version. `load(name, version=N)` loads that version. An unknown name or version raises `KeyError` identifying the requested name and version where applicable. An explicit version must be a positive @@ -49,6 +59,10 @@ class PipelineRepository: `PipelineJob.load`. Pass the original in-memory results database or the appropriate connector database explicitly when needed. Loaded jobs read stored results and may run only with `load_only=True`. +- Listings and `publish` return the labelled job hash, the sorted function node + labels, the publishing identity when available, and the optional description. + The identical-job no-op keeps the existing publication's metadata, including + its description and publisher. ## Stored table @@ -63,10 +77,14 @@ it in `contexts.stored.CURRENT_LAYOUTS`. Open only the current layout path. | `pipeline_name` | `large_string` | Canonical JSON array of name components | | `version` | `int64` | Version, starting at 1 for each name in the current data context | | `published_at` | `large_string` | UTC time in ISO 8601 with microseconds and `+00:00`, decoded as a timezone-aware `datetime` | +| `job_hash` | `large_string` | Labelled whole-job hash text | +| `function_nodes` | `large_string` | JSON array of sorted function node labels | +| `publisher` | `large_string`, nullable | Authenticated publisher identity when exposed by the backend | +| `description` | `large_string`, nullable | Optional free text supplied by the publisher | | `saved_job` | `large_string` | Full text produced by `PipelineJob.save` | | `__data_context` | `large_string` | Repository writer's current default data context key | -Every field is non-nullable. Use `contexts.stored.with_data_context` to add the +The remaining fields are non-nullable. Use `contexts.stored.with_data_context` to add the context column. A string name is one component, so `"sales"` and `("sales",)` identify the same name. `"sales/daily"` and `("sales", "daily")` identify distinct names. Encode the tuple as compact, ASCII-escaped JSON. Preserve case, component @@ -77,12 +95,16 @@ nested array. The context in the key lets rows from different contexts coexist. Use plain timestamp text because SQLite cannot store an Arrow timestamp. Refresh the table before looking up publications. Metadata reads filter by -`__data_context` and, for one name, by `pipeline_name`. They request only the -metadata columns. An exact load uses the database record key and checks the row's +`__data_context` and, for one name, by `pipeline_name`. Prefix matching compares +the decoded tuple components. Request only metadata columns. Extract function +node labels from the saved blueprint during publication, including function nodes +that take an invocation context. Listing never parses or reconstructs a job. The +current keyed SpiralDB adapter projects after its full scan, so the payload still +travels over the wire unless projection is pushed into that adapter. An exact load +uses the database record key and checks the row's context. Listing and loading use read-only database operations, including when the table has never been created. They perform no flush, table creation, or metadata -write, so a repository can be read through a viewer grant. The table is created -by the first successful insert. Publish reads the +write. The table is created by the first successful insert. Publish reads the highest version for the name, adds one row through the database protocol, and flushes it before returning. Version order determines the latest publication even when publication clocks tie or move backwards. @@ -159,20 +181,20 @@ SHA-256 of the canonical UTF-8 JSON bytes of the document defined above. Store the same `prdb_v1` layout because it has never shipped. Add a label and a producing site entry to the inventory in `docs/reference/hashing.md`, identifying this as the saved-job publication hash, and list `PipelineRepository.publish` as the -labelled-value write site. This recipe awaits approval. +labelled-value write site. The recipe and metadata columns await approval. ## Requested capabilities | Request | Recommendation | Reason and cost | | --- | --- | --- | | Read a published job's stored results without the publisher's function modules | v1 | `Pipeline.load` reconstructs function descriptors with `function_pod=None`, and the job loader attaches their saved result bindings. Exercise a published graph in a fresh subprocess after deleting the pod module. The same file-load rules still apply to in-memory source data, uncached operators, side-effect rows and unavailable custom types. | -| Let a viewer identity list and load with no writable flag | v1 for viewer access, later for flag-free opening | Today use `SpiralDBConnector(..., writable=True)` to select Orcapod's keyed-table format. Listing and loading only call read operations even with that flag. ITL-1961 covers opening the keyed format explicitly for read-only use. | -| Cheap listing of name, version, date, hash, function names and output schemas | v1 for publication metadata, later for node summaries | Project name, version and date from the repository table. Exposing the already-stored labelled hash as `PipelinePublication.job_hash: str` would add one projected column and requires approval. Function names and output schemas would duplicate blueprint data and require a catalogue schema with type and compatibility rules. | -| Keep tuple names and filter by component prefix | v1 for tuples, later for filtering | Return tuple names now. Callers can filter the returned metadata by tuple slicing. A backend-side component-prefix query needs a capability beyond the protocol's equality predicates or an extra index. | -| Record the verified publishing identity | later | PostgreSQL can identify its current database role and SpiralDB authenticates its service principal. The Arrow database protocol exposes neither. SQLite and in-memory stores have no authenticated publisher, and Delta local storage has none while remote storage credentials belong to the storage provider. A future identity capability should store a nullable identity for backends where it is unknown. | +| Let a viewer identity list and load with no writable flag | v1, blocked by the current SpiralDB open mode | A fake-backed reproduction confirmed that the plain connector sees the keyed table's physical name in its raw listing, but resolves logical paths through a different naming rule. Plain-mode `list_pipelines()` returns `[]` and `load()` raises `KeyError`. The current reader needs `writable=True` to select the keyed database format, even though listing and loading issue only reads. The flag-free design is pending direction on ITL-1961. | +| Cheap listing of name, version, date, hash, function names and output schemas | v1 for metadata and function labels, later for output schemas | Project one column per field. Labels come directly from the saved blueprint. A stable public schema type would require choices about Arrow types, nullable fields and unavailable custom types. Retaining schema descriptors also duplicates potentially wide metadata. | +| Keep tuple names and filter by component prefix | v1 | Match tuple components in the projected listing. Backend-side prefix matching would need more than equality predicates or a separate index. | +| Record the verified publishing identity | v1 | Propose an optional backend identity lookup. PostgreSQL can report `SESSION_USER`. SpiralDB authenticates a principal, but Orcapod's connector exposes no verified identity accessor. SQLite and in-memory stores have no authenticated publisher. Delta's remote credentials belong to the storage provider and the Delta database exposes no identity. Store `None` when unknown and avoid deriving an identity from connection strings or credentials. | | Allocate distinct versions to concurrent publishers and make the identical-hash no-op race-safe | later | In-memory stores share queues within a handle family, SQLite and PostgreSQL can ignore a conflicting primary key, Delta can merge on the record id, and keyed SpiralDB uses a single writer. None of those operations atomically couples the latest hash check with sequence allocation through `ArrowDatabaseProtocol`. This requires a new concurrency contract and backend-specific support. | | Pin by version or select the latest as of a time | v1 for exact version, later for time lookup | Exact version uses the record key. Time lookup adds decisions about ties, clock skew and backdated publications. Callers can inspect recorded times through `list_versions`. | -| Show an optional publication description in listings | later | Adds a metadata field and public API input. The field's effect on identical-job republishing would need a decision. | +| Show an optional publication description in listings | v1 | Store a nullable text column and take a keyword argument. The no-op rule preserves the existing publication and its metadata. | | Unpublish or retire a version | later | Keep earlier versions by default. Removal needs a portable delete capability or a retirement marker and rules for latest-version selection and existing pins. | ## Verification From 42e4386bb78fdb80eac2e3ae34e06c53ae0e61a5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 23:16:49 -0800 Subject: [PATCH 04/13] feat(pipeline): publish versioned jobs to a repository --- changelog.d/ITL-1965.md | 4 + docs/api/pipeline.md | 4 + docs/concepts/pipeline-job.md | 44 +++ .../dev/specs/itl-1965-pipeline-repository.md | 27 +- docs/reference/hashing.md | 3 + src/orcapod/__init__.py | 4 +- src/orcapod/contexts/stored.py | 2 + .../databases/connector_arrow_database.py | 9 +- .../databases/extension_aware_database.py | 11 +- src/orcapod/databases/postgresql_connector.py | 8 + src/orcapod/databases/spiraldb_connector.py | 20 + src/orcapod/databases/spiraldb_tables.py | 40 +- src/orcapod/pipeline/__init__.py | 3 + src/orcapod/pipeline/job.py | 37 +- src/orcapod/pipeline/repository.py | 308 +++++++++++++++ src/orcapod/protocols/database_protocols.py | 9 + src/orcapod/system_constants.py | 1 + .../test_postgresql_connector_integration.py | 24 +- .../test_pipeline/test_pipeline_repository.py | 351 ++++++++++++++++++ 19 files changed, 875 insertions(+), 34 deletions(-) create mode 100644 changelog.d/ITL-1965.md create mode 100644 src/orcapod/pipeline/repository.py create mode 100644 tests/test_pipeline/test_pipeline_repository.py diff --git a/changelog.d/ITL-1965.md b/changelog.d/ITL-1965.md new file mode 100644 index 000000000..bd6393371 --- /dev/null +++ b/changelog.d/ITL-1965.md @@ -0,0 +1,4 @@ +### Added + +- `PipelineRepository` publishes saved jobs to a database, lists published names + and their versions, and loads the latest or a specific version of a job. diff --git a/docs/api/pipeline.md b/docs/api/pipeline.md index 478a64be2..30cc2f332 100644 --- a/docs/api/pipeline.md +++ b/docs/api/pipeline.md @@ -13,6 +13,10 @@ blueprint; `PipelineJob` binds a pipeline to sources and a database and runs it. ::: orcapod.pipeline.PipelineJob +::: orcapod.pipeline.PipelineRepository + +::: orcapod.pipeline.PipelinePublication + ::: orcapod.pipeline.PipelineDiagram ::: orcapod.pipeline.LoadStatus diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index a5e036d6a..539b4447e 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -684,6 +684,50 @@ Delta matches these option names case-insensitively. | OpenDAL Google Cloud and TOS options | `opendal.google_service_account_key`, `opendal.tos_secret_access_key`, `opendal.tos_security_token`, `opendal.volcengine_secret_access_key`, `opendal.volcengine_session_token` | | Other OpenDAL names | `opendal.access_key`, `opendal.access_key_secret`, `opendal.account_key`, `opendal.application_key`, `opendal.client_secret`, `opendal.credential`, `opendal.delegation`, `opendal.encryption_key`, `opendal.master_key`, `opendal.password`, `opendal.sas_key`, `opendal.sas_token`, `opendal.secret_access_key`, `opendal.secret_key`, `opendal.security_token`, `opendal.service_account_key`, `opendal.session_token`, `opendal.temp_url_key`, `opendal.token` | +## Publishing jobs to a repository + +`PipelineRepository` stores saved jobs in a database so you can list them by +name and load them later. The repository holds the same saved text as +`PipelineJob.save`. For persisted node results, the loaded job uses its saved +database bindings or the overrides you pass to `load`. + +```python +from orcapod import PipelineRepository + +repository_database = InMemoryArrowDatabase() +repository = PipelineRepository(repository_database) +publication = repository.publish(job, description="Daily BMI calculation") + +reader = PipelineRepository(repository_database) +print([(entry.name, entry.version) for entry in reader.list_pipelines()]) +# [(('bmi',), 1)] + +published_job = reader.load("bmi", database=database, version=publication.version) +rows = published_job.nodes["bmi"].as_source().as_table().sort_by("subject_id") +print(rows["subject_id"].to_pylist()) +# ['mouse_02', 'mouse_03', 'mouse_11'] +``` + +Publish a changed job with the same name to create the next version. If the +job matches the latest publication's whole-job hash, `publish` returns that +publication with its original metadata. Use `list_versions(name)` for the +history and `load(name, version=...)` for a specific version. +Publishing saves the job's recorded bindings and identities. Changes to input +rows that leave the saved job's identities unchanged keep the same version. + +`list_pipelines(prefix=("measurements",))` matches whole leading name components. +A string such as `"bmi"` is equivalent to the one-component tuple `("bmi",)`. +Listings include the version, UTC publication time, job hash, function node +labels, and optional description. `publisher` is the PostgreSQL session user or +the authenticated SpiralDB principal, when available. Backends with no publisher +identity return `None`. + +List and load use read-only operations. For SpiralDB, a viewer opens the repository +with `SpiralDBConnector(..., writable=True)` to select the keyed table format +(ITL-1961, ITL-1962). Only publishing needs write access. A loaded job can run in +`load_only=True` mode, and nodes with stored results expose them through their +stored views without importing the publisher's function modules. + ## How it connects to other concepts - A job records applications of [Function Pods](function-pods.md) and diff --git a/docs/dev/specs/itl-1965-pipeline-repository.md b/docs/dev/specs/itl-1965-pipeline-repository.md index 7d495af8c..633cf65cd 100644 --- a/docs/dev/specs/itl-1965-pipeline-repository.md +++ b/docs/dev/specs/itl-1965-pipeline-repository.md @@ -98,10 +98,9 @@ Refresh the table before looking up publications. Metadata reads filter by `__data_context` and, for one name, by `pipeline_name`. Prefix matching compares the decoded tuple components. Request only metadata columns. Extract function node labels from the saved blueprint during publication, including function nodes -that take an invocation context. Listing never parses or reconstructs a job. The -current keyed SpiralDB adapter projects after its full scan, so the payload still -travels over the wire unless projection is pushed into that adapter. An exact load -uses the database record key and checks the row's +that take an invocation context. Listing never parses or reconstructs a job. +The keyed SpiralDB adapter requests only the physical columns needed for the +projection and its predicates. An exact load uses the database record key and checks the row's context. Listing and loading use read-only database operations, including when the table has never been created. They perform no flush, table creation, or metadata write. The table is created by the first successful insert. Publish reads the @@ -138,7 +137,7 @@ existing metadata, including its original timestamp, without writing or flushing. A job that matches only an older publication gets a new version. Earlier versions remain available by number. -## Whole-job hash proposal +## Whole-job hash The existing run snapshot hashes the sorted content hashes of sink nodes in the execution DAG and uses the first 16 hex characters in the run URI. It represents @@ -149,7 +148,7 @@ Neither recipe covers the whole saved job. The saved form carries the graph and labels, per-node identities and configuration, source bindings and their recorded identities, database bindings, and saved run state. -Recommend hashing the canonical saved document. Parse the same JSON text stored in +Hash the canonical saved document. Parse the same JSON text stored in `saved_job`, remove `orcapod_version` at the job and embedded blueprint levels, and remove `run.run_id` and `run.expected_rows`. Retain both file format versions, the rest of the blueprint and bindings, and `run.status`, `run.unbound_sources` and @@ -164,34 +163,36 @@ random run id, and its expected row counts are advisory. Save writes source bindings in name order and writes the already-compiled graph's order. The file is not a canonical encoding across independently built jobs. Source and database paths are serialized as the existing bindings report them, so their saved path -text may differ across environments. The proposed hash preserves that text. +text may differ across environments. The hash preserves that text. Changing a node label, saved source binding, or saved job or result database binding should create a version because the loaded job may expose different nodes -or read different data. This includes changed bound content when its source or -node identity is present in the saved form. Switching between in-memory database +or read different data. A data change counts when it changes a saved identity. +An explicitly named in-memory source can change its rows while keeping its source +and node identities, so those row changes alone keep the same publication. +Switching between in-memory database objects with identical saved configurations is indistinguishable to the saved form. Changes confined to the advisory fields above, runtime-only state outside the file, or the timestamp the repository assigns should leave the version alone. -Proposed algorithm `PIPELINE_JOB_PUBLICATION_HASH_LABEL = "pipeline_job_publication_v1"` +The algorithm declares `PIPELINE_JOB_PUBLICATION_HASH_LABEL = "pipeline_job_publication_v1"` in `orcapod.pipeline.repository`, beside `_publication_hash`. Its digest is SHA-256 of the canonical UTF-8 JSON bytes of the document defined above. Store `ContentHash.to_string()` in a new non-null `job_hash: large_string` column, with the same `prdb_v1` layout because it has never shipped. Add a label and a producing site entry to the inventory in `docs/reference/hashing.md`, identifying this as the saved-job publication hash, and list `PipelineRepository.publish` as the -labelled-value write site. The recipe and metadata columns await approval. +labelled-value write site. ## Requested capabilities | Request | Recommendation | Reason and cost | | --- | --- | --- | | Read a published job's stored results without the publisher's function modules | v1 | `Pipeline.load` reconstructs function descriptors with `function_pod=None`, and the job loader attaches their saved result bindings. Exercise a published graph in a fresh subprocess after deleting the pod module. The same file-load rules still apply to in-memory source data, uncached operators, side-effect rows and unavailable custom types. | -| Let a viewer identity list and load with no writable flag | v1, blocked by the current SpiralDB open mode | A fake-backed reproduction confirmed that the plain connector sees the keyed table's physical name in its raw listing, but resolves logical paths through a different naming rule. Plain-mode `list_pipelines()` returns `[]` and `load()` raises `KeyError`. The current reader needs `writable=True` to select the keyed database format, even though listing and loading issue only reads. The flag-free design is pending direction on ITL-1961. | +| Let a viewer identity list and load with no writable flag | v1 for viewer access, later for flag-free opening | A fake-backed reproduction confirmed that the plain connector uses a different naming rule. The v1 viewer uses `writable=True` to select the keyed database format. Listing and loading issue only reads. ITL-1961 and ITL-1962 cover the opening modes. | | Cheap listing of name, version, date, hash, function names and output schemas | v1 for metadata and function labels, later for output schemas | Project one column per field. Labels come directly from the saved blueprint. A stable public schema type would require choices about Arrow types, nullable fields and unavailable custom types. Retaining schema descriptors also duplicates potentially wide metadata. | | Keep tuple names and filter by component prefix | v1 | Match tuple components in the projected listing. Backend-side prefix matching would need more than equality predicates or a separate index. | -| Record the verified publishing identity | v1 | Propose an optional backend identity lookup. PostgreSQL can report `SESSION_USER`. SpiralDB authenticates a principal, but Orcapod's connector exposes no verified identity accessor. SQLite and in-memory stores have no authenticated publisher. Delta's remote credentials belong to the storage provider and the Delta database exposes no identity. Store `None` when unknown and avoid deriving an identity from connection strings or credentials. | +| Record the verified publishing identity | v1 | An optional backend lookup uses PostgreSQL's `SESSION_USER` or the pinned Spiral SDK's `authorization.read_caller()` response. SpiralDB stores the verified principal type and stable ID as `:`. SQLite, in-memory and Delta have no identity accessor and store `None`. | | Allocate distinct versions to concurrent publishers and make the identical-hash no-op race-safe | later | In-memory stores share queues within a handle family, SQLite and PostgreSQL can ignore a conflicting primary key, Delta can merge on the record id, and keyed SpiralDB uses a single writer. None of those operations atomically couples the latest hash check with sequence allocation through `ArrowDatabaseProtocol`. This requires a new concurrency contract and backend-specific support. | | Pin by version or select the latest as of a time | v1 for exact version, later for time lookup | Exact version uses the record key. Time lookup adds decisions about ties, clock skew and backdated publications. Callers can inspect recorded times through `list_versions`. | | Show an optional publication description in listings | v1 | Store a nullable text column and take a keyword argument. The no-op rule preserves the existing publication and its metadata. | diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e4ad91dcf..d80fc46ff 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -87,6 +87,7 @@ Hash labels: | `polars_series_v1` | the Polars Series value hash (§1e) | `PolarsSeriesHandler.HASH_LABEL`, `hashing/semantic_hashing/builtin_handlers.py` | | `function_signature_v1` | the stored function signature hash: a function's declared interface ([Data function types](data-function-types.md)) | `FUNCTION_SIGNATURE_HASH_LABEL`, `core/data_function.py` | | `function_content_v1` | the stored function content hash: its source text from the `def` line on ([Data function types](data-function-types.md)) | `FUNCTION_CONTENT_HASH_LABEL`, `core/data_function.py` | +| `pipeline_job_publication_v1` | the canonical saved job, excluding package versions, the run ID, and advisory row counts, with the blueprint edges sorted | `PIPELINE_JOB_PUBLICATION_HASH_LABEL`, `pipeline/repository.py` | | `batch_v1` | the folded source id and record id of `Batch` (site 6b) | `BATCH_FOLD_LABEL`, `core/operators/batch.py` | | `group_v1` | the folded source id and record id of `GroupBy` (site 6b), and the merged source-info token of a data-tag group key | `GROUP_BY_FOLD_LABEL`, `core/operators/group_by.py` | | `join_v1` | the merged source-info token of a key that is a data-tag on several inputs of a `Join` (site 6b) | `JOIN_FOLD_LABEL`, `core/operators/join.py` | @@ -399,6 +400,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | folds of `Batch` / `GroupBy` | the canonical JSON list of a group's member values, for each system tag | SHA-256 hex after the operation's label: `batch_v1` (`batch.py`), `group_v1` (`group_by.py`); one helper | folded source id and record id | `utils/arrow_utils.py:fold_system_tag_values` | | fold of a derived row's lineage | the canonical JSON array of triples in record-id column-name order, flattened as record-id column name, source-id value, and record-id value | SHA-256 hex after the operation's label, `derived_row_v1` | derived source record id and the corresponding source-info tokens | `core/sources/derived_source.py:DerivedSource._derive_from`, `utils/arrow_utils.py:fold_system_tag_values` | | run snapshot | sorted labelled sink hashes | SHA-256 hex, 16 digits | the run URI `@` (a name) | `pipeline/job.py:PipelineJob._prepare_run`, `pipeline/job.py:PipelineJob._prepare_run..` | +| saved-job publication | canonical saved job JSON, excluding package versions, the run ID, and advisory row counts, with the blueprint edges sorted | SHA-256, `pipeline_job_publication_v1` | decide whether publishing appends a version | `pipeline/repository.py:_publication_hash` | | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | | SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` | @@ -439,6 +441,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | the `_content_hash` column | `core/streams/arrow_table_stream.py:ArrowTableStream._assemble_table..hashes`, `core/function_pod.py:FunctionPodStream.as_table..all_content_hashes`, `core/function_pod.py:FunctionPodStream.head..shown_content_hashes`, `core/function_pod.py:FunctionPodStream.head..`, `core/nodes/function_node.py:FunctionNodeBase.as_table..all_content_hashes`, `core/nodes/function_node.py:FunctionNodeBase._head_of_pairs..`, `side_effects.py:_table_of_rows` | | `__pf_var_function_signature_hash`, `__pf_var_function_content_hash` | `core/data_function.py:function_signature_hash`, `core/data_function.py:function_content_hash`, `core/data_function.py:PythonDataFunction.__init__` | | saved pipeline and job files | `pipeline/graph.py:Pipeline.save`, `pipeline/job.py:PipelineJob.save`, `pipeline/job.py:PipelineJob.as_pipeline`, `core/sources/base.py:RootSource._identity_config` | +| pipeline repository `job_hash` | `pipeline/repository.py:PipelineRepository.publish` | | cached file hashes (in-memory writes compare validated hashes, SQLite and PostgreSQL read and write `b"sha256:" + digest`) | `hashing/hash_cachers.py:InMemoryHashCacher.put`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put`, `hashing/postgres_hash_cacher.py:PostgresHashCacher.get`, `hashing/postgres_hash_cacher.py:PostgresHashCacher.put`, `hashing/file_hashers.py:parse_stored_file_hash`, `hashing/file_hashers.py:serialize_storable_file_hash` | | `InvocationContext.invocation_hash` (`