From eb69703b108c8984799f808d383ce8a2e1bade31 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:29:04 -0800 Subject: [PATCH 1/5] fix(sources): serialize path-like inputs as text --- changelog.d/ITL-1489.md | 5 + docs/concepts/sources.md | 7 +- docs/dev/design_issues/PLT-4864-TUT1.md | 5 +- docs/troubleshooting.md | 8 - docs/tutorial/01-first-stream.md | 12 +- src/orcapod/core/sources/base.py | 13 ++ src/orcapod/core/sources/csv_source.py | 14 +- .../core/sources/delta_table_source.py | 24 +-- .../core/sources/sqlite_table_source.py | 21 ++- .../sources/test_file_source_paths.py | 165 ++++++++++++++++++ 10 files changed, 228 insertions(+), 46 deletions(-) create mode 100644 changelog.d/ITL-1489.md create mode 100644 tests/test_core/sources/test_file_source_paths.py diff --git a/changelog.d/ITL-1489.md b/changelog.d/ITL-1489.md new file mode 100644 index 000000000..2f5138ed4 --- /dev/null +++ b/changelog.d/ITL-1489.md @@ -0,0 +1,5 @@ +### Fixed + +- CSV, Delta, and SQLite sources accept text paths and path-like objects such as + `pathlib.Path`. Saved jobs store the original path text. Bytes paths raise + `TypeError` at construction. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 842dbebad..81eff1675 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -34,9 +34,12 @@ hashing) and produces the final immutable stream. | `DictSource` | `list[dict]` | Each dict becomes one (Tag, Data) pair | | `ListSource` | `list[Any]` | Each element stored under the data column given by `name`; the tag defaults to `element_index` | | `DataFrameSource` | Pandas or Polars `DataFrame` | Converts via Arrow | -| `CSVSource` | File path (string) | Reads CSV into Arrow | +| `CSVSource` | File path | Reads CSV into Arrow | | `DeltaTableSource` | Directory path | Reads Delta Lake table | +CSV, Delta, and SQLite sources accept strings and path-like objects such as +`pathlib.Path`. Saved jobs keep the supplied path text, including relative paths. + `orcapod.sources` also provides database-backed sources (`SQLiteTableSource`, `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over time (provisional in this release, see [Provisional sources](#provisional-sources)); see the @@ -519,7 +522,7 @@ trial_schema = pa.schema( ] ) trials = CSVSource( - str(csv_dir / "trials.csv"), + csv_dir / "trials.csv", tag_columns=["session", "trial"], tag_only_columns=True, schema=trial_schema, diff --git a/docs/dev/design_issues/PLT-4864-TUT1.md b/docs/dev/design_issues/PLT-4864-TUT1.md index 8a3c429a6..a574e0748 100644 --- a/docs/dev/design_issues/PLT-4864-TUT1.md +++ b/docs/dev/design_issues/PLT-4864-TUT1.md @@ -10,9 +10,8 @@ tutorial and `docs/troubleshooting.md` describe each of these as it behaves toda fixed here (this work does not touch `src/`). Re-checked against `main` on November 14, 2026; items found then to be fixed were removed. -1. **`CSVSource` rejects a `pathlib.Path`.** `CSVSource(Path("f.csv"), tag_columns=["a"])` - raises `TypeError: 'PosixPath' object is not iterable`; the `file_path` parameter is typed - `str` and the path is used as the default `source_id`. `CSVSource(str(path), ...)` works. +1. **`CSVSource` path-like inputs (resolved, ITL-1489).** The source reads the path's text + once at construction and uses it for the default source id and saved configuration. 2. **`list(job.nodes)` order depends on `PYTHONHASHSEED`** for source nodes: a job over two sources `units` and `sessions` lists `['units', 'sessions', 'Join', 'fn']` under some seeds and `['sessions', 'units', 'Join', 'fn']` under others. Cosmetic, but it makes diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 963a19eb4..b391a0ade 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -81,14 +81,6 @@ With polars, keep the frame `with_columns` returns: a pandas or polars `DataFrame` stored whole in one column is a library value, not a dictionary column. See [Arrow types of a source](concepts/sources.md#arrow-types-of-a-source). -### `TypeError: 'PosixPath' object is not iterable` from `CSVSource` - -**Cause.** `CSVSource` was given a `pathlib.Path` and no `source_id`. The file path is -typed as a string; without a `source_id` it is used to build the default one, which fails -for a `Path`. This is a known defect. - -**Fix.** `CSVSource(str(path), ...)`. - ### `ValueError: Parameter 'x' has no type annotation and is not specified in input_types.` **Cause.** A function passed to `@function_pod` has a parameter without a type annotation. diff --git a/docs/tutorial/01-first-stream.md b/docs/tutorial/01-first-stream.md index 1f76ad05c..3b1796b38 100644 --- a/docs/tutorial/01-first-stream.md +++ b/docs/tutorial/01-first-stream.md @@ -24,7 +24,7 @@ A **source** is where data enters Orcapod. `CSVSource` reads a CSV file: from orcapod.sources import CSVSource subjects = CSVSource( - str(data_dir / "subjects.csv"), + data_dir / "subjects.csv", tag_columns=["subject_id"], tag_only_columns=True, source_id="subjects", ) @@ -38,7 +38,7 @@ print(subjects.as_pandas_df()) -- The file path is a string, so a `pathlib.Path` needs `str(...)`. +- The file path can be a string or a `pathlib.Path`. - `tag_columns` names the columns that identify a row. - `tag_only_columns=True` makes those columns tags only, as the next section explains. - `source_id` names the source. Orcapod uses it when it records where a value came from. @@ -81,7 +81,7 @@ session is identified by the mouse and the session name together: ```python sessions = CSVSource( - str(data_dir / "sessions.csv"), + data_dir / "sessions.csv", tag_columns=["subject_id", "session"], tag_only_columns=True, source_id="sessions", ) @@ -174,7 +174,7 @@ every probe, probe names repeat in every session, and session names repeat for e ```python units = CSVSource( - str(data_dir / "units.csv"), + data_dir / "units.csv", tag_columns=["subject_id", "session", "probe", "unit"], tag_only_columns=True, source_id="units", ) @@ -196,14 +196,14 @@ column of `subjects.csv` a tag. ```python try: - CSVSource(str(data_dir / "subjects.csv"), tag_columns=["mouse"], tag_only_columns=True) + CSVSource(data_dir / "subjects.csv", tag_columns=["mouse"], tag_only_columns=True) except ValueError as err: print(err) # tag_columns not found in table: {'mouse'}. Available columns: ['subject_id', 'sex', 'age_weeks', 'genotype'] try: CSVSource( - str(data_dir / "subjects.csv"), + data_dir / "subjects.csv", tag_columns=["subject_id", "sex", "age_weeks", "genotype"], tag_only_columns=True, ) except ValueError as err: diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index cc06e210b..1752a9270 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import warnings from collections.abc import Callable, Collection, Iterator from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast @@ -37,6 +38,18 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol +def source_path_text(path: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str: + """Return the path text used for a file source's identity and configuration. + + Raises: + TypeError: If the path is bytes or its filesystem representation is bytes. + """ + text = os.fspath(path) + if isinstance(text, bytes): + raise TypeError("Source paths must be str or os.PathLike[str], not bytes") + return text + + def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: """Return the ``tag_only_columns`` of a saved source config (ITL-1019). diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 5292c493e..c56080ddd 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -12,7 +12,11 @@ from typing_extensions import override from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.base import RootSource, saved_tag_only_columns +from orcapod.core.sources.base import ( + RootSource, + saved_tag_only_columns, + source_path_text, +) from orcapod.core.sources.reload import keep_nullable_columns, same_rows from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.stream_builder import ( @@ -342,7 +346,7 @@ class CSVSource(RootSource): def __init__( self, - file_path: str, + file_path: str | os.PathLike[str], tag_columns: str | Collection[str] = (), record_id_columns: str | Collection[str] | None = None, source_id: str | None = None, @@ -351,16 +355,16 @@ def __init__( tag_only_columns: TagOnlyColumns = (), **kwargs: Any, ) -> None: + self._file_path = source_path_text(file_path) super().__init__(source_id=source_id, **kwargs) if self._source_name is None: # A default name is where the data lives, not a name the user gave: it is # not checked for a start shaped like a source id (ITL-1425). - self._source_name = location_source_name(str(file_path)) + self._source_name = location_source_name(self._file_path) - self._file_path = file_path # Every later read (a check, ITL-1102) opens the file found now, whatever the # working directory is then. - self._access_path = os.path.abspath(file_path) + self._access_path = os.path.abspath(self._file_path) self._schema = schema self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._record_id_columns = normalize_record_id_columns(record_id_columns) diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 464805d10..377db715e 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -9,7 +9,11 @@ from typing_extensions import override from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.base import RootSource, saved_tag_only_columns +from orcapod.core.sources.base import ( + RootSource, + saved_tag_only_columns, + source_path_text, +) from orcapod.core.sources.reload import same_rows from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.stream_builder import ( @@ -20,7 +24,6 @@ require_live_logical_types, ) from orcapod.databases.storage_utils import delta_to_pyarrow_dataset -from orcapod.types import PathLike from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import ( _normalize_column_list, @@ -60,7 +63,7 @@ class DeltaTableSource(RootSource): def __init__( self, - delta_table_path: PathLike, + delta_table_path: str | os.PathLike[str], tag_columns: str | Collection[str] = (), record_id_columns: str | Collection[str] | None = None, source_id: str | None = None, @@ -68,21 +71,20 @@ def __init__( tag_only_columns: TagOnlyColumns = (), **kwargs: Any, ) -> None: - resolved = Path(delta_table_path).resolve() + self._delta_table_path = source_path_text(delta_table_path) + self._access_path = Path(self._delta_table_path).resolve() super().__init__(source_id=source_id, **kwargs) if self._source_name is None: # The table folder's path or URI as passed: a relative path stays relative. # A default name is where the data lives, not a name the user gave: it is # not checked for a start shaped like a source id (ITL-1425). - self._source_name = location_source_name(os.fspath(delta_table_path)) - - self._delta_table_path = resolved + self._source_name = location_source_name(self._delta_table_path) try: - self._delta_table = deltalake.DeltaTable(str(self._delta_table_path)) + self._delta_table = deltalake.DeltaTable(str(self._access_path)) except deltalake.exceptions.TableNotFoundError: - raise ValueError(f"Delta table not found at {self._delta_table_path}") + raise ValueError(f"Delta table not found at {self._access_path}") self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._record_id_columns = normalize_record_id_columns(record_id_columns) @@ -154,7 +156,7 @@ def check_for_new_data(self) -> bool: if not table.schema.equals(self._table.schema, check_metadata=True): require_live_logical_types(table.schema) raise ValueError( - f"Delta table {str(self._delta_table_path)!r} changed its columns at " + f"Delta table {str(self._access_path)!r} changed its columns at " f"version {version}: the source was built with {self._table.schema}, " f"the table now has {table.schema}. Build a new DeltaTableSource to " "read it" @@ -174,7 +176,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize this source's configuration to a JSON-compatible dict.""" return { "source_type": self.SOURCE_KIND, - "delta_table_path": str(self._delta_table_path), + "delta_table_path": self._delta_table_path, "tag_columns": list(self._tag_columns), **self._tag_only_config(), "record_id_columns": None diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index 56ef7be27..eec938c18 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -31,7 +31,7 @@ from typing_extensions import override from orcapod.core.data_tags import TagOnlyColumns -from orcapod.core.sources.base import saved_tag_only_columns +from orcapod.core.sources.base import saved_tag_only_columns, source_path_text from orcapod.core.sources.db_table_source import DBTableSource from orcapod.core.sources.source_ids import joined_location from orcapod.core.sources.stream_builder import normalize_record_id_columns @@ -44,15 +44,14 @@ from orcapod.config import OrcapodConfig -def _access_path(db_path: str | os.PathLike[str]) -> str | os.PathLike[str]: +def _access_path(db_path: str) -> str: """The path a later read opens: a file path made absolute, a special name as given. ``":memory:"`` and ``file:`` URIs are not file system paths. """ - text = os.fspath(db_path) - if text == ":memory:" or text.startswith("file:"): + if db_path == ":memory:" or db_path.startswith("file:"): return db_path - return os.path.abspath(text) + return os.path.abspath(db_path) class SQLiteTableSource(DBTableSource): @@ -107,7 +106,7 @@ class SQLiteTableSource(DBTableSource): def __init__( self, - db_path: str | os.PathLike, + db_path: str | os.PathLike[str], table_name: str, tag_columns: str | Collection[str] | None = None, record_id_columns: str | Collection[str] | None = None, @@ -118,11 +117,11 @@ def __init__( *, tag_only_columns: TagOnlyColumns = (), ) -> None: - self._db_path = db_path + self._db_path = source_path_text(db_path) # A check (ITL-1102) reopens the database found now, whatever the working # directory is then; an in-memory database or a URI is kept as given. - self._access_path: str | os.PathLike[str] = _access_path(db_path) - connector = SQLiteConnector(db_path) + self._access_path = _access_path(self._db_path) + connector = SQLiteConnector(self._db_path) try: # A missing table is reported as missing, not as a table without a key. @@ -198,7 +197,7 @@ def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str # The path is read up to the last ``:main.``, so only the table name must not # hold a ``:``; the path is kept as passed, colons included (``C:\\data``). table = joined_location(":", f"main.{table_name}") - return f"{os.fspath(self._db_path)}:{table}" + return f"{self._db_path}:{table}" @contextmanager @override @@ -217,7 +216,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize source configuration to a JSON-compatible dict.""" base = super().to_config() base.pop("connector", None) - return {**base, "source_type": self.SOURCE_KIND, "db_path": str(self._db_path)} + return {**base, "source_type": self.SOURCE_KIND, "db_path": self._db_path} @classmethod def from_config( diff --git a/tests/test_core/sources/test_file_source_paths.py b/tests/test_core/sources/test_file_source_paths.py new file mode 100644 index 000000000..bf8c48fc4 --- /dev/null +++ b/tests/test_core/sources/test_file_source_paths.py @@ -0,0 +1,165 @@ +"""File sources use the same path text for identity, reads, and saved jobs.""" + +from __future__ import annotations + +import os +import sqlite3 +from collections.abc import Callable +from functools import partial +from pathlib import Path +from typing import cast, final + +import pyarrow as pa +import pytest +from deltalake import write_deltalake + +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import CSVSource, DeltaTableSource, SQLiteTableSource + +SourceFactory = Callable[ + [str | os.PathLike[str]], CSVSource | DeltaTableSource | SQLiteTableSource +] + + +@pytest.fixture(params=["csv", "delta", "sqlite"]) +def file_source( + request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> tuple[SourceFactory, Path, str]: + """Create two rows with two tags and two data columns for each format.""" + monkeypatch.chdir(tmp_path) + kind = cast(str, request.param) + tags = ["station", "trial"] + if kind == "csv": + path = Path("readings.csv") + _ = path.write_text("station,trial,reading,offset\na,1,12,2\nb,2,15,3\n") + return ( + partial(CSVSource, tag_columns=tags, tag_only_columns=True), + path, + "file_path", + ) + if kind == "delta": + path = Path("readings") + write_deltalake( + path, + pa.table( + { + "station": ["a", "b"], + "trial": [1, 2], + "reading": [12, 15], + "offset": [2, 3], + } + ), + ) + return ( + partial(DeltaTableSource, tag_columns=tags, tag_only_columns=True), + path, + "delta_table_path", + ) + path = Path("readings.sqlite") + with sqlite3.connect(path) as conn: + _ = conn.execute(""" + CREATE TABLE readings ( + station TEXT, trial INTEGER PRIMARY KEY, + reading INTEGER NOT NULL, offset INTEGER NOT NULL + ) + """) + _ = conn.executemany( + "INSERT INTO readings VALUES (?, ?, ?, ?)", + [("a", 1, 12, 2), ("b", 2, 15, 3)], + ) + return ( + partial( + SQLiteTableSource, + table_name="readings", + tag_columns=tags, + tag_only_columns=True, + ), + path, + "db_path", + ) + + +def test_string_and_path_sources_match( + file_source: tuple[SourceFactory, Path, str], +) -> None: + """A relative path's text survives in the config, and both forms read the same.""" + build, path, config_key = file_source + from_string = build(str(path)) + from_path = build(path) + + assert from_path.source_id == from_string.source_id + assert from_path.to_config() == from_string.to_config() + assert from_path.to_config()[config_key] == str(path) + assert from_path.as_table().equals(from_string.as_table()) + + +@final +class TextPath: + """A path-like object that tracks calls to its filesystem representation.""" + + def __init__(self, text: str) -> None: + self.text = text + self.calls = 0 + + def __fspath__(self) -> str: + """Return the original spelling of the path.""" + self.calls += 1 + return self.text + + +def test_source_converts_path_like_input_once( + file_source: tuple[SourceFactory, Path, str], +) -> None: + """Identity and config use the filesystem representation as given.""" + build, path, config_key = file_source + path_like = TextPath(f"./{path}") + source = build(path_like) + assert source.source_id == build(path_like.text).source_id + assert source.to_config()[config_key] == path_like.text + assert path_like.calls == 1 + + +@function_pod(output_keys="adjusted") +def adjust(reading: int | None, offset: int | None) -> int | None: + """Adjust a reading by its offset.""" + if reading is None or offset is None: + return None + return reading + offset + + +def test_job_round_trips_a_path_source( + file_source: tuple[SourceFactory, Path, str], +) -> None: + """Loading a saved job rebuilds its file source without rebinding it.""" + build, path, _ = file_source + source = build(path) + database = InMemoryArrowDatabase() + with PipelineJob(name="readings", database=database) as job: + _ = adjust.pod(source) + job.save("job.json") + + loaded = PipelineJob.load("job.json", database=database) + restored = loaded.sources[source.source_name] + assert restored.content_hash() == source.content_hash() + assert restored.as_table().equals(source.as_table()) + + +class BytesPath: + """A path-like object whose filesystem representation is bytes.""" + + def __fspath__(self) -> bytes: + """Return a bytes path.""" + return b"readings" + + +@pytest.mark.parametrize( + "path", [b"readings", BytesPath()], ids=["bytes", "bytes-path-like"] +) +def test_source_refuses_bytes_path( + file_source: tuple[SourceFactory, Path, str], path: bytes | BytesPath +) -> None: + """Reject bytes from either form before using the path.""" + build, _, _ = file_source + with pytest.raises(TypeError, match="Source paths must be str or os.PathLike"): + _ = build(cast(os.PathLike[str], path)) From f2f0fc30c1bb9e20d44871ff1d7b6466fcf0869c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 20:46:46 -0800 Subject: [PATCH 2/5] fix(sources): preserve resolved paths in saved Delta jobs --- changelog.d/ITL-1489.md | 4 +- docs/concepts/sources.md | 3 +- src/orcapod/core/sources/base.py | 2 +- .../core/sources/delta_table_source.py | 16 +- .../sources/test_file_source_paths.py | 259 ++++++++++++------ 5 files changed, 195 insertions(+), 89 deletions(-) diff --git a/changelog.d/ITL-1489.md b/changelog.d/ITL-1489.md index 2f5138ed4..6b6b0c085 100644 --- a/changelog.d/ITL-1489.md +++ b/changelog.d/ITL-1489.md @@ -1,5 +1,5 @@ ### Fixed - CSV, Delta, and SQLite sources accept text paths and path-like objects such as - `pathlib.Path`. Saved jobs store the original path text. Bytes paths raise - `TypeError` at construction. + `pathlib.Path`. Saved jobs store the supplied path text for CSV and SQLite, and + the resolved absolute path for Delta. Bytes paths raise `TypeError` at construction. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 81eff1675..3bbc690b2 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -38,7 +38,8 @@ hashing) and produces the final immutable stream. | `DeltaTableSource` | Directory path | Reads Delta Lake table | CSV, Delta, and SQLite sources accept strings and path-like objects such as -`pathlib.Path`. Saved jobs keep the supplied path text, including relative paths. +`pathlib.Path`. Saved jobs keep the supplied path text for CSV and SQLite, and the +resolved absolute path for Delta. `orcapod.sources` also provides database-backed sources (`SQLiteTableSource`, `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1752a9270..e6e662bd3 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -39,7 +39,7 @@ def source_path_text(path: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str: - """Return the path text used for a file source's identity and configuration. + """Return the filesystem representation of a source path as text. Raises: TypeError: If the path is bytes or its filesystem representation is bytes. diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 377db715e..64d0c014e 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -71,20 +71,22 @@ def __init__( tag_only_columns: TagOnlyColumns = (), **kwargs: Any, ) -> None: - self._delta_table_path = source_path_text(delta_table_path) - self._access_path = Path(self._delta_table_path).resolve() + path_text = source_path_text(delta_table_path) + resolved = Path(path_text).resolve() super().__init__(source_id=source_id, **kwargs) if self._source_name is None: # The table folder's path or URI as passed: a relative path stays relative. # A default name is where the data lives, not a name the user gave: it is # not checked for a start shaped like a source id (ITL-1425). - self._source_name = location_source_name(self._delta_table_path) + self._source_name = location_source_name(path_text) + + self._delta_table_path = resolved try: - self._delta_table = deltalake.DeltaTable(str(self._access_path)) + self._delta_table = deltalake.DeltaTable(str(self._delta_table_path)) except deltalake.exceptions.TableNotFoundError: - raise ValueError(f"Delta table not found at {self._access_path}") + raise ValueError(f"Delta table not found at {self._delta_table_path}") self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._record_id_columns = normalize_record_id_columns(record_id_columns) @@ -156,7 +158,7 @@ def check_for_new_data(self) -> bool: if not table.schema.equals(self._table.schema, check_metadata=True): require_live_logical_types(table.schema) raise ValueError( - f"Delta table {str(self._access_path)!r} changed its columns at " + f"Delta table {str(self._delta_table_path)!r} changed its columns at " f"version {version}: the source was built with {self._table.schema}, " f"the table now has {table.schema}. Build a new DeltaTableSource to " "read it" @@ -176,7 +178,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize this source's configuration to a JSON-compatible dict.""" return { "source_type": self.SOURCE_KIND, - "delta_table_path": self._delta_table_path, + "delta_table_path": str(self._delta_table_path), "tag_columns": list(self._tag_columns), **self._tag_only_config(), "record_id_columns": None diff --git a/tests/test_core/sources/test_file_source_paths.py b/tests/test_core/sources/test_file_source_paths.py index bf8c48fc4..cb7343285 100644 --- a/tests/test_core/sources/test_file_source_paths.py +++ b/tests/test_core/sources/test_file_source_paths.py @@ -1,97 +1,128 @@ -"""File sources use the same path text for identity, reads, and saved jobs.""" +"""File sources preserve the string-path behavior for equivalent path-like inputs.""" from __future__ import annotations -import os +import csv import sqlite3 from collections.abc import Callable +from contextlib import closing from functools import partial +from os import PathLike from pathlib import Path -from typing import cast, final +from typing import Literal, cast, final import pyarrow as pa import pytest from deltalake import write_deltalake from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.databases import InMemoryArrowDatabase from orcapod.sources import CSVSource, DeltaTableSource, SQLiteTableSource +from orcapod.types import ContentHash -SourceFactory = Callable[ - [str | os.PathLike[str]], CSVSource | DeltaTableSource | SQLiteTableSource -] +FileSource = CSVSource | DeltaTableSource | SQLiteTableSource +SourceFactory = Callable[[str | PathLike[str]], FileSource] +SourceKind = Literal["csv", "delta", "sqlite"] + + +def write_readings( + kind: SourceKind, path: Path, readings: list[int], *, alternate_layout: bool +) -> None: + """Write two rows with two tags and two data columns in the requested layout.""" + columns: dict[str, list[str] | list[int]] = { + "station": ["a", "b"], + "trial": [1, 2], + "reading": readings, + "offset": [2, 3], + } + if alternate_layout: + columns = { + name: columns[name] for name in ("offset", "trial", "reading", "station") + } + if kind == "csv": + with path.open("w", newline="") as file: + writer = csv.writer(file) + writer.writerow(columns) + writer.writerows(zip(*columns.values(), strict=True)) + elif kind == "delta": + write_deltalake( + path, pa.table({name: pa.array(values) for name, values in columns.items()}) + ) + else: + if alternate_layout: + definition = "offset INTEGER NOT NULL, trial INTEGER PRIMARY KEY, reading INTEGER NOT NULL, station TEXT" + else: + definition = "station TEXT, trial INTEGER PRIMARY KEY, reading INTEGER NOT NULL, offset INTEGER NOT NULL" + with closing(sqlite3.connect(path)) as conn, conn: + _ = conn.execute(f"CREATE TABLE readings ({definition})") + _ = conn.executemany( + "INSERT INTO readings VALUES (?, ?, ?, ?)", + zip(*columns.values(), strict=True), + ) + + +@pytest.fixture(params=[False, True], ids=["standard-layout", "alternate-layout"]) +def alternate_layout(request: pytest.FixtureRequest) -> bool: + """Exercise both tag orders and both physical column layouts.""" + return cast(bool, request.param) @pytest.fixture(params=["csv", "delta", "sqlite"]) def file_source( - request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + request: pytest.FixtureRequest, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + alternate_layout: bool, ) -> tuple[SourceFactory, Path, str]: - """Create two rows with two tags and two data columns for each format.""" - monkeypatch.chdir(tmp_path) - kind = cast(str, request.param) - tags = ["station", "trial"] + """Create fixtures with the same file name and different data in two directories.""" + kind = cast(SourceKind, request.param) + tags = ["trial", "station"] if alternate_layout else ["station", "trial"] if kind == "csv": path = Path("readings.csv") - _ = path.write_text("station,trial,reading,offset\na,1,12,2\nb,2,15,3\n") - return ( - partial(CSVSource, tag_columns=tags, tag_only_columns=True), - path, - "file_path", + build: SourceFactory = partial( + CSVSource, tag_columns=tags, tag_only_columns=True ) - if kind == "delta": + config_key = "file_path" + elif kind == "delta": path = Path("readings") - write_deltalake( - path, - pa.table( - { - "station": ["a", "b"], - "trial": [1, 2], - "reading": [12, 15], - "offset": [2, 3], - } - ), - ) - return ( - partial(DeltaTableSource, tag_columns=tags, tag_only_columns=True), - path, - "delta_table_path", - ) - path = Path("readings.sqlite") - with sqlite3.connect(path) as conn: - _ = conn.execute(""" - CREATE TABLE readings ( - station TEXT, trial INTEGER PRIMARY KEY, - reading INTEGER NOT NULL, offset INTEGER NOT NULL - ) - """) - _ = conn.executemany( - "INSERT INTO readings VALUES (?, ?, ?, ?)", - [("a", 1, 12, 2), ("b", 2, 15, 3)], - ) - return ( - partial( + build = partial(DeltaTableSource, tag_columns=tags, tag_only_columns=True) + config_key = "delta_table_path" + else: + path = Path("readings.sqlite") + build = partial( SQLiteTableSource, table_name="readings", tag_columns=tags, tag_only_columns=True, - ), - path, - "db_path", - ) + ) + config_key = "db_path" + for directory, readings in (("original", [12, 15]), ("other", [50, 15])): + folder = tmp_path / directory + folder.mkdir() + write_readings(kind, folder / path, readings, alternate_layout=alternate_layout) + monkeypatch.chdir(tmp_path / "original") + return build, path, config_key -def test_string_and_path_sources_match( - file_source: tuple[SourceFactory, Path, str], -) -> None: - """A relative path's text survives in the config, and both forms read the same.""" - build, path, config_key = file_source - from_string = build(str(path)) - from_path = build(path) - assert from_path.source_id == from_string.source_id - assert from_path.to_config() == from_string.to_config() - assert from_path.to_config()[config_key] == str(path) - assert from_path.as_table().equals(from_string.as_table()) +@pytest.fixture(params=[False, True], ids=["relative", "absolute"]) +def path_text( + request: pytest.FixtureRequest, file_source: tuple[SourceFactory, Path, str] +) -> str: + """Supply the same path as either relative or absolute text.""" + _, path, _ = file_source + return str(path.resolve() if cast(bool, request.param) else path) + + +def assert_main_path_contract(source: FileSource, config_key: str, text: str) -> None: + """Check the default source name and saved path used by string callers on main.""" + expected_name = f"{text}:main.readings" if config_key == "db_path" else text + expected_path = ( + str(Path(text).resolve()) if config_key == "delta_table_path" else text + ) + assert source.source_name == expected_name + assert source.to_config()[config_key] == expected_path @final @@ -111,12 +142,15 @@ def __fspath__(self) -> str: def test_source_converts_path_like_input_once( file_source: tuple[SourceFactory, Path, str], ) -> None: - """Identity and config use the filesystem representation as given.""" + """Use the filesystem spelling for identity and apply the string config rules.""" build, path, config_key = file_source path_like = TextPath(f"./{path}") source = build(path_like) - assert source.source_id == build(path_like.text).source_id - assert source.to_config()[config_key] == path_like.text + from_string = build(path_like.text) + assert_main_path_contract(from_string, config_key, path_like.text) + assert source.source_id == from_string.source_id + assert source.to_config() == from_string.to_config() + assert source.as_table().equals(from_string.as_table()) assert path_like.calls == 1 @@ -128,21 +162,90 @@ def adjust(reading: int | None, offset: int | None) -> int | None: return reading + offset -def test_job_round_trips_a_path_source( +def sorted_values(table: pa.Table, column: str) -> list[int]: + """Read the fixture's non-null integer values in sorted order.""" + return sorted(cast(list[int], table[column].to_pylist())) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +async def test_completed_job_round_trips_a_path_source( file_source: tuple[SourceFactory, Path, str], + path_text: str, + tmp_path: Path, + asynchronous: bool, ) -> None: - """Loading a saved job rebuilds its file source without rebinding it.""" - build, path, _ = file_source - source = build(path) - database = InMemoryArrowDatabase() - with PipelineJob(name="readings", database=database) as job: - _ = adjust.pod(source) - job.save("job.json") + """Save completed jobs and replay both input forms from persisted results.""" + build, _, config_key = file_source + from_string = build(path_text) + from_path = build(Path(path_text)) + assert_main_path_contract(from_string, config_key, path_text) + assert from_path.source_id == from_string.source_id + assert from_path.to_config() == from_string.to_config() + assert from_path.content_hash() == from_string.content_hash() + assert from_path.as_table().equals(from_string.as_table()) + + pipeline_hashes: list[ContentHash] = [] + for source, filename in ((from_string, "string.json"), (from_path, "path.json")): + database = InMemoryArrowDatabase() + with PipelineJob(name="readings", database=database) as job: + _ = adjust.pod(source) + summary = await job.run_async() if asynchronous else job.run() + assert summary.ok + output = cast(FunctionJobNode, job.nodes["adjust"]) + assert sorted_values(output.as_table(), "adjusted") == [14, 18] + pipeline_hashes.append(output.pipeline_hash()) + saved = tmp_path / filename + job.save(saved) + + loaded = PipelineJob.load(saved, database=database) + summary = ( + await loaded.run_async(load_only=True) + if asynchronous + else loaded.run(load_only=True) + ) + assert summary.ok + restored = loaded.sources[source.source_name] + assert restored.content_hash() == source.content_hash() + assert restored.as_table().equals(source.as_table()) + replayed = cast(FunctionJobNode, loaded.nodes["adjust"]) + assert replayed.pipeline_hash() == output.pipeline_hash() + assert replayed.content_hash() == output.content_hash() + assert sorted_values(replayed.as_table(), "adjusted") == [14, 18] + assert pipeline_hashes[0] == pipeline_hashes[1] + + +def test_refresh_and_job_load_after_working_directory_change( + file_source: tuple[SourceFactory, Path, str], + path_text: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Refresh the original source and load the job using each format's saved path.""" + build, _, config_key = file_source + from_string = build(path_text) + from_path = build(Path(path_text)) + assert_main_path_contract(from_string, config_key, path_text) + expected_rows = [12, 15] + if not Path(path_text).is_absolute() and config_key != "delta_table_path": + expected_rows = [15, 50] + + saved_jobs: list[tuple[FileSource, Path, InMemoryArrowDatabase]] = [] + for source, filename in ((from_string, "string.json"), (from_path, "path.json")): + database = InMemoryArrowDatabase() + with PipelineJob(name="readings", database=database) as job: + _ = adjust.pod(source) + saved = tmp_path / filename + job.save(saved) + saved_jobs.append((source, saved, database)) - loaded = PipelineJob.load("job.json", database=database) - restored = loaded.sources[source.source_name] - assert restored.content_hash() == source.content_hash() - assert restored.as_table().equals(source.as_table()) + monkeypatch.chdir(tmp_path / "other") + for source, saved, database in saved_jobs: + assert source.check_for_new_data() is False + assert sorted_values(source.as_table(), "reading") == [12, 15] + loaded = PipelineJob.load(saved, database=database) + restored = loaded.sources[source.source_name] + assert sorted_values(restored.as_table(), "reading") == expected_rows class BytesPath: @@ -162,4 +265,4 @@ def test_source_refuses_bytes_path( """Reject bytes from either form before using the path.""" build, _, _ = file_source with pytest.raises(TypeError, match="Source paths must be str or os.PathLike"): - _ = build(cast(os.PathLike[str], path)) + _ = build(cast(PathLike[str], path)) From fa643b121634e02509012f5c23830339526e8a3b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 21:04:50 -0800 Subject: [PATCH 3/5] fix(sources): preserve supplied Delta path text in saved jobs --- changelog.d/ITL-1489.md | 9 +++- docs/concepts/sources.md | 7 +++- .../core/sources/delta_table_source.py | 23 +++++++---- .../sources/test_file_source_paths.py | 41 ++++++++++++------- 4 files changed, 53 insertions(+), 27 deletions(-) diff --git a/changelog.d/ITL-1489.md b/changelog.d/ITL-1489.md index 6b6b0c085..8498823b0 100644 --- a/changelog.d/ITL-1489.md +++ b/changelog.d/ITL-1489.md @@ -1,5 +1,10 @@ +### Changed + +- Saved Delta sources keep the supplied path text. A relative path is interpreted + from the working directory when the job is loaded. An open source stays bound + to the table it found at construction. + ### Fixed - CSV, Delta, and SQLite sources accept text paths and path-like objects such as - `pathlib.Path`. Saved jobs store the supplied path text for CSV and SQLite, and - the resolved absolute path for Delta. Bytes paths raise `TypeError` at construction. + `pathlib.Path`. Bytes paths raise `TypeError` at construction. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 3bbc690b2..2c96bed34 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -38,8 +38,11 @@ hashing) and produces the final immutable stream. | `DeltaTableSource` | Directory path | Reads Delta Lake table | CSV, Delta, and SQLite sources accept strings and path-like objects such as -`pathlib.Path`. Saved jobs keep the supplied path text for CSV and SQLite, and the -resolved absolute path for Delta. +`pathlib.Path`. An open source keeps reading the local file or table it found at +construction, even if the working directory changes. Saved jobs keep the supplied +path text. When a job is loaded, a relative path is interpreted from the working +directory at load time. Delta also accepts table URIs such as `s3://bucket/table` +and passes them through unchanged. `orcapod.sources` also provides database-backed sources (`SQLiteTableSource`, `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 64d0c014e..1a53cc5fc 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -1,6 +1,7 @@ from __future__ import annotations import os +import re from collections.abc import Collection from pathlib import Path from typing import TYPE_CHECKING, Any, ClassVar @@ -71,22 +72,26 @@ def __init__( tag_only_columns: TagOnlyColumns = (), **kwargs: Any, ) -> None: - path_text = source_path_text(delta_table_path) - resolved = Path(path_text).resolve() + self._delta_table_path = source_path_text(delta_table_path) + if ( + re.match(r"[A-Za-z][A-Za-z0-9+.-]*://", self._delta_table_path) + and not os.path.splitdrive(self._delta_table_path)[0] + ): + self._access_path = self._delta_table_path + else: + self._access_path = str(Path(self._delta_table_path).resolve()) super().__init__(source_id=source_id, **kwargs) if self._source_name is None: # The table folder's path or URI as passed: a relative path stays relative. # A default name is where the data lives, not a name the user gave: it is # not checked for a start shaped like a source id (ITL-1425). - self._source_name = location_source_name(path_text) - - self._delta_table_path = resolved + self._source_name = location_source_name(self._delta_table_path) try: - self._delta_table = deltalake.DeltaTable(str(self._delta_table_path)) + self._delta_table = deltalake.DeltaTable(self._access_path) except deltalake.exceptions.TableNotFoundError: - raise ValueError(f"Delta table not found at {self._delta_table_path}") + raise ValueError(f"Delta table not found at {self._access_path}") self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._record_id_columns = normalize_record_id_columns(record_id_columns) @@ -158,7 +163,7 @@ def check_for_new_data(self) -> bool: if not table.schema.equals(self._table.schema, check_metadata=True): require_live_logical_types(table.schema) raise ValueError( - f"Delta table {str(self._delta_table_path)!r} changed its columns at " + f"Delta table {self._access_path!r} changed its columns at " f"version {version}: the source was built with {self._table.schema}, " f"the table now has {table.schema}. Build a new DeltaTableSource to " "read it" @@ -178,7 +183,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: """Serialize this source's configuration to a JSON-compatible dict.""" return { "source_type": self.SOURCE_KIND, - "delta_table_path": str(self._delta_table_path), + "delta_table_path": self._delta_table_path, "tag_columns": list(self._tag_columns), **self._tag_only_config(), "record_id_columns": None diff --git a/tests/test_core/sources/test_file_source_paths.py b/tests/test_core/sources/test_file_source_paths.py index cb7343285..6489616f5 100644 --- a/tests/test_core/sources/test_file_source_paths.py +++ b/tests/test_core/sources/test_file_source_paths.py @@ -1,4 +1,4 @@ -"""File sources preserve the string-path behavior for equivalent path-like inputs.""" +"""File sources save the filesystem spelling and pin their open inputs.""" from __future__ import annotations @@ -115,14 +115,11 @@ def path_text( return str(path.resolve() if cast(bool, request.param) else path) -def assert_main_path_contract(source: FileSource, config_key: str, text: str) -> None: - """Check the default source name and saved path used by string callers on main.""" +def assert_path_contract(source: FileSource, config_key: str, text: str) -> None: + """Check that the default name and saved path preserve the supplied text.""" expected_name = f"{text}:main.readings" if config_key == "db_path" else text - expected_path = ( - str(Path(text).resolve()) if config_key == "delta_table_path" else text - ) assert source.source_name == expected_name - assert source.to_config()[config_key] == expected_path + assert source.to_config()[config_key] == text @final @@ -147,7 +144,7 @@ def test_source_converts_path_like_input_once( path_like = TextPath(f"./{path}") source = build(path_like) from_string = build(path_like.text) - assert_main_path_contract(from_string, config_key, path_like.text) + assert_path_contract(from_string, config_key, path_like.text) assert source.source_id == from_string.source_id assert source.to_config() == from_string.to_config() assert source.as_table().equals(from_string.as_table()) @@ -167,6 +164,24 @@ def sorted_values(table: pa.Table, column: str) -> list[int]: return sorted(cast(list[int], table[column].to_pylist())) +def test_delta_source_preserves_table_uri( + tmp_path: Path, alternate_layout: bool +) -> None: + """A Delta table URI can be opened, saved, and restored verbatim.""" + path = tmp_path / "table with spaces" + write_readings("delta", path, [12, 15], alternate_layout=alternate_layout) + uri = path.as_uri() + tags = ["trial", "station"] if alternate_layout else ["station", "trial"] + from_string = DeltaTableSource(uri, tag_columns=tags, tag_only_columns=True) + from_path = DeltaTableSource(TextPath(uri), tag_columns=tags, tag_only_columns=True) + + assert_path_contract(from_string, "delta_table_path", uri) + assert from_path.to_config() == from_string.to_config() + restored = DeltaTableSource.from_config(from_path.to_config()) + assert restored.source_id == from_string.source_id + assert sorted_values(restored.as_table(), "reading") == [12, 15] + + @pytest.mark.asyncio @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) async def test_completed_job_round_trips_a_path_source( @@ -179,7 +194,7 @@ async def test_completed_job_round_trips_a_path_source( build, _, config_key = file_source from_string = build(path_text) from_path = build(Path(path_text)) - assert_main_path_contract(from_string, config_key, path_text) + assert_path_contract(from_string, config_key, path_text) assert from_path.source_id == from_string.source_id assert from_path.to_config() == from_string.to_config() assert from_path.content_hash() == from_string.content_hash() @@ -221,14 +236,12 @@ def test_refresh_and_job_load_after_working_directory_change( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Refresh the original source and load the job using each format's saved path.""" + """Refresh the original source and load using the saved path from the new directory.""" build, _, config_key = file_source from_string = build(path_text) from_path = build(Path(path_text)) - assert_main_path_contract(from_string, config_key, path_text) - expected_rows = [12, 15] - if not Path(path_text).is_absolute() and config_key != "delta_table_path": - expected_rows = [15, 50] + assert_path_contract(from_string, config_key, path_text) + expected_rows = [12, 15] if Path(path_text).is_absolute() else [15, 50] saved_jobs: list[tuple[FileSource, Path, InMemoryArrowDatabase]] = [] for source, filename in ((from_string, "string.json"), (from_path, "path.json")): From 398aac679bcfb3562e8de2bb0b9088f3e0483534 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 21:51:27 -0800 Subject: [PATCH 4/5] fix(sources): resolve local source paths once and refuse URIs for CSV and SQLite CSV, SQLite and Delta resolve a local path once at construction, following symbolic links before parent segments, and open that location for the first read and every check. CSV and SQLite read local paths only and refuse a URI at construction; Delta still passes table URIs through. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1489.md | 6 +++ docs/concepts/sources.md | 15 ++++-- src/orcapod/core/sources/base.py | 36 +++++++++++++ src/orcapod/core/sources/csv_source.py | 10 ++-- .../core/sources/delta_table_source.py | 13 +++-- .../core/sources/sqlite_table_source.py | 30 ++++++++--- .../sources/test_file_source_paths.py | 53 +++++++++++++++++++ 7 files changed, 140 insertions(+), 23 deletions(-) diff --git a/changelog.d/ITL-1489.md b/changelog.d/ITL-1489.md index 8498823b0..d065f7428 100644 --- a/changelog.d/ITL-1489.md +++ b/changelog.d/ITL-1489.md @@ -8,3 +8,9 @@ - CSV, Delta, and SQLite sources accept text paths and path-like objects such as `pathlib.Path`. Bytes paths raise `TypeError` at construction. +- CSV, Delta, and SQLite sources resolve a local path once at construction, + following symbolic links, and every read opens that location. A path such as + `link/../data.csv` now reads the file it names, and a SQLite check no longer + opens another database after the working directory changes. +- CSV and SQLite sources refuse a URI (a scheme followed by `://`, or SQLite's + `file:` form) at construction with `ValueError`; they read local paths only. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 2c96bed34..93a7b0c03 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -38,11 +38,16 @@ hashing) and produces the final immutable stream. | `DeltaTableSource` | Directory path | Reads Delta Lake table | CSV, Delta, and SQLite sources accept strings and path-like objects such as -`pathlib.Path`. An open source keeps reading the local file or table it found at -construction, even if the working directory changes. Saved jobs keep the supplied -path text. When a job is loaded, a relative path is interpreted from the working -directory at load time. Delta also accepts table URIs such as `s3://bucket/table` -and passes them through unchanged. +`pathlib.Path`. A local path is resolved once, when the source is built, following +symbolic links: the first read and every later check open that file or table, even +if the working directory changes. Saved jobs keep the supplied path text. When a +job is loaded, a relative path is interpreted from the working directory at load +time. + +CSV and SQLite sources read local file-system paths only. A URI (a scheme followed +by `://`, such as `s3://bucket/data.csv`, or SQLite's `file:` form) raises +`ValueError` when the source is built. Delta also accepts table URIs such as +`s3://bucket/table` and passes them to `deltalake` unchanged. `orcapod.sources` also provides database-backed sources (`SQLiteTableSource`, `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index e6e662bd3..58a286f6e 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,7 +1,9 @@ from __future__ import annotations import os +import re import warnings +from pathlib import Path from collections.abc import Callable, Collection, Iterator from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast @@ -50,6 +52,40 @@ def source_path_text(path: str | bytes | os.PathLike[str] | os.PathLike[bytes]) return text +_URI_START = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://") + + +def is_uri(text: str) -> bool: + """Return whether a source path text is a URI (a scheme followed by ``://``). + + A Windows drive (``C://data``) is a path, not a URI. + """ + return bool(_URI_START.match(text)) and not os.path.splitdrive(text)[0] + + +def resolved_local_path(text: str) -> str: + """Return the location a local source path names, resolved once. + + Symbolic links are followed before ``..`` is applied, as the operating system + does when it opens the path, so the result names the file the text names now, + whatever the working directory is later. + """ + return str(Path(text).resolve()) + + +def require_local_path(text: str) -> None: + """Refuse a URI where only a local file-system path is read. + + Raises: + ValueError: If the text starts with a scheme followed by ``://``. + """ + if is_uri(text): + raise ValueError( + f"{text!r} is a URI; this source reads a local file-system path. " + "Pass the path of a local file" + ) + + def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: """Return the ``tag_only_columns`` of a saved source config (ITL-1019). diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index c56080ddd..8c71a1dcc 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -14,6 +14,8 @@ from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.base import ( RootSource, + require_local_path, + resolved_local_path, saved_tag_only_columns, source_path_text, ) @@ -356,15 +358,17 @@ def __init__( **kwargs: Any, ) -> None: self._file_path = source_path_text(file_path) + require_local_path(self._file_path) super().__init__(source_id=source_id, **kwargs) if self._source_name is None: # A default name is where the data lives, not a name the user gave: it is # not checked for a start shaped like a source id (ITL-1425). self._source_name = location_source_name(self._file_path) - # Every later read (a check, ITL-1102) opens the file found now, whatever the - # working directory is then. - self._access_path = os.path.abspath(self._file_path) + # The first read and every later one (a check, ITL-1102) open the file the + # path names now, symbolic links followed, whatever the working directory is + # then. + self._access_path = resolved_local_path(self._file_path) self._schema = schema self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._record_id_columns = normalize_record_id_columns(record_id_columns) diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 1a53cc5fc..9d647f796 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -1,9 +1,7 @@ from __future__ import annotations import os -import re from collections.abc import Collection -from pathlib import Path from typing import TYPE_CHECKING, Any, ClassVar import pyarrow as pa @@ -12,6 +10,8 @@ from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.base import ( RootSource, + is_uri, + resolved_local_path, saved_tag_only_columns, source_path_text, ) @@ -73,13 +73,12 @@ def __init__( **kwargs: Any, ) -> None: self._delta_table_path = source_path_text(delta_table_path) - if ( - re.match(r"[A-Za-z][A-Za-z0-9+.-]*://", self._delta_table_path) - and not os.path.splitdrive(self._delta_table_path)[0] - ): + # A table URI is passed through; a local path is resolved once, symbolic + # links followed, and every read opens that location. + if is_uri(self._delta_table_path): self._access_path = self._delta_table_path else: - self._access_path = str(Path(self._delta_table_path).resolve()) + self._access_path = resolved_local_path(self._delta_table_path) super().__init__(source_id=source_id, **kwargs) if self._source_name is None: diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index eec938c18..6a82627c4 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -31,7 +31,12 @@ from typing_extensions import override from orcapod.core.data_tags import TagOnlyColumns -from orcapod.core.sources.base import saved_tag_only_columns, source_path_text +from orcapod.core.sources.base import ( + require_local_path, + resolved_local_path, + saved_tag_only_columns, + source_path_text, +) from orcapod.core.sources.db_table_source import DBTableSource from orcapod.core.sources.source_ids import joined_location from orcapod.core.sources.stream_builder import normalize_record_id_columns @@ -45,13 +50,21 @@ def _access_path(db_path: str) -> str: - """The path a later read opens: a file path made absolute, a special name as given. + """The location every read opens: a file path resolved once, ``:memory:`` as given. - ``":memory:"`` and ``file:`` URIs are not file system paths. + Raises: + ValueError: If the path is a URI (``file:`` or a scheme followed by ``://``): + the source reads a local file-system path. """ - if db_path == ":memory:" or db_path.startswith("file:"): + if db_path.startswith("file:"): + raise ValueError( + f"{db_path!r} is a SQLite URI; SQLiteTableSource reads a local " + "file-system path. Pass the path of the database file" + ) + require_local_path(db_path) + if db_path == ":memory:": return db_path - return os.path.abspath(db_path) + return resolved_local_path(db_path) class SQLiteTableSource(DBTableSource): @@ -118,10 +131,11 @@ def __init__( tag_only_columns: TagOnlyColumns = (), ) -> None: self._db_path = source_path_text(db_path) - # A check (ITL-1102) reopens the database found now, whatever the working - # directory is then; an in-memory database or a URI is kept as given. + # The first read and every check (ITL-1102) open the database the path names + # now, symbolic links followed, whatever the working directory is then; an + # in-memory database is kept as given. self._access_path = _access_path(self._db_path) - connector = SQLiteConnector(self._db_path) + connector = SQLiteConnector(self._access_path) try: # A missing table is reported as missing, not as a table without a key. diff --git a/tests/test_core/sources/test_file_source_paths.py b/tests/test_core/sources/test_file_source_paths.py index 6489616f5..3a7d13b11 100644 --- a/tests/test_core/sources/test_file_source_paths.py +++ b/tests/test_core/sources/test_file_source_paths.py @@ -279,3 +279,56 @@ def test_source_refuses_bytes_path( build, _, _ = file_source with pytest.raises(TypeError, match="Source paths must be str or os.PathLike"): _ = build(cast(PathLike[str], path)) + + +def test_source_follows_a_symlink_before_a_parent_segment( + file_source: tuple[SourceFactory, Path, str], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Read the file the path names, and keep that file after a directory change. + + ``alias`` links to a folder inside ``other``, so ``alias/..`` is ``other``, not + the working directory: removing ``..`` before following the link would read the + working directory's file. + """ + build, path, config_key = file_source + (tmp_path / "other" / "target").mkdir() + Path("alias").symlink_to(tmp_path / "other" / "target", target_is_directory=True) + text = f"alias/../{path}" + + source = build(text) + assert_path_contract(source, config_key, text) + assert sorted_values(source.as_table(), "reading") == [15, 50] + + monkeypatch.chdir(tmp_path) + assert source.check_for_new_data() is False + assert sorted_values(source.as_table(), "reading") == [15, 50] + + +@pytest.mark.parametrize( + "uri", + ["file:///data/readings", "s3://bucket/readings"], + ids=["file-uri", "s3-uri"], +) +@pytest.mark.parametrize("kind", ["csv", "sqlite"]) +def test_local_file_source_refuses_a_uri(kind: str, uri: str) -> None: + """CSV and SQLite read local paths: a URI is refused at construction.""" + with pytest.raises(ValueError, match="local file-system path"): + if kind == "csv": + _ = CSVSource(uri, tag_columns=["station"], tag_only_columns=True) + else: + _ = SQLiteTableSource(uri, "readings", tag_columns=["station"]) + + +def test_sqlite_source_refuses_a_sqlite_uri(tmp_path: Path) -> None: + """SQLite's own ``file:`` form is a URI, refused before the database is opened.""" + write_readings( + "sqlite", tmp_path / "readings.sqlite", [12, 15], alternate_layout=False + ) + with pytest.raises(ValueError, match="SQLite URI"): + _ = SQLiteTableSource( + f"file:{tmp_path / 'readings.sqlite'}?mode=ro", + "readings", + tag_columns=["station"], + ) From ab6a8bf8e0fcf73bf5029b587db3eb3a33c63430 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 22:47:35 -0800 Subject: [PATCH 5/5] fix(sources): infer CSV compression from the supplied path name A CSV source reads through the resolved target of its path, but the compression is now decided by the name as supplied, as before links were resolved: a link named with a .gz suffix to a file without one (or the reverse) is decompressed as its own name says, with a declared and an inferred schema, on construction and on a check. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/sources/csv_source.py | 51 +++++++++++--- .../sources/test_file_source_paths.py | 70 +++++++++++++++++++ 2 files changed, 113 insertions(+), 8 deletions(-) diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 8c71a1dcc..f9f3812dd 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -6,7 +6,7 @@ import os import re from collections.abc import Collection -from typing import Any, ClassVar +from typing import Any, ClassVar, Literal import pyarrow as pa from typing_extensions import override @@ -180,7 +180,40 @@ def _refuse_overflow(values: pa.ChunkedArray[Any], texts: pa.ChunkedArray[Any]) ) -def _read_declared(path: str, schema: pa.Schema) -> pa.Table: +_Compression = Literal["bz2", "gzip", "lz4", "zstd"] + +_COMPRESSION_SUFFIXES: dict[str, _Compression] = { + ".bz2": "bz2", + ".gz": "gzip", + ".lz4": "lz4", + ".zst": "zstd", +} +"""The suffixes pyarrow reads as a compression when it opens a file by its name.""" + + +def _compression_of(name: str) -> _Compression | None: + """Return the compression pyarrow would detect from a file's name, or ``None``. + + The name the user supplied decides it, not the name of the file a symbolic link + resolves to: the file is opened at its resolved location, but decompressed as + its supplied name says. + """ + for suffix, compression in _COMPRESSION_SUFFIXES.items(): + if name.endswith(suffix): # case-sensitive, as pyarrow's detection is + return compression + return None + + +def _open_csv(path: str, name: str) -> pa.NativeFile: + """Open the file at ``path``, decompressed as its supplied ``name`` says.""" + compression = _compression_of(name) + file = pa.OSFile(path, "r") + if compression is None: + return file + return pa.CompressedInputStream(file, compression) + + +def _read_declared(path: str, name: str, schema: pa.Schema) -> pa.Table: """Read a CSV file with every column parsed as ``schema`` declares it (ITL-1322). The text of each cell is parsed as its column's declared type; nothing is @@ -193,8 +226,8 @@ def _read_declared(path: str, schema: pa.Schema) -> pa.Table: - Any other column: pyarrow's null markers (an empty field, ``NA``, ``null``, ``N/A``, ``NaN`` and the rest of ``ConvertOptions().null_values``) are null. - The file is read once into memory (decompressed as the reader would from its - name) and every parse reads that one snapshot, so a file replaced meanwhile + The file at ``path`` is read once into memory (decompressed as the reader + would from ``name``, the path as supplied) and every parse reads that one snapshot, so a file replaced meanwhile cannot mix two versions. pyarrow's null list applies to a whole parse, so a file with both classes of columns is parsed twice with one set of read and parse options, the text-like columns the second time, and the row counts are compared. @@ -216,7 +249,7 @@ def _read_declared(path: str, schema: pa.Schema) -> pa.Table: import pyarrow.csv as pa_csv # Check the same snapshot the typed parser will receive. - with pa.input_stream(path) as stream: + with _open_csv(path, name) as stream: data = stream.read() _require_csv_header_names(pa.BufferReader(data)) reader_types: dict[str, pa.DataType] = {} @@ -405,8 +438,10 @@ def _read_table(self) -> pa.Table: import pyarrow.csv as pa_csv if self._schema is None: - _require_csv_header_names(pa.input_stream(self._access_path)) - table: pa.Table = pa_csv.read_csv(self._access_path) + # Opened at the resolved location, decompressed as the supplied name says. + _require_csv_header_names(_open_csv(self._access_path, self._file_path)) + with _open_csv(self._access_path, self._file_path) as stream: + table: pa.Table = pa_csv.read_csv(stream) # pyright: ignore[reportArgumentType] # pyarrow reads a NativeFile; its stubs name only paths and IO require_source_column_names(table.column_names) require_supported_nullable_types(table.schema) return table.cast(arrow_utils.infer_schema_nullable(table)) @@ -414,7 +449,7 @@ def _read_table(self) -> pa.Table: require_supported_nullable_types(self._schema) require_live_logical_types(self._schema) try: - return _read_declared(self._access_path, self._schema) + return _read_declared(self._access_path, self._file_path, self._schema) except ValueError as exc: # pyarrow's ArrowInvalid is a ValueError # The reader names a column by its position in the file, which is the # schema's field order (a schema names every column, in order). diff --git a/tests/test_core/sources/test_file_source_paths.py b/tests/test_core/sources/test_file_source_paths.py index 3a7d13b11..85a5bbdee 100644 --- a/tests/test_core/sources/test_file_source_paths.py +++ b/tests/test_core/sources/test_file_source_paths.py @@ -3,6 +3,7 @@ from __future__ import annotations import csv +import gzip import sqlite3 from collections.abc import Callable from contextlib import closing @@ -306,6 +307,75 @@ def test_source_follows_a_symlink_before_a_parent_segment( assert sorted_values(source.as_table(), "reading") == [15, 50] +def csv_readings_bytes( + folder: Path, readings: list[int], *, alternate_layout: bool +) -> bytes: + """Return the CSV text ``write_readings`` writes, as bytes.""" + path = folder / "readings-bytes.csv" + write_readings("csv", path, readings, alternate_layout=alternate_layout) + data = path.read_bytes() + path.unlink() + return data + + +@pytest.mark.parametrize("declared", [False, True], ids=["inferred", "declared"]) +@pytest.mark.parametrize( + ("link_name", "target_name", "compressed"), + [ + ("readings.csv.gz", "payload", True), + ("readings.csv", "payload.csv.gz", False), + ], + ids=["gz-link-to-plain-name", "plain-link-to-gz-name"], +) +def test_csv_compression_follows_the_supplied_name( + link_name: str, + target_name: str, + compressed: bool, + declared: bool, + alternate_layout: bool, + tmp_path: Path, +) -> None: + """A link's own name, not its target's, says how the CSV file is compressed. + + The file is read at the link's resolved target, on construction and on a check, + but decompressed as the supplied name says, as before links were resolved. + """ + target = tmp_path / target_name + + def write(readings: list[int]) -> None: + data = csv_readings_bytes(tmp_path, readings, alternate_layout=alternate_layout) + _ = target.write_bytes(gzip.compress(data) if compressed else data) + + write([12, 15]) + link = tmp_path / link_name + link.symlink_to(target) + types = { + "station": pa.large_string(), + "trial": pa.int64(), + "reading": pa.int64(), + "offset": pa.int64(), + } + order = ( + ("offset", "trial", "reading", "station") + if alternate_layout + else ("station", "trial", "reading", "offset") + ) + schema = pa.schema([(name, types[name]) for name in order]) if declared else None + + source = CSVSource( + str(link), + tag_columns=["trial", "station"] if alternate_layout else ["station", "trial"], + schema=schema, + tag_only_columns=True, + ) + assert_path_contract(source, "file_path", str(link)) + assert sorted_values(source.as_table(), "reading") == [12, 15] + + write([90, 15]) + assert source.check_for_new_data() is True + assert sorted_values(source.as_table(), "reading") == [15, 90] + + @pytest.mark.parametrize( "uri", ["file:///data/readings", "s3://bucket/readings"],