From e4065e1406460e201c5a994084eb5714c31895d0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 01:12:35 -0800 Subject: [PATCH 01/15] docs(dev): source identity, implementation versions and exact stand-ins (ITL-1425) Co-Authored-By: Claude Opus 5.5 --- .../itl-1425-source-identity-and-stand-in.md | 591 ++++++++++++++++++ .../scripts/__init__.py | 0 .../scripts/_fixtures.py | 133 ++++ .../scripts/cached_source_today.py | 81 +++ .../scripts/golden_moves.py | 196 ++++++ .../scripts/identity_structures.py | 155 +++++ .../scripts/identity_today.py | 133 ++++ .../scripts/ledger_prototype.py | 104 +++ .../scripts/row_hash_cost.py | 137 ++++ .../scripts/stand_in_explicit_kind.py | 97 +++ .../scripts/stand_in_job.py | 118 ++++ .../scripts/types_positions_changes.py | 151 +++++ 12 files changed, 1896 insertions(+) create mode 100644 docs/dev/specs/itl-1425-source-identity-and-stand-in.md create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/__init__.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/_fixtures.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/cached_source_today.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/golden_moves.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/identity_structures.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/identity_today.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/ledger_prototype.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/row_hash_cost.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/stand_in_explicit_kind.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/stand_in_job.py create mode 100644 docs/dev/specs/itl-1425-source-identity/scripts/types_positions_changes.py diff --git a/docs/dev/specs/itl-1425-source-identity-and-stand-in.md b/docs/dev/specs/itl-1425-source-identity-and-stand-in.md new file mode 100644 index 000000000..3768c41a6 --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity-and-stand-in.md @@ -0,0 +1,591 @@ +# Source identity, implementation versions and exact stand-ins (ITL-1425) + +A decision document. Nothing is implemented. Every statement about today's behaviour is +measured by a script in [`itl-1425-source-identity/scripts/`](itl-1425-source-identity/scripts/), +run on `main` at `8ee6c6d4` (identity code unchanged at `83c54764`) with the public API, from +that folder: `uv run python -m scripts.`. Synthetic data only. A design that is not +implemented is simulated by patching the library inside the script's own process; nothing +under `src/` changes. + +**The developer's direction (2026-11-23), to be confirmed with the moved golden list:** +every source id carries, explicitly and in one fixed place, the kind and implementation +version that read the data: `_v:` (`delta_v1:units`). Orcapod always adds +that part, to a given id as to a default. The record id never depends on the source id. A +source stands in for another, also of another kind or another version of the same kind, by +an explicit operation that keeps the name and swaps only the kind part, after the rows are +verified equal (ledger row hashes). Section 3 works this design out; section 4 compares the +other alternatives with it. + +| Script | What it measures | +|---|---| +| `identity_today` | content hash, pipeline hash, system tags, tokens, record ids and default ids of six kinds holding the same rows; record ids under several source ids | +| `identity_structures` | `identity_structure()` of every kind that can be built here; saved and loaded slots | +| `stand_in_job` | one kind in place of another in a job: bind, and a fresh job over one database; `--without-class-name` runs it under alternative C | +| `stand_in_explicit_kind` | the developer's design simulated: ids, tokens and a job with and without an explicit stand-in | +| `cached_source_today` | what `CachedSource` stores, where, and when it reads its source | +| `types_positions_changes` | inferred CSV types, a narrower Arrow type, positional record ids, a silent reader change | +| `ledger_prototype` | the ledger prototyped outside the library: stand-ins, types, a reader change, positions | +| `row_hash_cost` | cost of hashing every row (tutorial dataset, 1M rows) | +| `golden_moves` | which golden entries each design moves (lists in `golden-moves-.txt`) | + +## 0. The questions + +1. Can a source say which version of its kind's implementation read it, for example in + its source id? (Today: no.) +2. What are the alternatives, with their pros, cons and implications? +3. Requirement: one source can stand in **exactly** for another, also across kinds (a + CSV export in place of a database table that was migrated away). +4. Idea: make source caching a **record-keeping ledger** (per record: source id, record id, + the hash of the whole row, implementation columns) instead of a full cache. + +## 1. Today, measured + +### 1.1 What a source's identity is made of + +The same three rows (`subject` key, `weight: double`, `count: int64`) as six kinds, each +with the given `source_id="subjects"` and `record_id_columns=["subject"]` +(`identity_today`, `identity_structures`): + +| Kind | `identity_structure()` (content hash input) | Pipeline hash input | +|---|---|---| +| `ArrowTableSource`, `DictSource`, `ListSource`, `DataFrameSource`, `CSVSource`, `DeltaTableSource`, `SQLiteTableSource` (and, by code, `PostgreSQLTableSource`, `DBTableSource`) | `(class name, (tag schema hash, data schema hash), source_id, key columns)` | `(tag schema hash, data schema hash)` | +| `SpiralDBTableSource` (code; needs a server) | the root form, then `("tags_as_data", sorted mapping)` when given; a restriction adds nothing (`_restriction_identity` returns `None`) | the same | +| `CachedSource` | its inner source's structure (wrapping is invisible) | the inner's | +| `DerivedSource`, plain (`node.as_source()`) | `(origin node's content hash,)`: no class name, no source id, no schema | the origin's schema | +| `DerivedSource`, `tags_as_data` | root form with class name `DerivedSource`, then the sorted mapping | schema | +| `PollingSource` (provisional) | `(impl.identity(), sorted tag columns, key columns)`: **no source id and no schema**; a name only if the implementer puts one in `identity()` | schema | +| `SourceProxy` (code) | the saved content hash, as text | the saved pipeline hash | + +Measured across the six kinds holding the same rows under the same id and key: + +| Compared with `ArrowTableSource` | csv | delta_table | sqlite_table | dict | data_frame | +|---|---|---|---|---|---| +| content hash | differs | differs | differs | differs | differs | +| content hash input without the class name | equal | equal | equal | equal | equal | +| pipeline hash, Arrow schemas | equal | equal | equal | equal | equal | +| system-tag column names and values, source-info tokens, the whole table | equal | equal | equal | equal | equal | + +A source-info token is `subjects::{"subject":"s1"}::weight` for every kind; the system-tag +columns are `_tag_source_id::` (value `subjects`) and +`_tag_record_id::` (value `{"subject":"s1"}`). + +### 1.2 Where the kind enters a datum's identity today + +| Place | Kind in it? | Forced by Orcapod? | +|---|---|---| +| Source content hash (`RootSource.identity_structure`) | the class name | **yes**: no argument removes it | +| Everything downstream of it: node content hashes, `__node_content_hash` in stored pipeline rows, the `instance:` path component of a content-scoped table, a `CachedSource`'s table path, a plain `DerivedSource`'s default id (`derived:semantic_v1:`) | the class name, through the hash | **yes**, transitively | +| Default source ids (`csv:`, `sqlite_table::main.`, `arrow_table:arrow_v1:`, ...) | the kind | no: a given `source_id` replaces it, used exactly as given | +| Record ids (`row_`, key JSON) | no | - | +| Source-info tokens, system-tag column names | no (only the source id and the schema hash) | - | +| Pipeline hash | no | - | +| Function result memo (input data hash) | no | - | +| Saved job config (`source_type`) | the kind, to rebuild the source | not identity | + +So the **class name in the source content hash is the one place that forces the kind into +a datum's identity**; everything else that carries the kind is a default's choice. + +Unevenness to settle with any rule: `PollingSource` leaves out the source id and the schema +(a given `source_id` changes no hash: measured, `identity_structures`), and a plain +`DerivedSource` is named by its origin's hash only. + +### 1.3 Record ids do not depend on the source id + +`identity_today`: the same table under three given source ids (`subjects`, +`csv_v1:subjects`, `something_else`), keyed and positional, and the six kinds: + +| | Record ids | Token of row 0 (`weight`) | +|---|---|---| +| keyed, any source id | `{"subject":"s1"}`, `{"subject":"s2"}`, `{"subject":"s3"}` | `::{"subject":"s1"}::weight` | +| positional, any source id | `row_0`, `row_1`, `row_2` | `::row_0::weight` | +| six kinds, keyed | equal | equal under one source id | + +A record id is the row identifier only (ITL-1154: `row_` or the key JSON); the source id +enters a token, `::::`, and the source-id system tag, never the +record id. The developer's design needs no change here. + +### 1.4 One kind in place of another in a job + +`stand_in_job`: a function pod over a slot; the `ArrowTableSource` first, then each other +kind (same rows, same id and key). + +| | Bind into one job (`job.bind`) | A fresh job per kind, one database | +|---|---|---| +| bind accepted | yes, every kind | - | +| function calls after the first kind | 0 (results memoized by input data hash) | 0 | +| output, system tags and tokens included | identical | identical | +| node content hash | **unchanged** (see the bug below) | **differs per kind** | +| stored pipeline rows (`pdb_v1`) | 3 rows, 1 `__node_content_hash` | **12 rows, 4 `__node_content_hash` values** (one set per kind) | +| `node.as_source()` | - | 3 rows each (each kind sees only its own set) | + +Under alternative C (`stand_in_job --without-class-name`, section 4), both columns give one node +content hash and 3 stored pipeline rows for all six kinds: an exact stand-in. + +**Pre-existing bug found** (reported to the coordinator, not fixed here): after +`job.bind(...)` the bound slot's content hash changes, but a downstream function node keeps +the content hash it computed before the bind (`_content_hash_cache` is not invalidated +downstream). Its new rows are stored under the previous source's `__node_content_hash`. + +### 1.5 What `bind` accepts (ITL-1112, ITL-640) + +`SourceNodeBase.validate`: per column the declared Python type (or `T` into `T | None`) +and the Arrow type compared by `hash_schema`, with only a top-level non-null column +accepted where the slot is nullable; exactly one source-id and one record-id system-tag +column. `_DeclaredForm` presents the source's rows as the slot's declared schema. +Measured (`types_positions_changes`): + +| Stand-in | Accepted? | Recomputes? | +|---|---|---| +| CSV with inferred types (non-null columns) bound into a nullable slot | yes | 0 calls (rows given in the declared form) | +| the same CSV in a fresh job | - | **3 of 3**: another pipeline hash, and the input data hash includes nullability | +| Delta table with `count: int32` into an `int64` slot | refused, `SourceSpecMismatchError` | - | + +### 1.6 `CachedSource` today (`cached_source_today`) + +| Question | Answer | +|---|---| +| Path | `/source/node:/sdb_v1`: one table per kind for the same rows (4 tables for 4 kinds) | +| Columns | `_record_hash`, the user columns, both system-tag columns, the source-info columns, `__data_context`: a full copy | +| Row hash | `arrow_v1` of the one-row table **including the system tags**, so it holds the source id (the same rows under another id share no hash) | +| When the inner source is read | on the first read in a process; then again only when `check_for_new_data()` sees its modified time move | +| Semantics | cumulative union of every row ever read | + +### 1.7 Two silent cases + +| Case | Content / pipeline hash | What a job does | Signal | +|---|---|---|---| +| Positional record ids, the same rows in another order | unchanged | 0 calls; `s1` becomes `row_2` (tokens change) | none | +| A reader change: one value read differently, same id and key | unchanged | 1 call; the stored view holds both values for `s2` (4 rows for 3 records) | **none** | + +The second is R2's failure today: an implementation change that changes what a +row reads as is silent. + +### 1.8 Cost of hashing every row (`row_hash_cost`) + +Apple machine, 18 CPUs, load average about 4.6 during the runs, one process. + +| Input | Rows | Build and read the source | Hash the table once | Hash every row (one `hash_table` per one-row slice, as `CachedSource` does) | +|---|---|---|---|---| +| tutorial spikes (every spikes file stacked, CSV) | 36,616 | 0.049 s | 0.010 s | 1.32 s (36 us/row, 27x the read) | +| tutorial `units.csv` | 64 | 0.001 s | 0.000 s | 0.004 s | +| synthetic, 3 user columns | 1,000,000 | 1.42 s | 0.28 s | **32.8 s** (33 us/row, **23x the read**) | + +starfix has no per-row call (`ArrowDigester`: `hash_table`, `hash_record_batch`, +`hash_array`, ...), so a row hash is one Python call per row. Hashing the whole table once +costs a fifth of the read: a vectorized per-row digest in starfix would bring the per-row +cost near that (not measured; it does not exist). + +## 2. Requirements + +**Guiding principle** (developer, 2026-11-23, as revised the same day): the kind and the +implementation version of the source that read a datum are named **explicitly, in one fixed +and replaceable part of the source id**, and nowhere else in a datum's identity. The record +id never depends on the source id. So a stand-in changes exactly one thing, the kind part, +and changes it only by an explicit, verified operation. Nothing else in Orcapod (a class +name in a hash, a kind hidden in a name) may force the kind in, or a stand-in could not be +exact. + +| | Requirement | Test | +|---|---|---| +| R1 | Exact stand-in across kinds and versions | Same rows, same name, key columns, any two kinds or versions, after the explicit stand-in: equal source content hash, node content hashes, tokens, system tags, record ids; a job over one database computes nothing again and stores no second set of pipeline rows | +| R2 | An implementation change that changes what a row reads as is never silent | A reader that now reads one value differently: the next run raises or reports, naming the record | +| R3 | Provenance stays truthful | For a row read through a stand-in, something stored says which kind, version and location actually read it | +| R4 | Order never counts; no hash input from an implementation detail unless decided | Reordering columns or (keyed) rows changes no hash; the kind part is the one decided input | +| R5 | User-given names are kept | The given name appears verbatim after the kind part. (Today's rule "a given id is used exactly as given", ITL-957 and ITL-1154, is **reversed** by the developer's design: Orcapod adds the kind part) | +| R6 | Cost | Per-row work at most a small multiple of the read; measured on the tutorial dataset and 1M rows | + +Today: R1 fails (class name; 1.2, 1.4), R2 fails (1.7), R3 holds only as far as an id says, +R4 holds, R5 holds in its old form, R6 holds (nothing is hashed per row except in +`CachedSource`). + +## 3. The developer's design: the kind part in every source id + +### 3.1 Grammar + +| Part | Form | Rules | +|---|---|---| +| Source id | `:` | no `::` anywhere and no trailing `:` (today's rules, kept: a token splits at its first and last `::`) | +| Kind part | `_v`, e.g. `delta_v1`, `csv_v1`, `sqlite_v1` | lower case letters, digits and `_`; ends in `_v` and a positive integer; **never holds `:`**; added by Orcapod only | +| Name | the given id, or the default: a location (`/data/units.csv`, `:main.units`, `:/..`) or a hash (`arrow_v1:`) | not empty; may hold `:` (a SQLite default already does); a source id is split at its **first** `:` | + +Measured with the simulation (`stand_in_explicit_kind`, `golden_moves` variant `K_always`): + +| Source | Source id | Token of row 0 | +|---|---|---| +| `ArrowTableSource`, given `subjects` | `arrow_table_v1:subjects` | `arrow_table_v1:subjects::{"subject":"s1"}::weight` | +| `CSVSource`, given `subjects` | `csv_v1:subjects` | `csv_v1:subjects::{"subject":"s1"}::weight` | +| `ArrowTableSource`, default | `arrow_table_v1:arrow_v1:` | | +| `CSVSource`, default | `csv_v1:` | | + +The record id is the same in all of them (1.3). + +**The hash label beside the kind part.** A hash default reads `arrow_table_v1:arrow_v1:`: +two parts of the same shape, `_v`. The position decides (the kind part is always +first, a hash label only ever in the name), and a parser never confuses them, since it splits +at the first `:`. A reader may: the documentation must show the anatomy once. A different +shape for the kind part (`delta@1`, `delta.v1`) would remove the look-alike; the developer +chose `delta_v1`, and this document keeps it. + +**Which word is the kind.** Today `SOURCE_KIND` is also the config type key: `arrow_table`, +`dict`, `list`, `data_frame`, `csv`, `delta_table`, `sqlite_table`, `postgresql_table`, +`db_table`, `spiraldb_table`, `polling_source`, `derived`, `cached`. The developer's examples +use short words (`delta_v1`, `sqlite_v1`). The simulation used `SOURCE_KIND`; the golden +entries that move are the same whichever spelling is chosen. + +### 3.2 Given ids + +| Question | Options | Recommendation | +|---|---|---| +| Is a given id prefixed? | (a) always: `units` read by Delta v1 is `delta_v1:units` (developer, settled); (b) defaults only | (a), as settled: the id always names the implementation that read the data, and one grammar holds for every id. It reverses ITL-957/ITL-1154 ("a given id is used exactly as given"): what the user gives is now the **name**, used exactly as given | +| A given id that already starts with something shaped like a kind part (`delta_v1:units`, also `run_v2:x`) | refuse; nest (`csv_v1:delta_v1:units`); strip | **refuse**, with `ValueError` saying the kind part is Orcapod's and pointing to the stand-in operation: nesting would make a stand-in look like it was spelled by hand, and the rule is ours and certain ("when in doubt, refuse"). The cost: a user cannot name a source `run_v2:x`; the message says so | +| An empty name, `::`, a trailing `:` | refuse (as today) | unchanged | + +### 3.3 Identity + +The kind part names the implementation, so the class name must leave the content hash: +otherwise a stand-in that presents the original's id still has another identity (1.4, and +`stand_in_explicit_kind` part 2 shows the equality only with the class name removed). + +| Kind | Identity under the design | +|---|---| +| Every root source (Arrow, Dict, List, DataFrame, CSV, Delta, SQLite, PostgreSQL, DBTable, SpiralDB) | `(Arrow schema identity, source id, key columns)`; SpiralDB adds its sorted `tags_as_data` as today; a restriction adds nothing (as today) | +| `PollingSource` (provisional, ITL-1316) | **changes to the root form**: today `(impl.identity(), tags, keys)` with no source id and no schema (1.1); the default name is the semantic hash of `impl.identity()` as today, so the default id is `polling_v1:semantic_v1:` | +| `DerivedSource`, `tags_as_data` (provisional, ITL-1317) | root form with `derived_v1:`, then the sorted mapping | +| `DerivedSource`, plain | today `(origin content hash,)`. It reads stored records, so it is a kind: its id `derived_v1:semantic_v1:`; the identity can stay the origin's hash until ITL-956 gives it system tags and tokens | +| `CachedSource` | the wrapped source's identity and id (wrapping is not a read of another implementation); its table path follows the identity | +| `SourceProxy` | the saved hashes, as today | + +What remains in a datum's identity: the source id (kind part and name), the schema, the key +columns. The kind enters exactly once, in the kind part. + +### 3.4 The explicit stand-in + +| Question | Recommendation | +|---|---| +| Shape | a method on the source, returning a copy, as `where()` does: `csv.stand_in_for("sqlite_v1:units")`. Not on `bind`: the tokens are built by the source, so the source must know whose id it presents; and a stand-in is the same outside a job | +| Argument | the original's full source id. Usually the names are equal and only the kind part differs (`csv_v1:units` for `sqlite_v1:units`); for an original with a default name (a path that no longer exists) the stand-in presents the original's whole id. Refuse an id that does not parse (3.1) | +| What it presents | the original's id in `source_id`, the source-id system tag and every token; its own record ids (they never depended on the id); its own schema, which must hash equal to the slot's (`bind` checks it as today) | +| What is recorded | in the ledger (section 5), per read: presented source id, record id, row hash, and the reader's actual kind, version and location, and that it read as a stand-in. Provenance stays truthful through the ledger, not the token | +| Exactness | at the run's source check (ITL-1102), before anything is computed: every record read must hash equal to the ledger's latest row for that record id; a changed hash refuses the run naming the records; a record the ledger lacks is appended (sources grow); a record missing from the read changes nothing (a restriction reads fewer rows) | +| No ledger for the original (it was never read with a ledger) | **refuse**, unless the user passes `unverified=True`, which records the stand-in as unverified in the ledger. "When in doubt, refuse": nothing proves the rows equal | +| A library upgrade (`delta_v1` to `delta_v2`) | the same operation: `src.stand_in_for("delta_v1:units")`, accepted when the rows hash equal. Without it the source is `delta_v2:units`, a new source: its downstream nodes get new content hashes and new pipeline rows (function results are still reused when data is equal: memo by input data hash) | + +Measured (`stand_in_explicit_kind`): + +| | Source ids | Node content hash | Function calls (second source) | Stored pipeline rows | +|---|---|---|---|---| +| No stand-in: `arrow_table_v1:subjects`, then `csv_v1:subjects` | differ | differ | 0 | 6 (2 sets) | +| CSV stands in for `arrow_table_v1:subjects` (rows verified: 3 same, 0 changed) | equal | equal | 0 | 3 (1 set) | + +### 3.5 When a version is bumped + +The data function type's test, applied to a reader: **would a row read before the change +read as the same row after it (same values, same Arrow types, same record id)?** If not for +some row, bump `N`. A bump that changed no row costs a stand-in (verified, so no data moves); +a missing bump is caught by the ledger as changed hashes under known record ids (R2). The +version is a constant beside `SOURCE_KIND`; a test can pin it per kind with a golden ledger +of a fixed file. + +### 3.6 Saved jobs + +| Question | Recommendation | +|---|---| +| What a source's config stores | the name, the kind and the version as separate fields (`"name": "units", "source_type": "delta", "version": 1`), and, for a stand-in, the presented id; never one string to be parsed back | +| Loading under a newer version of the kind (saved 1, installed 2) | the loaded source is `delta_v2:units`, another source: the load reports the mismatch (saved and installed versions, per source) and refuses to bind it into the saved slot as the same identity; the explicit stand-in is the way through | +| Jobs saved before the change | none in use (no users before 0.4.0): refused with a message, no migration | + +### 3.7 What moves + +`golden_moves`, 2,411 entries computed (frozen-file: in files 0.4.0 will freeze; +provisional: outside the freeze): + +| Variant | Moves | schema | datagram | pipeline | torch | frozen-file / provisional | +|---|---|---|---|---|---|---| +| **K_always** (the design: class name out, every id prefixed) | **703** | 120 | 108 | 472 | 3 | **355 / 348** | +| K_defaults (class name out, defaults only prefixed) | 252 | 100 | 34 | 117 | 1 | 165 / 87 | +| C (class name out only) | 199 | 51 | 34 | 113 | 1 | 112 / 87 | + +No `semantic` or `arrow` entry moves in any variant. The full list is +`golden-moves-K_always.txt`; the largest groups by case: `rejoin_arrangement` 108, +`hash_in_key_order` 64, `rejoin_job` and `rejoin_job_async` 33 each, `job` 32, +`polars_filter_expr_job` 31, `rejoin` 27, `drop_nulls_job` 25, `group_by_arrangement` 24, +`arrow_source` 24, `row_identifiers` 18. A source id enters system-tag values, tokens and +row hashes, so every case that reads a source's rows moves, not only those that hash a source. + +| Also moves | | +|---|---| +| Stored paths | `CachedSource` tables, content-scoped `instance:` tables, a plain `DerivedSource`'s default id; pipeline-table rows (`__node_content_hash`, record ids built from system tags); token columns in result tables | +| Saved job files | the source config gains `name` and `version` (3.6) | +| Documentation | every sample that prints a source id or a token | +| Cost before 0.4.0 | the developer's approval of the exact list (`--remove`, then regenerate); v1 is open, a pre-release freezes nothing (RELEASING.md) | +| Cost after 0.4.0 | a new data context version, in a minor release | + +### 3.8 How the design meets the requirements + +| | | +|---|---| +| R1 | met with the explicit stand-in and the class name out (measured, 3.4) | +| R2 | met by the ledger's row hashes (section 5); the version bump is the declared signal | +| R3 | the id names the reader on every ordinary read; under a stand-in, the ledger does | +| R4 | the kind part is the one decided implementation input; the class name leaves | +| R5 | the name is kept exactly; the full id is no longer what the user typed (reversal, decided) | +| R6 | the id costs nothing; the ledger's per-row hashing costs 33 us/row today (1.8) | + +## 4. The other alternatives, compared with the developer's design + +The developer's design (section 3, "K") is the central one. The alternatives below were +worked out first, under the earlier principle (the kind not a necessary part of an id); +they stay for comparison. The ledger (D) is a part of K, described in section 5; it is listed +here also on its own. + +Golden moves are measured by `golden_moves` (2,411 entries computed; "frozen-file" entries +are in files the 0.4.0 release will freeze, "provisional" ones are outside the freeze; the +full lists are `golden-moves-.txt` beside the scripts). + +| | Moves | semantic | schema | arrow | datagram | pipeline | torch | frozen-file / provisional | +|---|---|---|---|---|---|---|---|---| +| **K** (section 3: class name out, every id `_v1:`) | **703** | 0 | 120 | 0 | 108 | 472 | 3 | **355 / 348** | +| K_defaults (class name out, defaults only) | 252 | 0 | 100 | 0 | 34 | 117 | 1 | 165 / 87 | +| A | 94 | 0 | 84 | 0 | 0 | 10 | 0 | 92 / 2 | +| B (class name + version) | 199 | 0 | 51 | 0 | 34 | 113 | 1 | 112 / 87 | +| B' (kind + version, no class name) | 199 | same | | | | | | 112 / 87 | +| C (class name out) | 199 | 0 | 51 | 0 | 34 | 113 | 1 | 112 / 87 | +| D (ledger) alone | 0 | | | | | | | new pins for the row hash only | + +Every change to the root identity tuple moves the same 199 entries (every case that hashes +a source or anything downstream of one): the cost of B and C is the same; only what they +mean differs. K moves more because a given id changes too, and a source id enters every +system-tag value and token, so every case that reads a source's rows moves. + +### A. Implementation version in the default id (`delta_table.v2:`) + +| | | +|---|---| +| R1 | no better than today: the class name still forces the kind into the content hash; a default that carries a version also differs between versions of one kind | +| R2 | only for default ids, and only if the implementer bumps the version; a given id never sees it | +| R3 | partly: the id says which version, until a stand-in is given that id | +| R4, R5 | R5 holds (given ids untouched); the version is a decided input | +| R6 | free | +| Pros | readable; cheap; no identity change for given ids | +| Cons | does not answer the question for given ids (most real pipelines); makes defaults less stable; a version bump changes every record's tokens and every downstream hash even when no row reads differently | +| Moves | 94 golden entries (default-id cases); stored paths of default-id sources' downstream nodes | +| User sees | new default ids; recomputation of nothing (memo by data), but new pipeline rows | +| Failure modes | an implementer forgets to bump; a bump that changed nothing still renames every record | +| Principle | allowed (a default's choice), but puts more implementation into defaults | + +### B. A declared version beside `SOURCE_KIND`, in the content hash, not the id + +| | | +|---|---| +| R1 | **worse**: the kind (and now its version) is forced in twice; two versions of one kind cannot stand in for each other | +| R2 | coarse: every node downstream gets a new content hash after a bump, whether or not any row changed; which rows changed is not said | +| R3 | no record of a read; the hash says only "some version" | +| R4 | the version is a decided input; fine | +| R5, R6 | hold | +| Pros | simple; follows the data function type's major | +| Cons | against the guiding principle; a bump is all-or-nothing; the data function model does not carry over (a function's major says what a value MEANS; a reader that reads the same rows produced the same data) | +| Moves | 199 (112 frozen-file, 87 provisional) | +| Failure modes | forgotten bumps; needless bumps re-address every stored pipeline row | + +### C. Identity is the logical source: the class name leaves the identity + +Root identity = `(Arrow schema identity, source_id, key columns)` for every root source, +with each kind's own decided additions (`tags_as_data` mapping). Kind and implementation +are recorded elsewhere (D, or the run summary). + +| | | +|---|---| +| R1 | **met**: measured with `stand_in_job --without-class-name`: one node content hash, one set of stored pipeline rows, 0 recomputations, for all six kinds, bound or in a fresh job | +| R2 | not by itself: a reader change stays silent (1.7) | +| R3 | not by itself: a stand-in given the original's id writes tokens naming the original | +| R4 | removes an implementation detail from every hash | +| R5, R6 | hold; free | +| Pros | the principle holds everywhere; one rule for all kinds; `CachedSource` and content-scoped tables follow automatically (same path for every kind) | +| Cons | two different sources given the same id, schema and key are one address. That is the stand-in contract itself, and it already holds today within one kind (two CSV files given one id). Without D nothing checks that a stand-in really holds the same rows | +| Moves | 199 golden entries (112 frozen-file, 87 provisional); stored paths: `CachedSource` tables and content-scoped `instance:` tables; `__node_content_hash` values of existing pipeline rows (rows stored before the change are not seen as the current node's) | +| User sees | nothing until a stand-in; then reuse instead of a second copy | +| Migration | none needed before 0.4.0 (no users; v1 open); after 0.4.0 a new data context | +| Failure modes | a user reuses an id for different data: not caught today either (a content hash is an address, not a digest of rows), within one kind or across kinds; D is what catches it | +| Uniformity | make `PollingSource` follow it: `(schema, source_id, key columns)`, its default id built from `impl.identity()` as today; it is provisional (ITL-1316), so outside the freeze. A plain `DerivedSource` stays named by its origin (a computation's output is named by the computation) until ITL-956 | + +### D. The record-keeping ledger + +Per source, a stored table, one row per (record, observed row content): + +| Column | Type | Meaning | +|---|---|---| +| `source_id` | `large_string` | as the source presents it | +| `record_id` | `large_string` | the record-id system tag value | +| `row_hash` | `large_binary` | `arrow_v1` of the record's user columns, prefixed digest (5.1) | +| `kind` | `large_string` | kind of the source that actually read it (under a stand-in, not the presented one) | +| `implementation_version` | `int64` | a declared reader revision of that kind (new constant) | +| `location` | `large_string` | what the source says it read (path, table, `@
`, cursor or snapshot version), as text | +| `observed_at` | `timestamp[us, tz=UTC]` | when this content was first seen | +| `run_id` | `large_string` | the run that saw it (uuid7; not a hash) | +| `stand_in` | `bool` | read through an explicit stand-in (K, 3.4); with `unverified=True` recorded as such | +| `__data_context` | `large_string` | as every stored table | + +Prototype (`ledger_prototype`), ledger written by the `ArrowTableSource`: + +| Read compared with the ledger | same | changed | new | missing | +|---|---|---|---|---| +| each of the six kinds, same rows | 3 | 0 | 0 | 0 | +| CSV with inferred (non-null) types, hashed as read | 0 | **3** | 0 | 0 | +| the same, hashed in the slot's declared form | 3 | 0 | 0 | 0 | +| a reader change (one value) | 2 | **1** | 0 | 0 | +| positional record ids, rows reversed | 1 | **2** | 0 | 0 | + +| | | +|---|---| +| R1 | checks it: a stand-in is exact when every record it reads hashes equal to the ledger's latest row for that record. Alone (without C) the class name still splits content hashes, so the stand-in is checked but not shared | +| R2 | **met**, per record, exactly (a changed hash under a known record id is certain) | +| R3 | **met**: kind, version and location of every observation are stored | +| R4 | the row hash ignores column order (`hash_table`); record ids are explicit; ledger row order is irrelevant | +| R5 | holds | +| R6 | **not met with today's per-row hashing**: 33 us/row, 23x a read of 1M rows. Needs a vectorized per-row digest in starfix, or hashing only when the source's modified time moved (the ITL-1102 check already decides that) | +| Pros | answers R2 and R3 without putting anything into identity; serves provenance (scenarios 4 and 7 of ITL-1421); small (one row per changed record, about 100 bytes) | +| Cons | a new stored table kind and a new hash site; a read hashes every row; a policy for mismatches is needed | +| Moves | no existing golden entry; the row hash gets new pins; a new layout `ldb_v1` in `CURRENT_LAYOUTS`; the hash site inventory | +| User sees | a refusal naming records when a source reads differently from before, with an explicit way to accept | +| Failure modes | cost on very large sources; a ledger shared by two jobs (concurrency, 5.6); positional ids make reorders look like changes (correct under today's rules, but noisy) | + +### E. Combinations, and how each compares with K + +| Design | R1 | R2 | R3 | Kind in the id | Moves | Compared with K | +|---|---|---|---|---|---|---| +| **K** (section 3, with the ledger) | met, by an explicit verified stand-in | met | met: the id names the reader; the ledger under a stand-in | always, explicit | 703 + ledger pins | the developer's direction | +| K_defaults + D | met; a given id is the user's choice | met | partly: a given id need not name the reader | defaults only | 252 + pins | keeps ITL-957/ITL-1154 for given ids; the id does not always name the implementation | +| C + D | met, with no operation: same name is the same source | met | met through the ledger only | defaults only | 199 + pins | the stand-in is implicit; a version upgrade is silent in identity, caught only by row hashes | +| C alone | met, unchecked | no | no | defaults only | 199 | | +| D alone | checked, not shared (class name) | met | met | defaults only | pins | the class name still forces the kind | +| B + D | no | met | met | hidden in the hash | 199 + pins | the kind is forced in, invisibly | +| A + C | met for given ids | defaults only | no | defaults, with version | 199 + 94 | half of K, without the stand-in | + +K and C + D differ in one choice: whether replacing the reader is an explicit, recorded act +(K) or implicit when the names agree (C + D). K is stricter: under C + D a reader upgrade or +another kind under the same name changes no identity and is seen only if a row reads +differently; under K it is a different source until the user says, and the ledger proves, +that it stands in. + +### The default-id decision (ITL-957, ITL-1154), under K + +ITL-957 and ITL-1154 decided that default ids are readable and name their kind first. K keeps +that and extends it: the kind part is now explicit (`_v`), carries the version, and +is added to given ids too. Two consequences: a default name no longer repeats the kind +(`csv_v1:`, not `csv_v1:csv:`), and the rule "a given id is used exactly as +given" becomes "a given name is used exactly as given" (R5). +## 5. The ledger, concretely + +Under K the ledger is what makes a stand-in verifiable and an implementation change +visible; its columns are those of alternative D (section 4). + +### 5.1 What a row hash covers + +| Question | Answer (recommended) | +|---|---| +| Columns | the user tag and data columns (data-tags once), nothing else: not the system tags (the source id and record id are the ledger's key; `CachedSource` includes them today, so its hash changes with the id), not source info, context or meta | +| Types | the slot's **declared form** (the Arrow schema the pipeline is built on, after large normalization): measured, the inferred CSV hashes differently as read (nullability enters `hash_table`) and equal in the declared form. Outside a job, the source's own Arrow schema | +| Nulls, floats, logical types | as `hash_table` does for Orcapod's tables: nulls hashed with validity, the float rule on, a logical type by its identifier and value hash | +| Label | `arrow_v1` (`hash_table` of a one-row table); stored with its label, `to_prefixed_digest()`. A new label only if the procedure differs from `hash_table` (a vectorized per-row digest would be a new procedure, so a new label: `arrow_row_v1`) | +| Per row or per table | per row: a mismatch must name the record | + +### 5.2 Why exact Arrow types + +The row hash and the function memo both hash Arrow types, nullability included. A stand-in +that reads `int32` where the original read `int64`, or a CSV whose types are inferred, is a +different datum unless brought to the declared form. Today's rules already give the route: +`CSVSource(schema=...)` reads each cell as its declared type (ITL-1322), and `bind` +presents a top-level non-null source in the slot's nullable form (`_DeclaredForm`). A +narrower width is refused (measured). So: the ledger hashes the declared form, and a +cross-kind stand-in declares its schema in Arrow. + +### 5.3 Positional record ids + +Measured: reversing three positional rows reports 2 of 3 records changed. That is the +truth under today's rule (a position is the record's name: "reorder is a change when +record ids are positional"), so the ledger need not require key columns. It should say so +in the refusal ("this source names its records by position; give it `record_id_columns`"), +and a stand-in across kinds should be keyed (a database may not return rows in file order). + +### 5.4 What a mismatch does + +| Observation | Recommended action | Why | +|---|---|---| +| same hash | nothing written | | +| new record id | append | sources grow | +| record missing from this read | nothing (the ledger keeps history) | a restricted read (`where`, `limit`) legitimately reads fewer rows | +| **changed hash under a known record id** | **refuse** the run before anything is computed, naming the source, the count and the first record ids; accept explicitly (`job.run(accept_source_changes=["subjects"])` or a ledger method), which appends the new hashes as the current content | a changed hash is exact and certain ("refuse only what is certain"), and "when in doubt, refuse" | +| kind, version or location differs, hashes equal | append an observation (R3), no refusal | an exact stand-in is what R1 allows | +| a stand-in (3.4) whose original has no ledger | refuse, unless `unverified=True` (recorded) | nothing proves the rows equal | + +### 5.5 Where it lives and what reads it + +| Question | Recommendation | +|---|---| +| Database | the job's database (as pipeline and result tables) | +| Path | `/source_ledger/node:/ldb_v1`. Under K the content hash is that of the presented id, so a stand-in reads and extends its original's ledger, and a new version without a stand-in starts its own | +| Layout | a new `ldb_v1`, added to `CURRENT_LAYOUTS`; not `sdb_v1` (that is a full copy with another hash) | +| `CachedSource` | stays a separate feature (availability: keeps rows a source may lose). Later it can take the ledger's row hash instead of its own `_record_hash` (a stored-schema change: `sdb_v2`) | +| Who reads and writes | `job.run()`, `run_async()` and a job node's `run()`, at the source check (ITL-1102, `node_run.check_sources`), for each source a run reads; `bind` does not read rows (it stays a schema check); `head()` and the preview never | +| When it hashes | when the run reads the source: if the source's modified time did not move since the last ledgered read in this process, nothing is hashed again | + +### 5.6 Concurrency and size + +| | | +|---|---| +| Writes | append-only; one row per (record, new content). Two jobs appending to one Delta table meet only at commit, where Delta's optimistic commit lets blind appends both succeed; the current content of a record is its latest `observed_at` | +| Size | about 100 bytes a row (record id, 44-byte prefixed digest `arrow_v1:` + 35 bytes, short text): 1M records about 100 MB uncompressed, written once; then only changed records | +| Read | one table scan per run per source, or a lookup by record id | + +### 5.7 The provenance showcase (ITL-1421) + +| Scenario | What the ledger gives | +|---|---| +| 4. Reproduce and prove a result | the row hash of every traced source record (source id, record id from the tokens): a manifest can list them, and a verification re-reads and compares | +| 7. New data arrived | which records are new and which changed since the last run, per source, before anything runs; with the function memo, which nodes would recompute | +| 1, 2. Trace back and forward | the kind, location and version that actually read a traced record (R3) | + +## 6. Interactions + +| With | Under K | +|---|---| +| `DerivedSource` plain, `as_source()`, ITL-956 | id `derived_v1:semantic_v1:`; identity stays the origin's hash until ITL-956 gives it system tags and tokens (new record ids); add it to the ledger after ITL-956 | +| `DerivedSource` `tags_as_data` | `derived_v1:` (a source id is still required, ITL-1313), root identity plus the mapping; provisional (ITL-1317), outside the freeze | +| `PollingSource` | takes the root identity (3.3); default `polling_v1:semantic_v1:`; a cursor or snapshot version is its ledger `location`; provisional (ITL-1316), outside the freeze | +| `SpiralDBTableSource` | `spiraldb_v1:..
@
` by default; a re-created table (new table id) under a given name stands in after verification | +| `CachedSource` | the wrapped source's id and identity; one cache table per presented source. It stays a full cache (availability); it may later take the ledger's row hash instead of its `_record_hash`, which today includes the system tags (1.6) | +| `bind` | unchanged: a schema check; it never reads rows. The stand-in is made on the source before binding. Fix first the bug of 1.4 (a bind leaves downstream content hashes stale) | +| Saved jobs | name, kind and version as separate fields; a version mismatch on load is reported, and the stand-in is the way through (3.6) | +| The run's source check (ITL-1102) | where the ledger is compared and appended, before anything is computed | +| Provenance showcase (ITL-1421) | scenario 4 (prove a result) takes the traced records' row hashes from the ledger; scenario 7 (new data) takes new and changed records from it (5.7) | +| Data context and the freeze | v1 is open until 0.4.0; a pre-release freezes nothing (RELEASING.md, ITL-1329); 0.4.0 freezes. K moves 355 frozen-file and 348 provisional entries: the developer approves the exact list (`golden-moves-K_always.txt`), then `--remove` and regenerate. After 0.4.0, K needs a new data context version. The stand-in operation and the ledger move no existing value (new pins only) and can land in any release | + +## 7. Recommendation + +**Adopt K (the developer's direction) with the ledger.** Before 0.4.0, land everything that +moves a hash: the class name out of the source identity, the kind part in every source id, +`PollingSource` on the root identity. After 0.4.0 (or before, if time allows; they move no +existing value), the ledger and the explicit stand-in. + +### Decisions for the developer + +| # | Decision | Recommendation | Commits to | +|---|---|---|---| +| 1 | Confirm K against its moved list | confirm: 703 entries, 355 frozen-file and 348 provisional (`golden-moves-K_always.txt`) | the reversal of "a given id is used exactly as given" (ITL-957, ITL-1154) to "a given name is used exactly as given" | +| 2 | Kind words | one vocabulary for the kind part and the config type key; choose short words (`delta`, `sqlite`, `postgresql`, `spiraldb`, `csv`, `polling`) or today's `SOURCE_KIND` (`delta_table`, ...). Recommend the short words, renaming `SOURCE_KIND` and the config keys with them (no users) | every default id and saved config; no extra golden move beyond decision 1 | +| 3 | A given id that already has a kind-part shape | refuse (3.2) | users cannot name a source `x_v2:...` | +| 4 | Parsing | the kind part never holds `:`; split at the first `:`; the name may hold `:`; no `::`, no trailing `:`, no empty name | one parser, used by the saved-job reader and the ledger | +| 5 | Class name out of the identity; root identity `(Arrow schema identity, source id, key columns)` for every root source, `PollingSource` included | adopt | part of decision 1's list | +| 6 | Version bump rule | bump when a row read before could read differently after (3.5); a constant beside the kind | a per-kind constant and a test pinning it | +| 7 | Stand-in API | `source.stand_in_for(original_source_id, *, unverified=False)`, returning a copy; checked at the run's source check against the ledger; refuse on a changed record; refuse without a ledger unless `unverified=True` | public API; a new error | +| 8 | Ledger | a new stored table `ldb_v1` in the job database, keyed by the presented source's content hash; row hash of the user columns in the slot's declared form, `arrow_v1` per one-row table now, a vectorized per-row digest in starfix (new label) before it is on by default (R6: 33 us/row today, 23x a 1M-row read) | a new table kind, a new hash site, new pins, a starfix request | +| 9 | Mismatch policy outside a stand-in | changed record under a known record id: refuse, explicit accept appends; new: append; missing: nothing (5.4) | a run argument (public API) | +| 10 | Saved jobs | name, kind, version as separate fields; refuse jobs saved before the change | the job file format | +| 11 | `CachedSource` | stays a full cache now; may adopt the ledger row hash later (`sdb_v2`) | nothing now | +| 12 | The bind bug of 1.4 | fix separately, before 0.4.0 | a Linear issue | + +### Before 0.4.0, and after + +| Before 0.4.0 (moves golden values) | After 0.4.0, or earlier if ready (moves none) | +|---|---| +| decisions 1-6 and 10: kind part in every id, class name out, `PollingSource` identity, version constants, saved-job fields; decision 12 (the bind bug); documentation of the id anatomy | decisions 7-9: the ledger and the explicit stand-in (until then a stand-in across kinds or versions is impossible: under K a different kind part is a different source); ITL-956 and then the derived source in the ledger; decision 11 | diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/__init__.py b/docs/dev/specs/itl-1425-source-identity/scripts/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/_fixtures.py b/docs/dev/specs/itl-1425-source-identity/scripts/_fixtures.py new file mode 100644 index 000000000..c95eaef0a --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/_fixtures.py @@ -0,0 +1,133 @@ +"""Shared synthetic fixtures: the same rows as four source kinds (ITL-1425). + +Synthetic data only. Every source gets the same given ``source_id`` and the same key +column, so any difference the scripts print comes from the kind, not from the names. +""" + +from __future__ import annotations + +import csv +import sqlite3 +import tempfile +from pathlib import Path +from typing import Any, TypedDict + +import pyarrow as pa + +SOURCE_ID = "subjects" +KEY = "subject" + +ROWS = [ + {"subject": "s1", "weight": 25.5, "count": 3}, + {"subject": "s2", "weight": 22.0, "count": 5}, + {"subject": "s3", "weight": 27.25, "count": 7}, +] + + +class Keyed(TypedDict): + """Keyword arguments of a source keyed by ``subject``.""" + + tag_columns: list[str] + record_id_columns: list[str] + tag_only_columns: bool + + +class Positional(TypedDict): + """Keyword arguments of a source whose record ids are positions.""" + + tag_columns: list[str] + record_id_columns: tuple[()] + tag_only_columns: bool + source_id: str + + +KEYED: Keyed = { + "tag_columns": [KEY], + "record_id_columns": [KEY], + "tag_only_columns": True, +} +POSITIONAL: Positional = { + "tag_columns": [KEY], + "record_id_columns": (), + "tag_only_columns": True, + "source_id": SOURCE_ID, +} + +SCHEMA = pa.schema( + [ + pa.field("subject", pa.large_string(), nullable=False), + pa.field("weight", pa.float64()), + pa.field("count", pa.int64()), + ] +) + + +def arrow_table(rows: list[dict[str, Any]] = ROWS) -> pa.Table: + return pa.Table.from_pylist(rows, schema=SCHEMA) + + +def write_files(folder: Path, rows: list[dict[str, Any]] = ROWS) -> dict[str, Path]: + """Write the rows as a CSV file, a Delta table and a SQLite table.""" + from deltalake import write_deltalake + + csv_path = folder / "subjects.csv" + with csv_path.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=list(SCHEMA.names)) + writer.writeheader() + writer.writerows(rows) + + delta_path = folder / "subjects_delta" + write_deltalake(str(delta_path), arrow_table(rows), mode="overwrite") + + sqlite_path = folder / "subjects.sqlite" + con = sqlite3.connect(sqlite_path) + con.execute("DROP TABLE IF EXISTS subjects") + con.execute( + "CREATE TABLE subjects (subject TEXT PRIMARY KEY NOT NULL, weight REAL, count INTEGER)" + ) + con.executemany( + "INSERT INTO subjects VALUES (?, ?, ?)", + [(r["subject"], r["weight"], r["count"]) for r in rows], + ) + con.commit() + con.close() + return {"csv": csv_path, "delta": delta_path, "sqlite": sqlite_path} + + +def same_rows_sources( + folder: Path, *, source_id: str | None = SOURCE_ID, csv_schema: bool = True +): + """The same rows as six source kinds, each with the same given id and key column.""" + import polars as pl + + from orcapod.sources import ( + ArrowTableSource, + CSVSource, + DataFrameSource, + DeltaTableSource, + DictSource, + SQLiteTableSource, + ) + + paths = write_files(folder) + return { + "arrow_table": ArrowTableSource(arrow_table(), source_id=source_id, **KEYED), + "csv": CSVSource( + str(paths["csv"]), + schema=SCHEMA if csv_schema else None, + source_id=source_id, + **KEYED, + ), + "delta_table": DeltaTableSource(paths["delta"], source_id=source_id, **KEYED), + "sqlite_table": SQLiteTableSource( + paths["sqlite"], "subjects", source_id=source_id, **KEYED + ), + "dict": DictSource(ROWS, data_schema=SCHEMA, source_id=source_id, **KEYED), + "data_frame": DataFrameSource( + pl.DataFrame(ROWS), schema=SCHEMA, source_id=source_id, **KEYED + ), + } + + +def scratch() -> Path: + return Path(tempfile.mkdtemp(prefix="itl1425-")) diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/cached_source_today.py b/docs/dev/specs/itl-1425-source-identity/scripts/cached_source_today.py new file mode 100644 index 000000000..d55b54aad --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/cached_source_today.py @@ -0,0 +1,81 @@ +"""What ``CachedSource`` stores today and where (ITL-1425, section 1). + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.cached_source_today``. +""" + +from __future__ import annotations + +import warnings + +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import CachedSource + +from ._fixtures import same_rows_sources, scratch + +warnings.simplefilter("ignore") + + +def short(path: tuple[str, ...]) -> str: + return "/".join(p if len(p) < 24 else p[:20] + "..." for p in path) + + +def main() -> None: + sources = same_rows_sources(scratch()) + db = InMemoryArrowDatabase() + cached = {k: CachedSource(s, cache_database=db) for k, s in sources.items()} + + print("== Cache path per kind (same rows, same source_id, same key) ==") + for kind, c in cached.items(): + print(f" {kind:13s} {short(c.cache_path)}") + paths = {c.cache_path for c in cached.values()} + print(f" distinct cache tables: {len(paths)}") + + print("\n== What one cache table holds after a read ==") + c = cached["csv"] + c.as_table() + stored = db.get_all_records(c.cache_path, record_id_column="_record_hash") + assert stored is not None + print(" columns:", stored.column_names) + print(" rows:", stored.num_rows) + print( + " _record_hash row 0 starts with:", + stored.column("_record_hash")[0].as_py()[:9], + ) + + print("\n== The record hash covers the system tags, so it holds the source id ==") + other = same_rows_sources(scratch(), source_id="subjects_v2")["csv"] + db2 = InMemoryArrowDatabase() + c2 = CachedSource(other, cache_database=db2) + c2.as_table() + h1 = set(stored.column("_record_hash").to_pylist()) + stored2 = db2.get_all_records(c2.cache_path, record_id_column="_record_hash") + assert stored2 is not None + h2 = set(stored2.column("_record_hash").to_pylist()) + print( + " same rows under another source_id share no record hash:", h1.isdisjoint(h2) + ) + + print("\n== When the inner source is read ==") + inner = sources["arrow_table"] + reads = {"n": 0} + original = inner.as_table + + def counting_as_table(*args, **kwargs): + reads["n"] += 1 + return original(*args, **kwargs) + + inner.as_table = counting_as_table # type: ignore[method-assign] + c3 = CachedSource(inner, cache_database=InMemoryArrowDatabase()) + c3.as_table() + first = reads["n"] + c3.as_table() + second = reads["n"] - first + changed = c3.check_for_new_data() + print(f" first read of the cached source reads the inner source: {first} time(s)") + print(f" a second read in the same process reads it again: {second} time(s)") + print(f" check_for_new_data() with nothing changed reports new data: {changed}") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/golden_moves.py b/docs/dev/specs/itl-1425-source-identity/scripts/golden_moves.py new file mode 100644 index 000000000..e02da7963 --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/golden_moves.py @@ -0,0 +1,196 @@ +"""Which golden entries an identity change would move (ITL-1425, section 3). + +Each variant patches the library in this process only (nothing under ``src/`` changes), +computes every golden group with the golden cases (``tests/test_hashing/golden/cases.py``) +and compares the values with the same computation unpatched. Each variant runs in its own +process, so no hash cached by one variant is seen by another. + +Variants: + +* ``C``: the class name leaves ``RootSource.identity_structure`` + (identity = Arrow schema identity, source id, key columns). +* ``B``: a declared implementation version enters it beside the class name + (identity = class name, version 1, Arrow schema identity, source id, key columns). +* ``B_no_class``: C plus a version (``SOURCE_KIND`` and version replace the class name). +* ``A``: the default source ids carry a version (``.v1:...``); identity unchanged. +* ``K_defaults``: the explicit-kind-in-id design for defaults only: C, and every default + id starts with ``_v1:`` (``csv_v1:``, ``arrow_table_v1:arrow_v1:``). +* ``K_always``: ``K_defaults``, and a given id is prefixed too (``subjects`` given to a + CSV source becomes ``csv_v1:subjects``); wrappers (``CachedSource``, ``SourceProxy``) + keep the id of what they wrap. + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.golden_moves`` (all variants) or ``... golden_moves C``. +""" + +from __future__ import annotations + +import json +import subprocess +import sys +import warnings +from collections import Counter +from pathlib import Path + +warnings.simplefilter("ignore") + +REPO = Path(__file__).resolve().parents[5] +VARIANTS = ("C", "B", "B_no_class", "A", "K_defaults", "K_always") + + +def patch(variant: str) -> None: + from orcapod.core.sources import base, source_ids + + original = base.RootSource.identity_structure + + if variant in ("K_defaults", "K_always"): + patch("C") + _patch_default_ids("_v1") + if variant == "K_always": + _prefix_given_ids() + return + if variant in ("C", "B", "B_no_class"): + + def identity_structure(self): # type: ignore[no-untyped-def] + full = original(self) + if not ( + isinstance(full, tuple) and full and full[0] == type(self).__name__ + ): + return full # a subclass's own form (DerivedSource plain form) + rest = full[1:] + if variant == "C": + return rest + if variant == "B": + return (full[0], ("version", 1), *rest) + return (self.SOURCE_KIND, ("version", 1), *rest) + + base.RootSource.identity_structure = identity_structure # type: ignore[method-assign] + elif variant == "A": + _patch_default_ids(".v1") + _ = source_ids + + +def _patch_default_ids(suffix: str) -> None: + """Make every default id start with ``:``.""" + from orcapod.core.sources import source_ids + + orig_hash, orig_loc = source_ids.hash_source_id, source_ids.location_source_id + + def hash_source_id(kind, content_hash, hexdigits=None): # type: ignore[no-untyped-def] + return orig_hash(f"{kind}{suffix}", content_hash, hexdigits) + + def location_source_id(kind, location): # type: ignore[no-untyped-def] + return orig_loc(f"{kind}{suffix}", location) + + for name, module in list(sys.modules.items()): + if not name.startswith("orcapod."): + continue + if getattr(module, "hash_source_id", None) is orig_hash: + setattr(module, "hash_source_id", hash_source_id) + if getattr(module, "location_source_id", None) is orig_loc: + setattr(module, "location_source_id", location_source_id) + + +def _prefix_given_ids() -> None: + """Prefix a given source id with ``_v1:`` (wrappers excepted).""" + from orcapod.core.sources import base + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.source_proxy import SourceProxy + + original_init = base.RootSource.__init__ + + def __init__(self, source_id=None, *args, **kwargs): # type: ignore[no-untyped-def] + tag = f"{self.SOURCE_KIND}_v1:" + if ( + source_id is not None + and not isinstance(self, (CachedSource, SourceProxy)) + and not source_id.startswith(tag) + ): + source_id = tag + source_id + original_init(self, source_id, *args, **kwargs) + + base.RootSource.__init__ = __init__ # type: ignore[method-assign] + + +def compute(variant: str | None) -> dict[str, dict[str, object]]: + sys.path.insert(0, str(REPO)) + import orcapod.core.sources # noqa: F401 - load the modules before patching + import orcapod.pipeline # noqa: F401 + from tests.test_hashing.golden import cases + + if variant: + patch(variant) + out: dict[str, dict[str, object]] = {} + for group in cases.GROUPS: + try: + live, _ = cases.compute_group_kinds(group, allow_errors=True) + except ModuleNotFoundError: + continue + out[group] = {k: repr(v) for k, v in live.items()} + return out + + +def run_child(variant: str) -> dict[str, dict[str, object]]: + proc = subprocess.run( + [sys.executable, "-m", "scripts.golden_moves", "--child", variant], + capture_output=True, + text=True, + check=True, + cwd=Path(__file__).resolve().parents[1], + ) + return json.loads(proc.stdout.strip().splitlines()[-1]) + + +def provisional_entries() -> set[tuple[str, str]]: + """The entries pinned in the provisional files (outside the freeze, ITL-1266).""" + sys.path.insert(0, str(REPO)) + from orcapod.contexts import get_default_context + from tests.test_hashing.golden import store + + version = get_default_context().version + manifest = store.read_json(store.manifest_path(REPO, version)) + folder = store.golden_folder(REPO, manifest) + return { + (g, e) for g, entries in store.load_provisional(folder).items() for e in entries + } + + +def main() -> None: + if len(sys.argv) > 2 and sys.argv[1] == "--child": + variant = None if sys.argv[2] == "none" else sys.argv[2] + print(json.dumps(compute(variant))) + return + chosen = sys.argv[1:] or list(VARIANTS) + baseline = run_child("none") + total = sum(len(v) for v in baseline.values()) + provisional = provisional_entries() + print(f"golden entries computed: {total}") + for variant in chosen: + live = run_child(variant) + moved = [ + (g, e) + for g, entries in baseline.items() + for e, v in entries.items() + if live.get(g, {}).get(e) != v + ] + per_group = Counter(g for g, _ in moved) + in_provisional = sum(1 for m in moved if m in provisional) + print( + f"\n== {variant}: {len(moved)} of {total} entries move " + f"({len(moved) - in_provisional} frozen-file, {in_provisional} provisional) ==" + ) + for group in baseline: + print( + f" {group:9s} {per_group.get(group, 0):4d} of {len(baseline[group])}" + ) + prefixes = Counter( + e.split(":")[0].split("/")[0].split(".")[0] for _, e in moved + ) + print(" moved entries by name prefix:", dict(sorted(prefixes.items()))) + listing = Path(__file__).resolve().parents[1] / f"golden-moves-{variant}.txt" + listing.write_text("".join(f"{g}:{e}\n" for g, e in sorted(moved))) + print(f" full list: {listing.name}") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/identity_structures.py b/docs/dev/specs/itl-1425-source-identity/scripts/identity_structures.py new file mode 100644 index 000000000..3ad349dc5 --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/identity_structures.py @@ -0,0 +1,155 @@ +"""The identity structure of every source kind that can be built here (ITL-1425). + +Prints ``identity_structure()`` (what the content hash is built from) per kind, with +whether it holds the class name, the ``source_id``, the Arrow schema identity and the key +columns. Kinds that need a server (PostgreSQL, SpiralDB, a generic ``DBTableSource``) are +not built; the document cites their code instead. ``SourceProxy`` is shown through a +saved and loaded job. + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.identity_structures``. +""" + +from __future__ import annotations + +import tempfile +import warnings +from pathlib import Path + +import pyarrow as pa + +from orcapod import PipelineJob +from orcapod.databases import DeltaTableDatabase +from orcapod.sources import CachedSource, ListSource, PollingSource +from orcapod.types import ContentHash, Schema + +from ._fixtures import same_rows_sources, scratch +from .stand_in_job import ratio + +warnings.simplefilter("ignore") + + +class ToyPolling: + """A minimal ``DynamicSourceProtocol`` implementation; never polled here.""" + + def identity(self): # type: ignore[no-untyped-def] + return ("ToyPolling", "endpoint-a") + + def to_config(self): # type: ignore[no-untyped-def] + return {} + + @classmethod + def from_config(cls, config): # type: ignore[no-untyped-def] + return cls() + + def schema(self) -> Schema: + return Schema({"subject": str, "weight": float}) + + async def poll(self, cursor=None): # type: ignore[no-untyped-def] + return False + + async def fetch(self, cursor=None): # type: ignore[no-untyped-def] + raise NotImplementedError + + async def close(self) -> None: + return None + + +def describe(kind: str, src) -> None: + structure = src.identity_structure() + flat = structure if isinstance(structure, tuple) else (structure,) + has_class = type(src).__name__ in flat or any( + isinstance(x, str) and x.endswith("Source") for x in flat + ) + has_id = src.source_id in flat + has_schema = any( + isinstance(x, tuple) + and len(x) == 2 + and all(isinstance(y, ContentHash) for y in x) + for x in flat + ) + + def show(x): # type: ignore[no-untyped-def] + if isinstance(x, ContentHash): + return f"<{x.method}:{x.to_hex()[:8]}>" + if isinstance(x, tuple): + return "(" + ", ".join(show(y) for y in x) + ")" + return repr(x) + + print(f"-- {kind} [{type(src).__name__}]") + print(f" structure: {show(structure)}") + print( + f" class name: {has_class}; source_id ({src.source_id!r}): {has_id}; " + f"Arrow schema identity: {has_schema}" + ) + + +def main() -> None: + folder = scratch() + sources = same_rows_sources(folder) + for kind, src in sources.items(): + describe(kind, src) + describe( + "list", + ListSource( + "weight", + [25.5, 22.0], + source_id="subjects", + tag_function=lambda v, i: {"subject": f"s{i}"}, + expected_tag_keys=["subject"], + ), + ) + describe( + "cached (over arrow_table)", + CachedSource( + sources["arrow_table"], cache_database=DeltaTableDatabase(folder / "c") + ), + ) + + db = DeltaTableDatabase(folder / "db") + job = PipelineJob(name="ids", database=db) + with job: + ratio.pod(sources["arrow_table"], label="ratio") + job.run() + node = job.nodes["ratio"] + describe("derived, plain (node.as_source())", node.as_source()) + describe( + "derived, tags_as_data", + node.as_source(tags_as_data={"subject": "subject_copy"}, source_id="ratios"), + ) + + describe( + "polling (toy impl)", + PollingSource(ToyPolling(), tag_columns="subject", record_id_columns="subject"), + ) + described = PollingSource( + ToyPolling(), + tag_columns="subject", + record_id_columns="subject", + source_id="subjects", + ) + describe("polling (toy impl, given source_id)", described) + + print("\n== Saved and loaded jobs: what the slot holds ==") + for kind in ("csv", "arrow_table"): + saved = PipelineJob( + name="ids", database=DeltaTableDatabase(folder / f"db_{kind}") + ) + with saved: + ratio.pod(sources[kind], label="ratio") + saved.run() + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "job.json" + saved.save(path) + loaded = PipelineJob.load(path) + slot = loaded.nodes["subjects"] + bound = slot.bound_source + print( + f" {kind:12s} loaded slot bound to: {type(bound).__name__}; slot content " + f"hash equal to the source's: {slot.content_hash() == sources[kind].content_hash()}" + ) + _ = pa + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/identity_today.py b/docs/dev/specs/itl-1425-source-identity/scripts/identity_today.py new file mode 100644 index 000000000..c217a1d54 --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/identity_today.py @@ -0,0 +1,133 @@ +"""Measure what enters a source's identity today, per kind (ITL-1425, section 1). + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.identity_today``. +""" + +from __future__ import annotations + +import warnings + +from ._fixtures import same_rows_sources, scratch + +warnings.simplefilter("ignore") + + +def main() -> None: + folder = scratch() + sources = same_rows_sources(folder) + + print("== Given source_id='subjects', record_id_columns=['subject'] ==") + first = None + for kind, src in sources.items(): + tbl = src.as_table(columns={"source": True, "system_tags": True}) + sys_cols = [c for c in tbl.column_names if c.startswith("_tag_")] + src_cols = [c for c in tbl.column_names if c.startswith("_source_")] + tag_s, data_s = src.arrow_schemas + rec = { + "class": type(src).__name__, + "SOURCE_KIND": src.SOURCE_KIND, + "source_id": src.source_id, + "content_hash": src.content_hash().to_string()[:40], + "pipeline_hash": src.pipeline_hash().to_string()[:40], + "arrow tag schema": str(tag_s).replace("\n", "; "), + "arrow data schema": str(data_s).replace("\n", "; "), + "identity_structure[0]": src.identity_structure()[0], + "system-tag columns": sys_cols, + "system-tag values row 0": [tbl.column(c)[0].as_py() for c in sys_cols], + "source-info token (weight)": tbl.column("_source_weight").to_pylist()[0] + if "_source_weight" in src_cols + else src_cols, + } + print(f"\n-- {kind}") + for k, v in rec.items(): + print(f" {k:28s} {v}") + if first is None: + first = rec + print("\n== Agreement with arrow_table ==") + for kind, src in list(sources.items())[1:]: + a, b = sources["arrow_table"], src + ta = a.as_table(columns={"source": True, "system_tags": True}) + tb = b.as_table(columns={"source": True, "system_tags": True}) + print( + f" {kind:13s} content_hash equal: {a.content_hash() == b.content_hash()}; " + f"pipeline_hash equal: {a.pipeline_hash() == b.pipeline_hash()}; " + f"arrow schemas equal: {a.arrow_schemas == b.arrow_schemas}; " + f"table with system tags and tokens equal: {ta.equals(tb)}" + ) + + print("\n== Same content hash once the class name is set aside ==") + for kind, src in sources.items(): + rest = src.identity_structure()[1:] + print( + f" {kind:13s} identity without class name equal to arrow_table's: " + f"{rest == sources['arrow_table'].identity_structure()[1:]}" + ) + + print("\n== Record ids do not depend on the source id ==") + from orcapod.sources import ArrowTableSource + + from ._fixtures import KEYED, POSITIONAL, arrow_table + + for label, kwargs in (("keyed", dict(KEYED)), ("positional", dict(POSITIONAL))): + kwargs.pop("source_id", None) + ids = {} + for sid in ("subjects", "csv_v1:subjects", "something_else"): + t = ArrowTableSource(arrow_table(), source_id=sid, **kwargs).as_table( # pyright: ignore[reportArgumentType] # kwargs is one of the two TypedDicts + columns={"system_tags": True, "source": True} + ) + rid = next(c for c in t.column_names if c.startswith("_tag_record_id")) + ids[sid] = ( + t.column(rid).to_pylist(), + t.column("_source_weight")[0].as_py(), + ) + record_ids = {sid: v[0] for sid, v in ids.items()} + print( + f" {label:10s} record ids under three source ids equal: " + f"{len({tuple(v) for v in record_ids.values()}) == 1} -> {record_ids['subjects']}" + ) + for sid, (_, token) in ids.items(): + print(f" token of row 0 under {sid!r}: {token}") + print( + " across the six kinds (keyed): record-id column values equal:", + all( + src.as_table(columns={"system_tags": True}) + .column( + next( + c + for c in src.as_table(columns={"system_tags": True}).column_names + if c.startswith("_tag_record_id") + ) + ) + .to_pylist() + == ['{"subject":"s1"}', '{"subject":"s2"}', '{"subject":"s3"}'] + for src in sources.values() + ), + ) + + print("\n== CSV without a declared schema (types inferred) ==") + inferred = same_rows_sources(scratch(), csv_schema=False)["csv"] + print( + " arrow schemas:", + [str(x).replace("\n", "; ") for x in inferred.arrow_schemas], + ) + print( + " equal to arrow_table's:", + inferred.arrow_schemas == sources["arrow_table"].arrow_schemas, + ) + print( + " pipeline_hash equal:", + inferred.pipeline_hash() == sources["arrow_table"].pipeline_hash(), + ) + + print("\n== Default source ids (no source_id given) ==") + defaults = same_rows_sources(scratch(), source_id=None) + for kind, src in defaults.items(): + sid = src.source_id + if folder.as_posix() in sid or "/" in sid: + sid = sid.split(":", 1)[0] + ":" + print(f" {kind:13s} {sid}") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/ledger_prototype.py b/docs/dev/specs/itl-1425-source-identity/scripts/ledger_prototype.py new file mode 100644 index 000000000..456019529 --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/ledger_prototype.py @@ -0,0 +1,104 @@ +"""A record-keeping ledger, prototyped outside the library (ITL-1425, section 4). + +The ledger of a source is one row per record: ``source_id``, ``record_id``, ``row_hash`` +and implementation columns (``kind``, ``class``). The row hash here is +``arrow_hasher.hash_table`` (``arrow_v1``) of a one-row table of the record's user +columns (tags and data), with their Arrow types, and nothing else: no system tag, +source-info token, context or meta column (the source id and record id are the ledger's +key, not part of what is compared). A later read is compared with the ledger, per record +id: same, changed, new, missing. + +Cases: + +1. Every other kind holding the same rows, against a ledger written by the + ``ArrowTableSource``. +2. A CSV read with inferred types (non-null columns) against the same ledger: hashed as + read, then hashed in the slot's declared form (the declared nullable schema, as + ``bind`` presents a narrower source). +3. A reader change: one value read differently under the same source id and key. +4. Positional record ids, the rows listed in another order. + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.ledger_prototype``. +""" + +from __future__ import annotations + +import warnings + +import pyarrow as pa + +from orcapod.sources import ArrowTableSource, CSVSource + +from ._fixtures import ( + KEYED, + POSITIONAL, + ROWS, + SCHEMA, + arrow_table, + same_rows_sources, + scratch, +) + +warnings.simplefilter("ignore") + + +def ledger(source, declared: pa.Schema | None = None) -> dict[str, bytes]: + """Map each record id to the hash of its user columns (optionally as declared).""" + full = source.as_table(columns={"system_tags": True}) + rid = next(c for c in full.column_names if c.startswith("_tag_record_id")) + tag_keys, data_keys = source.keys() + user = full.select([*tag_keys, *data_keys]) + if declared is not None: + user = pa.Table.from_arrays(user.columns, schema=declared) + hasher = source.data_context.arrow_hasher + out = {} + for i, record_id in enumerate(full.column(rid).to_pylist()): + out[record_id] = hasher.hash_table(user.slice(i, 1)).to_prefixed_digest() + return out + + +def compare(old: dict[str, bytes], new: dict[str, bytes]) -> dict[str, int]: + return { + "same": sum(1 for k in new if k in old and old[k] == new[k]), + "changed": sum(1 for k in new if k in old and old[k] != new[k]), + "new": sum(1 for k in new if k not in old), + "missing": sum(1 for k in old if k not in new), + } + + +def main() -> None: + folder = scratch() + sources = same_rows_sources(folder) + base = ledger(sources["arrow_table"]) + print("row hash label:", next(iter(base.values())).split(b":")[0].decode()) + + print("\n== 1. Other kinds, same rows ==") + for kind, src in sources.items(): + print(f" {kind:13s} {compare(base, ledger(src))}") + + print("\n== 2. CSV with inferred (non-null) types ==") + inferred = CSVSource(str(folder / "subjects.csv"), source_id="subjects", **KEYED) + print(" hashed as read: ", compare(base, ledger(inferred))) + print( + " hashed in declared form: ", compare(base, ledger(inferred, declared=SCHEMA)) + ) + + print("\n== 3. A reader change: one value read differently ==") + rows = [dict(r) for r in ROWS] + rows[1]["weight"] = 22.0001 + changed = ArrowTableSource(arrow_table(rows), source_id="subjects", **KEYED) + print(" ", compare(base, ledger(changed))) + + print("\n== 4. Positional record ids, rows in another order ==") + a = ArrowTableSource(arrow_table(), **POSITIONAL) + b = ArrowTableSource(arrow_table(list(reversed(ROWS))), **POSITIONAL) + print( + " ", + compare(ledger(a), ledger(b)), + "(same rows; the middle row keeps its position)", + ) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/row_hash_cost.py b/docs/dev/specs/itl-1425-source-identity/scripts/row_hash_cost.py new file mode 100644 index 000000000..a66d26f4c --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/row_hash_cost.py @@ -0,0 +1,137 @@ +"""Cost of hashing every row of a source (ITL-1425, requirement R6). + +Hashes each row the way ``CachedSource`` does today: ``arrow_hasher.hash_table`` of a +one-row slice (``arrow_v1``; starfix has no per-row call, so one digest per row). Compares +it with the time to read the source and to hash the whole table once. + +Two inputs: the tutorial dataset (``docs/tutorial/workshop_data.py``, its largest table: +every spikes file of every session stacked) and a synthetic table of N rows (default +1,000,000; one string key, one float, one integer). + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.row_hash_cost [N]``. One process; note the machine load. +""" + +from __future__ import annotations + +import importlib +import os +import sys +import tempfile +import time +import warnings +from pathlib import Path + +import pyarrow as pa +import pyarrow.csv as pacsv + +from orcapod.sources import ArrowTableSource, CSVSource + +warnings.simplefilter("ignore") + +HERE = Path(__file__).resolve() +TUTORIAL = HERE.parents[5] / "docs" / "tutorial" + + +def timed(fn): + start = time.perf_counter() + out = fn() + return out, time.perf_counter() - start + + +def per_row_hashes(table: pa.Table, hasher) -> list[bytes]: + out = [] + for batch in table.to_batches(): + for i in range(batch.num_rows): + out.append(hasher.hash_table(batch.slice(i, 1)).to_prefixed_digest()) + return out + + +def measure(name: str, build) -> None: + """``build`` constructs the source (which reads the data) and returns it.""" + source, t_build = timed(build) + table, t_as_table = timed( + lambda: source.as_table(columns={"system_tags": True, "source": True}) + ) + t_read = t_build + t_as_table + hasher = source.data_context.arrow_hasher + _, t_whole = timed(lambda: hasher.hash_table(table)) + hashes, t_rows = timed(lambda: per_row_hashes(table, hasher)) + n = table.num_rows + print(f"-- {name}: {n:,} rows, {table.num_columns} columns") + print( + f" build the source and read it (system tags and tokens): {t_read:8.3f} s" + ) + print( + f" hash the whole table once (hash_table): {t_whole:8.3f} s" + ) + print( + f" hash every row (one hash_table per one-row slice): {t_rows:8.3f} s" + f" ({t_rows / n * 1e6:.1f} us/row, {t_rows / max(t_read, 1e-9):.1f}x the read)" + ) + print(f" distinct row hashes: {len(set(hashes)):,}") + + +def tutorial(folder: Path) -> None: + sys.path.insert(0, str(TUTORIAL)) + make_dataset = importlib.import_module("workshop_data").make_dataset + root = make_dataset(folder / "workshop_data") + parts = [] + for f in sorted((root / "sessions").glob("*/spikes_*.csv")): + t = pacsv.read_csv(f) + session = f.parent.name + parts.append( + t.append_column("session", pa.array([session] * t.num_rows)).append_column( + "probe", pa.array([f.stem] * t.num_rows) + ) + ) + spikes = pa.concat_tables(parts) + stacked = folder / "spikes_all.csv" + pacsv.write_csv(spikes, stacked) + measure( + "tutorial spikes (CSVSource, every spikes file stacked)", + lambda: CSVSource( + str(stacked), + source_id="spikes", + tag_columns=["session", "probe"], + tag_only_columns=True, + ), + ) + for name in ("subjects.csv", "sessions.csv", "units.csv"): + measure( + f"tutorial {name}", + lambda name=name: CSVSource(str(root / name), source_id=name), + ) + + +def synthetic(n: int) -> None: + table = pa.table( + { + "key": pa.array([f"k{i:07d}" for i in range(n)], pa.large_string()), + "x": pa.array([i * 0.5 for i in range(n)], pa.float64()), + "y": pa.array(range(n), pa.int64()), + } + ) + measure( + "synthetic ArrowTableSource keyed by 'key'", + lambda: ArrowTableSource( + table, + tag_columns=["key"], + record_id_columns=["key"], + tag_only_columns=True, + source_id="synthetic", + ), + ) + + +def main() -> None: + n = int(sys.argv[1]) if len(sys.argv) > 1 else 1_000_000 + print("machine: cpus", os.cpu_count(), "| load averages", os.getloadavg()) + with tempfile.TemporaryDirectory() as d: + tutorial(Path(d)) + synthetic(n) + print("machine load after:", os.getloadavg()) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/stand_in_explicit_kind.py b/docs/dev/specs/itl-1425-source-identity/scripts/stand_in_explicit_kind.py new file mode 100644 index 000000000..7564d7057 --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/stand_in_explicit_kind.py @@ -0,0 +1,97 @@ +"""The explicit-kind-in-id design, simulated (ITL-1425, the developer's direction). + +In this process only (nothing under ``src/`` changes), ``golden_moves.patch("K_always")`` +makes every source id ``_v1:`` (a given ``subjects`` read by a CSV +source is ``csv_v1:subjects``) and removes the class name from the source identity. + +1. Without a stand-in: the same rows as two kinds under the given name ``subjects``. +2. With a simulated explicit stand-in: the CSV source swaps its kind part for the + original's (``arrow_table_v1``), keeping its name; the ledger prototype checks that + every record hashes equal first. + +For each it prints the source ids, the tokens, the record ids, function calls in a fresh +job over one database, node content hashes and stored pipeline rows. + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.stand_in_explicit_kind``. +""" + +from __future__ import annotations + +import warnings + +import orcapod.core.sources # noqa: F401 - load the modules before patching +import orcapod.pipeline # noqa: F401 +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import ArrowTableSource, CSVSource + +from ._fixtures import KEYED, SCHEMA, arrow_table, scratch, write_files +from .golden_moves import patch +from .ledger_prototype import compare, ledger +from .stand_in_job import calls, ratio, show_store + +warnings.simplefilter("ignore") + + +def run(db: InMemoryArrowDatabase, src) -> tuple[int, str]: + job = PipelineJob(name="k", database=db) + with job: + ratio.pod(src, label="ratio") + before = len(calls) + job.run() + return len(calls) - before, job.nodes["ratio"].content_hash().to_hex()[:12] + + +def describe(src) -> None: + t = src.as_table(columns={"system_tags": True, "source": True}) + rid = next(c for c in t.column_names if c.startswith("_tag_record_id")) + sid = next(c for c in t.column_names if c.startswith("_tag_source_id")) + print( + f" {type(src).__name__:16s} source_id {src.source_id!r}; system tag " + f"{t.column(sid)[0].as_py()!r}; record id {t.column(rid)[0].as_py()!r}; " + f"token {t.column('_source_weight')[0].as_py()!r}" + ) + + +def main() -> None: + patch("K_always") + folder = scratch() + paths = write_files(folder) + original = ArrowTableSource(arrow_table(), source_id="subjects", **KEYED) + csv = CSVSource(str(paths["csv"]), schema=SCHEMA, source_id="subjects", **KEYED) + + print("== 1. Two kinds, the same given name, no stand-in ==") + describe(original) + describe(csv) + db = InMemoryArrowDatabase() + for src in (original, csv): + n, h = run(db, src) + print(f" {type(src).__name__:16s} calls {n}; node content hash {h}") + show_store(db) + + print( + "\n== 2. Explicit stand-in: the CSV swaps its kind part for the original's ==" + ) + check = compare(ledger(original), ledger(csv)) + print(" ledger check (row hashes per record id):", check) + assert check["changed"] == 0 + kind = CSVSource.SOURCE_KIND + CSVSource.SOURCE_KIND = "arrow_table" # simulation of the swap only + try: + stand_in = CSVSource( + str(paths["csv"]), schema=SCHEMA, source_id="subjects", **KEYED + ) + finally: + CSVSource.SOURCE_KIND = kind + describe(stand_in) + db = InMemoryArrowDatabase() + for src in (original, stand_in): + n, h = run(db, src) + print(f" {type(src).__name__:16s} calls {n}; node content hash {h}") + show_store(db) + print(" the ledger would record kind csv, version 1 and the file for these reads") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/stand_in_job.py b/docs/dev/specs/itl-1425-source-identity/scripts/stand_in_job.py new file mode 100644 index 000000000..c634d634a --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/stand_in_job.py @@ -0,0 +1,118 @@ +"""Put each source kind in place of another in a job (ITL-1425, section 1). + +The same rows as an ``ArrowTableSource``, a ``CSVSource`` (declared ``schema=``), a +``DeltaTableSource`` and a ``SQLiteTableSource``, all with the given ``source_id`` +``subjects`` and the key column ``subject``. A function pod runs over them in two ways: + +* Part A, bind: one job, built over the ``ArrowTableSource``; each other kind is bound + into its slot in turn (``job.bind``) and the job runs again. +* Part B, a fresh job per kind over one shared database: what a user does when a table + moved (a new script names the new source). + +The script prints whether each bind is accepted, how many times the function ran, the +node hashes, whether the output (system tags and source-info tokens included) is equal, +and what the stored tables hold. + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.stand_in_job``. With ``--without-class-name`` the class name +is first removed from ``RootSource.identity_structure`` in this process (alternative C, +the patch of ``golden_moves``); nothing under ``src/`` changes. +""" + +from __future__ import annotations + +import sys +import warnings + +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase + +from ._fixtures import same_rows_sources, scratch + +warnings.simplefilter("ignore") + +calls: list[float] = [] + + +@function_pod(output_keys="ratio") +def ratio(weight: float | None, count: int | None) -> float | None: + calls.append(weight or 0.0) + if weight is None or not count: + return None + return weight / count + + +def show_store(db: InMemoryArrowDatabase) -> None: + for path in db.list_table_paths(): + table = db.get_all_records(path) + assert table is not None + name = "/".join(p if len(p) < 24 else p[:20] + "..." for p in path) + print(f" {name}: {table.num_rows} rows") + if "__node_content_hash" in table.column_names: + hashes = sorted( + {h for h in table.column("__node_content_hash").to_pylist() if h} + ) + print(f" distinct __node_content_hash values: {len(hashes)}") + + +def row(kind: str, job: PipelineJob, before: int, previous) -> object: + out = job.nodes["ratio"].as_table(columns={"source": True, "system_tags": True}) + print( + f" {kind:13s} calls: {len(calls) - before}; " + f"node content_hash {job.nodes['ratio'].content_hash().to_hex()[:12]}; " + f"slot content_hash {job.nodes['subjects'].content_hash().to_hex()[:12]}; " + f"pipeline_hash {job.nodes['ratio'].pipeline_hash().to_hex()[:12]}; " + f"output equal to previous: {previous.equals(out) if previous is not None else '-'}" + ) + return out + + +def main() -> None: + if "--without-class-name" in sys.argv: + from .golden_moves import patch + + patch("C") + print("** class name removed from the source identity (alternative C) **") + sources = same_rows_sources(scratch()) + + print("== Part A: one job, each kind bound in place of the previous ==") + db = InMemoryArrowDatabase() + job = PipelineJob(name="stand_in", database=db) + with job: + ratio.pod(sources["arrow_table"], label="ratio") + previous = None + for kind, src in sources.items(): + if kind != "arrow_table": + try: + job.bind(sources={"subjects": src}) + except Exception as exc: # noqa: BLE001 - the point is to show the refusal + print(f" {kind:13s} bind REFUSED: {type(exc).__name__}: {exc}") + continue + before = len(calls) + job.run() + previous = row(kind, job, before, previous) + print(" stored:") + show_store(db) + print( + " note: the function node keeps the content hash it computed before the " + "first bind; the slot's changes (see the column)." + ) + + print("\n== Part B: a fresh job per kind, one shared database ==") + db = InMemoryArrowDatabase() + previous = None + for kind, src in sources.items(): + job = PipelineJob(name="stand_in", database=db) + with job: + ratio.pod(src, label="ratio") + before = len(calls) + job.run() + previous = row(kind, job, before, previous) + stored_view = job.nodes["ratio"].as_source().as_table() + print(f" node.as_source() rows: {stored_view.num_rows}") + print(" stored:") + show_store(db) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1425-source-identity/scripts/types_positions_changes.py b/docs/dev/specs/itl-1425-source-identity/scripts/types_positions_changes.py new file mode 100644 index 000000000..34d1349ca --- /dev/null +++ b/docs/dev/specs/itl-1425-source-identity/scripts/types_positions_changes.py @@ -0,0 +1,151 @@ +"""Types, positional record ids and a silent implementation change, today (ITL-1425). + +Four measurements, all with the given ``source_id`` ``subjects``: + +1. A CSV read without a declared schema (types inferred) in place of the declared one. +2. A Delta table whose ``count`` is ``int32`` bound into a slot declared ``int64``. +3. Positional record ids (``record_id_columns=()``) when a stand-in lists the rows in + another order. +4. A reader change: the same source id and key, one value read differently (as a new + implementation of a kind might read it). What a job shows. + +Run from ``docs/dev/specs/itl-1425-source-identity``: +``uv run python -m scripts.types_positions_changes``. +""" + +from __future__ import annotations + +import warnings + +import pyarrow as pa +from deltalake import write_deltalake + +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import ArrowTableSource, CSVSource, DeltaTableSource + +from ._fixtures import ( + KEYED, + POSITIONAL, + KEY, + ROWS, + SCHEMA, + arrow_table, + same_rows_sources, + scratch, +) +from .stand_in_job import calls, ratio + +warnings.simplefilter("ignore") + + +def job_over(src, db): + job = PipelineJob(name="types", database=db) + with job: + ratio.pod(src, label="ratio") + return job + + +def run_counting(job) -> int: + before = len(calls) + job.run() + return len(calls) - before + + +def main() -> None: + folder = scratch() + sources = same_rows_sources(folder) + + print("== 1. CSV with inferred types in place of the declared source ==") + inferred = CSVSource(str(folder / "subjects.csv"), source_id="subjects", **KEYED) + print( + " inferred data schema:", str(inferred.arrow_schemas[1]).replace("\n", "; ") + ) + db = InMemoryArrowDatabase() + job = job_over(sources["arrow_table"], db) + print(" calls, declared source:", run_counting(job)) + try: + job.bind(sources={"subjects": inferred}) + print( + " bind of the inferred CSV into the declared slot: accepted;", + "calls:", + run_counting(job), + ) + except Exception as exc: # noqa: BLE001 + print(" bind REFUSED:", type(exc).__name__, str(exc)[:160]) + fresh = job_over(inferred, db) + print( + " fresh job over the inferred CSV: pipeline_hash equal:", + fresh.nodes["ratio"].pipeline_hash() == job.nodes["ratio"].pipeline_hash(), + "; calls:", + run_counting(fresh), + ) + + print("\n== 2. A Delta table with count as int32 into an int64 slot ==") + narrow = arrow_table().cast( + pa.schema([SCHEMA.field(0), SCHEMA.field(1), pa.field("count", pa.int32())]) + ) + write_deltalake(str(folder / "narrow"), narrow) + narrow_src = DeltaTableSource(folder / "narrow", source_id="subjects", **KEYED) + try: + job.bind(sources={"subjects": narrow_src}) + print(" bind accepted") + except Exception as exc: # noqa: BLE001 + print(" bind REFUSED:", type(exc).__name__) + + print("\n== 3. Positional record ids and another row order ==") + a = ArrowTableSource(arrow_table(), **POSITIONAL) + b = ArrowTableSource(arrow_table(list(reversed(ROWS))), **POSITIONAL) + ta = a.as_table(columns={"system_tags": True, "source": True}).sort_by(KEY) + tb = b.as_table(columns={"system_tags": True, "source": True}).sort_by(KEY) + rid = [c for c in ta.column_names if c.startswith("_tag_record_id")][0] + print(" content_hash equal:", a.content_hash() == b.content_hash()) + print(" record ids of s1, s2, s3 (original):", ta.column(rid).to_pylist()) + print(" record ids of s1, s2, s3 (reversed):", tb.column(rid).to_pylist()) + print( + " token of s1 weight:", + ta.column("_source_weight")[0].as_py(), + "vs", + tb.column("_source_weight")[0].as_py(), + ) + db = InMemoryArrowDatabase() + j1, j2 = job_over(a, db), job_over(b, db) + print(" calls original:", run_counting(j1), "; calls reversed:", run_counting(j2)) + + print("\n== 4. A reader change under the same name: what shows ==") + changed_rows = [dict(r) for r in ROWS] + changed_rows[1]["weight"] = 22.0001 # one value read differently + old = ArrowTableSource(arrow_table(), source_id="subjects", **KEYED) + new = ArrowTableSource(arrow_table(changed_rows), source_id="subjects", **KEYED) + print(" content_hash equal:", old.content_hash() == new.content_hash()) + print(" pipeline_hash equal:", old.pipeline_hash() == new.pipeline_hash()) + db = InMemoryArrowDatabase() + j_old, j_new = job_over(old, db), job_over(new, db) + print( + " calls before:", + run_counting(j_old), + "; calls after the change:", + run_counting(j_new), + ) + print( + " node content_hash equal:", + j_old.nodes["ratio"].content_hash() == j_new.nodes["ratio"].content_hash(), + ) + stored = j_new.nodes["ratio"].as_source().as_table() + print( + " stored view rows for the node (3 records):", + stored.num_rows, + "; s2 values:", + sorted( + v + for s, v in zip( + stored.column(KEY).to_pylist(), stored.column("ratio").to_pylist() + ) + if s == "s2" + ), + ) + print(" warnings or errors raised: none (the run completed)") + + +if __name__ == "__main__": + main() From 612c7198768f3f90e5f7306659339a3214c9c08f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 01:23:20 -0800 Subject: [PATCH 02/15] feat(sources): every source id names its kind and implementation version (ITL-1425) Every source id is _v:: Orcapod adds the kind part to a given name as to a default. The class name leaves the source content hash; the identity is (source id, Arrow schema identity, key columns). Saved configs hold the name and version apart. Test updates follow. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 16 +- .../core/sources/arrow_table_source.py | 14 +- src/orcapod/core/sources/base.py | 144 ++++++++---- src/orcapod/core/sources/cached_source.py | 25 +- src/orcapod/core/sources/csv_source.py | 19 +- src/orcapod/core/sources/data_frame_source.py | 12 +- src/orcapod/core/sources/db_table_source.py | 17 +- .../core/sources/delta_table_source.py | 21 +- src/orcapod/core/sources/derived_source.py | 32 +-- src/orcapod/core/sources/dict_source.py | 14 +- src/orcapod/core/sources/list_source.py | 14 +- src/orcapod/core/sources/polling_source.py | 96 ++++---- .../core/sources/postgresql_table_source.py | 6 +- src/orcapod/core/sources/source_ids.py | 218 +++++++++++++----- src/orcapod/core/sources/source_proxy.py | 14 +- .../core/sources/spiraldb_table_source.py | 23 +- .../core/sources/sqlite_table_source.py | 6 +- src/orcapod/core/sources/stream_builder.py | 68 +++--- src/orcapod/errors.py | 22 ++ src/orcapod/pipeline/restrictions.py | 2 +- src/orcapod/pipeline/serialization.py | 27 ++- .../sources/test_location_source_ids.py | 105 +++++---- tests/test_core/sources/test_source_ids.py | 186 +++++++++++++-- 23 files changed, 778 insertions(+), 323 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 15372f688..ef057f82e 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1360,8 +1360,10 @@ def from_stream( name is resolved in priority order: 1. *name* parameter (explicit override — highest priority). - 2. ``stream.source_id`` when *stream* is a ``RootSource`` — the canonical - source identity, stable across pipeline serialisation / deserialisation. + 2. ``stream.source_name`` when *stream* is a ``RootSource``: its source id + without the kind part (ITL-1425), so a slot keeps its name whichever kind + or implementation version reads the data, stable across pipeline + serialisation / deserialisation. 3. ``"{stream.label}:{hash_prefix}"`` for any other concrete stream type, combining the cosmetic label with a short content-hash suffix to ensure uniqueness. @@ -1385,7 +1387,7 @@ def from_stream( from orcapod.core.sources.base import RootSource if isinstance(stream, RootSource): - slot_name = stream.source_id + slot_name = stream.source_name else: slot_name = f"{stream.label}:{stream.content_hash().to_hex()}" if not isinstance(stream, SourceNodeBase): @@ -1905,8 +1907,8 @@ def from_stream( name: Optional explicit slot name. In all three cases, when *name* is provided it takes precedence over the stream's own name. For concrete streams (Case 3), when *name* is ``None`` the slot - name is resolved as: ``stream.source_id`` for ``RootSource`` - instances, or ``"{stream.label}:{hash_prefix}"`` for any other + name is resolved as: ``stream.source_name`` (the source id + without its kind part) for ``RootSource`` instances, or ``"{stream.label}:{hash_prefix}"`` for any other concrete stream type. Returns: @@ -1941,7 +1943,7 @@ def from_stream( # Case 3: concrete stream — bound SJN. # Slot name priority: # 1. explicit *name* parameter - # 2. stream.source_id for RootSource (canonical, stable identity) + # 2. stream.source_name for RootSource (its id without the kind part) # 3. label + short hash prefix for any other concrete stream type tag_schema, data_schema = stream.output_schema() if name is not None: @@ -1952,7 +1954,7 @@ def from_stream( from orcapod.core.sources.base import RootSource if isinstance(stream, RootSource): - slot_name = stream.source_id + slot_name = stream.source_name else: slot_name = f"{stream.label}:{stream.content_hash().to_hex()}" _require_stream_arrow_types(stream, slot_name) diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index 460075915..8bb95c545 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -87,8 +87,10 @@ class ArrowTableSource(RootSource): TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True - # The config type key; also the kind prefix of the default source id. + # The config type key; also the kind in the kind part of the source id. SOURCE_KIND: ClassVar[str] = "arrow_table" + # The version of this kind's implementation, in the kind part (ITL-1425). + SOURCE_VERSION: ClassVar[int] = 1 def __init__( self, @@ -118,8 +120,8 @@ def __init__( table, tag_columns=tag_columns, data_tags=source_data_tags(tag_columns, tag_only_columns), - source_id=self._source_id, - source_kind=self.SOURCE_KIND, + source_name=self._source_name, + kind_part=self.kind_part(), record_id_columns=normalize_record_id_columns(record_id_columns) or (), system_tag_columns=system_tag_columns, hash_in_key_order=hash_in_key_order, @@ -136,8 +138,8 @@ def __init__( self._record_id_columns = normalize_record_id_columns(record_id_columns) self._key_columns = self._record_id_columns or () - if self._source_id is None: - self._source_id = result.source_id + if self._source_name is None: + self._source_name = result.source_name def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize metadata-only config (in-memory table is not serializable).""" @@ -148,7 +150,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: if self._record_id_columns is None else list(self._record_id_columns), **self._tag_only_config(), - "source_id": self.source_id, + **self._source_id_config(), **self._identity_config(), } diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1eed1f022..f1e0fd6e8 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,5 +1,6 @@ from __future__ import annotations +import warnings from typing import TYPE_CHECKING, Any, ClassVar from orcapod import contexts @@ -9,10 +10,11 @@ typed_arrow_schemas, typed_zero_row_table, ) -from orcapod.system_constants import constants +from orcapod.errors import SourceVersionWarning from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Condition, ContentHash, Schema +from orcapod.core.sources import source_ids from orcapod.core.sources.provisional import warn_provisional_source from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.utils.schema_utils import arrow_schema_identity @@ -66,20 +68,45 @@ class RootSource(StreamBase): identity Merkle chain. Source identity: - Every source has a ``source_id`` — a canonical name that determines the - source's content identity and is used in the ``SourceRegistry`` so that - provenance tokens embedded in downstream data can be resolved back to the - originating source object. - - Concrete subclasses must ensure ``_source_id`` is set by the end of - ``__init__``. File-backed sources (DeltaTableSource, CSVSource) default + Every source has a ``source_id``, ``_v:`` (ITL-1425): the kind + part names the source's kind (``SOURCE_KIND``) and the version of its + implementation (``SOURCE_VERSION``), and the name is the given ``source_id`` + or the source's default. The source id is in every system tag and source-info + token of the source's rows, enters its content hash, and is used in the + ``SourceRegistry`` so that provenance tokens can be resolved back to the + source object. + + Concrete subclasses must ensure ``_source_name`` is set by the end of + ``__init__``. File-backed sources (DeltaTableSource, CSVSource) default to the file path; ``ArrowTableSource`` defaults to the table's data hash. + Every concrete class declares its own ``SOURCE_KIND`` and ``SOURCE_VERSION``. Concrete subclasses must set ``self._stream`` in their ``__init__`` to get the default stream delegation behavior. They may also override ``identity_structure()``. """ + SOURCE_KIND: ClassVar[str] + """The source's kind: its config type key and the first part of its source id.""" + + SOURCE_VERSION: ClassVar[int] + """The version of the kind's implementation, in the source id's kind part (ITL-1425). + + Bump it when a row read before a change could read differently after it (other + values, other Arrow types, another record id): a new version is a new source id. + """ + + @classmethod + def kind_part(cls) -> str: + """The kind part of this class's source ids: ``_v``.""" + return source_ids.kind_part(cls.SOURCE_KIND, cls.SOURCE_VERSION) + + def __init_subclass__(cls, **kwargs: Any) -> None: + super().__init_subclass__(**kwargs) + kind = cls.__dict__.get("SOURCE_KIND") + if kind is not None: + source_ids.register_kind(kind) + # Whether the source takes ``tag_only_columns`` and saves it in its config # (ITL-1019): from format 0.3.0 on such a config always holds it. TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = False @@ -109,23 +136,11 @@ def __init__( data_context=data_context, config=config, ) - if source_id == "": - raise ValueError( - "source_id is empty: a source id is the source's name, and an empty " - "one would make every source-info token start with " - f"{constants.BLOCK_SEPARATOR!r}; give the source a name, or leave " - "source_id unset for the default" - ) - if source_id is not None and ( - constants.BLOCK_SEPARATOR in source_id or source_id.endswith(":") - ): - raise ValueError( - f"source_id {source_id!r} contains {constants.BLOCK_SEPARATOR!r} or ends " - "with ':', which would blur the separator of the parts of a source-info " - "token (::::); give the source another " - "name" - ) - self._source_id = source_id + # A given source_id is the source's name: its kind part is added in front. + if source_id is not None: + source_ids.require_source_name(source_id) + source_ids.warn_if_name_looks_like_an_id(source_id) + self._source_name: str | None = source_id # ------------------------------------------------------------------------- # Source identity @@ -172,13 +187,60 @@ def pipeline_hash( @property def source_id(self) -> str: - """Canonical name for this source used in the registry and provenance - strings. If not set, raises ``ValueError``. + """The source id, ``_v:``: in the registry, system tags and tokens. + + Raises: + ValueError: If the source has no name yet. """ self._note_provisional_identity_use() - if self._source_id is None: - raise ValueError("source_id is not set") - return self._source_id + return source_ids.build_source_id( + self.SOURCE_KIND, self.SOURCE_VERSION, self.source_name + ) + + @property + def source_name(self) -> str: + """The source's name: the given ``source_id``, or the default (ITL-1425). + + Raises: + ValueError: If the source has no name yet. + """ + if self._source_name is None: + raise ValueError("the source has no name yet") + return self._source_name + + def _source_id_config(self) -> dict[str, Any]: + """The saved form of the source id: name and version apart (ITL-1425). + + The kind is the config's ``source_type``; ``saved_source_name`` reads it back. + """ + return {"source_name": self.source_name, "source_version": self.SOURCE_VERSION} + + @classmethod + def saved_source_name(cls, config: dict[str, Any]) -> str | None: + """Return the name a saved source config holds, warning on a version change. + + A source saved by another version of its kind is rebuilt as the installed + version, so its source id names that version: a different source id. The saved + id is not rewritten; ``SourceVersionWarning`` names both versions. + + Args: + config: A saved source config (``to_config``). + + Returns: + The saved name, or ``None`` when the source was saved with its default. + """ + saved_version = config.get("source_version") + if saved_version is not None and saved_version != cls.SOURCE_VERSION: + warnings.warn( + f"a {cls.SOURCE_KIND} source saved by version {saved_version} of its " + f"implementation is loaded as version {cls.SOURCE_VERSION}: its source " + f"id now names version {cls.SOURCE_VERSION}, so it is a different " + "source, and results stored for the saved source are not this " + "source's", + SourceVersionWarning, + stacklevel=2, + ) + return config.get("source_name") # ------------------------------------------------------------------------- # Restriction (ITL-1218) @@ -238,18 +300,20 @@ def _schema_identity(self) -> tuple[ContentHash, ContentHash]: return arrow_schema_identity(*self.arrow_schemas, self.data_context) def identity_structure(self) -> Any: - """Identity from the class name, Arrow schema, ``source_id`` and key columns. - - The key columns are the resolved ``record_id_columns`` (``()`` for the - position): two sources that differ only in how they name their rows are two - sources, so their records never share a cache (developer, November 16, 2026, - ITL-1154). The pipeline hash stays schema-only. + """Identity from the ``source_id``, the Arrow schema and the key columns. + + The source id's kind part names the kind and implementation version that read + the data; the class name is not part of the identity (ITL-1425), so the kind + enters a datum's identity in exactly one place. The key columns are the + resolved ``record_id_columns`` (``()`` for the position): two sources that + differ only in how they name their rows are two sources, so their records + never share a cache (developer, November 16, 2026, ITL-1154). The pipeline + hash stays schema-only. """ self._note_provisional_identity_use() # a direct read is a use (ITL-1331) return ( - self.__class__.__name__, - self._schema_identity(), self.source_id, + self._schema_identity(), self._key_columns, ) @@ -396,9 +460,9 @@ 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 itself is not changed.""" - if self.has_assigned_label or self._source_id is None: + if self.has_assigned_label or self._source_name is None: return self.label - return self._source_id + return self.source_id def head( self, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 4be081849..aaecbe38c 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -11,6 +11,7 @@ from orcapod import contexts from orcapod.core.data_tags import stream_data_tags from orcapod.config import OrcapodConfig +from orcapod.core.sources import source_ids from orcapod.core.sources.base import RootSource from orcapod.errors import InputValidationError, UnstorableColumnError from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -82,7 +83,9 @@ class CachedSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "cached" - """Config type key and default source-id kind of this source (one vocabulary).""" + """Config type key of this source. Not in its source id: it has its wrapped source's.""" + SOURCE_VERSION: ClassVar[int] = 1 + """The version of this kind's implementation (ITL-1425); not in its source id.""" HASH_COLUMN_NAME = "_record_hash" @@ -97,13 +100,16 @@ def __init__( cache_database: ArrowDatabaseProtocol, cache_path_prefix: tuple[str, ...] = (), cache_path: tuple[str, ...] | None = None, - source_id: str | None = None, label: str | None = None, data_context: str | contexts.DataContext | None = None, config: OrcapodConfig | None = None, ) -> None: """Wrap ``source`` in a cache kept in ``cache_database``. + The cached source has its wrapped source's ``source_id`` (ITL-1425): its rows + are that source's rows, with that source's system tags and tokens; a cache is + not another implementation reading the data. + Raises: ValueError: If ``source`` is restricted (a condition or a limit). """ @@ -112,10 +118,7 @@ def __init__( refuse_restricted_cache_input(source) if data_context is None: data_context = source.data_context_key - if source_id is None: - source_id = source.source_id super().__init__( - source_id=source_id, label=label, data_context=data_context, config=config, @@ -177,7 +180,6 @@ def to_config( "cache_path_prefix": list(self._cache_path_prefix), # The path without its layout component, as ``cache_path`` takes it. "cache_path": list(self._unversioned_cache_path), - "source_id": self.source_id, # Note: identity fields (content_hash, pipeline_hash, etc.) intentionally omitted } @@ -236,7 +238,6 @@ def from_config( cache_database=cache_db, cache_path_prefix=tuple(config.get("cache_path_prefix", ())), cache_path=tuple(config["cache_path"]) if "cache_path" in config else None, - source_id=config.get("source_id"), ) # ------------------------------------------------------------------------- @@ -246,6 +247,16 @@ def from_config( def identity_structure(self) -> Any: return self._source.identity_structure() + @property + def source_id(self) -> str: + """The wrapped source's source id: the cache presents that source's rows.""" + return self._source.source_id + + @property + def source_name(self) -> str: + """The name part of the wrapped source's source id.""" + return source_ids.parse_source_id(self._source.source_id).name + def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": """The wrapped source's Arrow schemas: the cache stores that source's rows.""" return typed_arrow_schemas(self._source) diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 6fbfb841a..9a05716e3 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -11,7 +11,7 @@ from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.source_ids import location_source_id +from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.reload import keep_nullable_columns, same_rows from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, @@ -282,7 +282,9 @@ class CSVSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "csv" - """Config type key and default source-id kind of this source (one vocabulary).""" + """Config type key and the kind in the source id's kind part (one vocabulary).""" + SOURCE_VERSION: ClassVar[int] = 1 + """The version of this kind's implementation, in the kind part (ITL-1425).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( @@ -298,7 +300,7 @@ def __init__( **kwargs: Any, ) -> None: if source_id is None: - source_id = location_source_id(self.SOURCE_KIND, str(file_path)) + source_id = location_source_name(str(file_path)) super().__init__(source_id=source_id, **kwargs) self._file_path = file_path @@ -325,8 +327,8 @@ def __init__( self._stream = result.stream self._tag_columns = result.tag_columns self._system_tag_columns = result.system_tag_columns - if self._source_id is None: - self._source_id = result.source_id + if self._source_name is None: + self._source_name = result.source_name def _read_table(self) -> pa.Table: """Read the file into an Arrow table, typed as at construction. @@ -364,7 +366,8 @@ def _build(self, table: pa.Table) -> SourceStreamResult: table, tag_columns=self._tag_columns, data_tags=source_data_tags(self._tag_columns, self._tag_only_columns), - source_id=self._source_id, + source_name=self._source_name, + kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), system_tag_columns=self._system_tag_columns, ) @@ -445,7 +448,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "record_id_columns": None if self._record_id_columns is None else list(self._record_id_columns), - "source_id": self.source_id, + **self._source_id_config(), **schema_config, **self._identity_config(), } @@ -505,6 +508,6 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> CSVSource: tag_only_columns=saved_tag_only_columns(config), system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), - source_id=config.get("source_id"), + source_id=cls.saved_source_name(config), schema=cls.saved_schema(config), ) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index d89ee808d..2d8fdf330 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -47,6 +47,8 @@ class DataFrameSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "data_frame" + # The version of this kind's implementation, in the kind part (ITL-1425). + SOURCE_VERSION: ClassVar[int] = 1 def __init__( self, @@ -100,8 +102,8 @@ def __init__( arrow_table, tag_columns=tag_columns, data_tags=source_data_tags(tag_columns, tag_only_columns), - source_id=self._source_id, - source_kind=self.SOURCE_KIND, + source_name=self._source_name, + kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, system_tag_columns=system_tag_columns, @@ -112,8 +114,8 @@ def __init__( self._tag_only_columns = tuple( c for c in result.tag_columns if c not in result.data_tags ) - if self._source_id is None: - self._source_id = result.source_id + if self._source_name is None: + self._source_name = result.source_name def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize metadata-only config (DataFrame is not serializable).""" @@ -121,7 +123,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "source_type": self.SOURCE_KIND, "tag_columns": list(self._tag_columns), **self._tag_only_config(), - "source_id": self.source_id, + **self._source_id_config(), **self._identity_config(), } diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 437b2aedc..67e4d1308 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -22,7 +22,7 @@ from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.source_ids import location_source_id +from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.reload import keep_nullable_columns, same_rows from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, @@ -84,7 +84,9 @@ class DBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "db_table" - """Config type key and default source-id kind of this source (one vocabulary).""" + """Config type key and the kind in the source id's kind part (one vocabulary).""" + SOURCE_VERSION: ClassVar[int] = 1 + """The version of this kind's implementation, in the kind part (ITL-1425).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( @@ -114,7 +116,7 @@ def __init__( "source of your database (SQLiteTableSource, " "PostgreSQLTableSource), whose default id holds the address." ) - source_id = location_source_id(self.SOURCE_KIND, address) + source_id = location_source_name(address) super().__init__( source_id=source_id, label=label, @@ -179,8 +181,8 @@ def __init__( self._stream = result.stream self._tag_columns = result.tag_columns self._system_tag_columns = result.system_tag_columns - if self._source_id is None: - self._source_id = result.source_id + if self._source_name is None: + self._source_name = result.source_name def _table_address( self, connector: DBConnectorProtocol, table_name: str @@ -251,7 +253,8 @@ def _build(self, table: pa.Table) -> SourceStreamResult: table, tag_columns=self._tag_columns, data_tags=source_data_tags(self._tag_columns, self._tag_only_columns), - source_id=self._source_id, + source_name=self._source_name, + kind_part=self.kind_part(), record_id_columns=self._key_columns, system_tag_columns=self._system_tag_columns, ) @@ -311,7 +314,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "record_id_columns": None if self._record_id_columns is None else list(self._record_id_columns), - "source_id": self.source_id, + **self._source_id_config(), **self._identity_config(), } diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 6bfad9f78..bd8038b65 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -10,7 +10,7 @@ from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.source_ids import location_source_id +from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.reload import same_rows from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, @@ -50,7 +50,9 @@ class DeltaTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "delta_table" - """Config type key and default source-id kind of this source (one vocabulary).""" + """Config type key and the kind in the source id's kind part (one vocabulary).""" + SOURCE_VERSION: ClassVar[int] = 1 + """The version of this kind's implementation, in the kind part (ITL-1425).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( @@ -68,9 +70,7 @@ def __init__( if source_id is None: # The table folder's path or URI as passed: a relative path stays relative. - source_id = location_source_id( - self.SOURCE_KIND, os.fspath(delta_table_path) - ) + source_id = location_source_name(os.fspath(delta_table_path)) super().__init__(source_id=source_id, **kwargs) self._delta_table_path = resolved @@ -99,8 +99,8 @@ def __init__( self._stream = result.stream self._tag_columns = result.tag_columns self._system_tag_columns = result.system_tag_columns - if self._source_id is None: - self._source_id = result.source_id + if self._source_name is None: + self._source_name = result.source_name def _read_table(self) -> "pa.Table": """Read the table at the Delta version ``self._delta_table`` is loaded at.""" @@ -117,7 +117,8 @@ def _build(self, table: "pa.Table") -> SourceStreamResult: table, tag_columns=self._tag_columns, data_tags=source_data_tags(self._tag_columns, self._tag_only_columns), - source_id=self._source_id, + source_name=self._source_name, + kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), system_tag_columns=self._system_tag_columns, ) @@ -173,7 +174,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "record_id_columns": None if self._record_id_columns is None else list(self._record_id_columns), - "source_id": self.source_id, + **self._source_id_config(), **self._identity_config(), } @@ -188,5 +189,5 @@ def from_config( tag_only_columns=saved_tag_only_columns(config), system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), - source_id=config.get("source_id"), + source_id=cls.saved_source_name(config), ) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 5b06672d2..8bf60994b 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -15,7 +15,7 @@ from orcapod.core.sources.base import RootSource from orcapod.core.sources.provisional import warn_provisional_source from orcapod.core.sources.reload import same_rows -from orcapod.core.sources.source_ids import hash_source_id +from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, @@ -192,8 +192,10 @@ class DerivedSource(RootSource): """ # The config type key (names the class a saved config is rebuilt with) and - # the kind prefix of the plain form's default source id. + # the kind in the source id's kind part, for both forms. SOURCE_KIND: ClassVar[str] = "derived" + # The version of this kind's implementation, in the kind part (ITL-1425). + SOURCE_VERSION: ClassVar[int] = 1 PROVISIONAL = True """Provisional in data context v1, both forms (ITL-1331, ``PROVISIONAL_SOURCES``).""" @@ -230,7 +232,7 @@ def require_saved_source_id(cls, config: Mapping[str, Any]) -> None: if ( config.get("source_type") == cls.SOURCE_KIND and config.get("tags_as_data") is not None - and config.get("source_id") is None + and config.get("source_name") is None ): raise cls._missing_source_id() for key in NESTED_SOURCE_CONFIG_KEYS: @@ -273,12 +275,10 @@ def __init__( self._explicit_source_id = source_id if source_id is None: - # Only the plain form gets here without a source id. A source id is the - # source's name, used as-is in system tags and source-info values; a - # default built from a hash keeps a source-kind prefix and the hash's - # label (developer, November 11, 2026): ``derived::`` of the origin's content hash. - source_id = hash_source_id(self.SOURCE_KIND, origin.content_hash()) + # Only the plain form gets here without a source id. Its default name is + # the origin's content hash with its label, after the kind part + # (ITL-1425): ``derived_v1::``. + source_id = hash_source_name(origin.content_hash()) super().__init__(source_id=source_id, **kwargs) self._origin = origin self._record_id_columns = key_columns @@ -299,8 +299,8 @@ def identity_structure(self) -> Any: """Return what the content hash is built from. The plain form is tied to the origin node's content hash. The - ``tags_as_data`` form is the root source rule (class name, output schema, - ``source_id``, key columns) followed by the sorted mapping items: two mappings can give + ``tags_as_data`` form is the root source rule (``source_id``, output schema, + key columns) followed by the sorted mapping items: two mappings can give the same schema (two tag columns of one type copied to one name) while the copy holds different values, so with an explicit ``source_id`` the mapping has to tell the sources apart (ITL-1000). @@ -344,7 +344,10 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: "record_id_columns": None if self._record_id_columns is None else list(self._record_id_columns), - "source_id": self._explicit_source_id, + # The plain form's default name is not written: it is recomputed from + # the origin. + "source_name": self._explicit_source_id, + "source_version": self.SOURCE_VERSION, } # Every concrete source has to_config; the abstract RootSource does not # declare it, so look it up as PipelineJob.save does. @@ -395,7 +398,7 @@ def from_config( origin = resolve_source_from_config(config["origin"], db_registry=db_registry) return cls( origin, - source_id=config.get("source_id"), + source_id=cls.saved_source_name(config), tags_as_data=config["tags_as_data"], record_id_columns=config.get("record_id_columns"), ) @@ -594,7 +597,8 @@ def _derive_from( table, tag_columns=self._origin.keys()[0], data_tags=self._data_tags(), - source_id=self.source_id, + source_name=self.source_name, + kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), ) return result.stream diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 234c9d6b2..97c5b349d 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -44,6 +44,8 @@ class DictSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "dict" + # The version of this kind's implementation, in the kind part (ITL-1425). + SOURCE_VERSION: ClassVar[int] = 1 def __init__( self, @@ -88,8 +90,8 @@ def __init__( arrow_table, tag_columns=tag_columns, data_tags=source_data_tags(tag_columns, tag_only_columns), - source_id=self._source_id, - source_kind=self.SOURCE_KIND, + source_name=self._source_name, + kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, system_tag_columns=system_tag_columns, @@ -100,9 +102,9 @@ def __init__( self._tag_only_columns = tuple( c for c in result.tag_columns if c not in result.data_tags ) - if self._source_id is None: - self._source_id = result.source_id - warn_source_tensor_conversions(self._source_id, rows) + if self._source_name is None: + self._source_name = result.source_name + warn_source_tensor_conversions(self.source_id, rows) def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize metadata-only config (data is not serializable).""" @@ -110,7 +112,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "source_type": self.SOURCE_KIND, "tag_columns": list(self._tag_columns), **self._tag_only_config(), - "source_id": self.source_id, + **self._source_id_config(), **self._identity_config(), } diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 48d8eae61..ce9ceb1a1 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -39,6 +39,8 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "list" + # The version of this kind's implementation, in the kind part (ITL-1425). + SOURCE_VERSION: ClassVar[int] = 1 def __init__( self, @@ -121,23 +123,23 @@ def __init__( result = builder.build( arrow_table, tag_columns=tag_columns, - source_id=self._source_id, - source_kind=self.SOURCE_KIND, + source_name=self._source_name, + kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, ) self._stream = result.stream - if self._source_id is None: - self._source_id = result.source_id - warn_source_tensor_conversions(self._source_id, rows) + if self._source_name is None: + self._source_name = result.source_name + warn_source_tensor_conversions(self.source_id, rows) def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize metadata-only config (data is not serializable).""" return { "source_type": self.SOURCE_KIND, "name": self.name, - "source_id": self.source_id, + **self._source_id_config(), **self._identity_config(), } diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 03d51bc42..8ad7da4b6 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -21,7 +21,7 @@ from typing_extensions import override from orcapod.core.sources.base import RootSource -from orcapod.core.sources.source_ids import hash_source_id +from orcapod.core.sources.source_ids import hash_source_name from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, @@ -275,7 +275,9 @@ async def close(self): """ SOURCE_KIND: ClassVar[str] = "polling_source" - """Config type key and default source-id kind of this source (one vocabulary).""" + """Config type key and the kind in the source id's kind part (one vocabulary).""" + SOURCE_VERSION: ClassVar[int] = 1 + """The version of this kind's implementation, in the kind part (ITL-1425).""" PROVISIONAL = True """Provisional in data context v1 (ITL-1314, ``PROVISIONAL_SOURCES``).""" @@ -317,12 +319,11 @@ def __init__( self._committed_record_ids: set[str] = set() self._state_lock: threading.Lock = threading.Lock() self._canonical_arrow_schema: pa.Schema | None = None - # The default source id is the kind and the semantic hash of the impl's identity: - # a hash, never the identity's repr, which is not stable (ITL-1154). - if self._source_id is None: - self._source_id = hash_source_id( - self.SOURCE_KIND, - self.data_context.semantic_hasher.hash_object(self._impl.identity()), + # The default name is the semantic hash of the impl's identity: a hash, never + # the identity's repr, which is not stable (ITL-1154). + if self._source_name is None: + self._source_name = hash_source_name( + self.data_context.semantic_hasher.hash_object(self._impl.identity()) ) # Split impl.schema() into tag/data schemas self._tag_schema: Schema | None = None @@ -428,17 +429,21 @@ def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": # ------------------------------------------------------------------------- def identity_structure(self) -> Any: - """Identity derived from the impl's own identity, tag columns and key columns. - - Delegates to ``impl.identity()`` so that the implementer fully - controls what makes two ``PollingSource`` instances distinct; the key - columns (``record_id_columns``) follow, as for every root source (ITL-1154). - The tag columns name a set: they enter in name order, so the order they are - declared in changes no hash (ITL-1271). The key columns keep their order: it - is the explicit order of the record id. + """Identity from the source id, the impl's own identity, tags and key columns. + + The source id (``polling_source_v1:``) comes first, as for every root + source (ITL-1425): a given ``source_id`` now tells two polling sources apart. + ``impl.identity()`` follows, so that the implementer still controls what makes + two ``PollingSource`` instances distinct; then the key columns + (``record_id_columns``), as for every root source (ITL-1154). The tag columns + name a set: they enter in name order, so the order they are declared in + changes no hash (ITL-1271). The key columns keep their order: it is the + explicit order of the record id. The schema is not part of it: it may be + known only after a poll (ITL-1316 decides this source's identity). """ self._note_provisional_identity_use() # a direct read is a use (ITL-1331) return ( + self.source_id, self._impl.identity(), tuple(sorted(self._tag_columns)), self._key_columns, @@ -690,7 +695,7 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: "tag_columns": list(self._tag_columns), "record_id_columns": list(self._record_id_columns), "polling_config": dataclasses.asdict(self._polling_config), - "source_id": self._source_id, + **self.source_id_config(), "impl_config": self._impl.to_config(), } @@ -736,7 +741,7 @@ def from_config( impl=impl, tag_columns=config["tag_columns"], polling_config=polling_config, - source_id=config.get("source_id"), + source_id=cls.saved_source_name(config), record_id_columns=config.get("record_id_columns"), ) @@ -765,7 +770,7 @@ def _sync_poll_and_commit(self) -> bool: if cursor_snapshot is None: # First access — no poll needed, fetch unconditionally. logger.debug( - "PollingSource %r: first sync access — fetching", self._source_id + "PollingSource %r: first sync access — fetching", self.source_id ) new_cursor, data = _run_sync(self._impl.fetch, cursor=None) new_stream = self._try_build_stream(data) @@ -785,7 +790,7 @@ def _sync_poll_and_commit(self) -> bool: if has_new: logger.debug( "PollingSource %r: sync poll found new data — fetching", - self._source_id, + self.source_id, ) new_cursor, data = _run_sync(self._impl.fetch, cursor=cursor_snapshot) new_stream = self._try_build_stream(data) @@ -803,7 +808,7 @@ def _sync_poll_and_commit(self) -> bool: committed = True return committed and self._mark_new_rows(new_stream) logger.debug( - "PollingSource %r: sync poll — cache still valid", self._source_id + "PollingSource %r: sync poll — cache still valid", self.source_id ) return False @@ -830,7 +835,7 @@ def _commit_batch(self, new_stream: ArrowTableStream) -> None: repeated = sorted(self._committed_record_ids.intersection(record_ids)) if repeated: raise RowIdentifierError( - f"PollingSource {self._source_id!r}: a polled batch repeats the key " + f"PollingSource {self.source_id!r}: a polled batch repeats the key " f"{repeated[0]} of a row polled earlier ({len(repeated)} repeated " "in all). A polled row is identified by its key alone, so a key is " "polled once; give the update a new key or start a new source." @@ -870,7 +875,7 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: if len(df.columns) == 0: logger.debug( "PollingSource %r: fetch returned data with no columns — skipping stream build", - self._source_id, + self.source_id, ) return None return self._build_stream_from_df(df) @@ -910,7 +915,7 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: "PollingSource %r: no schema declared via impl.schema(); " "inferring nullability from first batch. Implement impl.schema() " "to avoid schema drift on zero-row polls or null-free batches.", - self._source_id, + self.source_id, ) self._canonical_arrow_schema = arrow_utils.infer_schema_nullable( arrow_table @@ -939,7 +944,8 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: result = builder.build( arrow_table, tag_columns=self._tag_columns, - source_id=self._source_id, + source_name=self._source_name, + kind_part=self.kind_part(), record_id_columns=self._record_id_columns, ) return result.stream @@ -967,7 +973,7 @@ def _require_declared_types(self, arrow_table: pa.Table) -> None: ] if undeclared: raise SchemaInconsistencyError( - f"PollingSource {self._source_id!r}: the fetched columns {undeclared} " + f"PollingSource {self.source_id!r}: the fetched columns {undeclared} " f"are not in the declared schema {self._declared_arrow.names} (its " "identity was fixed by the declared schema; declare them in " "impl.schema(), or fetch only the declared columns)." @@ -982,7 +988,7 @@ def _require_declared_types(self, arrow_table: pa.Table) -> None: ): continue raise SchemaInconsistencyError( - f"PollingSource {self._source_id!r}: the fetched column " + f"PollingSource {self.source_id!r}: the fetched column " f"{declared.name!r} has the Arrow type {field.type}, but the source " f"declares {declared.type} (its identity was fixed by the declared " "schema; a Python type means one Arrow type, so declare impl.schema() " @@ -1006,11 +1012,11 @@ def _validate_against_declared_schemas(self, stream: ArrowTableStream) -> None: actual_tag_schema, actual_data_schema = stream.output_schema() if self._tag_schema is not None: _assert_schema_match( - "tag", self._tag_schema, actual_tag_schema, self._source_id + "tag", self._tag_schema, actual_tag_schema, self.source_id ) if self._data_schema is not None: _assert_schema_match( - "data", self._data_schema, actual_data_schema, self._source_id + "data", self._data_schema, actual_data_schema, self.source_id ) def _validate_combining_schemas( @@ -1039,14 +1045,14 @@ def _validate_combining_schemas( added = sorted(new_cols - old_cols) removed = sorted(old_cols - new_cols) raise SchemaInconsistencyError( - f"PollingSource {self._source_id!r}: schema mismatch between batches — " + f"PollingSource {self.source_id!r}: schema mismatch between batches — " f"added: {added!r}, removed: {removed!r}" ) old_tag_schema, old_data_schema = existing.output_schema() new_tag_schema, new_data_schema = new_stream.output_schema() - _assert_schema_match("tag", old_tag_schema, new_tag_schema, self._source_id) - _assert_schema_match("data", old_data_schema, new_data_schema, self._source_id) + _assert_schema_match("tag", old_tag_schema, new_tag_schema, self.source_id) + _assert_schema_match("data", old_data_schema, new_data_schema, self.source_id) def _combine( self, existing: ArrowTableStream, new_stream: ArrowTableStream @@ -1144,7 +1150,7 @@ async def async_iter_data(self): logger.info( "PollingSource %r starting (interval=%.2fs, duration=%.1fs)", - self._source_id, + self.source_id, cfg.interval, cfg.duration, ) @@ -1176,7 +1182,7 @@ async def async_iter_data(self): if has_new: logger.debug( "PollingSource %r: new data detected, fetching", - self._source_id, + self.source_id, ) # Fetch — no lock held across await. new_cursor, data = await self._impl.fetch( @@ -1217,13 +1223,13 @@ async def async_iter_data(self): ) logger.debug( "PollingSource %r: committed %d row(s)", - self._source_id, + self.source_id, emitted_count, ) else: logger.debug( "PollingSource %r: poll returned no new data", - self._source_id, + self.source_id, ) consecutive_errors = 0 @@ -1235,7 +1241,7 @@ async def async_iter_data(self): logger.error( "PollingSource %r: cursor invalidated — previous state cannot " "be reconciled with already-emitted rows. Terminating source.", - self._source_id, + self.source_id, ) raise @@ -1249,7 +1255,7 @@ async def async_iter_data(self): logger.error( "PollingSource %r: poll/fetch error (consecutive=%d, " "backoff=%.1fs): %s", - self._source_id, + self.source_id, consecutive_errors, backoff, e, @@ -1258,7 +1264,7 @@ async def async_iter_data(self): logger.error( "PollingSource %r: max consecutive errors (%d) reached. " "Terminating source.", - self._source_id, + self.source_id, cfg.max_consecutive_errors, ) break @@ -1273,7 +1279,7 @@ async def async_iter_data(self): logger.warning( "PollingSource %r: tick overrun — consumed %d interval(s) " "(consecutive_misses=%d/%d)", - self._source_id, + self.source_id, intervals_consumed, consecutive_misses, cfg.max_missed_intervals, @@ -1282,7 +1288,7 @@ async def async_iter_data(self): logger.error( "PollingSource %r: overrun threshold exceeded. " "Terminating source.", - self._source_id, + self.source_id, ) break else: @@ -1294,7 +1300,7 @@ async def async_iter_data(self): logger.info( "PollingSource %r: duration limit (%.1fs) reached. " "Terminating source.", - self._source_id, + self.source_id, cfg.duration, ) break @@ -1312,10 +1318,10 @@ async def async_iter_data(self): except asyncio.CancelledError: logger.info( "PollingSource %r: cancelled — shutting down cleanly.", - self._source_id, + self.source_id, ) finally: - logger.debug("PollingSource %r: calling impl.close()", self._source_id) + logger.debug("PollingSource %r: calling impl.close()", self.source_id) await self._impl.close() - logger.info("PollingSource %r: closed.", self._source_id) + logger.info("PollingSource %r: closed.", self.source_id) diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 0f12aa372..83f4a79ba 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -171,7 +171,9 @@ class PostgreSQLTableSource(DBTableSource): """ SOURCE_KIND: ClassVar[str] = "postgresql_table" - """Config type key and default source-id kind of this source (one vocabulary).""" + """Config type key and the kind in the source id's kind part (one vocabulary).""" + SOURCE_VERSION: ClassVar[int] = 1 + """The version of this kind's implementation, in the kind part (ITL-1425).""" def __init__( self, @@ -296,7 +298,7 @@ def from_config( tag_only_columns=saved_tag_only_columns(config), system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), - source_id=config.get("source_id"), + source_id=cls.saved_source_name(config), label=config.get("label"), data_context=config.get("data_context"), ) diff --git a/src/orcapod/core/sources/source_ids.py b/src/orcapod/core/sources/source_ids.py index c685f2c88..dc51b8237 100644 --- a/src/orcapod/core/sources/source_ids.py +++ b/src/orcapod/core/sources/source_ids.py @@ -1,92 +1,202 @@ -"""The forms of a default source id: the one place that builds them (ITL-957, ITL-1154). +"""Source ids: the one place that builds and parses them (ITL-957, ITL-1154, ITL-1425). -A source id is the source's name. A source given a ``source_id`` uses it exactly as given. -With none, every source builds a default that names its kind first (the class's -``SOURCE_KIND``, which is also its config type key): +Every source id is ``_v:`` (developer, November 23, 2026, ITL-1425): -* ``:
``; a given id is used as is.""" + """``sqlite_table_v1::main.
``; a given name is kept.""" assert SQLiteTableSource( sqlite_path, "trials", tag_only_columns=True - ).source_id == (f"sqlite_table:{sqlite_path}:main.trials") + ).source_id == (f"sqlite_table_v1:{sqlite_path}:main.trials") given = SQLiteTableSource( sqlite_path, "trials", source_id=GIVEN, tag_only_columns=True ) - assert given.source_id == GIVEN + assert given.source_id == f"sqlite_table_v1:{GIVEN}" def test_polling_default_is_the_hash_of_the_impl_identity() -> None: - """``polling_source:`` values. A source id -given by the user is never changed. +the source easy to identify. Every source id starts with its kind part, +``_v`` (November 23, 2026, ITL-1425); a default name built +from a hash carries the hash's own label. The one string is used unchanged as the +``source_id`` system tag value and inside the ``_source_`` values. A name given by +the user is never changed: the kind part is put in front of it. """ from __future__ import annotations @@ -116,7 +117,7 @@ def test_default_is_kind_label_hex(self, cls, kind, make, data_column): source = make() parts = source.source_id.split(":") assert len(parts) == 3, source.source_id - assert parts[0] == kind + assert parts[0] == f"{kind}_v1" assert parts[1] == _arrow_label(source) assert len(parts[2]) >= 64 int(parts[2], 16) # raises unless the last part is hex @@ -127,7 +128,7 @@ def test_kind_is_the_config_type_key_defined_once_on_the_class( source = make() assert cls.SOURCE_KIND == kind assert source.to_config()["source_type"] == cls.SOURCE_KIND - assert source.source_id.startswith(f"{cls.SOURCE_KIND}:") + assert source.source_id.startswith(f"{cls.SOURCE_KIND}_v{cls.SOURCE_VERSION}:") def test_same_string_in_system_tag_and_source_info( self, cls, kind, make, data_column @@ -150,16 +151,16 @@ def test_default_is_deterministic(self, cls, kind, make, data_column): assert make().source_id == make().source_id @pytest.mark.parametrize("given", ["my_source", "a:b:c", "0123abcd", "arrow_table"]) - def test_given_source_id_is_never_changed( - self, cls, kind, make, data_column, given - ): + def test_given_name_is_never_changed(self, cls, kind, make, data_column, given): source = make(source_id=given) - assert source.source_id == given - assert _source_id_values(source) == {given} + full = f"{kind}_v1:{given}" + assert source.source_name == given + assert source.source_id == full + assert _source_id_values(source) == {full} table = source.as_table(all_info=True) info = table.column(f"{constants.SOURCE_PREFIX}{data_column}").to_pylist() sep = constants.BLOCK_SEPARATOR - assert info == [f"{given}{sep}row_{i}{sep}{data_column}" for i in range(3)] + assert info == [f"{full}{sep}row_{i}{sep}{data_column}" for i in range(3)] def test_default_is_full_length_whatever_path_n_char( self, cls, kind, make, data_column @@ -174,7 +175,7 @@ class TestArrowTableDefaultIsTheLabelledTableHash: def test_default_is_kind_plus_the_table_hash_string(self): source = _arrow_table_source() table_hash = source.data_context.arrow_hasher.hash_table(_arrow_table()) - assert source.source_id == f"arrow_table:{table_hash.to_string()}" + assert source.source_id == f"arrow_table_v1:{table_hash.to_string()}" class TestKindsTellSourcesApart: @@ -227,13 +228,16 @@ class TestAsSourceDefaultSourceId: def test_as_source_id_is_derived_plus_the_labelled_content_hash(self, make_node): node = make_node() assert ( - node.as_source().source_id == f"derived:{node.content_hash().to_string()}" + node.as_source().source_id + == f"derived_v1:{node.content_hash().to_string()}" ) def test_kind_is_defined_once_on_the_class(self, make_node): node = make_node() assert DerivedSource.SOURCE_KIND == "derived" - assert node.as_source().source_id.startswith(f"{DerivedSource.SOURCE_KIND}:") + assert node.as_source().source_id.startswith( + f"{DerivedSource.SOURCE_KIND}_v{DerivedSource.SOURCE_VERSION}:" + ) def test_as_source_id_has_three_parts_and_no_node_path(self, make_node): node = make_node() @@ -253,5 +257,7 @@ def test_as_source_id_is_the_same_before_and_after_the_run(self, make_node): node.run() assert node.as_source().source_id == before - def test_given_source_id_is_never_changed(self, make_node): - assert DerivedSource(make_node(), source_id="my:name").source_id == "my:name" + def test_given_name_is_never_changed(self, make_node): + source = DerivedSource(make_node(), source_id="my:name") + assert source.source_name == "my:name" + assert source.source_id == "derived_v1:my:name" diff --git a/tests/test_core/sources/test_derived_source.py b/tests/test_core/sources/test_derived_source.py index fb924fbe3..b427b5f5c 100644 --- a/tests/test_core/sources/test_derived_source.py +++ b/tests/test_core/sources/test_derived_source.py @@ -410,10 +410,10 @@ def test_source_id_is_set(self): def test_source_id_has_no_pipeline_path(self): node = _make_node(n=3) src = node.as_source() - # The default is derived:
, - postgresql_table::/..
(the server the connection + the location, built only by location_source_name: csv_v1:, + delta_table_v1:, sqlite_table_v1::main.
, + postgresql_table_v1::/..
(the server the connection reached, as libpq reports it: a host name lower-cased, an IPv6 address bracketed and exploded, a socket directory as given, the port always a number; parameters naming several servers, or a host beside a hostaddr that is not that address, give no default; developer, November 18, 2026, ITL-1267), - spiraldb_table:..
@
(developer, November 16, 2026); a + spiraldb_table_v1:..
@
(developer, November 16, 2026); a location whose parts hold their separator has no default (source_ids.joined_location). A DBTableSource used directly (a generic connector, no database address) has no default: it requires a source_id (developer, November 16, 2026). :: @@ -1366,11 +1382,12 @@ data. The rules: a null key, a repeated key and an unordered collection of key columns (a set) are refused when the source is built, and a PollingSource refuses a key an earlier batch already holds. Never format one by hand, and - never write a label as a literal; a new root source declares SOURCE_KIND and builds its - default with one of the two. PollingSource hashes impl.identity(), never its repr. + never write a label as a literal; a new root source declares SOURCE_KIND and + SOURCE_VERSION and builds its default name with one of the two. PollingSource hashes + impl.identity(), never its repr, and its identity holds its source id (ITL-1425). node.as_source() gives no id of its own; it takes the DerivedSource default. The - origin's source id is never written into a default id. SourceStreamBuilder.build has no - bare-hash default: it needs a source_id or a source_kind. + origin's source id is never written into a default id. SourceStreamBuilder.build needs + the kind part (kind_part) and takes the name (source_name) or makes the hash default. - ArrowTableStream requires at least one data column; raises ValueError otherwise. - A job node shows its current run; node.as_source() shows everything stored for it (developer, November 13, 2026, ITL-1095). After a run, a FunctionJobNode returns exactly diff --git a/CLAUDE.md b/CLAUDE.md index 3f2b6a347..b45da821e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -636,9 +636,9 @@ algorithm produced it.** - A hash inside a name (path component, column name, `uri`, slot name, run URI) is the bare hex digest: `to_hex()`. A name later fed into a hash (the function `uri` in a pod's identity, system-tag column names in an entry-id table) is still a name. -- Source ids: a source id is the source's name. A default built from a hash is - `:
`, - `postgresql_table::/..
` (the server the connection + the location, built only by `location_source_name`: `csv_v1:`, + `delta_table_v1:`, `sqlite_table_v1::main.
`, + `postgresql_table_v1::/..
` (the server the connection reached, as libpq reports it: a host name lower-cased, an IPv6 address bracketed and exploded, a socket directory as given, the port always a number; parameters naming several servers, or a host beside a `hostaddr` that is not that address, give no default; developer, November 18, 2026, ITL-1267), - `spiraldb_table:..
@
` (developer, November 16, 2026); a + `spiraldb_table_v1:..
@
` (developer, November 16, 2026); a location whose parts hold their separator has no default (`source_ids.joined_location`). A `DBTableSource` used directly (a generic connector, no database address) has no default: it requires a `source_id` (developer, November 16, 2026). `::` @@ -1410,11 +1427,12 @@ data. The rules: a null key, a repeated key and an unordered collection of key columns (a set) are refused when the source is built, and a `PollingSource` refuses a key an earlier batch already holds. Never format one by hand, and - never write a label as a literal; a new root source declares `SOURCE_KIND` and builds its - default with one of the two. `PollingSource` hashes `impl.identity()`, never its `repr`. + never write a label as a literal; a new root source declares `SOURCE_KIND` and + `SOURCE_VERSION` and builds its default name with one of the two. `PollingSource` hashes + `impl.identity()`, never its `repr`, and its identity holds its source id (ITL-1425). `node.as_source()` gives no id of its own; it takes the `DerivedSource` default. The - origin's source id is never written into a default id. `SourceStreamBuilder.build` has no - bare-hash default: it needs a `source_id` or a `source_kind`. + origin's source id is never written into a default id. `SourceStreamBuilder.build` needs + the kind part (`kind_part`) and takes the name (`source_name`) or makes the hash default. - `ArrowTableStream` requires at least one data column; raises `ValueError` otherwise. - A job node shows its current run; `node.as_source()` shows everything stored for it (developer, November 13, 2026, ITL-1095). After a run, a `FunctionJobNode` returns exactly diff --git a/changelog.d/ITL-1425.md b/changelog.d/ITL-1425.md new file mode 100644 index 000000000..70297cda6 --- /dev/null +++ b/changelog.d/ITL-1425.md @@ -0,0 +1,29 @@ +### Breaking changes and migration + +- Every source id now names the kind and the implementation version of the source that + reads the data (ITL-1425): it is `_v:`, where the kind is the source's + config type key (`csv`, `delta_table`, `sqlite_table`, `arrow_table`, ...) and `N` the + version its class declares (`SOURCE_VERSION`, 1 for every kind today). Orcapod always adds + the kind part: a `source_id` you give is the name and is kept exactly + (`CSVSource(..., source_id="units").source_id == "csv_v1:units"`), and a default name + loses its kind prefix (`csv_v1:`, `arrow_table_v1:arrow_v1:`). The full id is + what system tags, source-info tokens and `source_id` show; record ids are unchanged and + never hold the source id. Code that compares a source id with the string it gave compares + `source.source_name` instead. +- The class name is no longer part of a source's content hash: a root source is identified + by its source id, its Arrow schema and its key columns. Content hashes of every source and + of everything downstream of one change, and so do stored pipeline rows, cache tables of + `CachedSource` and default ids of `node.as_source()`. Stores written before this change + are not migrated. +- A job slot (a `job.nodes` key and a `bind` key) is named by the source's name, not its + full id, so `job.bind(sources={"units": ...})` is unchanged. +- A saved source config holds `source_name` and `source_version` in place of `source_id`. + Job files saved before this change are refused on load; save them again. A job saved + under one version of a kind and loaded where the class declares another rebuilds the + source as the installed version, with that version's id, and warns + (`SourceVersionWarning`). +- `CachedSource` no longer takes `source_id`: it presents its wrapped source's id. +- A given name that starts like the id of a source kind (`delta_table_v1:units`) is kept as + the name, after the reader's own kind part, and warns (`SourceNameWarning`). +- `PollingSource`'s identity now holds its source id, so two polling sources over one + implementation with different given ids are two sources (provisional, ITL-1316). diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 186185fba..43e6105ee 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -37,9 +37,9 @@ hashing) and produces the final immutable stream. `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over time (provisional in this release, see [Provisional sources](#provisional-sources)); see the [API reference](../api/sources.md). Their default `source_id` names the table -where it lives (`sqlite_table::main.
`, -`postgresql_table::/..
`, with the server the connection -reached; the +where it lives (`sqlite_table_v1::main.
`, +`postgresql_table_v1::/..
`, with the server the +connection reached; the [hashing reference](../reference/hashing.md#default-source-ids-and-row-identifiers) has every form). A PostgreSQL DSN that names several servers (`host=a,b`), or gives a host beside a different `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`; with @@ -49,6 +49,40 @@ beside a different `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`; with over any connector; a connector gives no address of its database, so it then has no default and needs a `source_id`. +### Source ids name the kind that reads the data + +Every source id is `_v:`. The **kind part**, `_v`, names the kind +of source that read the data (`csv`, `delta_table`, `sqlite_table`, `arrow_table`, ...; the +same word as the source's config type) and the version of that kind's implementation. +Orcapod always adds it. The **name** is the `source_id` you give, kept exactly, or the +source's default: where the data lives (a file path, a table) or a hash of an in-memory +table. + +```python +import pyarrow as pa +from orcapod.sources import ArrowTableSource + +units_table = pa.table({"unit": ["u1", "u2"], "rate": [3.5, 7.25]}) +units = ArrowTableSource( + units_table, tag_columns=["unit"], tag_only_columns=True, source_id="units" +) +print(units.source_name) +# units +print(units.source_id) +# arrow_table_v1:units +``` + +The source id, kind part included, is what the source's system tags and source-info tokens +hold (`arrow_table_v1:units::row_0::rate`), and it is part of the source's identity, so the +same rows read by another kind, or by another version of one kind, are another source. The +record id names a row within its source and never holds the source id. A job names an input +slot by the source's name (`job.bind(sources={"units": ...})`). + +A kind's version moves when a row read before a change of its implementation could read +differently after it (other values, other Arrow types, another record id). Saved jobs keep +each source's name and version apart; a job loaded where a kind's version moved rebuilds the +source with the new version's id and warns (`SourceVersionWarning`). + Two construction rules apply to every source and are the most common first errors: - Every name in `tag_columns` must be a column of the data, otherwise the source raises @@ -312,9 +346,9 @@ Things to know about Spiral tables: timestamps without one) and Orcapod logical types such as `Path` (they come back as their storage type). - **Source identity.** A Spiral source is identified by where its table is, never by its - rows. The default `source_id` is `spiraldb_table:..
@..
@`, for example - `spiraldb_table:edi-tutorial-v1-841226.default.session@table_Jo7J0lpkLcOM`. The table id is + `spiraldb_table_v1:edi-tutorial-v1-841226.default.session@table_Jo7J0lpkLcOM`. The table id is SpiralDB's own, so tables with the same name in different projects stay apart, and a table that is dropped and created again under the same name is a different source: nothing recorded for the old table is reused. A renamed table also gets a new `source_id`. @@ -926,8 +960,8 @@ is reused rather than recomputed. Every source accepts `record_id_columns`, one or several key columns whose values name the row instead (`{"unit":"u1","time":1700000000}`), so the record ID follows the row. Both system tags must be stable: when you omit `source_id` an in-memory source is named after a -hash of its table, as `::` (for example -`dict:arrow_v1:000002fe…`), which changes when any row changes or is reordered. Whenever row +hash of its table, as `::` (for example +`dict_v1:arrow_v1:000002fe…`), which changes when any row changes or is reordered. Whenever row order or content can vary between runs, pass an explicit, stable `source_id` **and** name key columns that are unique per row; this avoids both the duplicate entries and the repeated deliveries. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index ce12e65d7..87e8894ca 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -23,7 +23,7 @@ appended, because it is a variant of the same system tag mechanism.) | 1 | `content_hash()` | `SemanticAwarePythonHasher` → JSON + SHA-256 | `ContentHash` | Unique per semantic content of the object; data-inclusive | | 2 | `pipeline_hash()` | `SemanticAwarePythonHasher` → JSON + SHA-256 | `ContentHash` | Unique per pipeline topology + schema; data-exclusive | | 3 | Schema hash (system tag column naming) | `SemanticAwarePythonHasher.hash_object((hash_schema(tag), hash_schema(data))).to_hex(n)` over the Arrow schemas | Truncated hex `str` | Unique per Arrow `(tag, data)` schema pair; embedded in system tag column names | -| 4 | Default `source_id` of an in-memory source | `":" + StarfixArrowHasher.hash_table(table).to_string()` | `str`, `::` | Unique per source kind and raw table content; used as the source's name when none is given | +| 4 | Default `source_id` of an in-memory source | `":" + StarfixArrowHasher.hash_table(table).to_string()` | `str`, `_v::` | Unique per kind, implementation version and raw table content; the hash is the source's name when none is given | | 5 | Per-row `record_id` (system tag value) | the row identifier itself: `row_`, or the canonical JSON of the key columns (`key_row_identifier`) | `str` (`large_string`) | Names the row within its source; stable as long as its position or its key is | | 6 | Join system tag suffix | `stream.pipeline_hash().to_hex(n)` + `:{idx}` appended to column name | Column name suffix | Unique per `(input topology, canonical join position)`; encodes full join lineage in column name | | 6b | Aggregating operator system tag fold | SHA-256 of the canonical JSON list of member values, after the operation's label, for both system tags | `":"` `str`, plus a column name suffix | Deterministic per ordered member set; keeps system tags scalar through a many-to-one reduction | @@ -54,7 +54,7 @@ Orcapod computes (developer, November 15, 2026; ITL-1154, revising ITL-945): | 4 | **A hash fed into another hash carries its label.** A nested hash in a structure is `{"__type__": "hash", "label": "
` (SQLite names a table `.
`; the main database's schema is `main`) | -| `PostgreSQLTableSource` | `postgresql_table` | `postgresql_table::/..
` (the server the connection reached, then the three-part name, from `current_database()` and `current_schema()`; see below) | -| `DBTableSource` (any other connector) | `db_table` | none: `source_id` is required. The connector protocol exposes no database address, and the table name alone does not say which database the table is in (developer decision, November 16, 2026) | -| `SpiralDBTableSource` | `spiraldb_table` | `spiraldb_table:..
@
` (Spiral's own table identifier, then SpiralDB's table id; `SPIRALDB_SOURCE_ID_HAS_TABLE_ID`) | -| `PollingSource` | `polling_source` | `polling_source:semantic_v1:` of `impl.identity()` (never its `repr`). Provisional (ITL-1314): not frozen with data context v1, and no golden value pins it | -| `CachedSource` | `cached` | the wrapped source's id | +| `ArrowTableSource` | `arrow_table_v1` | `arrow_table_v1:arrow_v1:` of the table | +| `DictSource` | `dict_v1` | `dict_v1:arrow_v1:` of the table | +| `ListSource` | `list_v1` | `list_v1:arrow_v1:` of the table | +| `DataFrameSource` | `data_frame_v1` | `data_frame_v1:arrow_v1:` of the table | +| `DerivedSource` (a node's records; `node.as_source()`) | `derived_v1` | `derived_v1:semantic_v1:` of the node's content hash | +| `DerivedSource` with `tags_as_data` | `derived_v1` | none: `source_id` is required (developer, November 21, 2026, ITL-1313). Its former default, a hash of the derivation, was of questionable stability: `record_id_columns=None` and `()`, one key policy, gave two ids | +| `CSVSource` | `csv_v1` | `csv_v1:` | +| `DeltaTableSource` | `delta_table_v1` | `delta_table_v1:` | +| `SQLiteTableSource` | `sqlite_table_v1` | `sqlite_table_v1::main.
` (SQLite names a table `.
`; the main database's schema is `main`) | +| `PostgreSQLTableSource` | `postgresql_table_v1` | `postgresql_table_v1::/..
` (the server the connection reached, then the three-part name, from `current_database()` and `current_schema()`; see below) | +| `DBTableSource` (any other connector) | `db_table_v1` | none: `source_id` is required. The connector protocol exposes no database address, and the table name alone does not say which database the table is in (developer decision, November 16, 2026) | +| `SpiralDBTableSource` | `spiraldb_table_v1` | `spiraldb_table_v1:..
@
` (Spiral's own table identifier, then SpiralDB's table id; `SPIRALDB_SOURCE_ID_HAS_TABLE_ID`) | +| `PollingSource` | `polling_source_v1` | `polling_source_v1:semantic_v1:` of `impl.identity()` (never its `repr`). Provisional (ITL-1314): not frozen with data context v1, and no golden value pins it | +| `CachedSource` | none of its own | the wrapped source's id | +| `SourceProxy` (a saved source that cannot be rebuilt) | none of its own | the saved id, rebuilt from the saved kind, version and name | + +A saved source config holds the name (`source_name`) and the version (`source_version`) +apart, the kind being `source_type`; the id is rebuilt from them, never parsed out of one +string. Loaded where the class declares another version, the source is rebuilt as the +installed version, with that version's id (`SourceVersionWarning`); the saved id is never +rewritten. A config saved before ITL-1425 (a `source_id`, no `source_name`) is refused. A +job's input slot is named by its source's name, not its full id. | folded source id of `Batch` / `GroupBy` (a system-tag value, not a source) | | `batch_v1:` / `group_v1:` | An in-memory default hashes the table as given, rows in the order they came in: the user may @@ -248,7 +265,7 @@ seen in the parameters: two servers reached under one name that way share a defa need a `source_id`. The same holds for a name that means this machine: a socket directory (`/var/run/postgresql`), `localhost` or a loopback address (`127.0.0.1`, `::1`). Two machines that each read their own server that way get one default id for one table name -(`postgresql_table:/var/run/postgresql:5432/d.public.t` on both), so when their rows or +(`postgresql_table_v1:/var/run/postgresql:5432/d.public.t` on both), so when their rows or provenance are combined, give each source a distinct `source_id`. No user name, password or other connection parameter enters the id. A row's record id is its row identifier (site 5), chosen by `record_id_columns` (a column name @@ -359,7 +376,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | source system-tag column name (schema digest) | `utils/schema_utils.py:compute_schema_hash` | | system-tag suffixes of `Join`, `MergeJoin`, `Batch`, `GroupBy` | `core/operators/join.py:Join._compute_system_tag_suffixes`, `core/operators/join.py:Join._predict_system_tag_schema`, `core/operators/join.py:Join.static_process`, `core/operators/merge_join.py:MergeJoin._system_tag_suffix`, `core/operators/batch.py:Batch.unary_output_schema`, `core/operators/batch.py:Batch.unary_static_process`, `core/operators/group_by.py:GroupBy.unary_output_schema`, `core/operators/group_by.py:GroupBy.unary_static_process` | | a saved hash shown as a digest | `core/nodes/function_node.py:_bare_digest` | -| source ids (`:
``, a PostgreSQL table's address. - The location of the default source id (``postgresql_table:
``, ITL-1267): + The default name of the source (its id is ``postgresql_table_v1:
``; ITL-1267, ITL-1425): the server the connection reached, then the table's three-part name. The host is written by ``_server_name``; the port is always the number. The address names one table only: the parts of the three-part name hold neither ``.`` nor ``/``, so the @@ -153,8 +153,9 @@ class PostgreSQLTableSource(DBTableSource): system_tag_columns: Additional system-level tag columns. record_id_columns: The key columns that identify a row; ``None``: the primary key (a table without one is refused); ``()``: the position. - source_id: Canonical source name. Defaults to - ``postgresql_table::/..
`` + source_id: The source's name; its id is ``postgresql_table_v1:`` + (ITL-1425). The name defaults to + ``:/..
`` (``postgresql_table_address``); connection parameters that name several servers, or a host beside a ``hostaddr``, give no default. label: Human-readable label for this source node. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index c533e38ff..57c7105e1 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -203,8 +203,8 @@ class SpiralDBTableSource(RootSource): not apply, and the header says how many rows the table has. Identity. The source is identified by where the table is, never by its rows. The - default ``source_id`` is ``spiraldb_table:..@
`` (``spiraldb_table_address``): Spiral's own table identifier, then the table id, + default ``source_id`` is ``spiraldb_table_v1:..@
`` (the name from ``spiraldb_table_address`` after the kind part, ITL-1425): Spiral's own table identifier, then the table id, SpiralDB's own, so a table dropped and created again under the same name is a different source, and a renamed table gets a new source id too. A row is identified by its primary key (or ``record_id_columns``) in the JSON key form. @@ -249,8 +249,9 @@ class SpiralDBTableSource(RootSource): memory, about 5 KB per row and node. batch_rows: The most rows handed on at once while iterating (default 8,192). A SpiralDB batch larger than this is held while its slices are handed on. - source_id: Canonical source name for the registry and provenance tokens. - Defaults to ``"/.@
"``. + source_id: The source's name; its id is ``spiraldb_table_v1:`` + (ITL-1425). The name defaults to + ``..@
``. label: Human-readable label for this source node. data_context: Data context governing type conversion and hashing. config: OrcaPod configuration. diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index 72d0f73ce..eab59a821 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -85,8 +85,9 @@ class SQLiteTableSource(DBTableSource): system_tag_columns: Additional system-level tag columns. record_id_columns: The key columns that identify a row; ``None``: the primary key (a table without one is refused); ``()``: the position. - source_id: Canonical source name. Defaults to - ``sqlite_table::main.
``. + source_id: The source's name; its id is ``sqlite_table_v1:`` + (ITL-1425). The name defaults to ``:main.
``, + so the default id is ``sqlite_table_v1::main.
``. label: Human-readable label for this source node. data_context: Data context governing type conversion and hashing. config: OrcaPod configuration. diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 06063117a..e17f3141b 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -509,14 +509,12 @@ def compile(self) -> None: # 2a. Validate source-node name uniqueness. # Source node names are identity-forming (used as bind() keys and # included in content_hash()). Two distinct source nodes with the - # same name indicate a source_id collision. If their schemas also - # differ the caller has assigned the same source_id to conceptually - # different sources — raise an error. If the schemas happen to match - # the nodes are functionally identical (same name + same schema would - # normally produce the same content_hash and be deduplicated at - # recording time, so this branch is only reached in unusual edge cases - # such as non-RootSource concrete streams with colliding label:hash - # names), and we leave them as-is. + # same name are refused: with different schemas by InconsistentSourceError, + # and when two or more are sources (RootSource), whatever their schemas, by + # SourceSlotNameCollisionError (ITL-1425: a slot is named by the source's + # name without its kind part, so another kind, version, key or id would + # otherwise share the slot). Only streams that are not sources, with equal + # schemas and colliding label:hash names, are left as they are. name_to_hashes: dict[str, list[str]] = {} for h, node in node_map.items(): name_to_hashes.setdefault(node._name, []).append(h) diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 59817a477..abbebf83d 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -651,6 +651,19 @@ def _source_proxy_from_config( from orcapod.core.sources.source_proxy import SourceProxy from orcapod.types import Schema + inner_config = config.get("inner_source") + if ( + node_descriptor is None + and not config.get("content_hash") + and config.get("source_type") == "cached" + and isinstance(inner_config, dict) + ): + # A cache has its wrapped source's identity (id, hashes, schemas), and its own + # config holds none: the proxy stands in with the wrapped source's, so a cache + # nested in another cache that cannot be rebuilt keeps its source id and the + # outer cache still reads its rows (ITL-1425). + return _source_proxy_from_config(cast("dict[str, Any]", inner_config)) + if node_descriptor is not None: # New format: top-level node descriptor carries identity content_hash = node_descriptor.get("content_hash") diff --git a/test-specification/unit/test_sources.py b/test-specification/unit/test_sources.py index 83b146710..c43b78562 100644 --- a/test-specification/unit/test_sources.py +++ b/test-specification/unit/test_sources.py @@ -91,14 +91,15 @@ def test_source_id_populated(self): assert len(source.source_id) > 0 def test_source_id_explicit(self): - """Explicit source_id is preserved.""" + """An explicit source_id is the name, kept exactly after the kind part (ITL-1425).""" source = ArrowTableSource( _simple_table(), tag_columns=["name"], source_id="my_source", infer_nullable=True, ) - assert source.source_id == "my_source" + assert source.source_name == "my_source" + assert source.source_id == "arrow_table_v1:my_source" def test_producer_is_none(self): """Root sources have producer == None.""" @@ -432,16 +433,17 @@ def test_before_run_correct_schema(self): assert "data_col" in table.column_names def test_source_id_derived_prefix(self): - """DerivedSource auto-generates a source_id with 'derived:' prefix.""" + """DerivedSource auto-generates a source_id with the 'derived_v1:' kind part.""" mock_origin = self._make_mock_origin(records=None) source = DerivedSource(origin=mock_origin) - assert source.source_id.startswith("derived:") + assert source.source_id.startswith("derived_v1:") def test_explicit_source_id(self): - """Explicit source_id overrides the auto-generated one.""" + """An explicit source_id is the name, after the kind part (ITL-1425).""" mock_origin = self._make_mock_origin(records=None) source = DerivedSource(origin=mock_origin, source_id="custom_id") - assert source.source_id == "custom_id" + assert source.source_name == "custom_id" + assert source.source_id == "derived_v1:custom_id" def test_output_schema_delegates_to_origin(self): """output_schema delegates to origin node.""" diff --git a/tests/test_core/sources/test_derived_source_tags_as_data.py b/tests/test_core/sources/test_derived_source_tags_as_data.py index c41a54415..f4c1fa4e6 100644 --- a/tests/test_core/sources/test_derived_source_tags_as_data.py +++ b/tests/test_core/sources/test_derived_source_tags_as_data.py @@ -412,6 +412,8 @@ def test_equals_the_hand_written_recipe_with_the_same_source_id(self): r_table = recipe.as_table(columns={"source": True, "system_tags": True}) d_table = derived.as_table(columns={"source": True, "system_tags": True}) assert d_table.column_names == r_table.column_names + # The same Arrow types and nullability (a copy keeps its tag's exact type). + assert d_table.schema.equals(r_table.schema), "schema mismatch" # The same rows, system tags and tokens, but for the kind part of the source # id, which names the source that read them (ITL-1425). for name in d_table.column_names: diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 8dca286db..e2fc69b92 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -324,7 +324,7 @@ def _source_id(dsn: str) -> str: def _expected(host: str, schema: str, port: str | None = None) -> str: return ( - f"postgresql_table:{host}:{port or _SERVER['port']}/" + f"postgresql_table_v1:{host}:{port or _SERVER['port']}/" f"{_SERVER['dbname']}.{schema}.t" ) @@ -460,7 +460,8 @@ def test_host_beside_hostaddr_in_the_dsn_has_no_default( given = PostgreSQLTableSource( dsn, "t", source_id="t_by_address", tag_only_columns=True ) - assert given.source_id == "t_by_address" + assert given.source_name == "t_by_address" + assert given.source_id == "postgresql_table_v1:t_by_address" @pytest.mark.parametrize( ("dsn_params", "env"), @@ -608,7 +609,8 @@ def test_several_hosts_in_the_dsn_have_no_default( given = PostgreSQLTableSource( dsn, "t", source_id="t_on_the_pool", tag_only_columns=True ) - assert given.source_id == "t_on_the_pool" + assert given.source_name == "t_on_the_pool" + assert given.source_id == "postgresql_table_v1:t_on_the_pool" def test_several_hosts_from_pghost_have_no_default( self, server_table: str, no_server_env: None, monkeypatch: pytest.MonkeyPatch diff --git a/tests/test_core/sources/test_source_id_review_findings.py b/tests/test_core/sources/test_source_id_review_findings.py index abea5b720..6efd2ea36 100644 --- a/tests/test_core/sources/test_source_id_review_findings.py +++ b/tests/test_core/sources/test_source_id_review_findings.py @@ -655,3 +655,74 @@ def test_derived_source_configs_say_whether_the_name_was_given( rebuilt = DerivedSource.from_config(config) assert rebuilt.source_id == named.source_id == "derived_v1:copied" assert rebuilt.to_config()["source_name_given"] is True + + +# --------------------------------------------------------------------------- +# CodeRabbit review of PR 525 (head 5e6ad527) +# --------------------------------------------------------------------------- + + +class TestCodeRabbitReview: + def _legacy_tags_as_data_config( + self, csv_path: Path, tags: list[str] + ) -> dict[str, object]: + from orcapod.sources import DerivedSource + + config = DerivedSource( + _csv(csv_path, tags, source_id="subjects"), + tags_as_data={"session": "session_copy", "subject": "subject_copy"}, + source_id="copied", + ).to_config() + config["source_id"] = config.pop("source_name") + del config["source_name_given"] + del config["source_version"] + return config + + @pytest.mark.parametrize("tags", TAG_ORDERS) + def test_a_legacy_tags_as_data_config_is_refused_as_legacy(self, csv_path, tags): + from orcapod.sources import DerivedSource + + config = self._legacy_tags_as_data_config(csv_path, tags) + with pytest.raises(ValueError, match="saved before") as caught: + DerivedSource.require_saved_source_id(config) + assert "needs a source_id" not in str(caught.value) + with pytest.raises(ValueError, match="saved before"): + DerivedSource.from_config(config) + nested = {"source_type": "cached", "inner_source": config} + with pytest.raises(ValueError, match="saved before"): + DerivedSource.require_saved_source_id(nested) + + def test_a_tags_as_data_config_without_a_name_still_needs_one(self, csv_path): + from orcapod.sources import DerivedSource + + config = self._legacy_tags_as_data_config(csv_path, KEY) + del config["source_id"] + with pytest.raises(ValueError, match="needs a source_id"): + DerivedSource.require_saved_source_id(config) + + @pytest.mark.parametrize("tags", TAG_ORDERS) + def test_a_nested_cache_that_cannot_be_rebuilt_keeps_its_source_id( + self, tmp_path, csv_path, tags + ): + inner = CachedSource( + _csv(csv_path, tags, source_id="subjects"), + cache_database=DeltaTableDatabase(tmp_path / "inner"), + ) + outer = CachedSource( + inner, cache_database=DeltaTableDatabase(tmp_path / "outer") + ) + assert outer.as_table().num_rows == len(ROWS) + config = outer.to_config() + # The cache configs hold no identity (ENG-320); the wrapped source's does. + assert "full_source_id" not in config["inner_source"] + assert config["inner_source"]["inner_source"]["full_source_id"] == ( + "csv_v1:subjects" + ) + # The inner cache cannot be rebuilt: a proxy stands in for it. + config["inner_source"]["cache_database"] = {"type": "not_a_database"} + reloaded = CachedSource.from_config(config) + assert isinstance(reloaded.cached_source, SourceProxy) + assert reloaded.source_id == outer.source_id == "csv_v1:subjects" + table = reloaded.as_table(columns={"system_tags": True}) + assert table.num_rows == len(ROWS) + assert _source_ids(table) == {"csv_v1:subjects"}