diff --git a/.zed/rules b/.zed/rules index 48b2f4209..c3fdd6a23 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1041,6 +1041,8 @@ are also provisional and will be designed alongside the side-effect log (ITL-947 their input-token columns become `_input_source_` (ITL-1524). Once released, a change to the common bookkeeping columns moves the layout version, so the table gets a new path. + ITL-1396 adds `__recorded_at` to the unreleased `sdb_v2` at the same path. An earlier + prerelease `sdb_v2` table without the column must be rebuilt. - A plain function's result table is at //v/python.function.v1/rev1/rdb_v1, three components with three owners (docs/reference/data-function-types.md): @@ -1547,6 +1549,35 @@ data. The rules: of the token values and of any list item fields. CachedSource writes these fields and their record hashes under `sdb_v2`. The operator cache stores and hashes the output stream's declared fields under `odb_v3` (ITL-1562). + A cached-source table (`sdb_v2`) also stores `__recorded_at` + (`cached_source.SOURCE_RECORDED_AT_COL`, `timestamp[us, tz=UTC]`, non-nullable; the + developer's "written-at" column, November 28, 2026, ITL-1396): when the cache wrote the + row, one time per write. It is appended after the record hashes, so it is in no hash, + record id or token; every read of the cache drops it (`CachedSource._STORED_ONLY_COLUMNS`); + a row delivered again is skipped and keeps its first time. Nothing selects by it: it + exists so that "present the latest" can be offered later without a new layout. A + `CachedSource` refuses, before anything is written, a delivery holding a row whose + record id the cache holds under another `_record_hash` (`CachedSourceChangedRowError`, + `_require_no_changed_rows`): one rule for every wrapped source, key columns or + position. A positional edit, reorder, insertion or removal is refused when it changes + the content delivered at a cached position. Rows at new positions are accepted if + every delivered cached position keeps its content. A cache table that already holds two + contents for one record id (two writers that both passed the check and both wrote, or + a table written by hand) is refused on read, with the same error, when the stored + schema identifies the generated record-id column + (developer, November 28, 2026: "(b) for now"; `_require_one_content_per_record_id`, + called by every read of the cache's rows, by the delivery check, by cold or changed + freshness checks and by `head()` when it holds no rows). A conflict requires different hashes + for one record id. A source object that holds rows it already read shows them without + reading the cache again, on a full read and on `head()` alike. An unchanged warm + freshness check uses the last read and the wrapped source's modified time. The two-writer race + itself stays open (both can still write). Resolving the case by + time or another tie-breaker instead of refusing is ITL-1592; never add it here. Tests + build the state with `tests/test_core/sources/cache_versions.write_outside_the_rule`. + Each cache validates its delivery before calling the database's append. Nested + caches use actual database readback. An inner cache can commit its own accepted + delivery before an enclosing cache refuses a changed row (ITL-1396-CS1). + The same applies to sibling cached sources: one may write before another refuses. A row built by `Data` still gives an untyped null the `large_string` type. PolarsFilter is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (arrow_utils.restore_column_types and @@ -1766,7 +1797,8 @@ data. The rules: each source feeding them (node_run.check_sources) before the state rule judges any node; head() and the preview never do. A source that finds new data takes it in and moves its modified time to NOW (never to a time the data reports, such as a cursor's modified_at); - one that finds nothing moves nothing. A check that raises warns once + one that finds nothing moves nothing. A `CachedSourceChangedRowError` fails the run + (ITL-1396). Any other failing check warns once (SourceCheckFailedWarning), keeps the source's data and modified time, lists the source in RunSummary.unchecked_sources, and the run proceeds (a PollingSource a run reads is polled again by that read, and a failing poll raises: ITL-1139). A SourceJobNode's run() checks diff --git a/CLAUDE.md b/CLAUDE.md index b544f018c..757761622 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1068,6 +1068,8 @@ are also provisional and will be designed alongside the side-effect log (ITL-947 tables keep `pdb_v2` when their input-token columns become `_input_source_` (ITL-1524). Once released, a change to the common bookkeeping columns moves the layout version, so the table gets a new path. + ITL-1396 adds `__recorded_at` to the unreleased `sdb_v2` at the same path. An earlier + prerelease `sdb_v2` table without the column must be rebuilt. - A plain function's result table is at `//v/python.function.v1/rev1/rdb_v1`, three components with three owners (`docs/reference/data-function-types.md`): @@ -1592,6 +1594,35 @@ data. The rules: of the token values and of any list item fields. CachedSource writes these fields and their record hashes under `sdb_v2`. The operator cache stores and hashes the output stream's declared fields under `odb_v3` (ITL-1562). + A cached-source table (`sdb_v2`) also stores `__recorded_at` + (`cached_source.SOURCE_RECORDED_AT_COL`, `timestamp[us, tz=UTC]`, non-nullable; the + developer's "written-at" column, November 28, 2026, ITL-1396): when the cache wrote the + row, one time per write. It is appended after the record hashes, so it is in no hash, + record id or token; every read of the cache drops it (`CachedSource._STORED_ONLY_COLUMNS`); + a row delivered again is skipped and keeps its first time. Nothing selects by it: it + exists so that "present the latest" can be offered later without a new layout. A + `CachedSource` refuses, before anything is written, a delivery holding a row whose + record id the cache holds under another `_record_hash` (`CachedSourceChangedRowError`, + `_require_no_changed_rows`): one rule for every wrapped source, key columns or + position. A positional edit, reorder, insertion or removal is refused when it changes + the content delivered at a cached position. Rows at new positions are accepted if + every delivered cached position keeps its content. A cache table that already holds two + contents for one record id (two writers that both passed the check and both wrote, or + a table written by hand) is refused on read, with the same error, when the stored + schema identifies the generated record-id column + (developer, November 28, 2026: "(b) for now"; `_require_one_content_per_record_id`, + called by every read of the cache's rows, by the delivery check, by cold or changed + freshness checks and by `head()` when it holds no rows). A conflict requires different hashes + for one record id. A source object that holds rows it already read shows them without + reading the cache again, on a full read and on `head()` alike. An unchanged warm + freshness check uses the last read and the wrapped source's modified time. The two-writer race + itself stays open (both can still write). Resolving the case by + time or another tie-breaker instead of refusing is ITL-1592; never add it here. Tests + build the state with `tests/test_core/sources/cache_versions.write_outside_the_rule`. + Each cache validates its delivery before calling the database's append. Nested + caches use actual database readback. An inner cache can commit its own accepted + delivery before an enclosing cache refuses a changed row (ITL-1396-CS1). + The same applies to sibling cached sources: one may write before another refuses. A row built by `Data` still gives an untyped null the `large_string` type. `PolarsFilter` is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (`arrow_utils.restore_column_types` and @@ -1812,7 +1843,8 @@ data. The rules: each source feeding them (`node_run.check_sources`) before the state rule judges any node; `head()` and the preview never do. A source that finds new data takes it in and moves its modified time to NOW (never to a time the data reports, such as a cursor's `modified_at`); - one that finds nothing moves nothing. A check that raises warns once + one that finds nothing moves nothing. A `CachedSourceChangedRowError` fails the run + (ITL-1396). Any other failing check warns once (`SourceCheckFailedWarning`), keeps the source's data and modified time, lists the source in `RunSummary.unchecked_sources`, and the run proceeds (a `PollingSource` a run reads is polled again by that read, and a failing poll raises: ITL-1139). A `SourceJobNode`'s `run()` checks diff --git a/changelog.d/ITL-1396.md b/changelog.d/ITL-1396.md new file mode 100644 index 000000000..517e77039 --- /dev/null +++ b/changelog.d/ITL-1396.md @@ -0,0 +1,73 @@ +### Breaking changes and migration + +- A `CachedSource` refuses a changed row under a record id its cache holds + (`CachedSourceChangedRowError`, ITL-1396). When the wrapped source delivers a row whose + record id is already cached with other content (any tag, data, system-tag or source-info + value), that cache refuses the delivery. A freshness check that sees the conflict + raises the same error and preserves the held rows and freshness timestamps. The error + names the source id, the first five record ids and the count. Before, the changed row + was cached beside the old one and both were presented. Use a new `cache_path` or cache + database for changed data. With an automatic cache path, a new `source_id` also selects + a new cache. The same row delivered again writes nothing, and a row under a new record + id is added, as before. +- A cache table that already holds two different rows for one record id (written by two + processes at the same moment, or by hand) is refused on read when the cache can identify + its generated record-id column. The same error reaches job runs, `as_table()`, + `iter_data()`, `run()`, nested caches and `head()` + (the notebook preview shows the error). Before, both rows were presented. Rebuild the + cache from the source in a new cache. +- For a source without key columns, the record id is the row's position. An edit, + reorder, insertion or removal is refused when it changes the content delivered at a + cached position. Rows at new positions are accepted if every delivered cached position + keeps its content. Declare `record_id_columns` for data whose rows may move. +- A cached-source table (`sdb_v2`) stores a new column, `__recorded_at` + (`timestamp[us, tz=UTC]`): when the cache wrote the row. An `sdb_v2` cache written by a + development version without the column is refused on read or ingestion with a message + to rebuild it from the source. Rebuilding from the live source can omit cached rows + that were removed from that source. Preserve the old table and rebuild from the + original inputs if you need the full history. +- SQLite cannot store the `__recorded_at` timestamp. Constructing a `CachedSource` with + a SQLite cache database raises `UnstorableColumnError` before any rows are read + (follow-up ITL-1766). Use a cache database that supports the timestamp type. + +### Added + +- `orcapod.errors.CachedSourceChangedRowError`. +- Each row of a cached-source table records when the cache wrote it (`__recorded_at`). No + read presents it and it is part of no record id, source-info token or hash; a row + delivered again keeps its first time. + +### Fixed + +- A `CachedSource` no longer presents two rows for one record id after its source changes + a value, even when stored or delivered columns arrive in a different order. An + enclosing cache checks the inner cache's actual readback. Cold freshness checks also + refuse conflicting caches when the source is unchanged. + Direct reads refresh long-lived database handles, and reloaded caches with an unbound + source proxy still detect conflicts when custom provenance columns are present. + Cold freshness checks, an unheld `head()`, and the notebook preview validate the stored + IDs and hashes without loading application columns. Warm freshness checks skip the cache + scan while the wrapped source's modified time stays unchanged. The checks also use the + stored record-id column when its generated + name differs from the current declaration, including when writer and reader assign + different roles to a custom provenance pair. Clean Delta caches remain readable + when the reader adds a nullable column or removes a data-tag role. An append that + uses the cache's generated record-id column for custom provenance is refused before + writing (ITL-1396). +- Projected Delta reads retain stored Arrow types, nullability, and nested fields when + all matching rows are still buffered (ITL-1396). +- A cached-source freshness check refuses circular proxy bindings with + `SourceSpecMismatchError` (ITL-1559). + +### Known limitations + +- Two processes writing one cache at the same moment can still both write a row for one + record id. The next read refuses when the generated record-id column is identifiable. +- Read-side conflict validation uses the writer's field order. If the stored schema + cannot establish the generated record-id column, reads proceed without that check. +- The cached sources of one job are checked one by one: when one is refused, another may + already have added its own new rows to its cache before the run fails. +- A positional derivation between caches reads the origin cache in database order. The + origin may commit an append before the enclosing cache refuses a changed position. +- An inner cache may commit its own accepted delivery before an enclosing cache refuses + a changed row. diff --git a/docs/api/errors.md b/docs/api/errors.md index 14b42268c..506ae657c 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -60,6 +60,8 @@ These exceptions and warnings report problems identifying, binding, or reading s ::: orcapod.errors.CachedSourceIdMismatchError +::: orcapod.errors.CachedSourceChangedRowError + ::: orcapod.errors.SourceSlotNameCollisionError ## Pipeline execution diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 842dbebad..88b049578 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1078,6 +1078,64 @@ which spiral-sdk does not read. Until their dataset is migrated they read as not schema that release read it with, so schemas, hashes and source ids stay the same ([the steps](https://github.com/metamorphic-labs/orcapod-python/blob/main/RELEASING.md#migrating-a-spiraldb-dataset-from-pyspiral)). +### `CachedSource`: a record id names one row + +A `CachedSource` (`source.cached(cache_database=...)`) keeps every row its wrapped source +ever delivered: a row later removed from the source stays in the cache. A record id names +one row, so the cache never takes a second, different row under a record id it holds: + +- **The same row again** (same record id, same content) is the normal case: nothing is + written. +- **A row under a new record id** is added. +- **A changed row under a record id the cache holds** is refused, with + `CachedSourceChangedRowError`. The refusing cache writes none of the delivery and + presents no rows. The job fails without storing results from the run. The error names the + source id, the first five record ids concerned and how many rows changed. "Changed" means + any stored value of the row differs: a tag, a data column, a system tag or a source-info + token. + +Nested caches check each delivery against the rows they already hold. The enclosing +cache uses the inner cache's actual readback, so an inner cache may commit its accepted +delivery before an enclosing cache refuses its own. A derivation that assigns record ids +by position uses its origin cache's database read order. + +Use a new `cache_path` or cache database for changed data. With an automatic cache path, +giving the source a new `source_id` also selects a new cache. + +A cache table can still come to hold two different rows for one record id: two processes +that both checked their delivery before either wrote, or a table written by hand. Such a +cache is refused on read when the stored schema identifies the generated record-id +column. The `CachedSourceChangedRowError` names the source, the first five conflicting +record IDs and the count. The check runs on sync and async jobs, `as_table()`, +`iter_data()`, `run()`, nested cache reads and `head()`. The head reads only the record +IDs and hashes for this check, and the notebook preview displays the error. Rebuild a +conflicted cache from the source in a new cache. Identical duplicate rows are accepted. +If the writer's field order is unavailable, the read continues without the conflict +check. A physical read such as `get_all_records()` refuses a conflicting snapshot. +Calls such as `as_table()` and `head()` can still reuse rows the source already holds +while its wrapped source is unchanged. + +The caches of one job are checked one by one. When two cached sources feed a job and one +is refused, the other may already have added its own new rows to its cache; the run fails +and no result of it is stored. + +The rule is the same for every wrapped source, whatever its record ids are made from: + +| Record ids | Accepted | Refused | +|---|---|---| +| Key columns (`record_id_columns=["subject", "session"]`) | the same rows in any order, a row under a new key, a missing row | another value under a key the cache holds | +| Position (no key columns) | unchanged content at every delivered position the cache holds, plus any rows at new positions | an edit, reorder, insertion or removal that changes the content delivered at a cached position | + +Each cached row also records when the cache wrote it, in the stored column +`__recorded_at` (a UTC timestamp). It is bookkeeping of the cache table only: no read of the +cached source presents it, and it is part of no record id, source-info token or hash. A row +delivered again keeps its first write time. Nothing selects rows by it +today. + +The cache database must support the `__recorded_at` timestamp type (`timestamp[us, tz=UTC]`). +SQLite lacks this support, so constructing a cached source with a SQLite cache raises +`UnstorableColumnError` (ITL-1766). + ### `DerivedSource` A `DerivedSource` is a source whose rows come from something Orcapod already has: another @@ -1248,7 +1306,7 @@ and neither does a source's own `run()` outside a job (`source.run()` does what | `SpiralDBTableSource` | holds no rows (every read scans the pinned version); reads the table's current version (no row of it, and `max_rows` does not apply) and pins it when it is newer, so the next read returns the new rows; an `asof` you gave never moves; record ids are the canonical JSON of the key columns, so only new or changed rows are new entries (a version that moves without a change, if SpiralDB moves it on compaction, re-runs the nodes below and reuses every stored result) | | `CSVSource` | reads the file's modification time and size; when either changed, reads the file again and holds the new rows if they changed (row order counts only without key columns) | | `SQLiteTableSource`, `PostgreSQLTableSource`, `DBTableSource` | reads the whole table again and holds the new rows if they changed (with key columns in any order, so an unordered `SELECT` is not a change) | -| `CachedSource` | checks the source it wraps; when that source's modified time moved since the cache last took in its rows (also when another source over it made the check), compares the rows' record hashes with the rows it presents (before its first read, with the cache: a read; nothing is written) and moves only when it will present new rows, (a row removed from the wrapped source stays cached); the check guarantees nothing for two cached sources that share one cache (the same `cache_path` or table): give each its own cache (ITL-1143) | +| `CachedSource` | checks the source it wraps; when that source's modified time moved since the cache last took in its rows (also when another source over it made the check), compares the rows' record hashes with the rows it presents (before its first read, with the cache: a read; nothing is written) and moves only when it will present new rows, (a row removed from the wrapped source stays cached; a changed row under a record id the cache holds refuses the next read, see [a record id names one row](#cachedsource-a-record-id-names-one-row)); the check guarantees nothing for two cached sources that share one cache (the same `cache_path` or table): give each its own cache (ITL-1143) | | `DerivedSource` | over a source, checks it; reads the origin's rows again when the origin's modified time moved since this source read them (a source that took in new data, a job node that ran again); holds the new rows if they changed; one that holds no rows (over a job node that had not run) moves when its origin's time moves | | `SourceProxy` | checks the source bound to it; its modified time follows that source's, and binding or unbinding moves it | @@ -1284,8 +1342,11 @@ its nullable type (where nullability is inferred from the rows: a CSV file read `schema=`, a database whose connector gives no column information), so it is not a change of columns. -A check that raises does not fail the run. The run issues one `SourceCheckFailedWarning` per -source, naming the source and the error; the source keeps its data and modified time; the +A `CachedSourceChangedRowError` during a freshness check fails the run (ITL-1396). +A cached source that has already read its rows skips the cache scan when the wrapped +source's modified time is unchanged. The next read of the cache validates the stored rows. +For other check failures, the run issues one `SourceCheckFailedWarning` per source, +naming the source and the error. The source keeps its data and modified time, the run proceeds with the data the source already holds, and its `RunSummary` lists the source in `unchecked_sources` ("sources not checked for new data (see the warning): ..."). A job node's `run()` that then runs nothing (the node holds a current run) makes no summary and diff --git a/docs/dev/design_issues/ITL-1396-CS1.md b/docs/dev/design_issues/ITL-1396-CS1.md new file mode 100644 index 000000000..1a2b1fd0b --- /dev/null +++ b/docs/dev/design_issues/ITL-1396-CS1.md @@ -0,0 +1,92 @@ +## `src/orcapod/core/sources/cached_source.py` + +### CS1 — A cached source presented two rows for one record id after its source changed a value +**Status:** resolved +**Severity:** high +**Issue:** ITL-1396 + +A `CachedSource` stores each delivered row under the hash of the whole row and keeps every +row it ever stored. When the wrapped source later delivered another value under a record id +the cache held (a CSV file whose `(s1, 2)` row went from 2.0 to 2.5, with +`record_id_columns=["subject", "session"]`), the new row was stored beside the old one and +the cached source presented both: one record id, two rows, no error, and every downstream +node stored results for both. A source with key columns refuses a repeated key when it is +built, so the cache was the one route to that state. The same happened for a source without +key columns, whose record id is the row's position (`row_1` twice). + +**Fix:** (developer, November 28, 2026: refuse, and record when each row was written) a +delivery holding a row whose record id the cache holds under another `_record_hash` is +refused before anything is written (`CachedSourceChangedRowError`, an +`InputValidationError`, from `CachedSource._require_no_changed_rows`), naming the source +id, the first five record ids and the count. Use a new cache path or database for changed +data. With an automatic cache path, a new source id also selects a new cache. An explicit +path keeps pointing to the original table when the source id changes. +Content is compared by the record hash the cache already stores (the +whole stored row: tags, data, system tags, source-info tokens); no new hash. One rule for +every wrapped source: with positional record ids a reorder or a row inserted before the last +is refused too, and an append is accepted. The same row again writes nothing; a row under a +new record id is added. The refusal is a decided rule, not a stopgap. + +For live rows the check uses the exact generated record-id field name from the source +builder or, for a public adapter, the writer's pair carried by the delivery. For stored +rows it uses the writer's field order from the storage schema: +the builder appends the generated pair after the custom system tags. The cache compares +values across the two field names if they differ. Custom system tags still contribute +to the row hash. The inferred pair must have exactly one full SHA-256 schema digest as +its suffix. Join, MergeJoin, Batch and GroupBy append provenance path segments to the +input's names. Those columns describe upstream provenance. +An append that uses the stored generated record-id column for custom +provenance is refused before writing. +A plain derived source has no generated record id and deduplicates by record hash. +Ingestion refreshes the cache table to see rows already committed by another writer. +Each cache checks its own delivery against the rows it holds. A changed-row refusal +fails a sync or async run and continues to do so on retry while the conflict remains. + +The cached-source table (`sdb_v2`, unreleased, so no new layout version) gains +`__recorded_at` (`timestamp[us, tz=UTC]`, non-nullable): when the cache wrote the row, one +time per write, appended after the record hashes (in no hash, record id or token) and +dropped by every read. Nothing selects by it. It exists so that a later mode, "present the +latest row of a record id by its recorded-at time", can be offered without a new layout. +An earlier prerelease table without the column is refused with a rebuild message. +SQLite refuses the timestamp at construction because its connector cannot store it. + +**Read side:** (developer, November 28, 2026: "(b) for now") a cache table that already +holds two contents for one record id (two writers that both passed the check before either +wrote, or a table written by hand) is refused whenever it is read, with the same +`CachedSourceChangedRowError` ("the cache ... holds N record ids with more than one +content"), naming the source id, the first five record ids and the count. One rule, +`CachedSource._require_one_content_per_record_id`, on record id and the stored +`_record_hash` (the same row stored twice is not a conflict), runs in +`_read_cache_table` for every cache read. Each read refreshes the database handle. +Cold freshness checks validate the cache before checking the wrapped source. After a +successful read, freshness checks reuse the held state while the wrapped source's modified +time stays unchanged and validate storage when that time moves. +Freshness checks and delivery reads check the live input graph before following wrapped +sources. Generated record-id lookup also checks proxy and derived-source bindings. +When the source holds no rows, `head()` projects the record ids and hashes, with the data +context as a filter. The notebook preview displays the error. A reloaded source with an +unbound proxy uses the same storage order as a bound source. A source object holding +rows it already read shows them, on a full read and on `head()` alike, without reading +the cache again. Read-side conflict validation requires an identifiable generated +record-id column. When the store cannot supply the writer's schema order, a read +continues without checking for duplicate record IDs. The handling of several held versions of one record in +`pipeline/provenance.py` is no longer reached through a cached source; it is left in place. + +A nested cache consumes the inner cache's actual readback, with the committed schema +and row order determined by the database. When a freshness comparison would need to +ingest a nested cache's rows, it requests a consuming read to complete the comparison. + +**Open:** the simultaneous-writer race itself: two writers can still both pass the check +and both write. Its result is refused at the next read. Resolving two contents for one +record id by time (`__recorded_at`) or another tie-breaker instead of refusing is ITL-1592. + +The cached sources of one job are checked one by one. When two cached sources feed a job +and one is refused, another that accepted its delivery may already have written it (and, +on the async path, its branch may have computed for the new rows) before the run fails. +The rows written are that source's own valid delivery. The same can happen when an inner cache accepts its own delivery. +`test_cached_source_conflicting_cache.py` pins the case. + +A positional `DerivedSource(tags_as_data=...)` interposed between caches assigns record +ids from its origin's database read order. A Delta append can change that order, so the +origin may commit the append before the enclosing cache refuses the changed positional +record. `test_cached_source_changed_rows.py` pins the case. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 3bd155117..86f61f3eb 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -2190,7 +2190,10 @@ The layout component is always the last component of a table's path, also when a `CachedSource` is given an explicit `cache_path`. The `sdb_v2` layout stores nullable token fields and hashes records with those flags. An `sdb_v1` table is reported as an older layout and left untouched. A bound source can -populate a new `sdb_v2` table from its live data. +populate a new `sdb_v2` table from its live data. Each row of an `sdb_v2` table also +stores `__recorded_at` (`timestamp[us, tz=UTC]`, never null): when the cache wrote the +row. It is appended after the row's `_record_hash` is computed, so it is in no hash, and +no read of the cache presents it. Operator caches use the output stream's declared Arrow fields for records and their hashes under `odb_v3`. An `odb_v2` table is reported as an older layout and left diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index cc06e210b..7583ff34f 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -679,6 +679,18 @@ def _typed_zero_row_table(self) -> "pa.Table | None": """ return typed_zero_row_table(getattr(self, "_stream", None)) + @property + def _generated_record_id_column(self) -> str | None: + """Return the exact record-ID field generated for the source's rows.""" + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + stream = getattr(self, "_stream", None) + return ( + stream.generated_record_id_column + if isinstance(stream, ArrowTableStream) + else None + ) + def _display_name(self) -> str: """The name a preview header shows: the label when one was given, else the source id (a source id is the source's name), e.g. a table's name. The label diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index c475f372e..773dd7807 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -2,7 +2,9 @@ import logging -from datetime import datetime +import re +from contextvars import ContextVar +from datetime import datetime, timezone from collections.abc import Iterator from typing import Any, ClassVar, TYPE_CHECKING, cast @@ -27,8 +29,10 @@ validate_source_table, ) from orcapod.errors import ( + CachedSourceChangedRowError, CachedSourceIdMismatchError, InputValidationError, + UnboundSourceError, UnstorableColumnError, ) from orcapod.core.streams.base import ( @@ -61,7 +65,7 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import schema_utils +from orcapod.utils import arrow_utils, schema_utils from orcapod.semantic_types._schema_conversion import arrow_schema_for_types @@ -73,6 +77,34 @@ logger = logging.getLogger(__name__) +SOURCE_RECORDED_AT_COL = "__recorded_at" +"""The cache table's column saying when the cache wrote a row (ITL-1396). + +Stored only: appended after the record hashes are computed, so it is in no hash, record +id or source-info token, and dropped by every read of the cache, so no stream presents +it. A row delivered again is not written again and keeps its first time. Nothing +selects rows by it today. +""" + +_CHANGED_ROWS_NAMED = 5 +"""How many record ids a ``CachedSourceChangedRowError`` names before the count.""" + + +class _CacheReadRequiresIngestion(Exception): + """A freshness check reached a cache that needs a consuming read.""" + + +_CHECKING_CACHE_FRESHNESS: ContextVar[bool] = ContextVar( + "checking_cache_freshness", default=False +) + + +def _recorded_at_field() -> "pa.Field[pa.DataType]": + """The ``__recorded_at`` field of a cached-source table: a UTC instant, never null.""" + return pa.field( + SOURCE_RECORDED_AT_COL, pa.timestamp("us", tz="UTC"), nullable=False + ) + class CachedSource(RootSource): """DB-backed wrapper around a source that caches every data. @@ -85,8 +117,17 @@ class CachedSource(RootSource): Behavior: - Cache is **always on**. - On first access, live source data is stored in the cache table - (deduped by per-row content hash). + (deduped by per-row content hash), each row with the time the cache + wrote it (``__recorded_at``, stored only). - Returns the union of all cached data (cumulative across runs). + - A row delivered under a record id the cache holds with other content is + refused before anything is written (``CachedSourceChangedRowError``, + ITL-1396): a record id names one row, whether it is made from key columns + or from the row's position. + - A cache table that already holds two contents for one record id (written + by two writers at the same moment, or by hand) is refused with the same + error on read when the stored schema identifies the generated record-id + column. Semantic guarantee: The cache is a correct cumulative record. The union of cache + live @@ -112,6 +153,13 @@ class CachedSource(RootSource): HASH_COLUMN_NAME = "_record_hash" + _STORED_ONLY_COLUMNS: ClassVar[list[str]] = [ + HASH_COLUMN_NAME, + SOURCE_RECORDED_AT_COL, + constants.DATA_CONTEXT_COL, + ] + """The cache table's own columns, which no read of the cache presents.""" + REPORTS_WHAT_IT_READS: ClassVar[bool] = False """It reads its cache, which holds what earlier reads stored (``explain()``, ITL-1402).""" @@ -140,6 +188,8 @@ def __init__( Raises: ValueError: If ``source`` is restricted (a condition or a limit). + UnstorableColumnError: If ``cache_database`` cannot store the cache's + own columns, as with ``__recorded_at`` on SQLite (ITL-1766). """ from orcapod.pipeline.restrictions import refuse_restricted_cache_input @@ -155,7 +205,10 @@ def __init__( # before anything is read (ITL-1162). The source's columns are checked # when they are written. try: - require_storable(cache_database, pa.schema([data_context_field()])) + require_storable( + cache_database, + pa.schema([_recorded_at_field(), data_context_field()]), + ) except UnstorableColumnError as exc: exc.add_context(node_label=self.label) raise @@ -457,8 +510,10 @@ def _live_records(self) -> pa.Table: cache was built, ITL-1218): nothing is read or stored then. """ from orcapod.pipeline.restrictions import refuse_restricted_cache_input + from orcapod.pipeline.source_consistency import require_live_source_bindings refuse_restricted_cache_input(self._source) + require_live_source_bindings((self,)) require_same_data_context(self._source.data_context_key, self.data_context_key) live_table = self._source.as_table( columns={"source": True, "system_tags": True, "meta": True} @@ -471,6 +526,27 @@ def _live_records(self) -> pa.Table: if name.startswith(constants.META_PREFIX) ] ) + if isinstance(self._source, RootSource): + record_id = self._source._generated_record_id_column + if record_id is not None: + source_id, _ = arrow_utils.system_tag_column_names( + record_id.split(constants.BLOCK_SEPARATOR, 1)[1] + ) + pair = [source_id, record_id] + system_tags = [ + name + for name in live_table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + if system_tags[-2:] != pair and all( + name in system_tags for name in pair + ): + # Preserve the writer's generated pair in storage order + # even if the wrapped source reorders its output. + live_table = live_table.select( + [name for name in live_table.column_names if name not in pair] + + pair + ) # Compute per-row record hashes for dedup: hash the full row including # all system tag columns. The record_id system tag encodes row origin @@ -492,29 +568,38 @@ def _live_records(self) -> pa.Table: pa.array(record_hashes, type=pa.large_binary()), ) - def _ingest_live_data(self) -> pa.Table | None: - """Store the live rows, or return them directly if an old binding owns the path.""" - self._refresh_source_bindings() - bindings = self._source_bindings - seen = self._source_modified_time() - # A cache of another source id is refused before reading the source. - self._require_rows_of_this_source() - live_with_hash = self._live_records() - # The context names the hashing generation and is added after row hashing. - records = with_data_context(live_with_hash, self.data_context_key) - with identity_lock: - require_current_bindings(bindings) - path = self._cache_path_for_io() - if path is not None: - self._account_for_stale_tables() - self._cache_database.add_records( - path, - records, - record_id_column=self.HASH_COLUMN_NAME, - skip_duplicates=True, - ) - self._cache_database.flush() - self._source_seen = seen + def _write_delivery( + self, live_with_hash: pa.Table, seen: datetime | None + ) -> pa.Table | None: + """Store an accepted delivery, or serve it live when the path is retired.""" + path = self._cache_path_for_io() + if path is not None: + # Refuse the entire delivery before writing if it changes a held row (ITL-1396). + _ = self._read_cache_table( + conflicts_only=True, check_system_tags=True, delivery=live_with_hash + ) + self._account_for_stale_tables() + # When the cache wrote these rows: one time for the whole write, appended + # after the record hashes like the data context, so in no hash. A row the + # cache already holds is skipped below and keeps its first time. + recorded_at = _recorded_at_field() + to_store = live_with_hash.append_column( + recorded_at, + pa.array( + [datetime.now(timezone.utc)] * live_with_hash.num_rows, + recorded_at.type, + ), + ) + records = with_data_context(to_store, self.data_context_key) + if path is not None: + self._cache_database.add_records( + path, + records, + record_id_column=self.HASH_COLUMN_NAME, + skip_duplicates=True, + ) + self._cache_database.flush() + self._source_seen = seen return records if path is None else None def _refresh_source_bindings(self) -> bool: @@ -543,14 +628,204 @@ def last_modified(self) -> datetime | None: self._refresh_source_bindings() return super().last_modified + def _require_no_changed_rows( + self, live_with_hash: pa.Table, records: pa.Table, stored_id_column: str | None + ) -> None: + """Refuse live rows that change a row the cache holds (ITL-1396). + + A record id names one row. A live row whose record id is in the cache (rows of + the current data context) under another record hash has other content than the + cached row: a tag, data, system-tag or source-info value differs. The rule is + the same whether the record id is made from key columns or is the row's + position. A live row whose record hash the cache holds is the same row again, + and one under a new record id is a new row: both are accepted. Sources + without a generated record id still deduplicate by record hash. + + Raises: + CachedSourceChangedRowError: Naming the source id, the first changed + record ids and how many rows changed. Nothing was written. + InputValidationError: If a delivered custom tag reuses the cache's + generated record-id column. + """ + id_column = getattr(self._source, "_generated_record_id_column", None) + if id_column is not None and id_column not in live_with_hash.column_names: + return + if stored_id_column is None or stored_id_column not in records.column_names: + return + if id_column is None: + # A public adapter may carry the writer's generated pair without + # exposing RootSource's declaration. + source_id_column, id_column = arrow_utils.system_tag_column_names( + stored_id_column.split(constants.BLOCK_SEPARATOR, 1)[1] + ) + if not {source_id_column, id_column} <= set(live_with_hash.column_names): + return + cached: dict[str, set[bytes | None]] = {} + for record_id, record_hash in zip( + cast("list[str]", records.column(stored_id_column).to_pylist()), + records.column(self.HASH_COLUMN_NAME).to_pylist(), + strict=True, + ): + cached.setdefault(record_id, set()).add(record_hash) + changed = sorted( + { + record_id + for record_id, record_hash in zip( + cast("list[str]", live_with_hash.column(id_column).to_pylist()), + live_with_hash.column(self.HASH_COLUMN_NAME).to_pylist(), + strict=True, + ) + if record_id in cached and record_hash not in cached[record_id] + } + ) + if not changed: + if ( + live_with_hash.num_rows + and id_column != stored_id_column + and stored_id_column in live_with_hash.column_names + ): + # Storage matches fields by name. The append would put a custom + # value into the column used to validate stored record IDs. + raise InputValidationError( + f"CachedSource over {self.source_id!r}: the cache at " + f"{'/'.join(self.cache_path)!r} stores generated record IDs in " + f"{stored_id_column!r}, which this delivery uses for custom provenance. " + "Nothing was written. Use a new cache path or database for this source." + ) + return + named = ", ".join(changed[:_CHANGED_ROWS_NAMED]) + more = len(changed) - _CHANGED_ROWS_NAMED + remedy = "Use a new cache path or cache database for the changed data." + if self._explicit_cache_path is None: + remedy += ( + " With an automatic cache path, a new source id selects a new cache." + ) + raise CachedSourceChangedRowError( + f"CachedSource over {self.source_id!r}: the source delivered " + f"{len(changed)} row{'s' if len(changed) != 1 else ''} whose record id " + f"the cache at {'/'.join(self.cache_path)!r} holds with other content: " + f"{named}{f' and {more} more' if more > 0 else ''}. Nothing was written " + f"in the refusing cache. A record id names one row. {remedy}" + ) + + @property + @override + def _generated_record_id_column(self) -> str | None: + """Return the field carried by this cache, or the one its source will write.""" + self._refresh_source_bindings() + path = self._cache_path_for_io() + schema = None if path is None else self._cache_database.get_table_schema(path) + if schema is not None: + return self._stored_record_id_column(schema) + source = self._source + return ( + source._generated_record_id_column + if isinstance(source, RootSource) + else None + ) + + def _stored_record_id_column(self, schema: pa.Schema | None = None) -> str | None: + """Read the generated column's name from the writer's storage field order.""" + if schema is None: + path = self._cache_path_for_io() + schema = ( + None if path is None else self._cache_database.get_table_schema(path) + ) + if schema is None: + return None + + # The source builder appends the generated source/record pair after + # the input, including any custom system tags. Use the order in the + # storage schema, never the order of a projected table or the reader's + # tag roles. The shared prefix identifies the system-tag group only. + recorded_at_index = schema.get_field_index(SOURCE_RECORDED_AT_COL) + if recorded_at_index < 0: + return None + system_tags = [ + (index, field) + for index, field in enumerate(schema) + if index < recorded_at_index + and field.name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + if len(system_tags) < 2: + return None + (first_index, first), (second_index, second) = system_tags[-2:] + if second_index != first_index + 1 or any( + field.nullable + or not ( + pa.types.is_string(field.type) or pa.types.is_large_string(field.type) + ) + for field in (first, second) + ): + return None + prefix = constants.SYSTEM_TAG_RECORD_ID_PREFIX + constants.BLOCK_SEPARATOR + suffix = second.name.removeprefix(prefix) + # A source's own pair has exactly one full SHA-256 schema digest. + # Join and MergeJoin append a pipeline digest and position; Batch and + # GroupBy append a pipeline digest. Those paths identify upstream rows. + if re.fullmatch(r"[0-9a-f]{64}", suffix) and ( + first.name, + second.name, + ) == arrow_utils.system_tag_column_names(suffix): + return second.name + # A reordered write can be recognized only with the declaration's + # exact generated name. A similarly named custom pair is insufficient. + if isinstance(self._source, RootSource) and first.name.startswith(prefix): + expected_source, expected_record = arrow_utils.system_tag_column_names( + first.name.removeprefix(prefix) + ) + if (second.name, first.name) == (expected_source, expected_record): + from orcapod.pipeline.source_consistency import ( + require_live_source_bindings, + ) + + try: + require_live_source_bindings((self,)) + if expected_record == self._source._generated_record_id_column: + return expected_record + except UnboundSourceError: + return None + return None + + def _require_one_content_per_record_id( + self, records: pa.Table, id_column: str | None + ) -> None: + """Refuse cached rows holding more than one hash for a generated record id.""" + if id_column is None or id_column not in records.column_names: + return + contents: dict[str, set[bytes | None]] = {} + for record_id, record_hash in zip( + cast("list[str]", records.column(id_column).to_pylist()), + records.column(self.HASH_COLUMN_NAME).to_pylist(), + strict=True, + ): + contents.setdefault(record_id, set()).add(record_hash) + conflicting = sorted( + record_id for record_id, hashes in contents.items() if len(hashes) > 1 + ) + if not conflicting: + return + named = ", ".join(conflicting[:_CHANGED_ROWS_NAMED]) + more = len(conflicting) - _CHANGED_ROWS_NAMED + raise CachedSourceChangedRowError( + f"CachedSource over {self.source_id!r}: the cache at " + f"{'/'.join(self.cache_path)!r} holds {len(conflicting)} record " + f"id{'s' if len(conflicting) != 1 else ''} with more than one content: " + f"{named}{f' and {more} more' if more > 0 else ''}. No row was presented " + "and nothing was written. A record id names one row, and this cache was " + "written outside that rule (by two writers at the same moment, or by " + "hand): rebuild it from the source in a new cache (another cache_path " + "or cache database)." + ) + def _source_modified_time(self) -> datetime | None: """The wrapped source's modified time, or ``None`` if it has none.""" return getattr(self._source, "last_modified", None) - def _cached_record_hashes(self) -> set[bytes]: - """The record hashes of the rows cached under the current data context.""" + def _cached_record_hashes(self, delivery: pa.Table) -> set[bytes]: + """Validate the delivery and get the cached hashes from the same snapshot.""" + records = self._read_cache_table(delivery=delivery) self._account_for_stale_tables() - records = self._read_cache_table() if records is None: return set() records = keep_rows_of_data_context(records, self.data_context_key) @@ -565,7 +840,9 @@ def _cached_record_hashes(self) -> set[bytes]: def check_for_new_data(self) -> bool: """Check the wrapped source; move only if the next read shows new rows (ITL-1102). - The wrapped source is checked first. When its modified time moved since the + A cold check validates the cache before checking the wrapped source. Once + the source holds a read result, an unchanged timestamp needs no cache read. + When the wrapped source's modified time moved since the cache last took in its rows (by this check, or by a check made through another source that wraps it), its rows are hashed and compared with the rows this source presents (recorded when it built its merged rows; before a build, the @@ -593,23 +870,36 @@ def check_for_new_data(self) -> bool: ``True`` if this source will present new rows at the next read. Raises: - CachedSourceIdMismatchError: If the cache holds rows of another source - id; raised before the wrapped source is checked (ITL-1425). + CachedSourceIdMismatchError: If the cache holds rows of another source id. + CachedSourceChangedRowError: If the cache or delivery conflicts with a stored row. + SourceSpecMismatchError: If the wrapped source reads through a cycle. """ rebound = self._refresh_source_bindings() if not isinstance(self._source, RootSource): return rebound - # The cache first: a cache of another source id is refused before the - # wrapped source is checked or read (ITL-1425). - self._require_rows_of_this_source() + # A cold source has no validated read result to reuse. + if self._presented_hashes is None: + _ = self._read_cache_table(conflicts_only=True, check_source_ids=True) + from orcapod.pipeline.source_consistency import require_live_source_bindings + + require_live_source_bindings((self,)) _ = self._source.check_for_new_data() seen = self._source_modified_time() if seen == self._source_seen: return rebound - live = self._live_records().column(self.HASH_COLUMN_NAME).to_pylist() + token = _CHECKING_CACHE_FRESHNESS.set(True) + try: + delivery = self._live_records() + except _CacheReadRequiresIngestion: + self._cached_stream = None + self._update_modified_time() + return True + finally: + _CHECKING_CACHE_FRESHNESS.reset(token) # The next read presents the cache's rows and the live rows together (the # cache keeps every row any source sharing it wrote). - cached = self._cached_record_hashes() + cached = self._cached_record_hashes(delivery) + live = delivery.column(self.HASH_COLUMN_NAME).to_pylist() presented = ( self._presented_hashes if self._presented_hashes is not None else cached ) @@ -630,47 +920,124 @@ def _cache_path_for_io(self) -> tuple[str, ...] | None: self._active_cache_path = path return path - def _read_cache_table(self) -> pa.Table | None: - """Read and validate the physical cache before using any of its columns.""" - self._refresh_source_bindings() - path = self._cache_path_for_io() - if path is None: + def _read_cache_table( + self, + *, + conflicts_only: bool = False, + check_source_ids: bool = False, + check_system_tags: bool = False, + preview: bool = False, + delivery: pa.Table | None = None, + ) -> pa.Table | None: + """Read the latest cache snapshot and check the current context for conflicts. + + The full read returns physical rows so callers can also account for other + data contexts. A head, freshness check or delivery check projects only + the fields it validates, filtering by data context inside the read. + When given a hashed delivery, compare it against those same cached rows. + The projected write check also validates the schema and system-tag fields. + """ + if preview: + # A preview does not claim the path for the current binding. In + # particular an empty fixed path must remain usable after a rebind. + path = self.cache_path + if path in self._previous_cache_paths or ( + path == self._active_cache_path + and bindings_changed(self._source_bindings) + ): + return None + else: + self._refresh_source_bindings() + path = self._cache_path_for_io() + if path is None: + return None + self._cache_database.refresh_table(path) + if conflicts_only: + schema = self._cache_database.get_table_schema(path) + if schema is None: + return None + self._require_recorded_at(schema) + id_column = self._stored_record_id_column(schema) + columns = [id_column] if id_column is not None else [] + if check_system_tags: + require_supported_nullable_types(schema) + columns = [ + name + for name in schema.names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + elif check_source_ids: + columns.extend( + name + for name in schema.names + if name.startswith(constants.SYSTEM_TAG_SOURCE_ID_PREFIX) + ) + if not columns: + return None + records = self._cache_database.get_records_with_column_value( + path, + {constants.DATA_CONTEXT_COL: self.data_context_key}, + record_id_column=self.HASH_COLUMN_NAME, + columns=columns, + ) + else: + records = self._cache_database.get_all_records( + path, record_id_column=self.HASH_COLUMN_NAME + ) + if records is None: + return None + self._require_recorded_at(records.schema) + id_column = self._stored_record_id_column() + + if records is None: return None - records = self._cache_database.get_all_records( - path, record_id_column=self.HASH_COLUMN_NAME - ) - return ( - None - if records is None - else validate_source_table(records, stored_cache=True) + validate_source_table(records, stored_cache=True) + current_records = ( + records + if conflicts_only + else keep_rows_of_data_context(records, self.data_context_key) ) + self._require_one_content_per_record_id(current_records, id_column) + if delivery is not None: + self._require_no_changed_rows(delivery, current_records, id_column) + if check_source_ids: + self._require_source_ids(current_records) + return records + + def _require_recorded_at(self, schema: pa.Schema) -> None: + """Refuse a prerelease cache written without its recorded-at column.""" + if SOURCE_RECORDED_AT_COL not in schema.names: + raise InputValidationError( + f"CachedSource at {'/'.join(self.cache_path)!r} is missing " + f"{SOURCE_RECORDED_AT_COL!r}. Rebuild the cache from the source " + "using a new cache path or database." + ) def _read_cached_records(self) -> "pa.Table | None": """Read the cached rows written under the current data context. Returns: - The cached rows without the record hash and ``__data_context`` columns, - or ``None`` when the cache table does not exist. + The cached rows without the stored-only columns (the record hash, + ``__recorded_at`` and ``__data_context``), or ``None`` when the cache table + does not exist. """ records = self._read_cached_records_with_hashes() if records is None: return None - return records.drop([self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL]) + return records.drop(self._STORED_ONLY_COLUMNS) def _read_cached_records_with_hashes(self) -> "pa.Table | None": """Read the cached rows written under the current data context, as stored. - Every read of the cache's rows goes through here: ``get_all_records()`` and - the merged stream behind ``as_table()`` and every other read of this source. - (``_cached_record_hashes`` reads the record-hash column only, and returns no - row value.) Rows of another data context stay in the table untouched, and a + Used by ``get_all_records()`` and the merged stream behind ``as_table()``. + Rows of another data context stay in the table untouched, and a cache at the older layout is not read (ITL-944). Rows whose Arrow types are not the source's are refused here (``_require_declared_types``), so no read can present them. Returns: - The cached rows with their record hash and ``__data_context`` columns, or - ``None`` when the cache table does not exist. + The cached rows with their record hash, ``__recorded_at`` and + ``__data_context`` columns, or ``None`` when the cache table does not exist. Raises: InputValidationError: If a cached column reads back as another Arrow type. @@ -681,8 +1048,7 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None": return None try: schema_utils.require_stored_stream_column_names( - records.column_names, - (self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL), + records.column_names, self._STORED_ONLY_COLUMNS ) except InputValidationError as exc: location = "/".join(self._cache_database.base_path + self.cache_path) @@ -704,9 +1070,9 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None": def _require_rows_of_this_source(self) -> None: """Refuse a cache table holding rows of another source id (ITL-1425). - Called before the wrapped source is checked (``check_for_new_data``) or its rows - are read, so once a cache is found to hold another id no row of the wrapped - source is read or returned and nothing is written. Building the wrapped source + Called before the wrapped source's rows are read, so once a cache is found to + hold another id no row of the wrapped source is read or returned and nothing + is written. Building the wrapped source (``from_config``) may read it before the first check. The cache table is read once per source object, until it is found to hold this source's rows; a table not yet written holds no other id. @@ -757,21 +1123,23 @@ def _require_source_ids(self, records: pa.Table) -> None: self._source_ids_checked = True def _build_merged_stream(self) -> ArrowTableStream: - """Ingest live data (if available), then return all cached records. - - If the inner source cannot provide data (e.g. an unbound - ``SourceProxy``), the method falls back to returning whatever is - already stored in the cache database. If the cache is empty, an - empty stream is returned. - """ + """Ingest live data and present the rows read back from the database.""" + bindings = self._source_bindings + seen = self._source_modified_time() stored = None try: - stored = self._ingest_live_data() + # Refuse another source's cache before reading any live rows (ITL-1425). + self._require_rows_of_this_source() + delivery = self._live_records() except NotImplementedError: logger.info( "Inner source %r cannot provide data; serving from cache only.", self._source.source_id, ) + else: + with identity_lock: + require_current_bindings(bindings) + stored = self._write_delivery(delivery, seen) if stored is None: stored = self._read_cached_records_with_hashes() @@ -784,16 +1152,17 @@ def _build_merged_stream(self) -> ArrowTableStream: for h in stored.column(self.HASH_COLUMN_NAME).to_pylist() if h is not None } - all_records = stored.drop( - [self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL] - ) + all_records = stored.drop(self._STORED_ONLY_COLUMNS) + + return self._stream_over(all_records) - tag_keys = self._source.keys()[0] + def _stream_over(self, records: pa.Table) -> ArrowTableStream: + """Present cached-source rows with the source's tag columns and context.""" # Cached rows are this source's: give them its data context, not the default. return _source_stream( - all_records, + records, self.data_context.type_converter, - tag_columns=tag_keys, + tag_columns=self._source.keys()[0], data_context=self.data_context, data_tags=stream_data_tags(self._source), ) @@ -850,34 +1219,41 @@ def is_stale(self) -> bool: Overrides ``StreamBase.is_stale`` because CachedSource is a RootSource (no upstreams/producer) yet still depends on the wrapped ``_source``. """ - own_time = self.last_modified + return self._source_is_newer_than(self.last_modified) + + def _source_is_newer_than(self, own_time: datetime | None) -> bool: + """Compare freshness against a captured cache modification time.""" if own_time is None: return True src_time = self._source.last_modified return src_time is None or src_time > own_time - def _ensure_stream(self) -> None: + def _ensure_stream(self) -> ArrowTableStream: """Build the merged stream on first access, or rebuild if source is stale.""" self._refresh_source_bindings() - if self._cached_stream is not None and self.is_stale: - self._cached_stream = None - if self._cached_stream is None: - bindings = self._source_bindings - stream = self._build_merged_stream() - require_current_bindings(bindings) - self._cached_stream = stream - self._update_modified_time() + if ( + self._cached_stream is not None + and not self.is_stale + and (stream := self._cached_stream) is not None + ): + return stream + if _CHECKING_CACHE_FRESHNESS.get(): + # A consuming read can ingest and use the database's actual readback. + raise _CacheReadRequiresIngestion + bindings = self._source_bindings + stream = self._build_merged_stream() + require_current_bindings(bindings) + self._cached_stream = stream + self._update_modified_time() + return stream def clear_cache(self) -> None: """Discard in-memory cached stream (forces rebuild on next access).""" self._cached_stream = None def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - self._ensure_stream() - assert self._cached_stream is not None - return binding_checked_rows( - self._cached_stream.iter_data(), self._source_bindings - ) + stream = self._ensure_stream() + return binding_checked_rows(stream.iter_data(), self._source_bindings) def as_table( self, @@ -885,9 +1261,7 @@ def as_table( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> "pa.Table": - self._ensure_stream() - assert self._cached_stream is not None - return self._cached_stream.as_table(columns=columns, all_info=all_info) + return self._ensure_stream().as_table(columns=columns, all_info=all_info) def _typed_zero_row_table(self) -> "pa.Table | None": """The wrapped source's zero-row table: the cache stores that source's rows. @@ -908,22 +1282,35 @@ def head( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> StreamView: - """Return the first rows without reading or writing the cache. + """Return the first rows without presenting or writing a row of the cache. Once the source has been used, its merged stream is in memory and this is a slice of it. Before that its rows are not known: they are the cache's earlier rows merged with the wrapped source's, and reading them writes the cache. The head then has the wrapped source's columns, no rows and ``NOT_COMPUTED`` (or the wrapped source's own reason when it has none to give). + + A head with no rows to show agrees with a full read about a cache no read may + present: it reads the cache table's record ids and record hashes (stored + values only; nothing is computed, and the wrapped source is not read) and + refuses a cache holding two contents for one record id. + + Raises: + CachedSourceChangedRowError: If the cache holds two contents for one + record id (ITL-1396). """ check_head_size(n) - # is_stale can discard the cached stream while refreshing its binding. + # Check the producing binding without refreshing it or discarding held rows. + bindings = self._source_bindings if ( - self._cached_stream is not None - and not self.is_stale - and (stream := self._cached_stream) is not None + (stream := self._cached_stream) is not None + and not bindings_changed(bindings) + and not self._source_is_newer_than(super().last_modified) + and not bindings_changed(bindings) ): return head_of(stream.head(n, columns=columns, all_info=all_info), self) + # No row is read, but a cache that a full read refuses is refused here too. + _ = self._read_cache_table(conflicts_only=True, preview=True) wrapped = head_of( self._source.head(0, columns=columns, all_info=all_info), self ) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 656521b2a..3083a6fe2 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -523,6 +523,15 @@ def keys( columns=columns, all_info=all_info ) + @property + @override + def _generated_record_id_column(self) -> str | None: + """Return the derived field's exact name, if the derivation generates one.""" + if self._tags_as_data is None: + return None + self._require_origin_bindings() + return self._columns_stream(self._tags_as_data).generated_record_id_column + def _columns_stream(self, tags_as_data: Mapping[str, str]) -> ArrowTableStream: """A stream with this ``tags_as_data`` source's columns, read without its rows. @@ -813,8 +822,8 @@ def _get_stream(self) -> ArrowTableStream: if (cached := self._current_cached_stream()) is not None: return cached if self._tags_as_data is not None: - seen = self._origin.last_modified stream, has_rows = self._build_derived_stream(self._tags_as_data) + seen = self._origin.last_modified require_current_bindings(bindings) self._origin_seen = seen # An origin node that has not run yet is not cached, so the rows diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index fcd15779a..9b2aefbd7 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -50,7 +50,6 @@ SchemaInconsistencyError, ) from orcapod.logical_types.canonical_form import declaration_form_schema -from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Cursor, PollingConfig, Schema from orcapod.utils import arrow_utils from orcapod.utils.arrow_utils import system_tag_column_names @@ -587,6 +586,12 @@ def keys( _ = self._sync_poll_and_commit() return self._get_combined_stream().keys(columns=columns, all_info=all_info) + @property + @override + def _generated_record_id_column(self) -> str | None: + """Return the field generated when the first batch was built.""" + return self._batches[0].generated_record_id_column if self._batches else None + def _typed_zero_row_table(self) -> pa.Table | None: """The zero-row table of the rows polled so far; ``None`` before a poll. @@ -875,11 +880,8 @@ def _commit_batch(self, new_stream: ArrowTableStream) -> None: committed earlier. Nothing is committed and the cursor does not move. """ table = new_stream.as_table(columns={"system_tags": True}) - (column,) = [ - name - for name in table.column_names - if name.startswith(constants.SYSTEM_TAG_RECORD_ID_PREFIX) - ] + column = new_stream.generated_record_id_column + assert column is not None record_ids = cast("list[str]", table.column(column).to_pylist()) repeated = sorted(self._committed_record_ids.intersection(record_ids)) if repeated: diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 50d30c183..83177ac20 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -125,6 +125,20 @@ def is_bound(self) -> bool: """``True`` if a live source has been bound via `bind`.""" return self._delegate is not None + @property + @override + def _generated_record_id_column(self) -> str | None: + """Return the exact field name from the bound source, when available.""" + from orcapod.pipeline.source_consistency import require_live_source_bindings + + require_live_source_bindings((self,)) + delegate = self._delegate + return ( + delegate._generated_record_id_column + if isinstance(delegate, RootSource) + else None + ) + def bind(self, source: SourceProtocol) -> None: """Bind a live source to this proxy, enabling data access. diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 762758cdb..d3d2a3fdd 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -1074,12 +1074,14 @@ def _attach_provenance( source_id, row_identifiers, ) + _, record_id_column = arrow_utils.system_tag_column_names(schema_hash) # Nullable flags are already correct — the caller set them. return _source_stream( table, self._data_context.type_converter, tag_columns=tag_columns, data_tags=data_tags, + generated_record_id_column=record_id_column, data_context=self._data_context, ) @@ -1091,6 +1093,7 @@ def _source_stream( tag_columns: Collection[str], data_tags: Collection[str] = (), data_context: DataContext | None = None, + generated_record_id_column: str | None = None, ) -> ArrowTableStream: """Validate and wrap a source's rows, including batches and stored records. @@ -1112,4 +1115,5 @@ def _source_stream( tag_columns=tag_columns, data_tags=data_tags, data_context=data_context, + generated_record_id_column=generated_record_id_column, ) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 7f3c7dfbc..289878f44 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -204,11 +204,23 @@ def _from_derived_table( upstreams: tuple[StreamProtocol, ...] = (), data_context: str | contexts.DataContext | None = None, label: str | None = None, + generated_record_id_column: str | None = None, ) -> Self: - """Wrap a table whose system columns were built by Orcapod.""" + """Wrap a table whose system columns were built by Orcapod. + + When a source generated a record-ID field, it supplies its exact name. + """ stream = cls.__new__(cls) super(ArrowTableStream, stream).__init__(data_context=data_context, label=label) - stream._initialize(table, tag_columns, None, producer, upstreams, data_tags) + stream._initialize( + table, + tag_columns, + None, + producer, + upstreams, + data_tags, + generated_record_id_column=generated_record_id_column, + ) return stream def _initialize( @@ -219,9 +231,12 @@ def _initialize( producer: PodProtocol | None, upstreams: tuple[StreamProtocol, ...], data_tags: Collection[str], + *, + generated_record_id_column: str | None = None, ) -> None: self._producer = producer self._upstreams = upstreams + self.generated_record_id_column = generated_record_id_column if upstreams: self._output_bindings = capture_output_bindings(*upstreams) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index db796bf55..b29b0c4cf 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -489,9 +489,13 @@ def _find_committed_table( return None def _get_committed_table( - self, record_path: tuple[str, ...], *, schema: str | None + self, + record_path: tuple[str, ...], + *, + schema: str | None, + columns: Collection[str] | None = None, ) -> pa.Table | None: - """Fetch all committed records for a path from the connector. + """Fetch committed records for a path, with an optional column selection. Raises: OrcapodDatabaseReadError: If the table cannot be found or read, on @@ -515,11 +519,19 @@ def _get_committed_table( return None schema, name = table if (tables := self._spiral) is not None: - batches = list(tables.scan(name)) + batches = [ + batch if columns is None else batch.select(columns) + for batch in tables.scan(name) + ] else: + projection = ( + "*" + if columns is None + else ", ".join(map(sql_table_identifier, columns)) + ) batches = list( self._connector.iter_batches( - f"SELECT * FROM {sql_table_identifier(name, schema)}" + f"SELECT {projection} FROM {sql_table_identifier(name, schema)}" ) ) except (OrcapodDatabaseError, SpiralTableCollisionError): @@ -1513,19 +1525,38 @@ def get_records_with_column_value( column_values: Collection[tuple[str, Any]] | Mapping[str, Any], record_id_column: str | None = None, flush: bool = False, + *, + columns: Collection[str] | None = None, ) -> pa.Table | None: if flush: self.flush() - all_records = self.get_all_records( - record_path, record_id_column=self.RECORD_ID_COLUMN + pairs = ( + list(cast(Mapping[str, Any], column_values).items()) + if isinstance(column_values, Mapping) + else list(cast(Collection[tuple[str, Any]], column_values)) ) - if all_records is None: - return None - if isinstance(column_values, Mapping): - pairs = list(column_values.items()) + if columns is None: + all_records = self.get_all_records( + record_path, record_id_column=self.RECORD_ID_COLUMN + ) else: - pairs = cast(list[tuple[str, Any]], list(column_values)) + # Keep the requested and predicate columns for readback and filtering. + required = list(dict.fromkeys([*columns, self.RECORD_ID_COLUMN])) + required.extend(name for name, _ in pairs if name not in required) + key = self._get_record_key(record_path) + committed = self._get_committed_table( + record_path, schema=self._schema_from_record_key(key), columns=required + ) + pending = self._pending_batches.get(key) + parts = [ + part.select(required) + for part in (committed, pending) + if part is not None and part.num_rows + ] + all_records = pa.concat_tables(_alike(parts)) if parts else None + if all_records is None: + return None expr = None for col, val in pairs: @@ -1535,6 +1566,8 @@ def get_records_with_column_value( filtered = all_records.filter(expr) if filtered.num_rows == 0: return None + if columns is not None: + filtered = filtered.select([*columns, self.RECORD_ID_COLUMN]) return self._handle_record_id_column(filtered, record_id_column) # ── Config ──────────────────────────────────────────────────────────────── diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 27fe581a9..e8d0f21fe 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -3780,11 +3780,15 @@ def _combine_stored_and_pending( if len(parts) == 1: table = parts[0] else: - table = pa.concat_tables( - [self._large_layout(t) for t in parts], promote_options="default" - ) + table = self._concat_read_parts(parts) return self._handle_record_id_column(table, record_id_column) + def _concat_read_parts(self, parts: list[pa.Table]) -> pa.Table: + """Combine read parts in Delta's large layout with typed nulls for omissions.""" + return pa.concat_tables( + [self._large_layout(table) for table in parts], promote_options="default" + ) + @staticmethod def _large_layout(table: pa.Table) -> pa.Table: """Return ``table`` with every column in its large layout. @@ -3857,6 +3861,8 @@ def get_records_with_column_value( column_values: Collection[tuple[str, Any]] | Mapping[str, Any], record_id_column: str | None = None, flush: bool = False, + *, + columns: Collection[str] | None = None, ) -> "pa.Table | None": if flush: self.flush_batch(record_path) @@ -3874,6 +3880,15 @@ def get_records_with_column_value( for next_expression in expressions[1:]: combined_expression = combined_expression & next_expression + if columns is not None: + return self._read_projected_matches( + record_path, + columns, + pair_list, + combined_expression, + record_id_column, + ) + pending = self._pending_rows(record_path) if pending is not None: # Rows are pending: the stored ids decide which of them a read returns. @@ -3909,6 +3924,105 @@ def get_records_with_column_value( result, pending_matches, record_id_column ) + def _read_projected_matches( + self, + record_path: tuple[str, ...], + columns: Collection[str], + pairs: list[tuple[str, Any]], + expression: pc.Expression, + record_id_column: str | None, + ) -> pa.Table | None: + """Scan just the selected and predicate columns, without loading the row index.""" + projection = list(columns) + if record_id_column is not None: + projection.append(self.RECORD_ID_COLUMN) + pending = self._pending_not_stored(record_path) + pending_schema = pending.schema if pending is not None else pa.schema([]) + predicate_columns = {name for name, _ in pairs} + stored_schema = pa.schema([]) + stored = None + if (delta_table := self._get_delta_table(record_path)) is not None: + try: + fields = {field.name: field for field in delta_table.schema().fields} + required = dict.fromkeys([*projection, *(name for name, _ in pairs)]) + for name in required: + if name not in fields and name not in pending_schema.names: + raise KeyError(f"Column {name!r} does not exist in the table") + scan_columns = [name for name in required if name in fields] + # Delta decodes partition values from the dataset schema even + # when the scanner does not request those columns. + dataset_columns = dict.fromkeys( + [*scan_columns, *delta_table.metadata().partition_columns] + ) + delta_schema = deltalake.Schema( + [fields[name] for name in dataset_columns] + ) + dataset_schema = pa.schema(delta_schema.to_arrow(as_large_types=True)) # pyright: ignore[reportArgumentType] # Arrow C data interface + restored = from_delta_layout( + dataset_schema.empty_table().select(scan_columns) + ) + stored_schema = restored.schema + if predicate_columns <= set(scan_columns): + dataset = delta_to_pyarrow_dataset( + delta_table, schema=dataset_schema + ) + # Evaluate the predicate on restored types, batchwise to avoid + # comparing string_view in Parquet statistics (ENG-601). + batches = ( + matched + for batch in dataset.to_batches(columns=scan_columns) + for matched in from_delta_layout(pa.Table.from_batches([batch])) + .filter(expression) + .to_batches() + ) + stored = self._project_matches( + pa.Table.from_batches(batches, schema=stored_schema), + projection, + pending_schema, + ) + except TypeIdentityError: + raise + except Exception as exc: + raise self._read_failed(record_path) from exc + + pending_matches = None + if pending is not None and ( + delta_table is None or predicate_columns <= set(pending_schema.names) + ): + pending = pending.filter(expression) + if pending.num_rows: + if projection and delta_table is not None: + # Even when no stored rows matched, their fields still supply the + # types, metadata and missing children of the pending projection. + committed = stored_schema.empty_table().select( + [name for name in projection if name in stored_schema.names] + ) + pending = pending.select( + [name for name in projection if name in pending_schema.names] + ) + pending = self._concat_read_parts([committed, pending]) + pending_matches = pending.select(projection) + return self._combine_stored_and_pending( + stored, pending_matches, record_id_column + ) + + @staticmethod + def _project_matches( + table: pa.Table, columns: list[str], other_schema: pa.Schema + ) -> pa.Table: + """Project the requested fields, filling omissions from the other side's schema.""" + names = set(table.column_names) + for name in columns: + if name not in names: + field = other_schema.field(name) + field = field.with_type( + arrow_utils.normalize_to_large_types(field.type, keep_null=True) + ).with_nullable(True) + table = table.append_column( + field, pa.nulls(table.num_rows, type=field.type) + ) + return table.select(columns) + def get_record_by_id( self, record_path: tuple[str, ...], diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index cdd34b130..1e78cc312 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -25,6 +25,7 @@ from collections.abc import Callable, Collection, Mapping from typing import TYPE_CHECKING, Any, cast + from orcapod.logical_types.database_hooks import register_discovered_logical_types from orcapod.protocols.database_protocols import ArrowDatabaseProtocol @@ -32,6 +33,7 @@ from contextlib import AbstractContextManager import pyarrow as pa + from orcapod.databases._pending_commits import PendingCommit from orcapod.logical_types.protocols import TypeConverterProtocol @@ -130,6 +132,8 @@ def get_records_with_column_value( column_values: Collection[tuple[str, Any]] | Mapping[str, Any], record_id_column: str | None = None, flush: bool = False, + *, + columns: Collection[str] | None = None, ) -> pa.Table | None: return self._process( self._db.get_records_with_column_value( @@ -137,6 +141,7 @@ def get_records_with_column_value( column_values, record_id_column=record_id_column, flush=flush, + **({"columns": columns} if columns is not None else {}), ) ) diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 7a917cc6f..d7cbf9fb9 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -712,6 +712,8 @@ def get_records_with_column_value( column_values: "Collection[tuple[str, Any]] | Mapping[str, Any]", record_id_column: str | None = None, flush: bool = False, + *, + columns: Collection[str] | None = None, ) -> "pa.Table | None": if flush: self.flush() @@ -747,6 +749,8 @@ def get_records_with_column_value( filtered = parts[0] if len(parts) == 1 else pa.concat_tables(parts) if filtered.num_rows == 0: return None + if columns is not None: + filtered = filtered.select([*columns, self.RECORD_ID_COLUMN]) return self._handle_record_id_column(filtered, record_id_column) def _filter_committed( diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index 5320007a2..01e9af92e 100644 --- a/src/orcapod/databases/noop_database.py +++ b/src/orcapod/databases/noop_database.py @@ -91,6 +91,8 @@ def get_records_with_column_value( column_values: Collection[tuple[str, Any]] | Mapping[str, Any], record_id_column: str | None = None, flush: bool = False, + *, + columns: Collection[str] | None = None, ) -> "pa.Table | None": return None diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index a298a05d9..f72432023 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -892,10 +892,11 @@ class SourceCheckFailedWarning(UserWarning): """A source could not be checked for new data at the start of a run (ITL-1102). Every run (``job.run()``, ``run_async()``, a job node's ``run()``) first asks each - source feeding it whether its data changed (``check_for_new_data``). A check that - raises does not fail the run: this warning is issued once per source and run, naming - the source and the error, the source keeps the data and modified time it had, and - the run proceeds with that data. The run's ``RunSummary`` lists the source in + source feeding it whether its data changed (``check_for_new_data``). + A ``CachedSourceChangedRowError`` aborts the run. Other exceptions issue this + warning once per source and run, naming the source and the error. The source + keeps its data and modified time, and the run proceeds with that data. + The run's ``RunSummary`` lists the source in ``unchecked_sources``. A later failure to read the source raises as it always has. """ @@ -938,6 +939,30 @@ class CachedSourceIdMismatchError(ValueError): """ +class CachedSourceChangedRowError(InputValidationError): + """A cached source would hold or present two contents for one record id (ITL-1396). + + A ``CachedSource`` keeps every row its wrapped source ever delivered, and a record + id names one row. When the wrapped source delivers a row whose record id (its key + columns, or its position when it has none) is already in the cache with other + content (any tag, data, system-tag or source-info value), the read is refused + before that cache writes any of the delivery or presents rows. + The same row delivered again is the normal case and writes nothing; a row under a + new record id is added. A source without key columns names a row by its position, + so an edit, reorder, insertion or removal that changes the content delivered at a + cached position is refused. + + Use a new ``cache_path`` or cache database for changed data. With an automatic + cache path, giving the source a new ``source_id`` also selects a new cache. + + Reading the cache table raises this error when the stored schema identifies + the generated record-ID column and one ID has different stored hashes. + Identical duplicates are accepted. A source can continue presenting rows it + already holds in memory until it reads the table again. If the table holds a + conflict, rebuild it from the source in a new cache. + """ + + class SourceSlotNameCollisionError(ValueError): """Two different sources would take one slot name in a job (ITL-1425). diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index f6e5a0680..bb2c4361e 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -22,6 +22,7 @@ from typing import TYPE_CHECKING, Any from orcapod.errors import ( + CachedSourceChangedRowError, OrcapodDatabaseError, OrcapodDatabaseWriteError, live_input_cycle_error, @@ -446,8 +447,8 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: Called at the start of a run, before the state rule decides which nodes run: a source that found new data has moved its modified time, so the nodes below it are - stale. A check that raises does not stop the run (developer, November 14, 2026: - "For check that fails, issues a warning"): one ``SourceCheckFailedWarning`` names + stale. A changed cached row refuses the run (ITL-1396). Other check failures + issue one ``SourceCheckFailedWarning`` (developer, November 14, 2026) naming the source and the error, at the user's line that started the run and at every run, and the run proceeds with the data the source holds (a ``PollingSource`` that a run reads is polled again by that read, and a poll that fails then raises: ITL-1139). @@ -467,6 +468,8 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: for source in run_sources(streams): try: source.check_for_new_data() + except CachedSourceChangedRowError: + raise except Exception as exc: name = source_name(source) unchecked.append(name) diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index b87eb12dc..110c1f57f 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -136,7 +136,15 @@ def get_records_with_column_value( column_values: Collection[tuple[str, Any]] | Mapping[str, Any], record_id_column: str | None = None, flush: bool = False, - ) -> pa.Table | None: ... + *, + columns: Collection[str] | None = None, + ) -> pa.Table | None: + """Read matching rows, projecting only the requested data columns if given. + + Column names in the filter refer to the stored schema. The database's + record id is returned separately when ``record_id_column`` is supplied. + """ + ... def flush(self) -> None: """Flush any buffered writes to the underlying storage.""" diff --git a/tests/test_core/sources/cache_versions.py b/tests/test_core/sources/cache_versions.py new file mode 100644 index 000000000..ec43b9039 --- /dev/null +++ b/tests/test_core/sources/cache_versions.py @@ -0,0 +1,91 @@ +"""Seed a source cache with rows written outside the changed-row rule (ITL-1396). + +A ``CachedSource`` refuses a delivery that changes a row its cache holds, so a cache +never comes to hold two contents for one record id through one. A cache table can +still hold them when it was written outside that rule (two writers that both passed +the check, a table written by hand), and is then refused whenever it is read. Tests +of that refusal build the state with ``write_outside_the_rule``. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from hashlib import sha256 +from typing import Any + +import pyarrow as pa + +from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import ArrowTableSource, CachedSource +from orcapod.system_constants import constants +from orcapod.utils.arrow_utils import system_tag_column_names + + +def with_custom_provenance( + source: ArrowTableSource, tags: Mapping[str, str] +) -> ArrowTableSource: + """Simulate an adapter with extra provenance in its enriched source table. + + Raw source inputs reserve system-column names. An adapter's declaration + still distinguishes its generated pair when custom tags reuse another + source's generated names. + """ + if not tags: + return source + stream = source._stream # pyright: ignore[reportPrivateUsage] + record_id = stream.generated_record_id_column + assert record_id is not None + digest = record_id.split(constants.BLOCK_SEPARATOR, 1)[1] + pair = system_tag_column_names(digest) + names = [f"{constants.SYSTEM_TAG_PREFIX}{name}" for name in tags] + table = source.table + if set(names).intersection(pair): + other_digest = sha256(f"adapter:{digest}".encode()).hexdigest() + new_pair = system_tag_column_names(other_digest) + table = table.rename_columns(dict(zip(pair, new_pair, strict=True))) + pair = new_pair + start = table.schema.get_field_index(pair[0]) + for offset, (name, value) in enumerate(zip(names, tags.values(), strict=True)): + table = table.add_column( + start + offset, + pa.field(name, pa.large_string(), nullable=False), + pa.array([value] * table.num_rows, pa.large_string()), + ) + source._stream = ArrowTableStream._from_derived_table( # pyright: ignore[reportPrivateUsage] + table, + tag_columns=source.keys()[0], + data_tags=stream.data_tags, + data_context=source.data_context, + generated_record_id_column=pair[1], + ) + return source + + +def write_outside_the_rule( + source: Any, cache_database: Any, cache_path: tuple[str, ...] | None = None +) -> None: + """Add ``source``'s rows to a cache table without the changed-row check. + + The rows are cached once in a scratch database, as a ``CachedSource`` stores + them, and that stored table is appended to the cache as it is. + + Args: + source: The source whose rows to add. + cache_database: The database holding the cache. + cache_path: The cache's explicit path, when it has one. + """ + scratch = InMemoryArrowDatabase() + seeded = CachedSource(source, cache_database=scratch, cache_path=cache_path) + _ = seeded.as_table() + stored = scratch.get_all_records( + seeded.cache_path, record_id_column=CachedSource.HASH_COLUMN_NAME + ) + assert stored is not None + cache_database.add_records( + seeded.cache_path, + stored, + record_id_column=CachedSource.HASH_COLUMN_NAME, + skip_duplicates=True, + ) + cache_database.flush() diff --git a/tests/test_core/sources/test_cached_source_changed_rows.py b/tests/test_core/sources/test_cached_source_changed_rows.py new file mode 100644 index 000000000..42d1171b0 --- /dev/null +++ b/tests/test_core/sources/test_cached_source_changed_rows.py @@ -0,0 +1,1649 @@ +"""A cached source refuses a changed row under a record id it holds (ITL-1396). + +A ``CachedSource`` keeps every row its wrapped source ever delivered. A row whose record +id (its key columns, or its position) is already in the cache with other content is +refused before anything is written; the same row delivered again writes nothing; a row +under a new record id is added. Every cached row records when the cache wrote it, in a +column no read presents and no hash covers. +""" + +from __future__ import annotations + +import asyncio +import os +import subprocess +import sys +import textwrap +import warnings +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, cast +from unittest.mock import Mock + +import pyarrow as pa +import pytest + +from orcapod.contexts import resolve_context + +from orcapod import PipelineJob, function_pod +from orcapod.core.sources import cached_source +from orcapod.core.sources.cached_source import SOURCE_RECORDED_AT_COL +from orcapod.core.sources.source_proxy import SourceProxy +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase +from orcapod.databases.extension_aware_database import ExtensionAwareDatabase +from orcapod.databases.sqlite_connector import SQLiteConnector +from orcapod.errors import ( + CachedSourceChangedRowError, + CachedSourceIdMismatchError, + InputValidationError, + SourceCheckFailedWarning, + UnstorableColumnError, +) +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.core_protocols import SourceProtocol +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.sources import ArrowTableSource, CachedSource, CSVSource, DerivedSource +from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants +from tests.test_core.sources.cache_versions import with_custom_provenance +from tests.test_databases import fake_spiral_sdk as fake +from tests.test_databases.test_spiraldb_writable_mode import writable_connector + +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + +Row = tuple[str, int, float, int] +"""One reading: subject, session, value, count.""" + +ROWS: list[Row] = [("s1", 1, 1.0, 10), ("s1", 2, 2.0, 20), ("s2", 1, 3.0, 30)] + + +def test_cached_source_freshness_refuses_a_circular_proxy() -> None: + """Cache reads and freshness refuse cycles and recover after rebinding.""" + # Bound the whole probe so an infinite freshness traversal fails the test. + script = textwrap.dedent("""\ + import pyarrow as pa + import pytest + + from orcapod.core.sources import SourceProxy + from orcapod.databases import InMemoryArrowDatabase + from orcapod.errors import SourceSpecMismatchError + from orcapod.sources import ArrowTableSource + + source = ArrowTableSource( + pa.table({"id": [1], "value": [10]}), + source_id="input", + record_id_columns="id", + tag_columns="id", + tag_only_columns=True, + ) + for via_cache in (False, True): + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + *source.output_schema(), + ) + cache = proxy.cached(InMemoryArrowDatabase()) + proxy.bind(cache if via_cache else proxy) + for operation in (cache.as_table, cache.check_for_new_data): + with pytest.raises(SourceSpecMismatchError, match=r"cycle.*ITL-1559"): + operation() + + proxy.bind(source) + assert cache.check_for_new_data() + assert cache.as_table().num_rows == 1 + """) + _ = subprocess.run([sys.executable, "-c", script], check=True, timeout=20) + + +# Two arrangements of one dataset: the order of the file's columns, of the declared +# tags and of the key columns. +ARRANGEMENTS: dict[str, dict[str, list[str]]] = { + "as_declared": { + "file": ["subject", "session", "value", "count"], + "tags": ["subject", "session"], + "keys": ["subject", "session"], + }, + "rearranged": { + "file": ["count", "session", "value", "subject"], + "tags": ["session", "subject"], + "keys": ["subject", "session"], + }, +} + +CALLS: list[tuple[float, int]] = [] + + +@function_pod(output_keys=("total", "double")) +def summarize(value: float, count: int) -> tuple[float, int]: + """Return ``value + count`` and twice ``count``.""" + CALLS.append((value, count)) + return value + count, 2 * count + + +@pytest.fixture(autouse=True) +def _reset() -> None: + """Clear the recorded pod calls before each test.""" + CALLS.clear() + + +def _write(path: Path, rows: list[Row], arrangement: str = "as_declared") -> None: + """Write the CSV in the chosen field order and advance its modification time.""" + previous = path.stat() if path.exists() else None + names = ARRANGEMENTS[arrangement]["file"] + lines = [",".join(names)] + for subject, session, value, count in rows: + cells = {"subject": subject, "session": session, "value": value, "count": count} + lines.append(",".join(str(cells[name]) for name in names)) + path.write_text("\n".join(lines) + "\n") + if previous is not None: + # CSV freshness uses mtime and size. Same-size rewrites must be observable. + os.utime(path, ns=(previous.st_atime_ns, previous.st_mtime_ns + 1_000_000_000)) + + +def _csv(path: Path, arrangement: str = "as_declared", *, keyed: bool = True) -> Any: + """Declare the CSV input without materializing a cache.""" + kwargs: dict[str, Any] = {} + if keyed: + kwargs["record_id_columns"] = ARRANGEMENTS[arrangement]["keys"] + return CSVSource( + str(path), + tag_columns=ARRANGEMENTS[arrangement]["tags"], + tag_only_columns=True, + source_id="readings", + **kwargs, + ) + + +def _cached( + path: Path, cache: Any, arrangement: str = "as_declared", *, keyed: bool = True +) -> CachedSource: + """Wrap the source without reading or writing the cache.""" + return CachedSource(_csv(path, arrangement, keyed=keyed), cache_database=cache) + + +def _job(source: Any, database: Any) -> PipelineJob: + """Build the job without running it.""" + job = PipelineJob(name="readings_job", database=database) + with job: + summarize.pod(source, label="summary") + return job + + +def _run(job: PipelineJob, orchestrator: str) -> Any: + """Run the job and materialize the caches it reads.""" + return job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + + +def _presented(source: Any) -> list[Row]: + """Read the source, materializing its cache if needed, and sort its rows.""" + return sorted( + (r["subject"], r["session"], r["value"], r["count"]) + for r in source.as_table().to_pylist() + ) + + +def _stored_cache(source: CachedSource, cache: Any) -> pa.Table: + """The cache table as the database holds it, every stored column.""" + table = cache.get_all_records( + source.cache_path, record_id_column=CachedSource.HASH_COLUMN_NAME + ) + assert table is not None + return table + + +def _cache_rows(source: CachedSource, cache: Any) -> list[tuple[Any, ...]]: + """Every stored cell of the cache, rows sorted: equal when nothing was written.""" + table = _stored_cache(source, cache) + names = sorted(table.column_names) + return sorted(tuple(row[name] for name in names) for row in table.to_pylist()) + + +def _stored_tables(database: InMemoryArrowDatabase) -> dict[tuple[str, ...], int]: + """Every table of a job database with its number of rows.""" + counts: dict[tuple[str, ...], int] = {} + for path in database.list_table_paths(()): + table = database.get_all_records(tuple(path)) + counts[tuple(path)] = 0 if table is None else table.num_rows + return counts + + +def _changed(rows: list[Row], *keys: tuple[str, int]) -> list[Row]: + """``rows`` with the value of each named key moved by a half.""" + return [ + (s, n, v + 0.5, c) if (s, n) in keys else (s, n, v, c) for s, n, v, c in rows + ] + + +# --------------------------------------------------------------------------- +# A changed row under an existing key is refused +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_a_changed_value_under_an_existing_key_is_refused_in_a_new_job( + tmp_path: Path, orchestrator: str, arrangement: str +) -> None: + """Refuse a revised payload when a new job opens an existing keyed cache.""" + path = tmp_path / "readings.csv" + cache, database = InMemoryArrowDatabase(), InMemoryArrowDatabase() + _write(path, ROWS, arrangement) + first = _cached(path, cache, arrangement) + _ = _run(_job(first, database), orchestrator) + assert len(CALLS) == 3 + cache_before = _cache_rows(first, cache) + stored_before = _stored_tables(database) + CALLS.clear() + + _write(path, _changed(ROWS, ("s1", 2)), arrangement) + second = _cached(path, cache, arrangement) + with pytest.raises(CachedSourceChangedRowError) as refused: + _ = _run(_job(second, database), orchestrator) + + message = str(refused.value) + assert "csv_v1:readings" in message + assert '{"subject":"s1","session":2}' in message + assert "1 row" in message + assert "source id" in message and "cache" in message # the remedy + assert isinstance(refused.value, InputValidationError) + assert CALLS == [] + assert _cache_rows(second, cache) == cache_before + assert _stored_tables(database) == stored_before + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_a_changed_value_is_refused_in_the_job_that_cached_it( + tmp_path: Path, orchestrator: str +) -> None: + """The file changes under a live job: its next run is refused, nothing written.""" + path = tmp_path / "readings.csv" + cache, database = InMemoryArrowDatabase(), InMemoryArrowDatabase() + _write(path, ROWS) + source = _cached(path, cache) + job = _job(source, database) + _ = _run(job, orchestrator) + cache_before = _cache_rows(source, cache) + stored_before = _stored_tables(database) + CALLS.clear() + + _write(path, _changed(ROWS, ("s2", 1))) + with pytest.raises(CachedSourceChangedRowError, match="csv_v1:readings"): + _ = _run(job, orchestrator) + assert CALLS == [] + assert _cache_rows(source, cache) == cache_before + assert _stored_tables(database) == stored_before + # It stays refused: a later read does not present the cache as if nothing changed. + with pytest.raises(CachedSourceChangedRowError): + _ = source.as_table() + + +def test_unchanged_cache_io_matches_main_except_conflict_validation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Pin the database calls for each phase with unchanged source rows. + + Initial ingestion makes two full reads, two schema checks, three refreshes, + one append, and one flush. Warm freshness and reads make zero calls. A + reopened cache's preview and freshness check each make one projected read, + one schema check, and one refresh. Reading the reopened cache makes one + full read, one projected read, two schema checks, two refreshes, one + append, and one flush. Each phase makes zero calls of any unlisted kind. + """ + path = tmp_path / "readings.csv" + _write(path, ROWS) + db = InMemoryArrowDatabase() + methods = ( + "get_all_records", + "get_records_with_column_value", + "get_table_schema", + "refresh_table", + "add_records", + "flush", + ) + spies = {name: Mock(wraps=getattr(db, name)) for name in methods} + for name, spy in spies.items(): + monkeypatch.setattr(db, name, spy) + + def assert_calls( + *, + full: int = 0, + projected: int = 0, + schema: int = 0, + refresh: int = 0, + writes: int = 0, + ) -> None: + """Assert one phase's exact I/O counts and reset every spy for the next. + + Args: + full: Expected full reads. + projected: Expected projected reads. + schema: Expected schema checks. + refresh: Expected table refreshes. + writes: Expected calls each to `add_records` and `flush`. + """ + assert tuple(spies[name].call_count for name in methods) == ( + full, + projected, + schema, + refresh, + writes, + writes, + ) + for spy in spies.values(): + spy.reset_mock() + + source = _cached(path, db) + assert _presented(source) == ROWS + # Main makes the same full reads and writes. Validation also checks schema + # and refreshes the handle, including before the first append. + assert_calls(full=2, schema=2, refresh=3, writes=1) + assert not source.check_for_new_data() + assert_calls() + assert _presented(source) == ROWS + assert_calls() + + reopened = _cached(path, db) + assert reopened.head().table.num_rows == 0 + # Main's preview skips storage. The projection checks for stored conflicts. + assert_calls(projected=1, schema=1, refresh=1) + assert not reopened.check_for_new_data() + # Conflict validation is projected here. Main makes one full read. + assert_calls(projected=1, schema=1, refresh=1) + assert _presented(reopened) == ROWS + # Main makes the same write and full readback. Validate before the append. + assert_calls(full=1, projected=1, schema=2, refresh=2, writes=1) + + +def test_warm_refusal_preserves_the_held_stream( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Verify that refusing changed rows preserves the same held stream object. + + The refusal happens before any append or flush. It preserves the source + bindings and freshness timestamps, and leaves the stored rows and metadata + intact. + """ + path = tmp_path / "readings.csv" + _write(path, ROWS) + db = InMemoryArrowDatabase() + source = _csv(path).cached(db, cache_path=("warm",)) + assert _presented(source) == ROWS + before = _stored_cache(source, db) + stream = source._cached_stream + bindings = source._source_bindings + modified = source.last_modified + seen = source._source_seen + assert stream is not None + + _write(path, _changed(ROWS, ("s1", 2))) + + def unexpected_write(*args: object, **kwargs: object) -> None: + pytest.fail("A changed-row refusal must occur before add_records or flush") + + monkeypatch.setattr(type(db), "add_records", unexpected_write) + monkeypatch.setattr(type(db), "flush", unexpected_write) + for check in ( + source.check_for_new_data, + source.check_for_new_data, + source.as_table, + ): + with pytest.raises(CachedSourceChangedRowError, match='"session":2'): + _ = check() + + assert _stored_cache(source, db).equals(before, check_metadata=True) + assert source._source_bindings is bindings + assert source.last_modified == modified + assert source._source_seen == seen + assert source._cached_stream is stream + + new: Row = ("s2", 2, 4.0, 40) + _write(path, [*ROWS, new]) + assert source.check_for_new_data() + assert not source.check_for_new_data() + assert source._cached_stream is None + assert _stored_cache(source, db).equals(before, check_metadata=True) + + +def test_writable_cache_freshness_refuses_a_mixed_delivery(tmp_path: Path) -> None: + """Reject an edit with an append before a job computes or writes either row.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + with fake.install(tmp_path): + cache = ConnectorArrowDatabase(writable_connector(held=False)) + source = _cached(path, cache) + results = InMemoryArrowDatabase() + job = _job(source, results) + _ = asyncio.run(job.run_async()) + before = _stored_cache(source, cache) + stored_before = _stored_tables(results) + held = source._cached_stream + seen = source._source_seen + modified = source.last_modified + assert held is not None + CALLS.clear() + + new: Row = ("s3", 1, 5.0, 50) + _write(path, [*_changed(ROWS, ("s1", 2)), new]) + for check in (source.check_for_new_data, lambda: asyncio.run(job.run_async())): + with pytest.raises(CachedSourceChangedRowError, match='"session":2'): + _ = check() + assert source._cached_stream is held + assert source._source_seen == seen + assert source.last_modified == modified + assert _stored_cache(source, cache).equals(before, check_metadata=True) + assert _stored_tables(results) == stored_before + assert CALLS == [] + + _write(path, [*ROWS, new]) + assert source.check_for_new_data() + assert _stored_cache(source, cache).equals(before, check_metadata=True) + _ = asyncio.run(job.run_async()) + assert _presented(source) == sorted([*ROWS, new]) + assert CALLS == [(5.0, 50)] + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_several_changed_keys_are_named_up_to_five_with_their_count( + tmp_path: Path, arrangement: str +) -> None: + """Report the total conflict count and name the first five IDs in order.""" + path = tmp_path / "readings.csv" + cache = InMemoryArrowDatabase() + rows: list[Row] = [(f"s{i}", i, float(i), i) for i in range(8)] + _write(path, rows, arrangement) + first = _cached(path, cache, arrangement) + assert len(_presented(first)) == 8 + before = _cache_rows(first, cache) + + changed_keys = [(f"s{i}", i) for i in range(7)] + _write(path, _changed(rows, *changed_keys), arrangement) + second = _cached(path, cache, arrangement) + with pytest.raises(CachedSourceChangedRowError) as refused: + _ = second.as_table() + message = str(refused.value) + assert "7 rows" in message + named = [ + key + for key in changed_keys + if f'{{"subject":"{key[0]}","session":{key[1]}}}' in message + ] + assert named == changed_keys[:5] # the first five, in record-id order + assert _cache_rows(second, cache) == before + + +@pytest.mark.parametrize( + ("column", "tag_only_columns"), + [("site", True), ("count", True), ("site", False)], + ids=["plain-tag", "data", "data-tag"], +) +def test_a_changed_non_key_cell_is_a_changed_row( + column: str, tag_only_columns: bool +) -> None: + """Changing a non-key tag, data cell or data-tag is refused before writing.""" + cache = InMemoryArrowDatabase() + + def cached(site: str, count: int) -> CachedSource: + """Build a delivery with the same generated record key.""" + return ArrowTableSource( + pa.table({"id": [1], "site": [site], "value": [2.0], "count": [count]}), + record_id_columns="id", + tag_columns="site", + tag_only_columns=tag_only_columns, + source_id="readings", + ).cached(cache) + + first = cached("west", 20) + assert first.as_table().num_rows == 1 + tags, data = first.keys() + assert "site" in tags + assert ("site" in data) is not tag_only_columns + before = _stored_cache(first, cache) + changed = cached("east", 20) if column == "site" else cached("west", 21) + with pytest.raises(CachedSourceChangedRowError): + _ = changed.as_table() + assert _stored_cache(first, cache).equals(before) + + +@pytest.mark.parametrize("explicit_path", [False, True], ids=["automatic", "explicit"]) +def test_changed_delivery_recommends_a_new_source_id_only_for_automatic_paths( + explicit_path: bool, +) -> None: + """Changing the source ID selects fresh storage only for automatic paths.""" + database = InMemoryArrowDatabase() + path = ("explicit",) if explicit_path else None + + def cache( + name: str, value: int, cache_path: tuple[str, ...] | None + ) -> CachedSource: + """Declare a delivery under the selected source ID and cache path.""" + return ArrowTableSource( + pa.table({"id": [1], "value": [value]}), + record_id_columns="id", + source_id=name, + ).cached(database, cache_path=cache_path) + + _ = cache("readings", 10, path).as_table() + with pytest.raises( + CachedSourceChangedRowError, match="Use a new cache path" + ) as exc: + _ = cache("readings", 20, path).as_table() + assert ("new source id" in str(exc.value)) == (not explicit_path) + + if explicit_path: + with pytest.raises(CachedSourceIdMismatchError): + _ = cache("changed", 20, path).as_table() + assert cache("changed", 20, ("fresh",) if explicit_path else path).as_table()[ + "value" + ].to_pylist() == [20] + + +class _CacheClock: + """A controllable UTC clock for cached-source writes.""" + + early = datetime(2026, 1, 1, 12, tzinfo=timezone.utc) + later = datetime(2026, 1, 2, 12, tzinfo=timezone.utc) + instant = early + + @classmethod + def now(cls, tz: timezone) -> datetime: + """Return the current test instant in the requested timezone.""" + return cls.instant.astimezone(tz) + + +@pytest.fixture +def cache_clock(monkeypatch: pytest.MonkeyPatch) -> type[_CacheClock]: + """Replace only the cached-source write clock for this test.""" + monkeypatch.setattr(_CacheClock, "instant", _CacheClock.early) + monkeypatch.setattr(cached_source, "datetime", _CacheClock) + return _CacheClock + + +# --------------------------------------------------------------------------- +# What stays accepted +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_the_same_rows_delivered_again_write_nothing( + tmp_path: Path, orchestrator: str, arrangement: str, cache_clock: type[_CacheClock] +) -> None: + """Reuse cached results when the same keyed rows are delivered again.""" + path = tmp_path / "readings.csv" + cache, database = InMemoryArrowDatabase(), InMemoryArrowDatabase() + _write(path, ROWS, arrangement) + first = _cached(path, cache, arrangement) + _ = _run(_job(first, database), orchestrator) + before = _cache_rows(first, cache) # every cell, the write times included + CALLS.clear() + + cache_clock.instant = cache_clock.later + _write(path, list(reversed(ROWS)), arrangement) # keyed: order is not content + second = _cached(path, cache, arrangement) + _ = _run(_job(second, database), orchestrator) + assert CALLS == [] + assert _cache_rows(second, cache) == before + assert _presented(second) == sorted(ROWS) + + +def test_plain_derived_source_redelivery_writes_nothing(tmp_path: Path) -> None: + """Keep the cache and pod calls unchanged on plain derived-source redelivery.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + job = _job(_csv(path), InMemoryArrowDatabase()) + _ = job.run() + cache = InMemoryArrowDatabase() + + first = CachedSource(DerivedSource(job.nodes["summary"]), cache) + presented = first.as_table(all_info=True) + assert presented.num_rows == len(ROWS) + assert all( + not name.startswith(constants.SYSTEM_TAG_RECORD_ID_PREFIX) + for name in presented.column_names + ) + before = _cache_rows(first, cache) + + second = CachedSource(DerivedSource(job.nodes["summary"]), cache) + assert second.as_table(all_info=True).equals(presented) + assert _cache_rows(second, cache) == before + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_a_row_under_a_new_key_is_added( + tmp_path: Path, orchestrator: str, arrangement: str +) -> None: + """Compute and cache a row whose key has never been delivered.""" + path = tmp_path / "readings.csv" + cache, database = InMemoryArrowDatabase(), InMemoryArrowDatabase() + _write(path, ROWS, arrangement) + _ = _run(_job(_cached(path, cache, arrangement), database), orchestrator) + CALLS.clear() + + new: Row = ("s2", 2, 4.0, 40) + _write(path, [new, *ROWS], arrangement) + second = _cached(path, cache, arrangement) + _ = _run(_job(second, database), orchestrator) + assert CALLS == [(4.0, 40)] + assert _presented(second) == sorted([*ROWS, new]) + assert _stored_cache(second, cache).num_rows == 4 + + +def test_a_row_removed_from_the_source_stays_and_may_come_back(tmp_path: Path) -> None: + """Retain a missing key and deduplicate its identical reappearance.""" + path = tmp_path / "readings.csv" + cache = InMemoryArrowDatabase() + _write(path, ROWS) + assert _presented(_cached(path, cache)) == sorted(ROWS) + _write(path, ROWS[:2]) + assert _presented(_cached(path, cache)) == sorted(ROWS) # cumulative + _write(path, ROWS) + assert _presented(_cached(path, cache)) == sorted(ROWS) + # A removed key that comes back with other content is a changed row. + _write(path, ROWS[:2]) + assert _presented(_cached(path, cache)) == sorted(ROWS) + _write(path, _changed(ROWS, ("s2", 1))) + with pytest.raises(CachedSourceChangedRowError, match='"subject":"s2"'): + _ = _cached(path, cache).as_table() + + +# --------------------------------------------------------------------------- +# Another store, another session, a reloaded job +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_a_cache_kept_on_disk_refuses_in_a_later_session( + tmp_path: Path, orchestrator: str +) -> None: + """New database, source and job objects over one stored cache, as a new process.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + + def session() -> tuple[CachedSource, DeltaTableDatabase, PipelineJob]: + """Open new source, database and job objects over the same storage.""" + cache = DeltaTableDatabase(str(tmp_path / "cache")) + source = _cached(path, cache) + job = _job(source, DeltaTableDatabase(str(tmp_path / "store"))) + return source, cache, job + + source, cache, job = session() + _ = _run(job, orchestrator) + before = _cache_rows(source, cache) + CALLS.clear() + + source, cache, job = session() + _ = _run(job, orchestrator) # the same rows: accepted + assert CALLS == [] + assert _cache_rows(source, cache) == before + + _write(path, _changed(ROWS, ("s1", 1), ("s1", 2))) + source, cache, job = session() + with pytest.raises(CachedSourceChangedRowError, match="2 rows"): + _ = _run(job, orchestrator) + assert CALLS == [] + source, cache, _ = session() + assert _cache_rows(source, cache) == before + + +def test_a_reloaded_job_refuses_a_changed_row(tmp_path: Path) -> None: + """Apply the changed-row rule after restoring a job from its definition.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + cache = DeltaTableDatabase(str(tmp_path / "cache")) + database = DeltaTableDatabase(str(tmp_path / "store")) + source = _cached(path, cache) + job = _job(source, database) + _ = job.run() + before = _cache_rows(source, cache) + job.save(str(tmp_path / "job.json")) + CALLS.clear() + + _write(path, _changed(ROWS, ("s1", 2))) + loaded = PipelineJob.load(str(tmp_path / "job.json")) + with pytest.raises(CachedSourceChangedRowError, match='"session":2'): + _ = loaded.run(load_only=True) + assert CALLS == [] + assert _cache_rows(_cached(path, cache), cache) == before + + +@pytest.mark.parametrize("warm_table", [True, False], ids=["present", "absent"]) +def test_a_delta_writer_checks_a_delivery_against_the_latest_snapshot( + tmp_path: Path, warm_table: bool +) -> None: + """Refuse a changed row using the latest Delta snapshot across handles.""" + path = tmp_path / "readings.csv" + cache_dir = str(tmp_path / "cache") + first_db = DeltaTableDatabase(cache_dir) + _write(path, ROWS[:1]) + first = _cached(path, first_db) + if warm_table: + assert _presented(first) == ROWS[:1] + else: + assert first.get_all_records() is None + + _write(path, ROWS[:2]) + second_db = DeltaTableDatabase(cache_dir) + second = _cached(path, second_db) + assert _presented(second) == ROWS[:2] + before = _cache_rows(second, second_db) + + _write(path, _changed(ROWS[:2], ("s1", 2))) + delivery = _cached(path, first_db) + with pytest.raises(CachedSourceChangedRowError, match='"session":2'): + _ = delivery.as_table() + fresh_db = DeltaTableDatabase(cache_dir) + assert _cache_rows(delivery, fresh_db) == before + + +# --------------------------------------------------------------------------- +# Record ids by position: one rule for every source +# --------------------------------------------------------------------------- + + +def test_a_positional_source_refuses_a_changed_row_at_a_position( + tmp_path: Path, +) -> None: + """Refuse changed content at a cached positional record ID.""" + path = tmp_path / "readings.csv" + cache = InMemoryArrowDatabase() + _write(path, ROWS) + first = _cached(path, cache, keyed=False) + assert _presented(first) == sorted(ROWS) + before = _cache_rows(first, cache) + + _write(path, _changed(ROWS, ("s1", 2))) + second = _cached(path, cache, keyed=False) + with pytest.raises(CachedSourceChangedRowError) as refused: + _ = second.as_table() + assert "row_1" in str(refused.value) + assert _cache_rows(second, cache) == before + + +def test_a_positional_source_accepts_an_append_and_refuses_a_reorder( + tmp_path: Path, +) -> None: + """Accept a new position and refuse reordering that changes cached positions.""" + path = tmp_path / "readings.csv" + cache = InMemoryArrowDatabase() + _write(path, ROWS) + assert _presented(_cached(path, cache, keyed=False)) == sorted(ROWS) + + new: Row = ("s2", 2, 4.0, 40) + _write(path, [*ROWS, new]) + appended = _cached(path, cache, keyed=False) + assert _presented(appended) == sorted([*ROWS, new]) + before = _cache_rows(appended, cache) + + # A reorder, and an insert in the middle, give positions other rows. + for rows in ( + [ROWS[1], ROWS[0], ROWS[2], new], + [ROWS[0], ("s9", 9, 9.0, 9), *ROWS[1:]], + ): + _write(path, rows) + moved = _cached(path, cache, keyed=False) + with pytest.raises(CachedSourceChangedRowError, match="row_"): + _ = moved.as_table() + assert _cache_rows(moved, cache) == before + + +def test_an_in_memory_source_is_held_to_the_same_rule() -> None: + """Not a CSV matter: any wrapped source kind, here an Arrow table with keys.""" + + def source(value: float) -> ArrowTableSource: + """Build two keyed Arrow rows with a configurable second payload.""" + return ArrowTableSource( + pa.table( + { + "subject": pa.array(["s1", "s1"], pa.large_string()), + "session": pa.array([1, 2], pa.int64()), + "value": pa.array([1.0, value], pa.float64()), + "count": pa.array([10, 20], pa.int64()), + } + ), + tag_columns=["subject", "session"], + record_id_columns=["session", "subject"], + tag_only_columns=True, + source_id="readings", + ) + + cache = InMemoryArrowDatabase() + assert CachedSource(source(2.0), cache_database=cache).as_table().num_rows == 2 + assert CachedSource(source(2.0), cache_database=cache).as_table().num_rows == 2 + with pytest.raises( + CachedSourceChangedRowError, match="arrow_table_v1:readings" + ) as refused: + _ = CachedSource(source(2.5), cache_database=cache).as_table() + assert '{"session":2,"subject":"s1"}' in str(refused.value) + + +@pytest.mark.parametrize("extension_aware", [False, True], ids=["raw", "extension"]) +@pytest.mark.parametrize("committed", [False, True], ids=["queued", "committed"]) +def test_memory_refusal_does_not_append_or_flush( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + extension_aware: bool, + committed: bool, +) -> None: + """Mixed changed and new keys leave existing cache rows and their queue intact.""" + path = tmp_path / "readings.csv" + _write(path, ROWS[:2]) + seed_db = InMemoryArrowDatabase() + seed = _cached(path, seed_db) + assert _presented(seed) == ROWS[:2] + original = _stored_cache(seed, seed_db) + + memory = InMemoryArrowDatabase() + converter = resolve_context(None).type_converter + assert isinstance(converter, UniversalTypeConverter) + database: ArrowDatabaseProtocol = ( + ExtensionAwareDatabase(memory, converter) if extension_aware else memory + ) + database.add_records( + seed.cache_path, + original, + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=committed, + ) + _write(path, _changed(ROWS, ("s1", 1))) + refusing = _cached(path, database.at()) + assert refusing.cache_path == seed.cache_path + + def unexpected_write(*args: object, **kwargs: object) -> None: + pytest.fail("A changed-row refusal must occur before add_records or flush") + + with monkeypatch.context() as patch: + patch.setattr(type(memory), "add_records", unexpected_write) + patch.setattr(type(memory), "flush", unexpected_write) + with pytest.raises(CachedSourceChangedRowError, match='"session":1'): + _ = refusing.as_table() + + after = _stored_cache(refusing, database.at()) + assert after.num_rows == original.num_rows + assert after.equals(original, check_metadata=True) + database.flush() + assert _stored_cache(refusing, database.at()).equals(original, check_metadata=True) + + +class _ReorderedReadDatabase(InMemoryArrowDatabase): + """Return the same stored columns in a different order.""" + + def get_all_records( + self, record_path: tuple[str, ...], record_id_column: str | None = None + ) -> pa.Table | None: + """Return a readback with its fields in reverse order.""" + records = super().get_all_records(record_path, record_id_column) + if records is None: + return None + return records.select(sorted(records.column_names)) + + +class _ReorderedDeliverySource(ArrowTableSource): + """Return the same delivered columns in a different order.""" + + def as_table(self, **kwargs: Any) -> pa.Table: + """Present the delivery with its fields in reverse order.""" + table = super().as_table(**kwargs) + return table.select(sorted(table.column_names)) + + +@pytest.mark.parametrize("custom_tags", [False, True], ids=["generated", "custom"]) +def test_a_clean_cache_accepts_a_sorted_first_delivery(custom_tags: bool) -> None: + """An adapter reordering a delivery still identifies the generated record ID.""" + table = pa.table({"id": [1, 2], "value": [10, 20]}) + source = _ReorderedDeliverySource( + table, + record_id_columns="id", + source_id="sorted_readings", + ) + if custom_tags: + with_custom_provenance( + source, + {"record_id::custom": "constant", "source_id::custom": source.source_id}, + ) + database = InMemoryArrowDatabase() + cached = source.cached(database) + assert cached.as_table().equals(source.as_table()) + reopened = source.cached(database) + rows = reopened.get_all_records() + assert rows is not None + assert rows.select(["id", "value"]).equals(source.as_table()) + + +@pytest.mark.parametrize("store", ["memory", "delta"]) +@pytest.mark.parametrize( + "suffix", ["custom", "ab12", "f81d4fae7dec11d0a76500a0c91e6bf6"] +) +def test_a_source_adapter_can_cache_custom_provenance_without_a_generated_id( + tmp_path: Path, store: str, suffix: str +) -> None: + """A custom provenance token can describe more than one distinct row.""" + table = pa.table({"id": [1, 2], "value": [10, 20]}) + provenance = { + f"source_id::{suffix}": "arrow_table_v1:readings", + f"record_id::{suffix}": "shared", + } + source = with_custom_provenance( + ArrowTableSource(table, record_id_columns="id", source_id="readings"), + provenance, + ) + + class CustomProvenanceSource: + """Expose custom provenance without declaring a generated record ID.""" + + def __getattr__(self, name: str) -> Any: + """Delegate source attributes to the wrapped source.""" + return getattr(source, name) + + def as_table(self, **kwargs: Any) -> pa.Table: + """Return the source table with just the custom provenance pair.""" + rows = source.as_table(**kwargs) + return rows.drop( + [ + name + for name in rows.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + and name.removeprefix(constants.SYSTEM_TAG_PREFIX) not in provenance + ] + ) + + adapter = cast(SourceProtocol, cast(object, CustomProvenanceSource())) + database = ( + InMemoryArrowDatabase() if store == "memory" else DeltaTableDatabase(tmp_path) + ) + path = ("custom_provenance",) + live = CachedSource(adapter, database, cache_path=path) + assert live.as_table().sort_by("id").equals(source.as_table()) + assert CachedSource(adapter, database, cache_path=path).as_table().num_rows == 2 + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + *source.output_schema(), + ) + offline = CachedSource(proxy, database, cache_path=path) + assert offline.head().table.num_rows == 0 + held = offline.get_all_records() + assert held is not None and held.num_rows == 2 + assert not any(name.startswith(constants.META_PREFIX) for name in held.column_names) + + +@pytest.mark.parametrize("store", ["memory", "delta"]) +@pytest.mark.parametrize("adapter_writes_first", [True, False]) +@pytest.mark.parametrize("delivery", ["source", "adapter", "bound-adapter"]) +def test_a_transparent_adapter_preserves_the_generated_cache_id( + tmp_path: Path, + store: str, + adapter_writes_first: bool, + delivery: str, +) -> None: + """Redelivering through an adapter preserves refusal of later changed rows.""" + + def source(value: int) -> ArrowTableSource: + """Build a single keyed row for delivery through the adapter.""" + return ArrowTableSource( + pa.table({"id": [1], "value": [value]}), + record_id_columns="id", + source_id="readings", + ) + + original = source(10) + + class TransparentSource: + """Expose a source's table unchanged through a public adapter.""" + + def __init__(self, delegate: ArrowTableSource) -> None: + """Wrap the source for public-interface delegation.""" + self.delegate = delegate + + def __getattr__(self, name: str) -> Any: + """Delegate only public source attributes.""" + if name.startswith("_"): + raise AttributeError(name) + return getattr(self.delegate, name) + + adapter = cast(SourceProtocol, cast(object, TransparentSource(original))) + database = ( + InMemoryArrowDatabase() if store == "memory" else DeltaTableDatabase(tmp_path) + ) + first, second = (adapter, original) if adapter_writes_first else (original, adapter) + seeded = CachedSource(first, database) + assert seeded.as_table().num_rows == 1 + assert CachedSource(second, database).as_table().num_rows == 1 + before = _stored_cache(seeded, database) + modified = source(11) + updated: SourceProtocol = modified + if delivery != "source": + updated = cast(SourceProtocol, cast(object, TransparentSource(modified))) + if delivery == "bound-adapter": + proxy = SourceProxy( + modified.source_id, + modified.content_hash().to_string(), + modified.pipeline_hash().to_string(), + *modified.output_schema(), + ) + proxy.bind(updated) + updated = proxy + changed = CachedSource(updated, database) + assert changed.cache_path == seeded.cache_path + with pytest.raises(CachedSourceChangedRowError) as refused: + _ = changed.as_table() + after = _stored_cache(seeded, database) + assert after.num_rows == before.num_rows == 1 + assert after.equals(before) + assert "the source delivered" in str(refused.value) + + +@pytest.mark.parametrize("reordered", ["stored", "delivered", "both"]) +def test_a_changed_row_is_refused_with_reordered_fields(reordered: str) -> None: + """Match generated record IDs even when a delivery or readback reorders fields.""" + database = ( + InMemoryArrowDatabase() + if reordered == "delivered" + else _ReorderedReadDatabase() + ) + + def cached(value: float, *, first: bool = False) -> CachedSource: + """Control field order for the initial write and later deliveries.""" + source = ( + ArrowTableSource + if first or reordered == "stored" + else _ReorderedDeliverySource + ) + return source( + pa.table({"id": [1], "value": [value]}), + record_id_columns="id", + source_id="readings", + ).cached(database) + + first = cached(1.0, first=True) + assert first.as_table().num_rows == 1 + before = _stored_cache(first, database) + assert cached(1.0).as_table().num_rows == 1 + assert _stored_cache(first, database).equals(before) + with pytest.raises(CachedSourceChangedRowError, match='"id":1'): + _ = cached(2.0).as_table() + assert _stored_cache(first, database).equals(before) + + +@pytest.mark.parametrize("entry", ["table", "rows", "proxy"]) +def test_a_refused_read_leaves_the_refusing_nested_cache_unchanged( + tmp_path: Path, entry: str +) -> None: + """Leave the refusing cache intact after inner caches accept a delivery.""" + path = tmp_path / "readings.csv" + inner_db, middle_db, outer_db = (InMemoryArrowDatabase() for _ in range(3)) + + def outer_source(source: CachedSource) -> CachedSource | SourceProxy: + """Route the outer cache directly or through a bound source proxy.""" + if entry != "proxy": + return source + tag_schema, data_schema = source.output_schema() + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + tag_schema, + data_schema, + ) + proxy.bind(source) + return proxy + + _write(path, ROWS[:1]) + first = outer_source(_cached(path, InMemoryArrowDatabase())).cached(outer_db) + assert _presented(first) == ROWS[:1] + before = _stored_cache(first, outer_db) + new: Row = ("s9", 1, 9.0, 90) + _write(path, [new]) + seed_middle = _cached(path, middle_db) + assert _presented(seed_middle) == [new] + + changed = _changed(ROWS, ("s1", 1)) + _write(path, changed) + inner = _cached(path, inner_db) + middle = inner.cached(middle_db) + wrapped = outer_source(middle) + outer = wrapped.cached(outer_db) + # The inner and middle caches accept the delivery before the outer cache checks it. + with pytest.raises(CachedSourceChangedRowError): + if entry == "rows": + _ = list(outer.iter_data()) + else: + _ = outer.as_table() + assert _stored_cache(outer, outer_db).equals(before) + assert _stored_cache(middle, middle_db).num_rows == 4 + assert _stored_cache(inner, inner_db).num_rows == 3 + + accepted = wrapped.cached(InMemoryArrowDatabase()) + assert _presented(accepted) == sorted([*changed, new]) + + +@pytest.mark.parametrize("backend", ["memory", "delta"]) +def test_checking_for_new_data_leaves_a_nested_delivery_for_the_read( + tmp_path: Path, backend: str +) -> None: + """Freshness leaves a nested append to the consuming read.""" + path = tmp_path / "readings.csv" + inner_db = ( + DeltaTableDatabase(tmp_path / "inner") + if backend == "delta" + else InMemoryArrowDatabase() + ) + outer_db = InMemoryArrowDatabase() + + _write(path, ROWS[:1]) + seed = _cached(path, outer_db) + assert _presented(seed) == ROWS[:1] + outer_before = _stored_cache(seed, outer_db) + + _write(path, ROWS[1:]) + inner = _cached(path, inner_db) + assert _presented(inner) == ROWS[1:] + inner_before = _stored_cache(inner, inner_db) + outer = inner.cached(outer_db) + + _write(path, _changed(ROWS, ("s1", 1))) + assert outer.check_for_new_data() + assert _stored_cache(inner, inner_db).equals(inner_before) + with pytest.raises(CachedSourceChangedRowError): + _ = outer.as_table() + assert _stored_cache(inner, inner_db).num_rows == len(ROWS) + assert _stored_cache(outer, outer_db).equals(outer_before) + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@pytest.mark.parametrize("depth", [2, 3]) +def test_a_nested_conflict_refuses_every_job_rerun( + tmp_path: Path, orchestrator: str, depth: int +) -> None: + """Raise on each job retry until a nested source restores the original row.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + caches: list[tuple[CachedSource, InMemoryArrowDatabase]] = [] + source = _csv(path) + for _ in range(depth): + cache = InMemoryArrowDatabase() + source = source.cached(cache) + caches.append((source, cache)) + + database = InMemoryArrowDatabase() + job = _job(source, database) + + def run() -> None: + """Run the job through the selected orchestration mode.""" + if orchestrator == "async": + _ = asyncio.run(job.run_async()) + else: + _ = job.run() + + run() + before = [_stored_cache(source, cache) for source, cache in caches] + stored_before = _stored_tables(database) + CALLS.clear() + _write(path, _changed(ROWS, ("s1", 2))) + + for _ in range(2): + with warnings.catch_warnings(): + warnings.simplefilter("error", SourceCheckFailedWarning) + with pytest.raises(CachedSourceChangedRowError, match='"session":2'): + run() + assert CALLS == [] + assert _stored_tables(database) == stored_before + for (source, cache), snapshot in zip(caches, before, strict=True): + assert _stored_cache(source, cache).equals(snapshot) + + _write(path, ROWS) + run() + assert CALLS == [] + + +def test_a_refused_keyed_derivation_uses_the_origin_caches_readback() -> None: + """Keep the origin cache's readback when a keyed derivation refuses a delivery.""" + inner_db, outer_db = InMemoryArrowDatabase(), InMemoryArrowDatabase() + + def nested(value: int, database: InMemoryArrowDatabase) -> DerivedSource: + """Derive a keyed source over a separately cached origin.""" + origin = ArrowTableSource( + pa.table({"id": [1], "site": ["lab"], "value": [value]}), + source_id="origin", + record_id_columns="id", + tag_columns=["id", "site"], + tag_only_columns=True, + ).cached(database) + return DerivedSource( + origin, + source_id="derived", + tags_as_data={"site": "copied_site"}, + record_id_columns="id", + ) + + seed = nested(10, InMemoryArrowDatabase()).cached(outer_db) + assert seed.as_table()["value"].to_pylist() == [10] + before = _stored_cache(seed, outer_db) + incoming = nested(20, inner_db) + outer = incoming.cached(outer_db) + + for _ in range(2): + with pytest.raises(CachedSourceChangedRowError, match='"id":1'): + _ = outer.as_table() + assert _stored_cache(outer, outer_db).equals(before) + assert len(list(inner_db.list_table_paths(()))) == 1 + + accepted = incoming.cached(InMemoryArrowDatabase()) + assert accepted.as_table()["value"].to_pylist() == [20] + + +@function_pod(output_keys=("total", "extra")) +def _with_extra(value: int | None) -> tuple[int, int | None]: + """Return the total with an additional nullable output column.""" + return value or 0, 42 + + +@function_pod(output_keys="total") +def _without_extra(value: int | None) -> int: + """Return just the total.""" + return value or 0 + + +@pytest.mark.parametrize("omit_on_append", [True, False], ids=["omitted", "added"]) +def test_a_nested_delta_cache_preserves_schema_evolution( + tmp_path: Path, omit_on_append: bool +) -> None: + """Read back the nullable field layout negotiated by nested Delta caches.""" + + def source(key: int, *, extra: bool) -> DerivedSource: + """Build a keyed derivation with an optional nullable output.""" + origin = ArrowTableSource( + pa.table({"id": [key], "value": [10]}), + source_id="origin", + record_id_columns="id", + tag_columns="id", + tag_only_columns=True, + ) + job = PipelineJob(name="origin", database=InMemoryArrowDatabase()) + with job: + (_with_extra if extra else _without_extra).pod(origin, label="values") + _ = job.run() + return DerivedSource(job.nodes["values"], source_id="plain") + + database = DeltaTableDatabase(tmp_path) + seed = source(1, extra=omit_on_append).cached(database, cache_path=("fixed",)) + assert seed.as_table()["id"].to_pylist() == [1] + inner = source(2, extra=not omit_on_append).cached(database, cache_path=("fixed",)) + outer = inner.cached(InMemoryArrowDatabase()) + + result = outer.as_table().sort_by("id") + assert result["id"].to_pylist() == [1, 2] + assert result["extra"].to_pylist() == ([42, None] if omit_on_append else [None, 42]) + assert inner.as_table().sort_by("id").equals(result) + + +def _derived(table: pa.Table, pod: Any, tags: list[str]) -> DerivedSource: + """A plain derived source over a job node computed from ``table``.""" + origin = ArrowTableSource( + table, + source_id="origin", + record_id_columns="id", + tag_columns=tags, + tag_only_columns=True, + ) + job = PipelineJob(name="origin", database=InMemoryArrowDatabase()) + with job: + pod.pod(origin, label="values") + _ = job.run() + return DerivedSource(job.nodes["values"], source_id="plain") + + +@pytest.mark.parametrize("children", [("x", "y"), ("y", "x")]) +def test_a_nested_delta_cache_accepts_an_added_nullable_struct_child( + tmp_path: Path, children: tuple[str, str] +) -> None: + """Independent review of 76912324: the stored struct has one child, the appended + rows two. Delta evolves the struct; the check of the delivery, made before the + write, must not hold the stored rows to the new declaration.""" + + def source(key: int, names: tuple[str, ...]) -> DerivedSource: + """Build a derivation with the requested struct children.""" + values = {"x": key * 10, "y": key * 20} + payload = pa.StructArray.from_arrays( + [pa.array([values[name]]) for name in names], + fields=[pa.field(name, pa.int64()) for name in names], + ) + table = pa.table( + {"id": [key], "site": ["lab"], "payload": payload, "value": [key * 3]} + ) + return _derived(table, _without_extra, ["id", "site", "payload"]) + + database = DeltaTableDatabase(tmp_path) + seed = source(1, ("x",)).cached(database, cache_path=("fixed",)) + assert seed.as_table()["id"].to_pylist() == [1] + inner = source(2, children).cached(database, cache_path=("fixed",)) + outer = inner.cached(InMemoryArrowDatabase()) + + result = outer.as_table().sort_by("id") + assert result["payload"].to_pylist() == [{"x": 10, "y": None}, {"x": 20, "y": 40}] + assert result["total"].to_pylist() == [3, 6] + assert inner.as_table().sort_by("id").equals(result) + + +@pytest.mark.parametrize("omit_on_append", [True, False], ids=["omitted", "added"]) +def test_a_nested_cache_over_a_wrapped_delta_store_preserves_schema_evolution( + tmp_path: Path, omit_on_append: bool +) -> None: + """Independent review of 76912324: a Delta store behind the extension-aware + wrapper appends as Delta does; the store's kind is never read from its class.""" + from orcapod.databases.extension_aware_database import ExtensionAwareDatabase + from orcapod.semantic_types.universal_converter import UniversalTypeConverter + + def source(key: int, *, extra: bool) -> DerivedSource: + """Build a derivation with or without the extra output field.""" + table = pa.table({"id": [key], "site": ["lab"], "value": [10], "count": [3]}) + return _derived( + table.drop(["count"]), + _with_extra if extra else _without_extra, + ["id", "site"], + ) + + database = ExtensionAwareDatabase( + DeltaTableDatabase(tmp_path), UniversalTypeConverter() + ) + seed = source(1, extra=omit_on_append).cached(database, cache_path=("fixed",)) + assert seed.as_table()["id"].to_pylist() == [1] + inner = source(2, extra=not omit_on_append).cached(database, cache_path=("fixed",)) + outer = inner.cached(InMemoryArrowDatabase()) + + result = outer.as_table().sort_by("id") + assert result["id"].to_pylist() == [1, 2] + assert result["extra"].to_pylist() == ([42, None] if omit_on_append else [None, 42]) + assert inner.as_table().sort_by("id").equals(result) + + +def test_a_positional_derivation_uses_the_delta_caches_readback( + tmp_path: Path, +) -> None: + """Assign positions from the origin cache's actual readback order.""" + inner_db = DeltaTableDatabase(tmp_path / "inner") + outer_db = InMemoryArrowDatabase() + + def nested(ids: list[int]) -> tuple[CachedSource, CachedSource]: + """Build a keyed origin cache and a positional derived cache.""" + inner = ArrowTableSource( + pa.table({"id": ids, "value": ids}), + source_id="readings", + record_id_columns="id", + tag_columns="id", + tag_only_columns=True, + ).cached(inner_db) + derived = DerivedSource( + inner, source_id="derived", tags_as_data={"id": "copied_id"} + ) + return inner, derived.cached(outer_db) + + initial_inner, initial_outer = nested([1]) + _ = initial_outer.as_table() + assert _stored_cache(initial_inner, inner_db).num_rows == 1 + + updated_inner, updated_outer = nested([1, 2]) + try: + presented = updated_outer.as_table() + except CachedSourceChangedRowError as error: + assert "row_0" in str(error) + assert updated_inner.as_table()["id"].to_pylist() == [2, 1] + assert _stored_cache(updated_outer, outer_db).num_rows == 1 + else: + assert updated_inner.as_table()["id"].to_pylist() == [1, 2] + assert presented.sort_by("copied_id")["copied_id"].to_pylist() == [1, 2] + assert _stored_cache(updated_inner, inner_db).num_rows == 2 + + +@pytest.mark.parametrize( + ("name", "source_tag"), + [ + ("record_id_extra", None), + ("record_id", None), + ("record_id::custom", None), + pytest.param("record_id::custom", "source_id::custom", id="matched-pair"), + pytest.param( + "record_id::" + "a1" * 32, "source_id::" + "a1" * 32, id="hex-pair" + ), + ], +) +def test_a_custom_record_id_like_tag_cannot_mask_a_changed_row( + name: str, source_tag: str | None +) -> None: + """Use the generated record ID even when a custom tag looks like one.""" + cache = InMemoryArrowDatabase() + + def cached(value: float, tag: str) -> CachedSource: + """Attach record-like custom provenance alongside the generated ID.""" + schema = pa.schema( + [ + pa.field("subject", pa.large_string()), + pa.field("session", pa.int64()), + pa.field("value", pa.float64()), + pa.field("count", pa.int64()), + ] + ) + row = {"subject": "s1", "session": 1, "value": value, "count": 10} + custom = {name: tag} + if source_tag is not None: + custom[source_tag] = "arrow_table_v1:readings" + table = pa.Table.from_pylist([row], schema=schema) + source = ArrowTableSource( + table, + tag_columns=["subject", "session"], + tag_only_columns=True, + record_id_columns=["subject", "session"], + source_id="readings", + ) + return with_custom_provenance(source, custom).cached(cache) + + first = cached(1.0, "before") + assert _presented(first) == ROWS[:1] + before = _cache_rows(first, cache) + + changed = cached(1.5, "after") + with pytest.raises(CachedSourceChangedRowError, match='"session":1'): + _ = changed.as_table() + assert _cache_rows(changed, cache) == before + + +# --------------------------------------------------------------------------- +# The recorded-at column +# --------------------------------------------------------------------------- + + +def test_sqlite_refuses_the_source_cache_timestamp_at_construction( + tmp_path: Path, +) -> None: + """Reject SQLite when it cannot store the cache write timestamp type.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + cache = ConnectorArrowDatabase(SQLiteConnector()) + with pytest.raises(UnstorableColumnError, match=SOURCE_RECORDED_AT_COL): + _ = _cached(path, cache) + assert list(cache.list_table_paths(())) == [] + + +@pytest.mark.parametrize("ingest", [False, True], ids=["read", "ingest"]) +@pytest.mark.parametrize("committed", [False, True], ids=["pending", "committed"]) +def test_a_prerelease_source_cache_without_recorded_at_requires_rebuild( + tmp_path: Path, ingest: bool, committed: bool +) -> None: + """Require a new cache when a stored table lacks the write timestamp.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + current_db = InMemoryArrowDatabase() + current = _cached(path, current_db) + assert _presented(current) == sorted(ROWS) + prerelease = _stored_cache(current, current_db).drop([SOURCE_RECORDED_AT_COL]) + _write(path, [*ROWS, ("s2", 2, 4.0, 40)]) + + old_db = InMemoryArrowDatabase() + old = _cached(path, old_db) + old_db.add_records( + old.cache_path, + prerelease, + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=committed, + ) + with pytest.raises( + InputValidationError, match=r"sdb_v2.*__recorded_at.*[Rr]ebuild" + ): + if ingest: + _ = old.as_table() + else: + _ = old.get_all_records() + assert _stored_cache(old, old_db).equals(prerelease) + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_every_cached_row_records_when_it_was_written( + tmp_path: Path, arrangement: str, cache_clock: type[_CacheClock] +) -> None: + """Keep first-write timestamps across redelivery and give new rows a fresh time.""" + path = tmp_path / "readings.csv" + cache = InMemoryArrowDatabase() + _write(path, ROWS, arrangement) + first = _cached(path, cache, arrangement) + _ = first.as_table() + + assert SOURCE_RECORDED_AT_COL == "__recorded_at" + assert first.cache_path[-1] == SOURCE_DB_SCHEMA_VERSION == "sdb_v2" + stored = _stored_cache(first, cache) + field = stored.schema.field(SOURCE_RECORDED_AT_COL) + assert field.type == pa.timestamp("us", tz="UTC") + assert not field.nullable + times = cast("list[datetime]", stored.column(SOURCE_RECORDED_AT_COL).to_pylist()) + assert times == [cache_clock.instant] * len(ROWS) + + # A later write: the rows already cached keep their time, the new row has its own. + cache_clock.instant = cache_clock.later + new: Row = ("s2", 2, 4.0, 40) + _write(path, [*ROWS, new], arrangement) + second = _cached(path, cache, arrangement) + _ = second.as_table() + by_key = { + (r["subject"], r["session"]): r[SOURCE_RECORDED_AT_COL] + for r in _stored_cache(second, cache).to_pylist() + } + assert {by_key[(s, n)] for s, n, _, _ in ROWS} == {times[0]} + assert by_key[("s2", 2)] == cache_clock.later + + +def test_the_recorded_at_column_is_in_nothing_a_read_presents(tmp_path: Path) -> None: + """Omit the storage timestamp from public cache read formats.""" + path = tmp_path / "readings.csv" + cache = InMemoryArrowDatabase() + _write(path, ROWS) + cached = _cached(path, cache) + plain = _csv(path) + + assert cached.keys(all_info=True) == plain.keys(all_info=True) + assert cached.output_schema(all_info=True) == plain.output_schema(all_info=True) + table = cached.as_table(all_info=True) + assert table.schema.names == plain.as_table(all_info=True).schema.names + assert SOURCE_RECORDED_AT_COL not in table.schema.names + records = cached.get_all_records() + assert records is not None + assert SOURCE_RECORDED_AT_COL not in records.schema.names + assert not any( + name.startswith(constants.META_PREFIX) for name in records.schema.names + ) + for tag, data in cached.iter_data(): + assert SOURCE_RECORDED_AT_COL not in tag.as_dict(all_info=True) + assert SOURCE_RECORDED_AT_COL not in data.as_dict(all_info=True) + assert ( + SOURCE_RECORDED_AT_COL not in cached.head(3, all_info=True).table.schema.names + ) + + +def test_the_time_of_writing_is_in_no_hash( + tmp_path: Path, cache_clock: type[_CacheClock] +) -> None: + """Two caches written at two times hold and present the same hashes.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + plain = _csv(path) + + def cached_now() -> tuple[CachedSource, pa.Table, pa.Table]: + """Capture public and stored rows at the current test clock time.""" + cache = InMemoryArrowDatabase() + source = _cached(path, cache) + presented = source.as_table(all_info=True).sort_by( + [("subject", "ascending"), ("session", "ascending")] + ) + stored = _stored_cache(source, cache).sort_by( + [("subject", "ascending"), ("session", "ascending")] + ) + return source, presented, stored + + early, early_rows, early_stored = cached_now() + cache_clock.instant = cache_clock.later + late, late_rows, late_stored = cached_now() + assert ( + early_stored.column(SOURCE_RECORDED_AT_COL).to_pylist() + != late_stored.column(SOURCE_RECORDED_AT_COL).to_pylist() + ) + + assert early.content_hash() == late.content_hash() == plain.content_hash() + assert early.pipeline_hash() == late.pipeline_hash() == plain.pipeline_hash() + assert early.source_id == late.source_id == plain.source_id + assert early.cache_path == late.cache_path + # Every presented cell: values, record ids, tokens, row content hashes. + assert early_rows.equals(late_rows) + assert early_rows.equals( + plain.as_table(all_info=True).sort_by( + [("subject", "ascending"), ("session", "ascending")] + ) + ) + # The stored record hashes, and every stored column but the time. + assert early_stored.drop([SOURCE_RECORDED_AT_COL]).equals( + late_stored.drop([SOURCE_RECORDED_AT_COL]) + ) + for (early_tag, early_data), (late_tag, late_data) in zip( + sorted(early.iter_data(), key=lambda pair: str(pair[0].as_dict())), + sorted(late.iter_data(), key=lambda pair: str(pair[0].as_dict())), + strict=True, + ): + assert early_tag.content_hash() == late_tag.content_hash() + assert early_data.content_hash() == late_data.content_hash() + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_downstream_ids_do_not_follow_the_time_of_writing( + tmp_path: Path, orchestrator: str, cache_clock: type[_CacheClock] +) -> None: + """A job over a cache written earlier stores what a job over a fresh cache does.""" + path = tmp_path / "readings.csv" + _write(path, ROWS) + + def node_rows() -> tuple[Any, list[dict[str, Any]], list[bytes]]: + """Capture the node hash, public rows and stored instance IDs.""" + database = InMemoryArrowDatabase() + job = _job(_cached(path, InMemoryArrowDatabase()), database) + _ = _run(job, orchestrator) + node = job.nodes["summary"] + rows = node.as_table(columns={"system_tags": True}).to_pylist() + # The id the node's pipeline table keeps each row under: the instance id + # covers the input's tags, system tags, values and source-info tokens. + (pipeline_path,) = [ + path for path in database.list_table_paths(()) if path[-1] == "pdb_v2" + ] + stored = database.get_all_records(tuple(pipeline_path)) + assert stored is not None + ids = sorted( + cast("list[bytes]", stored.column("__pipeline_instance_id").to_pylist()) + ) + return ( + node.content_hash(), + sorted(rows, key=lambda r: (r["subject"], r["session"])), + ids, + ) + + early = node_rows() + assert len(early[2]) == 3 + cache_clock.instant = cache_clock.later + assert node_rows() == early diff --git a/tests/test_core/sources/test_cached_source_conflicting_cache.py b/tests/test_core/sources/test_cached_source_conflicting_cache.py new file mode 100644 index 000000000..5f465660a --- /dev/null +++ b/tests/test_core/sources/test_cached_source_conflicting_cache.py @@ -0,0 +1,690 @@ +"""A cached source refuses a cache holding two contents for one record id (ITL-1396). + +A delivery that changes a cached row is refused before it is written, so one cached +source never writes two contents for one record id. A cache table can still come to hold +them: two writers that both passed the check before either wrote, or a table written by +hand. Such a cache is refused whenever it is read (developer, November 28, 2026), on every +read path, so a cached source never presents two rows for one record id. The same row +stored twice is not a conflict. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.errors import CachedSourceChangedRowError, InputValidationError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource, CachedSource +from tests.test_core.sources.cache_versions import ( + with_custom_provenance, + write_outside_the_rule, +) + +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + +Row = tuple[str, int, float, int] +"""One reading: subject, session, value, count.""" + +ROWS: list[Row] = [("s1", 1, 1.0, 10), ("s1", 2, 2.0, 20), ("s2", 1, 3.0, 30)] + +# Two arrangements of one dataset: the table's column order and the declared tag order. +ARRANGEMENTS: dict[str, dict[str, list[str]]] = { + "as_declared": { + "table": ["subject", "session", "value", "count"], + "tags": ["subject", "session"], + }, + "rearranged": { + "table": ["count", "session", "value", "subject"], + "tags": ["session", "subject"], + }, +} +KEYS = ["subject", "session"] + +CALLS: list[tuple[float, int]] = [] + + +@function_pod(output_keys=("total", "double")) +def summarize(value: float, count: int) -> tuple[float, int]: + """Return ``value + count`` and twice ``count``.""" + CALLS.append((value, count)) + return value + count, 2 * count + + +@pytest.fixture(autouse=True) +def _reset() -> None: + """Clear the recorded pod calls before each test.""" + CALLS.clear() + + +def _source( + rows: list[Row], + arrangement: str = "as_declared", + *, + keyed: bool = True, + extra: bool = False, + custom: dict[str, str] | None = None, +) -> Any: + """Build a synthetic source with keyed or positional record IDs.""" + cells = { + "subject": pa.array([r[0] for r in rows], pa.large_string()), + "session": pa.array([r[1] for r in rows], pa.int64()), + "value": pa.array([r[2] for r in rows], pa.float64()), + "count": pa.array([r[3] for r in rows], pa.int64()), + } + names = ARRANGEMENTS[arrangement]["table"] + kwargs: dict[str, Any] = {"record_id_columns": KEYS} if keyed else {} + table = pa.table({name: cells[name] for name in names}) + if extra: + table = table.append_column("extra", pa.nulls(len(rows), pa.int32())) + source = ArrowTableSource( + table.cast( + pa.schema([f.with_nullable(f.name == "extra") for f in table.schema]) + ), + tag_columns=ARRANGEMENTS[arrangement]["tags"], + tag_only_columns=True, + source_id="readings", + **kwargs, + ) + return with_custom_provenance(source, custom or {}) + + +def _database(store: str, tmp_path: Path, name: str = "cache") -> Any: + """Create the selected test cache backend.""" + if store == "delta": + return DeltaTableDatabase(base_path=str(tmp_path / name)) + return InMemoryArrowDatabase() + + +def _changed(rows: list[Row], *keys: tuple[str, int]) -> list[Row]: + """``rows`` with another value and count under each of ``keys``.""" + return [ + (s, n, v + 0.5, c + 1) if (s, n) in keys else (s, n, v, c) + for s, n, v, c in rows + ] + + +def _conflicting_cache( + cache: Any, + arrangement: str = "as_declared", + *, + keyed: bool = True, + rows: list[Row] = ROWS, + keys: tuple[tuple[str, int], ...] = (("s1", 2), ("s2", 1)), +) -> None: + """Fill ``cache`` with ``rows``, then with other content under ``keys``.""" + first = CachedSource(_source(rows, arrangement, keyed=keyed), cache_database=cache) + _ = first.as_table() + write_outside_the_rule( + _source(_changed(rows, *keys), arrangement, keyed=keyed), cache + ) + + +def _stored(source: CachedSource, cache: Any) -> list[tuple[Any, ...]]: + """Every stored cell of the cache, rows sorted: equal when nothing was written.""" + table = cache.get_all_records( + source.cache_path, record_id_column=CachedSource.HASH_COLUMN_NAME + ) + assert table is not None + names = sorted(table.column_names) + return sorted(tuple(row[name] for name in names) for row in table.to_pylist()) + + +READS: dict[str, Any] = { + "as_table": lambda source: source.as_table(), + "as_table_all_info": lambda source: source.as_table(all_info=True), + "iter_data": lambda source: list(source.iter_data()), + "run": lambda source: source.run(), + "head": lambda source: source.head(), + "head_all_info": lambda source: source.head(2, all_info=True), + "get_all_records": lambda source: source.get_all_records(), +} + + +@pytest.mark.parametrize("read", list(READS)) +@pytest.mark.parametrize("store", ["memory", "delta"]) +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_every_read_of_a_cache_with_two_contents_for_a_record_id_is_refused( + tmp_path: Path, arrangement: str, store: str, read: str +) -> None: + """Refuse all supported reads when storage holds conflicting versions.""" + cache = _database(store, tmp_path) + _conflicting_cache(cache, arrangement) + source = CachedSource(_source(ROWS, arrangement), cache_database=cache) + before = _stored(source, cache) + + with pytest.raises(CachedSourceChangedRowError) as refusal: + READS[read](source) + + message = str(refusal.value) + assert "the cache" in message and "holds" in message + assert "cached_v" not in message and "'arrow_table_v1:readings'" in message + assert "2 record ids" in message + assert '{"subject":"s1","session":2}, {"subject":"s2","session":1}' in message + assert _stored(source, cache) == before + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +@pytest.mark.parametrize("read", ["head", "get_all_records"]) +def test_a_conflicting_cache_uses_its_stored_record_id_column( + arrangement: str, read: str +) -> None: + """Find the conflicting ID using the writer's stored field layout.""" + cache = InMemoryArrowDatabase() + path = ("fixed",) + seed = _source(ROWS, arrangement).cached(cache, cache_path=path) + _ = seed.as_table() + write_outside_the_rule(_source(_changed(ROWS, ("s1", 2)), arrangement), cache, path) + + source = _source(ROWS, arrangement, extra=True).cached(cache, cache_path=path) + assert source.cache_path == seed.cache_path + before = _stored(source, cache) + + with pytest.raises(CachedSourceChangedRowError, match="1 record id"): + READS[read](source) + + assert _stored(source, cache) == before + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_a_changed_delivery_compares_record_ids_across_declared_schemas( + tmp_path: Path, arrangement: str +) -> None: + """Match a live record to its cached ID across source schemas.""" + cache = DeltaTableDatabase(tmp_path) + path = ("fixed",) + seed = _source(ROWS[:1], arrangement).cached(cache, cache_path=path) + _ = seed.as_table() + before = _stored(seed, cache) + source = _source(_changed(ROWS, ("s1", 1)), arrangement, extra=True).cached( + cache, cache_path=path + ) + + with pytest.raises( + CachedSourceChangedRowError, match=r'\{"subject":"s1","session":1\}' + ): + source.as_table() + + assert _stored(seed, cache) == before + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_a_delta_delivery_cannot_alias_the_stored_record_id_as_custom( + tmp_path: Path, arrangement: str +) -> None: + """Refuse a live custom tag that would overwrite the stored generated ID.""" + cache = DeltaTableDatabase(tmp_path, allow_schema_evolution=False) + path = ("fixed",) + original = _source(ROWS[:1], arrangement) + seed = original.cached(cache, cache_path=path) + _ = seed.as_table() + before = _stored(seed, cache) + original_row = original.as_table(columns={"system_tags": True}).to_pylist()[0] + custom = { + name.removeprefix("_tag_"): value + for name, value in original_row.items() + if name.startswith("_tag_") + } + changed_rows = _changed(ROWS[:1], ("s1", 1)) + reader = _source(changed_rows, arrangement, custom=custom).cached( + cache, cache_path=path + ) + + with pytest.raises(CachedSourceChangedRowError, match="the source delivered"): + reader.as_table() + assert _stored(seed, cache) == before + + # A conflict already in storage is also visible through the aliased declaration. + write_outside_the_rule(_source(changed_rows, arrangement), cache, path) + for read in ("head", "get_all_records"): + with pytest.raises(CachedSourceChangedRowError, match="1 record id"): + READS[read](reader) + + +@pytest.mark.parametrize("allow_schema_evolution", [False, True]) +@pytest.mark.parametrize( + "reuse_existing_id", [True, False], ids=["same-id", "other-ids"] +) +def test_a_delta_append_cannot_store_custom_provenance_as_generated_record_ids( + tmp_path: Path, allow_schema_evolution: bool, reuse_existing_id: bool +) -> None: + """Prevent an append from persisting a custom tag as a generated record ID.""" + cache = DeltaTableDatabase(tmp_path, allow_schema_evolution=allow_schema_evolution) + path = ("fixed",) + seed = _source(ROWS[:1]).cached(cache, cache_path=path) + expected = seed.as_table() + before = _stored(seed, cache) + + legacy_rows = ROWS[:1] if reuse_existing_id else [ROWS[2], ("s3", 1, 0.0, 0)] + value = ROWS[1] + for legacy in legacy_rows: + original_tags = _source([legacy]).as_table(columns={"system_tags": True}) + custom = { + name.removeprefix("_tag_"): original_tags[name][0].as_py() + for name in original_tags.column_names + if name.startswith("_tag_") + } + delivery = _source([value], custom=custom).cached(cache, cache_path=path) + + with pytest.raises(InputValidationError, match="custom provenance"): + delivery.as_table() + + assert _stored(seed, cache) == before + value = _changed([value], (value[0], value[1]))[0] + + fresh = _source(ROWS[:1]).cached(cache, cache_path=path) + assert fresh.get_all_records().select(expected.column_names) == expected + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_a_clean_delta_cache_is_readable_after_removing_custom_provenance( + tmp_path: Path, arrangement: str +) -> None: + """Read a clean cache after a declaration drops custom provenance.""" + cache = DeltaTableDatabase(tmp_path) + path = ("fixed",) + custom = { + "record_id::legacy": "other-id", + "source_id::legacy": "arrow_table_v1:readings", + } + seed = _source(ROWS[:1], arrangement, custom=custom).cached(cache, cache_path=path) + _ = seed.as_table() + before = _stored(seed, cache) + expected = seed.get_all_records() + reader = _source(ROWS[:1], arrangement, extra=True).cached(cache, cache_path=path) + + assert "not read yet" in str(reader.head()) + assert reader.get_all_records() == expected + assert _stored(seed, cache) == before + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_the_notebook_preview_shows_the_refusal_and_no_row(arrangement: str) -> None: + """A display hook never raises: the preview shows the error ``head()`` raises.""" + cache = InMemoryArrowDatabase() + _conflicting_cache(cache, arrangement) + source = CachedSource(_source(ROWS, arrangement), cache_database=cache) + + html = source._repr_html_() + + assert "could not read" in html + assert "2 record ids with more than one content" in html + assert " None: + """Stop a job before any pod call when its cached input conflicts.""" + cache = _database(store, tmp_path) + _conflicting_cache(cache, arrangement) + source = CachedSource(_source(ROWS, arrangement), cache_database=cache) + database = InMemoryArrowDatabase() + job = PipelineJob(name="readings_job", database=database) + with job: + summarize.pod(source, label="summary") + + for _ in range(2): + with pytest.raises(CachedSourceChangedRowError, match="the cache"): + job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + + assert CALLS == [] + assert list(database.list_table_paths(())) == [] + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_a_positional_cache_with_two_contents_for_a_position_is_refused( + arrangement: str, +) -> None: + """Refuse a cache storing two payloads for one positional ID.""" + cache = InMemoryArrowDatabase() + _conflicting_cache(cache, arrangement, keyed=False, keys=(("s1", 2),)) + source = CachedSource(_source(ROWS, arrangement, keyed=False), cache_database=cache) + + with pytest.raises(CachedSourceChangedRowError, match="1 record id .*: row_1\\."): + source.as_table() + + +def test_more_than_five_record_ids_are_named_up_to_five_with_the_count() -> None: + """Report all stored conflicts in the count and name the first five IDs.""" + rows: list[Row] = [("s", n, float(n), n) for n in range(8)] + cache = InMemoryArrowDatabase() + _conflicting_cache(cache, rows=rows, keys=tuple(("s", n) for n in range(7))) + source = CachedSource(_source(rows), cache_database=cache) + + with pytest.raises(CachedSourceChangedRowError) as refusal: + source.as_table() + + message = str(refusal.value) + assert "7 record ids" in message and "and 2 more" in message + named = [n for n in range(8) if f'{{"subject":"s","session":{n}}}' in message] + assert named == [0, 1, 2, 3, 4] + + +class _RepeatingDatabase(InMemoryArrowDatabase): + """A store that gives every cached row back twice: identical duplicates.""" + + def get_all_records(self, *args: Any, **kwargs: Any) -> pa.Table | None: + """Repeat an identical cached row in the physical readback.""" + records = super().get_all_records(*args, **kwargs) + return None if records is None else pa.concat_tables([records, records]) + + +def test_the_same_row_stored_twice_is_not_a_conflict() -> None: + """Accept physically repeated rows that share an ID and content hash.""" + cache = _RepeatingDatabase() + source = CachedSource(_source(ROWS), cache_database=cache) + + rows = source.as_table().to_pylist() + + assert len(rows) == 2 * len(ROWS) + assert {(r["subject"], r["session"], r["value"], r["count"]) for r in rows} == set( + ROWS + ) + + +@pytest.mark.parametrize("store", ["memory", "delta"]) +def test_a_delivery_to_such_a_cache_writes_nothing(tmp_path: Path, store: str) -> None: + """The delivery agrees with one of the two contents and brings a new row.""" + cache = _database(store, tmp_path) + _conflicting_cache(cache) + source = CachedSource(_source([*ROWS, ("s3", 1, 4.0, 40)]), cache_database=cache) + before = _stored(source, cache) + + with pytest.raises(CachedSourceChangedRowError, match="the cache"): + source.as_table() + + assert _stored(source, cache) == before + + +@pytest.mark.parametrize("conflict", ["inner", "outer"]) +@pytest.mark.parametrize("store", ["memory", "delta"]) +@pytest.mark.parametrize("read", ["as_table", "iter_data", "head"]) +def test_a_conflict_in_any_nested_cache_refuses_the_read_and_writes_nothing( + tmp_path: Path, read: str, store: str, conflict: str +) -> None: + """Reject a nested cache read when either layer holds conflicting rows.""" + inner_cache = _database(store, tmp_path, "inner") + outer_cache = _database(store, tmp_path, "outer") + _conflicting_cache(inner_cache if conflict == "inner" else outer_cache) + inner = CachedSource(_source(ROWS), cache_database=inner_cache) + outer = CachedSource(inner, cache_database=outer_cache) + other = outer_cache if conflict == "inner" else inner_cache + + # A head asks the wrapped source for its head, so an inner cache refuses it too. + with pytest.raises(CachedSourceChangedRowError, match="the cache"): + READS[read](outer) + + assert ( + other.get_all_records( + inner.cache_path, record_id_column=CachedSource.HASH_COLUMN_NAME + ) + is None + ) + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@pytest.mark.parametrize("conflict", ["inner", "outer"]) +def test_a_job_over_nested_caches_is_refused_for_a_conflict_in_either( + conflict: str, orchestrator: str +) -> None: + """Stop a job for conflicts in either cache layer.""" + inner_cache, outer_cache = InMemoryArrowDatabase(), InMemoryArrowDatabase() + _conflicting_cache(inner_cache if conflict == "inner" else outer_cache) + outer = CachedSource( + CachedSource(_source(ROWS), cache_database=inner_cache), + cache_database=outer_cache, + ) + database = InMemoryArrowDatabase() + job = PipelineJob(name="readings_job", database=database) + with job: + summarize.pod(outer, label="summary") + + with pytest.raises(CachedSourceChangedRowError, match="the cache"): + job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + + assert CALLS == [] + assert list(database.list_table_paths(())) == [] + + +@pytest.mark.parametrize("arrangement", list(ARRANGEMENTS)) +def test_a_source_holding_its_rows_shows_them_until_it_reads_the_cache_again( + arrangement: str, +) -> None: + """A full read and a head agree: both show the held rows, then both refuse.""" + cache = InMemoryArrowDatabase() + source = CachedSource(_source(ROWS, arrangement), cache_database=cache) + held = source.as_table() + write_outside_the_rule(_source(_changed(ROWS, ("s1", 2)), arrangement), cache) + + # The held rows were checked when they were read; the cache is not read again. + assert source.as_table().equals(held) + assert source.head().table.num_rows == len(ROWS) + + source.clear_cache() + with pytest.raises(CachedSourceChangedRowError, match="the cache"): + source.head() + with pytest.raises(CachedSourceChangedRowError, match="the cache"): + source.as_table() + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_another_source_of_the_job_may_write_before_a_refusal_fails_the_run( + orchestrator: str, +) -> None: + """A stated limit (independent review of 76912324): the cached sources of one job + are checked one by one. The refused cache is unchanged and no result of the run is + stored for it; a sibling source that accepted its own delivery has written it.""" + + def other(rows: list[Row]) -> Any: + """Build the separate source that the job may ingest first.""" + table = ( + _source(rows) + .as_table() + .rename_columns({"value": "other_value", "count": "other_count"}) + ) + return ArrowTableSource( + table, + tag_columns=["subject", "session"], + tag_only_columns=True, + record_id_columns=KEYS, + source_id="others", + ) + + accepted_cache, refused_cache = InMemoryArrowDatabase(), InMemoryArrowDatabase() + _ = CachedSource(other(ROWS[:2]), cache_database=accepted_cache).as_table() + _ = CachedSource(_source(ROWS), cache_database=refused_cache).as_table() + accepted = CachedSource(other(ROWS), cache_database=accepted_cache) + refused = CachedSource( + _source(_changed(ROWS, ("s1", 2))), cache_database=refused_cache + ) + before = _stored(refused, refused_cache) + database = InMemoryArrowDatabase() + job = PipelineJob(name="two_sources", database=database) + with job: + summarize.pod(refused, label="summary") + accepted.select_tag_columns(["subject", "session"], label="others") + + with pytest.raises(CachedSourceChangedRowError, match="the source delivered"): + job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + + assert _stored(refused, refused_cache) == before + assert CALLS == [] + assert len(_stored(accepted, accepted_cache)) == len(ROWS) + + +@pytest.mark.parametrize("read", ["head", "get_all_records", "as_table"]) +def test_an_unbound_proxy_refuses_conflicts_with_a_custom_provenance_pair( + tmp_path: Path, read: str +) -> None: + """Detect a stored conflict through an unbound proxy with custom provenance.""" + + def with_custom_pair(value: int) -> ArrowTableSource: + """Add a custom provenance pair alongside the generated ID.""" + table = pa.table({"id": [1], "value": [value]}) + source = ArrowTableSource( + table.cast(pa.schema([f.with_nullable(False) for f in table.schema])), + source_id="proxy", + record_id_columns="id", + tag_columns="id", + tag_only_columns=True, + ) + return with_custom_provenance( + source, + {"record_id::custom": "constant", "source_id::custom": source.source_id}, + ) + + db = DeltaTableDatabase(tmp_path) + source = with_custom_pair(10).cached(db) + assert source.as_table()["value"].to_pylist() == [10] + config = source.to_config() + write_outside_the_rule(with_custom_pair(20), db) + + loaded = CachedSource.from_config(config) + with pytest.raises( + CachedSourceChangedRowError, match=r'1 record id .*: \{"id":1\}' + ): + READS[read](loaded) + + +def test_freshness_refuses_a_conflicted_cache_over_an_unchanged_source() -> None: + """Refuse a cold freshness check on conflicting storage with a stable input.""" + db = InMemoryArrowDatabase() + _conflicting_cache(db) + source = CachedSource(_source(ROWS), cache_database=db) + + with pytest.raises(CachedSourceChangedRowError, match="2 record ids"): + source.check_for_new_data() + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_an_unchanged_job_reuses_held_rows_until_it_reads_a_new_conflict( + orchestrator: str, +) -> None: + """Reuse a held job result until a fresh read discovers a stored conflict.""" + db = InMemoryArrowDatabase() + source = CachedSource(_source(ROWS), cache_database=db) + job = PipelineJob(name="unchanged_readings", database=InMemoryArrowDatabase()) + with job: + summarize.pod(source, label="summary") + job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + assert len(CALLS) == len(ROWS) + write_outside_the_rule(_source(_changed(ROWS, ("s1", 2))), db) + + job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + assert len(CALLS) == len(ROWS) + with pytest.raises(CachedSourceChangedRowError, match="1 record id"): + source.get_all_records() + + +@pytest.mark.parametrize("read", ["head", "get_all_records"]) +def test_a_warm_delta_reader_refuses_conflicts_committed_by_another_handle( + tmp_path: Path, read: str +) -> None: + """Detect conflicting rows committed by a separate Delta writer.""" + observer = DeltaTableDatabase(tmp_path) + writer = DeltaTableDatabase(tmp_path) + _ = CachedSource(_source(ROWS), cache_database=observer).as_table() + source = CachedSource(_source(ROWS), cache_database=observer) + assert source.get_all_records() is not None + write_outside_the_rule(_source(_changed(ROWS, ("s1", 2))), writer) + + with pytest.raises(CachedSourceChangedRowError, match="1 record id"): + READS[read](source) + + +@pytest.mark.parametrize( + "operation", + [ + "head", + "notebook", + "cold-freshness", + "warm-freshness", + "redelivery", + "append", + "refusal", + ], +) +def test_delta_cache_validation_skips_payload_columns( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, operation: str +) -> None: + """Conflict checks avoid reading payloads needed only for full cache reads.""" + from orcapod.databases import delta_lake_databases + + db = DeltaTableDatabase(tmp_path) + _ = CachedSource(_source(ROWS), cache_database=db).as_table() + source = CachedSource(_source(ROWS), cache_database=DeltaTableDatabase(tmp_path)) + if operation == "warm-freshness": + _ = source.as_table() + scans: list[list[str]] = [] + original = delta_lake_databases.delta_to_pyarrow_dataset + + class ScanProbe: + """Record which columns the Delta reader scans.""" + + def __init__(self, dataset: Any) -> None: + """Keep the backing dataset for delegated scans.""" + self.dataset = dataset + + def to_table(self, *args: Any, **kwargs: Any) -> pa.Table: + """Record the columns returned by an Arrow table scan.""" + table = self.dataset.to_table(*args, **kwargs) + scans.append(table.column_names) + return table + + def to_batches(self, *, columns: list[str]) -> Any: + """Record the projection passed to the batch scan.""" + scans.append(columns) + return self.dataset.to_batches(columns=columns) + + def tracked(*args: Any, **kwargs: Any) -> ScanProbe: + return ScanProbe(original(*args, **kwargs)) + + monkeypatch.setattr(delta_lake_databases, "delta_to_pyarrow_dataset", tracked) + if operation == "warm-freshness": + assert not source.check_for_new_data() + assert scans == [] + return + if operation in ("redelivery", "append", "refusal"): + if operation == "refusal": + source = CachedSource(_source(_changed(ROWS, ("s1", 2))), cache_database=db) + with pytest.raises(CachedSourceChangedRowError): + _ = source.as_table() + full_reads = 1 + else: + delivery = [*ROWS, ("s3", 1, 4.0, 40)] if operation == "append" else ROWS + source = CachedSource(_source(delivery), cache_database=db) + assert source.as_table().num_rows == len(delivery) + full_reads = 2 + assert sum("value" in scan for scan in scans) == full_reads + return + if operation == "cold-freshness": + assert not source.check_for_new_data() + elif operation == "notebook": + assert "could not read" not in source._repr_html_() + else: + assert source.head(0).table.num_rows == 0 + (columns,) = scans + (record_id,) = [name for name in columns if name.startswith("_tag_record_id::")] + expected = { + record_id, + DeltaTableDatabase.RECORD_ID_COLUMN, + "__data_context", + } + if operation == "cold-freshness": + expected.add(record_id.replace("_tag_record_id::", "_tag_source_id::")) + assert ( + sum( + bool(set(scan) & {"subject", "session", "value", "count"}) for scan in scans + ) + == 0 + ) + assert set(columns) == expected diff --git a/tests/test_core/sources/test_clean_delta_cache_reads.py b/tests/test_core/sources/test_clean_delta_cache_reads.py new file mode 100644 index 000000000..6ff11bea5 --- /dev/null +++ b/tests/test_core/sources/test_clean_delta_cache_reads.py @@ -0,0 +1,115 @@ +"""Public reads of a clean Delta cache agree with the stacked base.""" + +from pathlib import Path + +import pyarrow as pa +import pytest + +from orcapod.core.streams.view import ViewStatus +from orcapod.databases import DeltaTableDatabase +from orcapod.sources import ArrowTableSource +from orcapod.system_constants import constants +from tests.test_core.sources.cache_versions import with_custom_provenance + + +def _source( + custom: dict[str, str] | None = None, + *, + new_tag: bool = False, + data_tag: bool = False, +) -> ArrowTableSource: + """Make a keyed source with optional custom provenance and a nullable tag.""" + table = pa.table({"id": [1, 2], "session": [1, 1], "value": [10, 20]}) + tag_only = ["id", "session"] + if new_tag: + table = table.append_column("site", pa.array(["lab", None])) + tag_only.append("site") + source = ArrowTableSource( + table, + source_id="readings", + tag_columns=[*tag_only, "value"] if data_tag else tag_only, + tag_only_columns=tag_only, + record_id_columns=["id", "session"], + ) + return with_custom_provenance(source, custom or {}) + + +@pytest.mark.parametrize("read", ["head", "get_all_records"]) +@pytest.mark.parametrize( + "change", ["matching_custom_pair", "added_nullable_tag", "removed_data_tag"] +) +def test_clean_delta_cache_reads_match_the_base( + tmp_path: Path, change: str, read: str +) -> None: + """Preserve the clean Delta cache output and stored rows.""" + database = DeltaTableDatabase(tmp_path) + path = ("fixed",) + if change == "matching_custom_pair": + reader = _source() + tags, _ = reader.keys(columns={"system_tags": True}) + custom = { + name.removeprefix(constants.SYSTEM_TAG_PREFIX): ( + reader.source_id + if name.startswith(constants.SYSTEM_TAG_SOURCE_ID_PREFIX) + else "same-custom-id" + ) + for name in tags + if name.startswith(constants.SYSTEM_TAG_PREFIX) + } + writer = _source(custom) + else: + custom = { + "record_id::legacy": "same-custom-id", + "source_id::legacy": "arrow_table_v1:readings", + } + writer = _source(custom, data_tag=change == "removed_data_tag") + reader = _source(custom, new_tag=change == "added_nullable_tag") + seed = writer.cached(database, cache_path=path) + assert seed.as_table().sort_by("id")["value"].to_pylist() == [10, 20] + expected = seed.get_all_records() + assert expected is not None + reopened = reader.cached(DeltaTableDatabase(tmp_path), cache_path=path) + + if read == "head": + assert reopened.head().status is ViewStatus.NOT_COMPUTED + else: + assert reopened.get_all_records() == expected + + assert seed.get_all_records() == expected + + +def test_a_short_custom_suffix_cannot_impersonate_the_stored_record_id( + tmp_path: Path, +) -> None: + """Keep a clean cache readable when a data-tag becomes data only.""" + custom = { + "record_id::a": "same-custom-id", + "source_id::a": "arrow_table_v1:readings", + } + # This schema makes the reader's old one-character hash guess match "a". + table = pa.table( + {"id": [1, 2], "site": ["lab", "lab"], "value": [10, 20], "count6": [100, 200]} + ) + + def source(*, data_tag: bool) -> ArrowTableSource: + """Vary the declaration while keeping the custom provenance pair.""" + built = ArrowTableSource( + table, + source_id="readings", + tag_columns=["id", "site", "value"] if data_tag else ["id", "site"], + tag_only_columns=["id", "site"], + record_id_columns="id", + ) + return with_custom_provenance(built, custom) + + path = ("fixed",) + writer = source(data_tag=True).cached(DeltaTableDatabase(tmp_path), cache_path=path) + assert writer.as_table().num_rows == 2 + expected = writer.get_all_records() + assert expected is not None + + reader = source(data_tag=False).cached( + DeltaTableDatabase(tmp_path), cache_path=path + ) + assert reader.head().status is ViewStatus.NOT_COMPUTED + assert reader.get_all_records() == expected diff --git a/tests/test_core/sources/test_repeated_dict_keys.py b/tests/test_core/sources/test_repeated_dict_keys.py index 3c72a79d3..b80b61b3f 100644 --- a/tests/test_core/sources/test_repeated_dict_keys.py +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -926,14 +926,26 @@ def test_a_cached_source_refuses_a_stored_row_with_a_repeated_key() -> None: key = cache.HASH_COLUMN_NAME stored = database.get_all_records(cache.cache_path, record_id_column=key) assert stored is not None - legacy = stored.set_column( - stored.schema.get_field_index("d"), - stored.schema.field("d"), - _one_row(["dup", "other", "dup"])["d"], - ).set_column( - stored.schema.get_field_index(key), - stored.schema.field(key), - pa.array([b"legacy-row"], stored.schema.field(key).type), + # Give the malformed row its own position so it violates only the dict rule. + record_id = next( + name for name in stored.column_names if name.startswith("_tag_record_id::") + ) + legacy = ( + stored.set_column( + stored.schema.get_field_index("d"), + stored.schema.field("d"), + _one_row(["dup", "other", "dup"])["d"], + ) + .set_column( + stored.schema.get_field_index(key), + stored.schema.field(key), + pa.array([b"legacy-row"], stored.schema.field(key).type), + ) + .set_column( + stored.schema.get_field_index(record_id), + stored.schema.field(record_id), + pa.array(["row_1"], stored.schema.field(record_id).type), + ) ) database.add_records(cache.cache_path, legacy, record_id_column=key, flush=True) with pytest.raises(RepeatedDictKeyError) as info: diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 156f6f6b0..6ca05f6f2 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -10,6 +10,7 @@ from re import escape from collections.abc import Collection, Iterator from dataclasses import dataclass +from datetime import datetime, timezone from pathlib import Path from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, TypedDict from uuid import UUID @@ -53,6 +54,7 @@ SQLiteTableSource, stream_builder, ) +from orcapod.core.sources.cached_source import SOURCE_RECORDED_AT_COL from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams import ArrowTableStream from orcapod.databases import ( @@ -1690,6 +1692,15 @@ def test_a_raw_arrow_table_stream_preserves_nested_null() -> None: ) +def _with_recorded_at(table: pa.Table) -> pa.Table: + """Add the current cache layout's write timestamp to a hand-built fixture.""" + timestamp = pa.timestamp("us", tz="UTC") + return table.append_column( + pa.field(SOURCE_RECORDED_AT_COL, timestamp, nullable=False), + pa.array([datetime.now(timezone.utc)] * table.num_rows, timestamp), + ) + + def test_cached_source_refuses_an_existing_stored_null_column() -> None: table = _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]) source = ArrowTableSource( @@ -1710,7 +1721,7 @@ def test_cached_source_refuses_an_existing_stored_null_column() -> None: raw = raw.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) database.add_records( cached.cache_path, - with_data_context(raw, source.data_context_key), + with_data_context(_with_recorded_at(raw), source.data_context_key), record_id_column=CachedSource.HASH_COLUMN_NAME, flush=True, ) @@ -1749,7 +1760,7 @@ def test_reopened_cache_refuses_legacy_system_tag_metadata( ) DeltaTableDatabase(tmp_path).add_records( cache.cache_path, - with_data_context(records, source.data_context_key), + with_data_context(_with_recorded_at(records), source.data_context_key), record_id_column=CachedSource.HASH_COLUMN_NAME, flush=True, ) @@ -1903,7 +1914,7 @@ def test_cached_source_presents_stored_token_fields_as_nullable( table = table.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) database.add_records( cache.cache_path, - with_data_context(table, source.data_context_key), + with_data_context(_with_recorded_at(table), source.data_context_key), record_id_column=CachedSource.HASH_COLUMN_NAME, flush=True, ) @@ -2395,7 +2406,7 @@ def test_cached_source_refuses_reserved_stored_user_columns() -> None: raw = raw.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) store.add_records( cached.cache_path, - with_data_context(raw, source.data_context_key), + with_data_context(_with_recorded_at(raw), source.data_context_key), record_id_column=CachedSource.HASH_COLUMN_NAME, flush=True, ) diff --git a/tests/test_databases/test_append_parity.py b/tests/test_databases/test_append_parity.py new file mode 100644 index 000000000..11a138580 --- /dev/null +++ b/tests/test_databases/test_append_parity.py @@ -0,0 +1,359 @@ +"""Exercise database append compatibility and verify reopened rows.""" + +from __future__ import annotations + +import pickle +import sqlite3 +import subprocess +import sys +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from uuid import UUID + +import numpy as np + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +from orcapod.contexts import resolve_context +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, +) +from orcapod.databases.extension_aware_database import ExtensionAwareDatabase +from orcapod.databases.noop_database import NoOpArrowDatabase +from orcapod.databases.sqlite_connector import SQLiteConnector +from orcapod.errors import InputValidationError +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter + +_PATH = ("records",) +_KEY = "key" + + +def _batches(change: str) -> tuple[pa.Table, pa.Table]: + """Make a seed row and a distinct incoming row with the specified change.""" + text_types = { + "string": pa.string(), + "large_string": pa.large_string(), + "string_view": pa.string_view(), + } + if change in text_types: + held_value = pa.field("value", pa.string()) + new_value = pa.field("value", text_types[change]) + held_values, new_values = ["one"], ["two"] + else: + held_value = pa.field( + "value", pa.int64(), nullable=change not in ("nullability", "typed null") + ) + new_value = held_value + held_values, new_values = [1], [2] + if change == "type": + new_value = pa.field("value", pa.float64()) + new_values = [2.5] + elif change in ("nullability", "typed null"): + new_value = held_value.with_nullable(True) + if change == "typed null": + new_values = [None] + elif change == "metadata": + new_value = held_value.with_metadata({b"unit": b"seconds"}) + elif change == "logical identifier": + new_value = held_value.with_metadata( + { + b"ARROW:extension:name": b"example.int", + b"ARROW:extension:metadata": b'{"value_hash":"stored","version":1}', + } + ) + + key = pa.field(_KEY, pa.large_binary()) + other = pa.field("other", pa.int64()) + seed = pa.Table.from_arrays( + [pa.array([b"first"]), pa.array(held_values, held_value.type), pa.array([1])], + schema=pa.schema([key, held_value, other]), + ) + incoming = pa.Table.from_arrays( + [pa.array([b"second"]), pa.array(new_values, new_value.type), pa.array([2])], + schema=pa.schema([key, new_value, other]), + ) + if change == "extra": + incoming = incoming.append_column("extra", pa.array([3])) + elif change == "missing": + incoming = incoming.drop(["other"]) + elif change == "reordered": + incoming = incoming.select(["other", _KEY, "value"]) + return seed, incoming + + +_BACKENDS = [ + "memory", + "extension-memory", + "delta", + "delta-evolution", + "extension-delta", + "connector", + "noop", +] +_MEMORY_BACKENDS = {"memory", "extension-memory"} + + +def _converter() -> UniversalTypeConverter: + """Get the built-in context's converter, including its logical type registry.""" + converter = resolve_context(None).type_converter + assert isinstance(converter, UniversalTypeConverter) + return converter + + +def _open_database(backend: str, path: Path) -> Callable[[], ArrowDatabaseProtocol]: + """Open a fresh reader or a fresh view of the same in-memory store.""" + if backend in _MEMORY_BACKENDS: + memory = InMemoryArrowDatabase() + if backend == "memory": + return memory.at + return ExtensionAwareDatabase(memory, _converter()).at + if backend == "connector": + return lambda: ConnectorArrowDatabase(SQLiteConnector(path / "append.sqlite")) + if backend == "noop": + return NoOpArrowDatabase + if backend == "extension-delta": + return lambda: ExtensionAwareDatabase( + DeltaTableDatabase(path, allow_schema_evolution=False), + _converter(), + ) + return lambda: DeltaTableDatabase( + path, allow_schema_evolution=backend == "delta-evolution" + ) + + +def _assert_same_rows(first: pa.Table | None, second: pa.Table | None) -> None: + """Compare every field including metadata, then compare rows by record ID.""" + if first is None or second is None: + assert first is second + else: + assert first.schema.equals(second.schema, check_metadata=True) + assert first.sort_by(_KEY).equals(second.sort_by(_KEY), check_metadata=True) + + +def _append_error( + database: ArrowDatabaseProtocol, incoming: pa.Table +) -> type[Exception] | None: + """Return the exact exception class observed at the real append.""" + try: + database.add_records(_PATH, incoming, record_id_column=_KEY, flush=True) + except Exception as exc: # noqa: BLE001 + return type(exc) + return None + + +def _append_and_read( + open_database: Callable[[], ArrowDatabaseProtocol], incoming: pa.Table +) -> tuple[type[Exception] | None, pa.Table | None]: + """Check append results and require a refusal to leave the table unchanged.""" + database = open_database() + stored = database.get_all_records(_PATH, record_id_column=_KEY) + append_error = _append_error(database, incoming) + actual = open_database().get_all_records(_PATH, record_id_column=_KEY) + _assert_same_rows(actual, database.get_all_records(_PATH, record_id_column=_KEY)) + if append_error is not None: + _assert_same_rows(stored, actual) + return append_error, actual + + +@pytest.mark.parametrize("backend", _BACKENDS) +@pytest.mark.parametrize("empty", [False, True], ids=["nonempty", "empty"]) +@pytest.mark.parametrize( + "change", + [ + "same", + "extra", + "missing", + "type", + "nullability", + "typed null", + "metadata", + "logical identifier", + "reordered", + "string", + "large_string", + "string_view", + ], +) +def test_append_parity(backend: str, empty: bool, change: str, tmp_path: Path) -> None: + """Check compatibility of layouts, types, metadata and empty appends.""" + open_database = _open_database(backend, tmp_path) + seed, incoming = _batches(change) + if empty: + incoming = incoming.slice(0, 0) + elif change == "typed null": + # Insert a valid row before the invalid NULL to check transaction rollback. + valid = pa.Table.from_pylist( + [{"key": b"valid", "value": 3, "other": 4}], schema=incoming.schema + ) + incoming = pa.concat_tables([valid, incoming]) + + assert _append_error(open_database(), seed) is None + append_error, actual = _append_and_read(open_database, incoming) + + if actual is not None and append_error is None and not empty: + assert set(actual[_KEY].to_pylist()) == {b"first", b"second"} + + if backend == "noop": + assert append_error is None and actual is None + elif empty: + assert append_error is None and actual is not None and actual.num_rows == 1 + elif backend == "connector": + if change == "typed null": + assert append_error is sqlite3.IntegrityError + elif change in {"extra", "missing", "type", "metadata", "logical identifier"}: + assert append_error is ValueError + else: + assert append_error is None and actual is not None and actual.num_rows == 2 + elif backend in _MEMORY_BACKENDS: + if change in {"metadata", "logical identifier"}: + assert append_error is InputValidationError + elif change in { + "extra", + "missing", + "type", + "nullability", + "typed null", + "large_string", + "string_view", + }: + assert append_error is pa.ArrowInvalid + else: + assert append_error is None and actual is not None and actual.num_rows == 2 + else: + if change in {"type", "typed null", "metadata"}: + assert append_error is InputValidationError + else: + assert append_error is None and actual is not None and actual.num_rows == 2 + if backend != "delta-evolution" and change == "nullability": + # Delta's merge accepts the value while retaining the required field. + assert not actual.schema.field("value").nullable + if backend == "delta-evolution" and change == "logical identifier": + assert ( + actual.schema.field("value").metadata + == incoming.schema.field("value").metadata + ) + + +@pytest.mark.parametrize("backend", sorted(_MEMORY_BACKENDS)) +def test_append_promotes_queued_rows(backend: str, tmp_path: Path) -> None: + """Read the stored, queued and incoming rows after an append flushes the queue.""" + open_database = _open_database(backend, tmp_path) + database = open_database() + seed, incoming = _batches("same") + assert _append_error(database, seed) is None + key = seed.schema.field(_KEY) + queued = seed.set_column(0, key, pa.array([b"queued"], type=key.type)) + database.add_records(_PATH, queued, record_id_column=_KEY) + database.add_records( + _PATH, incoming, record_id_column=_KEY, skip_duplicates=True, flush=True + ) + _assert_same_rows( + pa.concat_tables([seed, queued, incoming]), + open_database().get_all_records(_PATH, record_id_column=_KEY), + ) + + +@dataclass +class _Payload: + """An example application value stored through its logical Arrow type.""" + + value: int + + +@pytest.fixture(scope="module", params=["path", "uuid", "user-class", "array"]) +def logical_batches( + request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory +) -> dict[bool, tuple[pa.Table, pa.Table]]: + """Build live logical values and read the same files without their Arrow registry.""" + annotations_and_values = { + "path": (Path, [Path("/a"), Path("/b")]), + "uuid": (UUID, [UUID(int=1), UUID(int=2)]), + "user-class": (_Payload, [_Payload(1), _Payload(2)]), + "array": (np.ndarray, [np.array([1, 2]), np.array([3, 4])]), + } + annotation, values = annotations_and_values[request.param] + converter = _converter() + live = converter.python_dicts_to_arrow_table( + [ + {"key": key, "value": value} + for key, value in zip((b"first", b"second"), values, strict=True) + ], + {"key": bytes, "value": annotation}, + ) + assert isinstance(live.schema.field("value").type, pa.ExtensionType) + paths = tmp_path_factory.mktemp("append-parity") + files = [paths / "first.parquet", paths / "second.parquet"] + live_batches = (live.slice(0, 1), live.slice(1, 1)) + for table, file in zip(live_batches, files, strict=True): + pq.write_table(table, file) + # A fresh PyArrow process has no Orcapod extension registrations. Pickling the + # plain Arrow arrays preserves their extension metadata across the process boundary. + tables = subprocess.check_output( + [ + sys.executable, + "-c", + "import pickle, sys; import pyarrow.parquet as pq; " + "sys.stdout.buffer.write(pickle.dumps(tuple(map(pq.read_table, sys.argv[1:]))))", + *map(str, files), + ] + ) + parquet_batches: tuple[pa.Table, pa.Table] = pickle.loads(tables) + for table in parquet_batches: + field = table.schema.field("value") + assert not isinstance(field.type, pa.ExtensionType) + assert b"ARROW:extension:name" in (field.metadata or {}) + return {False: live_batches, True: parquet_batches} + + +def _with_nullability(table: pa.Table, nullable: bool) -> pa.Table: + """Set only the logical field's nullability, keeping its other attributes.""" + field = table.schema.field("value") + return table.set_column(1, field.with_nullable(nullable), table.column(1)) + + +@pytest.mark.parametrize("backend", _BACKENDS) +@pytest.mark.parametrize("parquet", [False, True], ids=["live", "parquet"]) +@pytest.mark.parametrize( + "held_nullable", [False, True], ids=["held-required", "held-nullable"] +) +@pytest.mark.parametrize( + "incoming_nullable", [False, True], ids=["incoming-required", "incoming-nullable"] +) +def test_logical_append_parity( + backend: str, + parquet: bool, + held_nullable: bool, + incoming_nullable: bool, + logical_batches: dict[bool, tuple[pa.Table, pa.Table]], + tmp_path: Path, +) -> None: + """Compare the represented field types, nullability and metadata after reopening.""" + open_database = _open_database(backend, tmp_path) + seed, incoming = logical_batches[parquet] + seed = _with_nullability(seed, held_nullable) + incoming = _with_nullability(incoming, incoming_nullable) + + database = open_database() + if backend == "connector": + # SQLite does not persist the logical fields in this matrix. + assert _append_error(database, seed) is not None + assert open_database().get_all_records(_PATH, record_id_column=_KEY) is None + return + assert _append_error(database, seed) is None + append_error, actual = _append_and_read(open_database, incoming) + if backend == "noop": + assert append_error is None and actual is None + elif held_nullable == incoming_nullable: + assert append_error is None and actual is not None and actual.num_rows == 2 + if backend.startswith("extension"): + assert isinstance(actual.schema.field("value").type, pa.ExtensionType) + elif backend in _MEMORY_BACKENDS: + assert append_error is pa.ArrowInvalid + else: + assert append_error is None and actual is not None and actual.num_rows == 2 diff --git a/tests/test_databases/test_delta_database_lookup_equivalence.py b/tests/test_databases/test_delta_database_lookup_equivalence.py index 0582152fa..de5dcff6a 100644 --- a/tests/test_databases/test_delta_database_lookup_equivalence.py +++ b/tests/test_databases/test_delta_database_lookup_equivalence.py @@ -12,10 +12,12 @@ from pathlib import Path from typing import Any, cast +import deltalake import pyarrow as pa import pyarrow.compute as pc import pytest +from orcapod.contexts import get_default_context from orcapod.databases import DeltaTableDatabase PATH = ("results", "v1") @@ -73,6 +75,161 @@ def _assert_same(actual: pa.Table | None, expected: pa.Table | None) -> None: assert _sorted(actual) == _sorted(expected) +def test_projected_lookup_omits_unqueried_partition_columns(tmp_path: Path) -> None: + """The file partition still has a type when the projection omits it.""" + deltalake.write_deltalake( + tmp_path.joinpath(*PATH), + pa.table( + { + "__record_id": [b"a", b"b", b"c"], + "key": [1, 1, 2], + "value": ["a", "b", "c"], + "region": ["west", None, "east"], + "year": [2025, 2026, 2026], + } + ), + partition_by=["region", "year"], + ) + db = DeltaTableDatabase(tmp_path) + predicate = {"key": 1} + expected = _expected(db, predicate) + assert expected is not None and expected.num_rows == 2 + actual = db.get_records_with_column_value( + PATH, predicate, record_id_column="rid", columns=["value"] + ) + _assert_same(actual, expected.select(["value", "rid"])) + + +@pytest.mark.parametrize( + ("predicate", "selected"), + [ + ({"pending_only": "added"}, "stored_only"), + ({"stored_only": "held"}, "pending_only"), + ({"group": "match"}, "pending_only"), + ({"group": "pending"}, "stored_only"), + ({"key": 200}, "group"), + ], + ids=[ + "pending-predicate", + "stored-predicate", + "pending-column", + "omitted-column", + "unsigned-predicate", + ], +) +def test_projected_lookup_matches_full_schema_with_pending_rows( + tmp_path: Path, predicate: dict[str, Any], selected: str +) -> None: + """Projection retains typed nulls across schema evolution and restores predicate types.""" + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + pa.table( + { + "rid": [b"a"], + "key": pa.array([200], pa.uint8()), + "group": ["match"], + "stored_only": ["held"], + } + ), + record_id_column="rid", + ) + db.flush() + db.add_records( + PATH, + pa.table( + { + "rid": [b"b", b"c"], + "key": pa.array([100, 101], pa.uint8()), + "group": ["pending", "match"], + "pending_only": ["added", "also added"], + } + ), + record_id_column="rid", + ) + expected = _expected(db, predicate) + assert expected is not None + actual = db.get_records_with_column_value( + PATH, predicate, record_id_column="rid", columns=[selected] + ) + _assert_same(actual, expected.select([selected, "rid"])) + + +@pytest.mark.parametrize("columns", [("maybe", "score"), ("score", "maybe")]) +@pytest.mark.parametrize( + "predicates", + [(("key", b"key-3"), ("group", "match")), (("group", "match"), ("key", b"key-3"))], +) +def test_projected_lookup_preserves_column_order_and_matches_both_predicates( + tmp_path: Path, columns: tuple[str, str], predicates: tuple[tuple[str, Any], ...] +) -> None: + """Both predicate orders match the same committed and pending rows.""" + db = DeltaTableDatabase(tmp_path) + db.add_record(PATH, b"committed", _row(3, "match", 10)) + db.add_record(PATH, b"wrong-group", _row(3, "other", 11)) + db.flush() + db.add_record(PATH, b"pending", _row(10, "match", 20)) + db.add_record(PATH, b"wrong-key", _row(4, "match", 21)) + + expected = _expected(db, dict(predicates)) + assert expected is not None + assert set(expected["rid"].to_pylist()) == {b"committed", b"pending"} + actual = db.get_records_with_column_value( + PATH, predicates, record_id_column="rid", columns=columns + ) + _assert_same(actual, expected.select([*columns, "rid"])) + + +@pytest.mark.parametrize("kind", ["scalar", "list", "struct", "extension"]) +def test_projected_pending_only_match_has_the_flushed_schema( + tmp_path: Path, kind: str +) -> None: + """Only the pending row matches, but the committed schema still applies.""" + if kind == "scalar": + stored, pending = pa.array([10]), pa.nulls(1) + elif kind == "list": + stored = pa.array([[{"x": 10, "y": 20}]]) + pending = pa.array([[{"x": 30}]]) + elif kind == "struct": + stored = pa.array([{"x": 10, "y": 20}]) + pending = pa.array([{"x": 30}]) + else: + converter = get_default_context().type_converter + path_type = converter.python_type_to_arrow_type(Path) + assert isinstance(path_type, pa.ExtensionType) + stored = pa.ExtensionArray.from_storage( + path_type, pa.array(["/first"], type=path_type.storage_type) + ) + pending = pa.ExtensionArray.from_storage( + path_type, pa.array(["/second"], type=path_type.storage_type) + ) + + db = DeltaTableDatabase(tmp_path) + for record_id, key, values in [(b"a", 100, stored), (b"b", 200, pending)]: + row = pa.table({"key": [key], "unselected": ["payload"]}).append_column( + pa.field( + "out", + values.type, + nullable=kind != "extension", + metadata={"unit": "sample"}, + ), + values, + ) + db.add_record(PATH, record_id, row) + if key == 100: + db.flush() + + before = db.get_records_with_column_value( + PATH, {"key": 200}, record_id_column="rid", columns=["out"] + ) + db.flush() + after = db.get_records_with_column_value( + PATH, {"key": 200}, record_id_column="rid", columns=["out"] + ) + assert before is not None and after is not None and after.num_rows == 1 + assert before.equals(after, check_metadata=True) + + LOOKUPS: list[dict[str, Any]] = [ {"key": b"key-3"}, # indexed binary {"group": "g1"}, # indexed string diff --git a/tests/test_pipeline/test_function_node_held_order.py b/tests/test_pipeline/test_function_node_held_order.py index af5d20d9b..cb585b467 100644 --- a/tests/test_pipeline/test_function_node_held_order.py +++ b/tests/test_pipeline/test_function_node_held_order.py @@ -24,9 +24,11 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.errors import CachedSourceChangedRowError from orcapod.operators import Batch, GroupBy from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.sources import CachedSource, DictSource +from tests.test_core.sources.cache_versions import write_outside_the_rule @function_pod(output_keys=["y", "w"]) @@ -270,11 +272,9 @@ def test_async_held_rows_are_the_sync_rows_as_a_set( @pytest.mark.parametrize("mode", ["sync", "async"]) def test_tied_group_members_follow_the_held_order(mode: str) -> None: """Two cached versions of one record (identical system tags, so GroupBy's member - order ties) with only the newer result stored beforehand. Synchronous: GroupBy - over the held rows gives the members in the order the whole job's GroupBy - received them (the held order). Asynchronous (no order promised, ITL-1437): the - held rows and the group's members are the same set of rows as the synchronous - run's.""" + order would tie) are refused when the cache is read (ITL-1396): no run holds two + rows with one record id, so no group has tied members from a cache. Nothing is + computed for the refused run.""" orchestrator = ORCHESTRATORS[mode] store, cache = InMemoryArrowDatabase(), InMemoryArrowDatabase() old = ROWS[0] @@ -283,25 +283,20 @@ def test_tied_group_members_follow_the_held_order(mode: str) -> None: CachedSource( _source([old], tags), cache_database=cache, cache_path=("joint",) ).as_table() + write_outside_the_rule(_source([new], tags), cache, ("joint",)) versions = CachedSource( _source([new], tags), cache_database=cache, cache_path=("joint",) ) _job(store, [new], tags).run(orchestrator=orchestrator()) job = _job(store, [new], tags) job.bind(sources={"input": versions}) - job.run(orchestrator=orchestrator()) - node = job.nodes["f"] - held = [(d.as_dict()["y"], d.as_dict()["w"]) for _, d in node.iter_data()] - versions_rows = [(10, -old["z"]), (90, -5)] # the cache's order: old first - groups = job.nodes["GroupBy"].as_table().to_pylist() - members = [list(zip(g["y"], g["w"], strict=True)) for g in groups] - if mode == "sync": - assert held == versions_rows - assert members == [held] - assert GroupBy(["g"])(node).as_table().to_pylist() == groups - else: - assert sorted(held) == sorted(versions_rows) - assert len(members) == 1 and sorted(members[0]) == sorted(versions_rows) + with pytest.raises( + CachedSourceChangedRowError, + match="holds 1 record id with more than one content", + ): + job.run(orchestrator=orchestrator()) + assert list(job.nodes["f"].iter_data()) == [] + assert job.nodes["GroupBy"].as_table().num_rows == 0 def test_async_held_order_is_the_order_the_output_took_the_rows() -> None: diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index 504555197..b1d9c8908 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -29,9 +29,11 @@ from orcapod.core.data_function import PythonDataFunction from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.errors import InputValidationError, ProvenanceInconsistencyError -from orcapod.protocols.core_protocols import DataFunctionProtocol -from orcapod.types import Schema +from orcapod.errors import ( + CachedSourceChangedRowError, + InputValidationError, + ProvenanceInconsistencyError, +) from orcapod.operators import ( Batch, DropTagColumns, @@ -43,8 +45,19 @@ SelectDataColumns, SemiJoin, ) +from orcapod.protocols.core_protocols import DataFunctionProtocol from orcapod.sources import ArrowTableSource, CachedSource, DictSource from orcapod.system_constants import constants +from orcapod.types import Schema +from tests.test_core.sources.cache_versions import write_outside_the_rule + +# A cache holding two contents for one record id is refused when it is read (ITL-1396, +# developer, November 28, 2026). The tests below that build one used to check how a +# trace treats several held versions of one record; no run reaches that state now, so +# each asserts the refusal for its own shape of cache and pipeline. +TWO_VERSIONS_REFUSED = ( + "the cache at .* holds 1 record id with more than one content: row_0" +) pytestmark = pytest.mark.filterwarnings("ignore::Warning") @@ -154,6 +167,7 @@ def test_merge_join_of_inputs_with_equal_pipeline_hashes() -> None: def test_two_cached_versions_of_one_record(tmp_path: Path) -> None: + """A Delta cache holding two data versions of one record refuses the run.""" cache = DeltaTableDatabase(tmp_path / "cache") first = DictSource( [{"k": "a", "g": "1", "x": 1, "y": 0}], @@ -168,18 +182,14 @@ def test_two_cached_versions_of_one_record(tmp_path: Path) -> None: tag_only_columns=True, source_id="v", ) + write_outside_the_rule(second, cache, ("shared",)) cached = CachedSource(second, cache_database=cache, cache_path=("shared",)) job = PipelineJob(name="v", database=InMemoryArrowDatabase()) with job: SelectDataColumns(["x"])(cached) - job.run() - node = job.nodes["SelectDataColumns"] - held = sorted(r["x"] for r in node.as_table().to_pylist()) - assert held == [1, 2] # both versions are held, so both are tested - for x in held: - trace = node.trace({"k": "a", "g": "1", "x": x}, "x") - # The held version, never the other one. - assert [c.value for c in trace.source_cells()] == [x] + with pytest.raises(CachedSourceChangedRowError, match=TWO_VERSIONS_REFUSED): + job.run() + assert job.nodes["SelectDataColumns"].as_table().num_rows == 0 def test_a_value_the_held_rows_do_not_hold_is_refused() -> None: @@ -557,6 +567,7 @@ def rows_dropped_text(self, *args: Any, **kwargs: Any) -> Any: def test_two_versions_of_one_record_are_both_source_cells(tmp_path: Path) -> None: + """Two versions of one record under a GroupBy: refused, so no group holds both.""" cache = DeltaTableDatabase(tmp_path / "cache") first = DictSource( [{"k": "a", "g": "1", "x": 1, "y": 0}], @@ -571,14 +582,14 @@ def test_two_versions_of_one_record_are_both_source_cells(tmp_path: Path) -> Non tag_only_columns=True, source_id="v", ) + write_outside_the_rule(second, cache, ("shared",)) cached = CachedSource(second, cache_database=cache, cache_path=("shared",)) job = PipelineJob(name="vv", database=InMemoryArrowDatabase()) with job: GroupBy(["g"])(SelectDataColumns(["x"])(cached)) - job.run() - trace = job.nodes["GroupBy"].trace({"g": "1"}, "x") - assert sorted(trace.root.value) == [1, 2] - assert sorted(c.value for c in trace.source_cells()) == [1, 2] + with pytest.raises(CachedSourceChangedRowError, match=TWO_VERSIONS_REFUSED): + job.run() + assert job.nodes["GroupBy"].as_table().num_rows == 0 def test_a_collapsed_edge_over_merged_paths_is_highlighted() -> None: @@ -755,6 +766,7 @@ def test_two_inputs_carrying_one_id_are_told_apart_by_position( def test_date_versions_of_one_record_are_both_source_cells(tmp_path: Path) -> None: + """Two versions of one record that differ in a date value: refused all the same.""" from datetime import date cache = DeltaTableDatabase(tmp_path / "cache") @@ -771,16 +783,14 @@ def test_date_versions_of_one_record_are_both_source_cells(tmp_path: Path) -> No tag_only_columns=True, source_id="v", ) + write_outside_the_rule(second, cache, ("shared",)) cached = CachedSource(second, cache_database=cache, cache_path=("shared",)) job = PipelineJob(name="dates", database=InMemoryArrowDatabase()) with job: GroupBy(["g"])(SelectDataColumns(["d"])(cached)) - job.run() - trace = job.nodes["GroupBy"].trace({"g": "1"}, "d") - assert sorted(c.value for c in trace.source_cells()) == [ - date(2025, 1, 1), - date(2025, 1, 2), - ] + with pytest.raises(CachedSourceChangedRowError, match=TWO_VERSIONS_REFUSED): + job.run() + assert job.nodes["GroupBy"].as_table().num_rows == 0 def test_a_source_output_schema_is_not_called_through_a_schema_prediction() -> None: @@ -1484,7 +1494,7 @@ def test_an_input_row_must_keep_the_tags_the_step_keeps( mode: str, tmp_path: Path ) -> None: """A cache holding two versions of one record that differ only in a tag (equal data - and tokens): the k='new' output row comes from the k='new' input row.""" + and tokens) is refused: a tag is part of a row's content.""" cache = InMemoryArrowDatabase() def data(key: str) -> DictSource: @@ -1496,20 +1506,13 @@ def data(key: str) -> DictSource: ) CachedSource(data("old"), cache_database=cache, cache_path=("shared",)).as_table() + write_outside_the_rule(data("new"), cache, ("shared",)) current = CachedSource(data("new"), cache_database=cache, cache_path=("shared",)) job = PipelineJob(name=f"tagged{mode}", database=InMemoryArrowDatabase()) with job: SelectDataColumns(["x"])(SelectDataColumns(["x", "y"])(current)) - run(job, mode) - target = next( - n - for n in job.nodes.values() - if n.label.startswith("SelectDataColumns") - and n.upstreams[0].label.startswith("SelectDataColumns") - ) - trace = target.trace({"k": "new", "i": 0}, "x") - (step,) = trace.root.inputs - assert dict(step.tags)["k"] == "new" + with pytest.raises(CachedSourceChangedRowError, match=TWO_VERSIONS_REFUSED): + run(job, mode) # --------------------------------------------------------------------------- @@ -2074,8 +2077,8 @@ def test_a_semi_join_right_record_is_explained_by_row_flow_alone(mode: str) -> N def test_every_held_version_of_a_record_gets_its_reason( mode: str, first: str, second: str ) -> None: - """A cache holds two versions of s's row_0; b matches only old, c only new. Both - versions' reasons are given, in one order whichever was cached first.""" + """A cache holds two versions of s's row_0; b matches only old, c only new. The + run is refused whichever version was cached first, so no reason is asked for.""" cache = InMemoryArrowDatabase() def data(key: str) -> DictSource: @@ -2087,6 +2090,7 @@ def data(key: str) -> DictSource: ) CachedSource(data(first), cache_database=cache, cache_path=("shared",)).as_table() + write_outside_the_rule(data(second), cache, ("shared",)) a = CachedSource(data(second), cache_database=cache, cache_path=("shared",)) b = DictSource( [{"k": "old", "y": 2}], tag_columns=["k"], tag_only_columns=True, source_id="b" @@ -2097,12 +2101,8 @@ def data(key: str) -> DictSource: job = PipelineJob(name=f"versions{mode}{first}", database=InMemoryArrowDatabase()) with job: Join()(SelectDataColumns(["x"])(a), b, c) - run(job, mode) - answer = job.nodes["Join"].why_missing("s", "row_0") - assert answer.missing - assert answer.because == ( - "no row with k='new' in 'b' (reads b); no row with k='old' in 'c' (reads c)" - ) + with pytest.raises(CachedSourceChangedRowError, match=TWO_VERSIONS_REFUSED): + run(job, mode) @function_pod(output_keys="length") @@ -3265,36 +3265,34 @@ def test_a_trace_keeps_the_selector_it_answered() -> None: def test_batches_of_two_cached_versions_of_one_record( tmp_path: Path, mode: str ) -> None: - """Batch(batch_size=1) over a cache holding two versions of one record: both - batches fold to one system-tag key; each is told apart by its members' values.""" + """Batch(batch_size=1) over a cache holding two versions of one record: refused, + so no two batches fold to one system-tag key.""" from orcapod.operators import Batch cache = DeltaTableDatabase(tmp_path / "cache") - def version(x: int) -> CachedSource: - return CachedSource( - DictSource( - [{"k": "a", "g": "1", "x": x, "y": 0}], - tag_columns=["k", "g"], - tag_only_columns=True, - source_id="v", - ), - cache_database=cache, - cache_path=("shared",), + def data(x: int) -> DictSource: + """Build a row at the same position with the selected payload.""" + return DictSource( + [{"k": "a", "g": "1", "x": x, "y": 0}], + tag_columns=["k", "g"], + tag_only_columns=True, + source_id="v", ) + def version(x: int) -> CachedSource: + """Wrap the delivery in the shared cache used by the job.""" + return CachedSource(data(x), cache_database=cache, cache_path=("shared",)) + version(1).as_table() # the first version is cached + write_outside_the_rule(data(2), cache, ("shared",)) cached = version(2) job = PipelineJob(name=f"vb{mode}", database=InMemoryArrowDatabase()) with job: Batch(batch_size=1)(SelectDataColumns(["x"])(cached)) - run(job, mode) - node = job.nodes["Batch"] - held = sorted(r["x"] for r in node.as_table().to_pylist()) - assert held == [[1], [2]] - for x in held: - trace = node.trace({"x": x}, "x") - assert [c.value for c in trace.source_cells()] == x + with pytest.raises(CachedSourceChangedRowError, match=TWO_VERSIONS_REFUSED): + run(job, mode) + assert job.nodes["Batch"].as_table().num_rows == 0 @pytest.mark.parametrize("keys", [("k", "g"), ("g", "k")]) diff --git a/tests/test_pipeline/test_stale_outputs.py b/tests/test_pipeline/test_stale_outputs.py index d7fdc5b56..95329055e 100644 --- a/tests/test_pipeline/test_stale_outputs.py +++ b/tests/test_pipeline/test_stale_outputs.py @@ -431,16 +431,45 @@ def test_cached_head_after_rebind_discards_warm_view(run_async: bool) -> None: cached = CachedSource(stored, InMemoryArrowDatabase()) assert cached.as_table()["value"].to_pylist() == [12] assert cached.head().table["value"].to_pylist() == [12] + held = cached._cached_stream + bindings = cached._source_bindings + active_path = cached._active_cache_path + assert held is not None + assert active_path is not None job.bind(sources={"input": b}) _run(job, run_async) _ = stored.last_modified assert cached.head().table["value"].to_pylist() == [] + assert cached._cached_stream is held + assert cached._source_bindings is bindings + assert cached._active_cache_path == active_path + assert active_path not in cached._previous_cache_paths assert cached.as_table()["value"].to_pylist() == [112] assert cached.head().table["value"].to_pylist() == [112] +def test_cold_cached_head_leaves_an_unused_fixed_path_available() -> None: + """Leave an empty fixed cache path available after a preview and rebind.""" + _, job, _, b, _, _ = _job(as_function=True) + job.run() + origin = job.nodes["step"] + assert isinstance(origin, FunctionJobNode) + database = InMemoryArrowDatabase() + cached = CachedSource(origin.as_source(), database, cache_path=("fixed",)) + + assert cached.head().table.num_rows == 0 + assert not database.table_exists(cached.cache_path) + + job.bind(sources={"input": b}) + job.run() + assert cached.as_table()["value"].to_pylist() == [112] + stored = database.get_all_records(cached.cache_path) + assert stored is not None + assert stored["value"].to_pylist() == [112] + + @pytest.mark.parametrize("load_only", [False, True]) @pytest.mark.parametrize("kind", ["function", "operator", "side_effect"]) def test_rejected_stale_input_clears_held_rows(kind: str, load_only: bool) -> None: