diff --git a/changelog.d/ITL-1489.md b/changelog.d/ITL-1489.md new file mode 100644 index 000000000..d065f7428 --- /dev/null +++ b/changelog.d/ITL-1489.md @@ -0,0 +1,16 @@ +### 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`. 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 88b049578..7f84b8f50 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -34,9 +34,21 @@ 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`. 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 time (provisional in this release, see [Provisional sources](#provisional-sources)); see the @@ -519,7 +531,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 7583ff34f..f4cb7e2a2 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,6 +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 @@ -37,6 +40,52 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol +def source_path_text(path: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str: + """Return the filesystem representation of a source path as text. + + 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 + + +_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 5292c493e..f9f3812dd 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -6,13 +6,19 @@ 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 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, + require_local_path, + resolved_local_path, + 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 ( @@ -174,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 @@ -187,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. @@ -210,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] = {} @@ -342,7 +381,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 +390,18 @@ def __init__( tag_only_columns: TagOnlyColumns = (), **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(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) + # 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) @@ -397,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)) @@ -406,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/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 464805d10..9d647f796 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -2,14 +2,19 @@ import os from collections.abc import Collection -from pathlib import Path from typing import TYPE_CHECKING, Any, ClassVar import pyarrow as pa 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, + is_uri, + resolved_local_path, + 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 +25,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 +64,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 +72,25 @@ 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) + # 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 = resolved_local_path(self._delta_table_path) 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(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 +162,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" @@ -174,7 +182,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..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 +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 @@ -44,15 +49,22 @@ from orcapod.config import OrcapodConfig -def _access_path(db_path: str | os.PathLike[str]) -> str | os.PathLike[str]: - """The path a later read opens: a file path made absolute, a special name as given. +def _access_path(db_path: str) -> str: + """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. """ - text = os.fspath(db_path) - if text == ":memory:" or text.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(text) + return resolved_local_path(db_path) class SQLiteTableSource(DBTableSource): @@ -107,7 +119,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 +130,12 @@ def __init__( *, tag_only_columns: TagOnlyColumns = (), ) -> None: - self._db_path = 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._db_path = source_path_text(db_path) + # 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._access_path) try: # A missing table is reported as missing, not as a table without a key. @@ -198,7 +211,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 +230,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..85a5bbdee --- /dev/null +++ b/tests/test_core/sources/test_file_source_paths.py @@ -0,0 +1,404 @@ +"""File sources save the filesystem spelling and pin their open inputs.""" + +from __future__ import annotations + +import csv +import gzip +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 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 + +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, + alternate_layout: bool, +) -> tuple[SourceFactory, Path, str]: + """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") + build: SourceFactory = partial( + CSVSource, tag_columns=tags, tag_only_columns=True + ) + config_key = "file_path" + elif kind == "delta": + path = Path("readings") + 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, + ) + 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 + + +@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_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 + assert source.source_name == expected_name + assert source.to_config()[config_key] == text + + +@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: + """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) + from_string = build(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()) + 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 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())) + + +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( + file_source: tuple[SourceFactory, Path, str], + path_text: str, + tmp_path: Path, + asynchronous: bool, +) -> None: + """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_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 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_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")): + 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)) + + 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: + """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(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] + + +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"], + 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"], + )