Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions changelog.d/ITL-1489.md
Original file line number Diff line number Diff line change
@@ -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.
16 changes: 14 additions & 2 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 2 additions & 3 deletions docs/dev/design_issues/PLT-4864-TUT1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 0 additions & 8 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 6 additions & 6 deletions docs/tutorial/01-first-stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -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",
)
Expand All @@ -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.
Expand Down Expand Up @@ -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",
)
Expand Down Expand Up @@ -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",
)
Expand All @@ -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:
Expand Down
49 changes: 49 additions & 0 deletions src/orcapod/core/sources/base.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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).

Expand Down
73 changes: 58 additions & 15 deletions src/orcapod/core/sources/csv_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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] = {}
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand Down Expand Up @@ -397,16 +438,18 @@ 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))
require_source_column_names(self._schema.names)
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).
Expand Down
Loading
Loading