From 2818eba7a199658838fdb7c580036f4b8a051c15 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:20:41 -0800 Subject: [PATCH 1/3] feat(core): row spool, rows fetched by number from memory and local disk (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 359 ++++++++++++++++++++++++++++++ tests/test_core/test_row_spool.py | 238 ++++++++++++++++++++ 2 files changed, 597 insertions(+) create mode 100644 src/orcapod/core/row_spool.py create mode 100644 tests/test_core/test_row_spool.py diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py new file mode 100644 index 000000000..e56b5c8d7 --- /dev/null +++ b/src/orcapod/core/row_spool.py @@ -0,0 +1,359 @@ +"""Rows held for a later fetch by row number: some in memory, the rest on local disk. + +A join on the async path keeps its inputs' join keys in memory and the rows behind them +here (ITL-1464). ``RowSpool.append`` numbers rows in the order they come; ``take`` fetches +rows by those numbers; ``discard`` says that rows are never fetched again. + +Format: rows wait in memory until they exceed a byte limit, then become one segment: an +Arrow IPC file of one record batch, uncompressed, read memory-mapped (a mapped page is +the operating system's to drop, not memory this process holds). An extension column is +written as its storage and wrapped again when read, so reading needs no registered type. + +Lifetime: a segment is deleted once every row of it is discarded; a spool's files are +removed by ``close`` (a spool is a context manager: normal end, exception and +cancellation alike) and when it is collected. A process keeps its spools in one directory +of its own, removed at interpreter exit. A killed process leaves its directory behind; the +next process to spill there removes it: every directory holds a lock file its process +keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on +Windows, nothing is swept.) A spool is not a store: nothing in it outlives the run, is +found by a later process as rows, or enters a hash. +""" + +from __future__ import annotations + +import atexit +import os +import shutil +import tempfile +import threading +import weakref +from typing import IO, Any, Self + +import numpy as np +import numpy.typing as npt +import pyarrow as pa + +try: + import fcntl +except ImportError: # no such module on Windows + fcntl = None + +SPOOL_MEMORY_BYTES = 64 * 1024 * 1024 +"""How many bytes of rows a spool keeps in memory before they become a segment.""" + +_PREFIX = "orcapod-spool-" +_LOCK_NAME = "lock" + + +class _ProcessDirectories: + """The directory of this process under each root, made and swept on first use.""" + + def __init__(self) -> None: + self._guard = threading.Lock() + self._pid: int = os.getpid() + self._held: dict[str, tuple[str, IO[str]]] = {} + + def get(self, root: str) -> str: + """This process's directory under ``root``.""" + with self._guard: + if self._pid != os.getpid(): + # A forked child: the directories held are its parent's. + self._pid, self._held = os.getpid(), {} + if root not in self._held or not os.path.isdir(self._held[root][0]): + self._held[root] = _make_process_directory(root) + return self._held[root][0] + + def remove(self) -> None: + """Remove this process's directories (at exit).""" + if self._pid != os.getpid(): + return # a forked child holds none of its own + for directory, lock in self._held.values(): + shutil.rmtree(directory, ignore_errors=True) + lock.close() + self._held = {} + + +def _make_process_directory(root: str) -> tuple[str, IO[str]]: + """Make this process's directory under ``root``, locked, and sweep abandoned ones. + + Both happen under one lock of the root, so a sweep never sees a directory that is + made but not yet locked. + """ + os.makedirs(root, exist_ok=True) + if fcntl is None: + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + return directory, open(os.path.join(directory, _LOCK_NAME), "w") + name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") + flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC + with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: + fcntl.flock(root_lock, fcntl.LOCK_EX) + _sweep(root) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.flock(lock, fcntl.LOCK_EX) + return directory, lock + + +def _sweep(root: str) -> None: + """Remove this user's spool directories under ``root`` that no process holds.""" + assert fcntl is not None + with os.scandir(root) as entries: + candidates = [ + entry.path + for entry in entries + if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) + ] + for directory in candidates: + try: + if os.stat(directory).st_uid != os.getuid(): + continue + with open(os.path.join(directory, _LOCK_NAME)) as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + shutil.rmtree(directory, ignore_errors=True) + except OSError: + continue # held by a live process, being removed, or not a spool's + + +_directories = _ProcessDirectories() +_ = atexit.register(_directories.remove) + + +def _remove_directory(directory: str, owner: int) -> None: + """Remove a spool's directory, in the process that made it only.""" + if os.getpid() == owner: + shutil.rmtree(directory, ignore_errors=True) + + +class _Segment: + """Rows of one run of row numbers, in memory (``table``) or in a file (``path``).""" + + def __init__(self, start: int, table: pa.Table) -> None: + self.start: int = start + self.rows: int = table.num_rows + self.live: int = table.num_rows + self.table: pa.Table | None = table + self.path: str | None = None + + def drop(self) -> None: + """Let the rows go, and delete their file.""" + self.table = None + if self.path is not None: + os.unlink(self.path) + self.path = None + + +class RowSpool: + """Rows numbered from 0 in the order appended, fetched by number. + + Args: + memory_bytes: How many bytes of rows stay in memory; beyond that the rows in + memory are written to a file. + root: The directory to keep files under; by default the system's temporary + directory. Nothing is made there until rows are written. + """ + + def __init__( + self, memory_bytes: int = SPOOL_MEMORY_BYTES, root: str | None = None + ) -> None: + self._memory_bytes: int = memory_bytes + self._root: str | None = root + self._closed: bool = False + self._schema: pa.Schema | None = None + self._segments: list[_Segment] = [] + self._starts: npt.NDArray[np.int64] | None = None + self._in_memory: int = 0 + self._directory: str | None = None + self._cleanup: weakref.finalize[..., Any] | None = None # pyright: ignore[reportExplicitAny] # any finalizer + self.size: int = 0 + """How many rows were appended: the next row's number.""" + + @property + def memory_bytes(self) -> int: + """How many bytes of rows are in memory now.""" + return self._in_memory + + def append(self, table: pa.Table) -> None: + """Hold ``table``'s rows, numbered from ``size`` on. + + Args: + table: The rows; every table appended has one schema. + + Raises: + ValueError: If the spool is closed. + OSError: If the rows in memory cannot be written to the local disk. + """ + if self._closed: + raise ValueError("the row spool is closed") + if not table.num_rows: + return + if self._schema is None: + self._schema = table.schema + # One chunk that owns its rows: a slice would keep its whole parent alive. + self._add(_Segment(self.size, _owned(table))) + self.size += table.num_rows + if self._in_memory > self._memory_bytes: + self._spill() + + def _add(self, segment: _Segment) -> None: + self._segments.append(segment) + self._starts = None + if segment.table is not None: + self._in_memory += segment.table.nbytes + + def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: + """The rows with these numbers, in this order, as one chunk per column. + + Only the segments that hold a wanted row are read, each once. + + Args: + rows: Row numbers, at least one, none of them discarded. + """ + if self._starts is None: + self._starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(self._starts, rows, side="right") - 1 + order = np.argsort(held_in, kind="stable") + sorted_rows, sorted_in = rows[order], held_in[order] + edges = np.flatnonzero(np.diff(sorted_in)) + 1 + parts: list[pa.Table] = [] + for group in np.split(np.arange(len(rows)), edges): + segment = self._segments[int(sorted_in[group[0]])] + local = pa.array(sorted_rows[group] - segment.start, pa.int64()) + parts.append(self._take_from(segment, local)) + if len(parts) == 1: + # One segment: the stable sort changed nothing. + return parts[0].combine_chunks() + taken = pa.concat_tables(parts).combine_chunks() + back = np.empty(len(order), np.int64) + back[order] = np.arange(len(order)) + return taken.take(pa.array(back, pa.int64())).combine_chunks() + + def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # pyright: ignore[reportExplicitAny] # row numbers + """Rows of one segment, by their numbers in it.""" + if segment.table is not None: + return segment.table.take(local) + assert segment.path is not None and self._schema is not None + with pa.memory_map(segment.path) as mapped: + stored = pa.ipc.open_file(mapped).read_all() + return _wrapped(stored.take(local), self._schema) + + def discard(self, rows: npt.NDArray[np.int64]) -> None: + """Say that these rows are never fetched again. + + A segment whose rows are all discarded is let go, and its file deleted. + + Args: + rows: Row numbers, each discarded once only. + """ + if not len(rows): + return + starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(starts, rows, side="right") - 1 + counts = np.bincount(held_in, minlength=len(self._segments)) + emptied = False + for index in np.flatnonzero(counts): + segment = self._segments[int(index)] + segment.live -= int(counts[index]) + if not segment.live: + if segment.table is not None: + self._in_memory -= segment.table.nbytes + segment.drop() + emptied = True + if emptied: + self._segments = [s for s in self._segments if s.live] + self._starts = None + + def _spill(self) -> None: + """Write the segments in memory to one file, as one segment.""" + waiting = [s for s in self._segments if s.table is not None] + assert self._schema is not None + # Neighbours only: a segment's rows have consecutive numbers. + runs: list[list[_Segment]] = [] + for segment in waiting: + if runs and runs[-1][-1].start + runs[-1][-1].rows == segment.start: + runs[-1].append(segment) + else: + runs.append([segment]) + for run in runs: + tables = [s.table for s in run if s.table is not None] + table = pa.concat_tables(tables).combine_chunks() + merged = _Segment(run[0].start, table) + merged.live = sum(s.live for s in run) + merged.path = self._write(merged) + merged.table = None + replaced = set(map(id, run)) + position = self._segments.index(run[0]) + self._segments = [s for s in self._segments if id(s) not in replaced] + self._segments.insert(position, merged) + self._in_memory -= sum(t.nbytes for t in tables) + self._starts = None + + def _write(self, segment: _Segment) -> str: + """Write a segment's rows to a file of their own; return its path.""" + assert segment.table is not None + if self._directory is None: + process_directory = _directories.get(self._root or tempfile.gettempdir()) + self._directory = tempfile.mkdtemp(dir=process_directory) + self._cleanup = weakref.finalize( + self, _remove_directory, self._directory, os.getpid() + ) + path = os.path.join(self._directory, f"{segment.start}.arrow") + table = _as_storage(segment.table) + with ( + pa.OSFile(path, "wb") as sink, + pa.ipc.new_file(sink, table.schema) as writer, + ): + writer.write_table(table) + return path + + def close(self) -> None: + """Let every row go and remove the files. Calling it again does nothing.""" + self._closed = True + self._segments = [] + self._starts = None + self._in_memory = 0 + if self._cleanup is not None: + _ = self._cleanup() + self._directory = self._cleanup = None + + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + +def _owned(table: pa.Table) -> pa.Table: + """``table`` as one chunk over buffers of its own size, copied only if needed.""" + table = table.combine_chunks() + if table.get_total_buffer_size() > 2 * table.nbytes: + table = table.take(pa.array(np.arange(table.num_rows), pa.int64())) + return table + + +def _as_storage(table: pa.Table) -> pa.Table: + """``table`` with each extension column as its storage, no field metadata. + + Flags are dropped too: a field declared non-nullable may hold a null (a column not + settled yet), and ``_wrapped`` puts the schema back. + """ + columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column + for column in table.combine_chunks().columns: + array: Any = column.chunk(0) # pyright: ignore[reportExplicitAny] # any column + is_extension = isinstance(column.type, pa.BaseExtensionType) + columns.append(array.storage if is_extension else array) + return pa.Table.from_arrays(columns, names=table.column_names) + + +def _wrapped(table: pa.Table, schema: pa.Schema) -> pa.Table: + """Undo ``_as_storage``: the columns of ``table``, one chunk each, under ``schema``.""" + columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column + for column, field in zip(table.combine_chunks().columns, schema): + array = column.chunk(0) + if isinstance(field.type, pa.BaseExtensionType): + array = pa.ExtensionArray.from_storage(field.type, array) + columns.append(array) + return pa.Table.from_arrays(columns, schema=schema) diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py new file mode 100644 index 000000000..848fcb94a --- /dev/null +++ b/tests/test_core/test_row_spool.py @@ -0,0 +1,238 @@ +"""Rows held by number, in memory and on local disk (``core/row_spool``, ITL-1464).""" + +from __future__ import annotations + +import asyncio +import gc +import os +import subprocess +import sys +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod.core import row_spool +from orcapod.core.row_spool import RowSpool + + +def _table(start: int, rows: int) -> pa.Table: + """Rows with two tags and two data columns, a list and an extension among them.""" + numbers = list(range(start, start + rows)) + return pa.table( + { + "session": pa.array([f"s{n % 3}" for n in numbers], pa.large_string()), + "at": pa.array( + [datetime.fromtimestamp(n, timezone.utc) for n in numbers], + pa.timestamp("us", "UTC"), + ), + "values": pa.array( + [None if n % 5 == 0 else [n, None] for n in numbers], + pa.large_list(pa.int64()), + ), + "id": pa.ExtensionArray.from_storage( + pa.uuid(), + pa.array([n.to_bytes(16, "big") for n in numbers], pa.binary(16)), + ), + } + ) + + +def _filled( + root: Path, sizes: list[int], memory_bytes: int +) -> tuple[RowSpool, pa.Table]: + spool = RowSpool(memory_bytes, str(root)) + tables, start = [], 0 + for size in sizes: + tables.append(_table(start, size)) + spool.append(tables[-1]) + start += size + return spool, pa.concat_tables(tables) + + +def _files(root: Path) -> list[Path]: + return sorted(root.rglob("*.arrow")) + + +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_rows_come_back_by_number_in_the_order_asked( + tmp_path: Path, memory_bytes: int +) -> None: + spool, rows = _filled(tmp_path, [1, 50, 0, 7, 120, 3], memory_bytes) + assert spool.size == rows.num_rows + assert bool(_files(tmp_path)) == (memory_bytes < 10**9) + assert spool.memory_bytes <= max(memory_bytes, 0) + rng = np.random.default_rng(0) + for count in (1, 5, 400): # 400: every row several times + wanted = rng.integers(0, rows.num_rows, count) + taken = spool.take(wanted) + assert taken.schema.equals(rows.schema, check_metadata=True) + assert taken.equals(rows.take(pa.array(wanted, pa.int64()))) + spool.close() + + +def test_a_field_flagged_non_nullable_keeps_the_null_it_holds(tmp_path: Path) -> None: + schema = pa.schema([pa.field("a", pa.int64(), nullable=False, metadata={"k": "v"})]) + table = pa.Table.from_arrays([pa.array([1, None])], schema=schema) + with RowSpool(0, str(tmp_path)) as spool: + spool.append(table) + taken = spool.take(np.array([1, 0])) + assert taken.schema.equals(schema, check_metadata=True) + assert taken.column("a").to_pylist() == [None, 1] + + +def test_a_slice_does_not_keep_its_parent(tmp_path: Path) -> None: + spool = RowSpool(10**9, str(tmp_path)) + spool.append(_table(0, 10_000).slice(5, 2)) + held = spool._segments[0].table # pyright: ignore[reportPrivateUsage] # what it keeps alive + assert held is not None and held.get_total_buffer_size() < 2_000 + assert spool.memory_bytes < 1_000 + assert spool.take(np.array([1])).equals(_table(6, 1)) + + +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_discarded_rows_free_their_segment_and_the_rest_stay( + tmp_path: Path, memory_bytes: int +) -> None: + spool, rows = _filled(tmp_path, [40, 40, 40], memory_bytes) + spool.discard(np.arange(0, 120, 2)) + spool.discard(np.array([], dtype=np.int64)) + odd = np.arange(1, 120, 2) + assert spool.take(odd).equals(rows.take(pa.array(odd, pa.int64()))) + spool.append(_table(120, 40)) # numbered after the discarded rows + assert spool.take(np.array([159, 1])).equals( + pa.concat_tables([_table(159, 1), _table(1, 1)]).combine_chunks() + ) + spool.discard(odd) + spool.discard(np.arange(120, 160)) + assert spool.memory_bytes == 0 + assert _files(tmp_path) == [] + + +def test_rows_spilled_after_a_segment_between_them_was_freed(tmp_path: Path) -> None: + spool = RowSpool(1 << 16, str(tmp_path)) + for start in (0, 10, 20): + spool.append(_table(start, 10)) + spool.discard(np.arange(10, 20)) + spool.append(_table(30, 5_000)) # past the limit: what is in memory is written + assert spool.memory_bytes == 0 + wanted = np.array([0, 25, 30, 5_029, 9]) + expected = pa.concat_tables([_table(0, 30), _table(30, 5_000)]) + assert spool.take(wanted).equals(expected.take(pa.array(wanted, pa.int64()))) + spool.close() + + +def test_nothing_is_written_below_the_limit(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10, 10], 10**9) + assert list(tmp_path.iterdir()) == [] + spool.close() + + +def _spool_directories(root: Path) -> list[Path]: + return [p for d in root.glob("orcapod-spool-*") for p in d.iterdir() if p.is_dir()] + + +def test_close_removes_the_files_and_refuses_more_rows(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + assert _files(tmp_path) + spool.close() + spool.close() + assert _spool_directories(tmp_path) == [] + with pytest.raises(ValueError, match="closed"): + spool.append(_table(0, 1)) + + +def test_an_exception_removes_the_files(tmp_path: Path) -> None: + with pytest.raises(RuntimeError, match="stop"), RowSpool(0, str(tmp_path)) as spool: + spool.append(_table(0, 10)) + raise RuntimeError("stop") + assert _spool_directories(tmp_path) == [] + + +@pytest.mark.asyncio +async def test_a_cancellation_removes_the_files(tmp_path: Path) -> None: + async def hold() -> None: + with RowSpool(0, str(tmp_path)) as spool: + spool.append(_table(0, 10)) + await asyncio.Event().wait() + + task = asyncio.create_task(hold()) + await asyncio.sleep(0) + assert _files(tmp_path) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert _spool_directories(tmp_path) == [] + + +def test_a_collected_spool_removes_its_files(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + assert _files(tmp_path) + del spool + gc.collect() + assert _spool_directories(tmp_path) == [] + + +_CHILD = """ +import os, sys +import pyarrow as pa +from orcapod.core.row_spool import RowSpool +spool = RowSpool(0, sys.argv[1]) +spool.append(pa.table({"a": [1]})) +print("ready", flush=True) +if sys.argv[2] == "kill": + os.kill(os.getpid(), 9) +if sys.argv[2] == "wait": + sys.stdin.read() +""" + + +def _child(root: Path, end: str) -> subprocess.Popen[str]: + return subprocess.Popen( + [sys.executable, "-c", _CHILD, str(root), end], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + + +def test_a_process_that_ends_normally_leaves_nothing(tmp_path: Path) -> None: + child = _child(tmp_path, "exit") + _ = child.communicate() + assert child.returncode == 0 + assert list(tmp_path.glob("orcapod-spool-*")) == [] + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None: + killed = _child(tmp_path, "kill") + _ = killed.communicate() + (left,) = tmp_path.glob("orcapod-spool-*") + assert _files(left) + live = _child(tmp_path, "wait") + assert live.stdout is not None + assert live.stdout.readline() == "ready\n" + try: + assert not left.exists() # the second process swept it + (held,) = tmp_path.glob("orcapod-spool-*") + other = tmp_path / "orcapod-spool-not-ours" # no lock file: left alone + other.mkdir() + spool, _ = _filled(tmp_path, [10], 0) + assert held.exists() and _files(held) + assert other.exists() + spool.close() + finally: + _ = live.communicate() + assert not held.exists() + + +def test_a_forked_child_never_removes_its_parents_files(tmp_path: Path) -> None: + # A child inherits its parent's finalizers; the owner check is what stops them. + directory = tmp_path / "spool" + directory.mkdir() + row_spool._remove_directory(str(directory), os.getpid() + 1) # pyright: ignore[reportPrivateUsage] # the owner check itself + assert directory.exists() + row_spool._remove_directory(str(directory), os.getpid()) # pyright: ignore[reportPrivateUsage] # the owner check itself + assert not directory.exists() From 35fe2572918ba2cae3edb21c7c951edf4b7e65cc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:41:15 -0800 Subject: [PATCH 2/3] fix(core): row spool survives forks and failed spills; whole tables and slices without copying (ITL-1464) A forked child neither waits for a lock of its parent's threads nor touches its parent's files; a failed spill leaves the spool as it was; an unlocked or partly removed directory is swept. table() and slice() give rows through their mappings and outlive the spool. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 205 ++++++++++++++++++---- tests/test_core/test_row_spool.py | 283 +++++++++++++++++++++++++++++- 2 files changed, 448 insertions(+), 40 deletions(-) diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py index e56b5c8d7..2ac0de2e2 100644 --- a/src/orcapod/core/row_spool.py +++ b/src/orcapod/core/row_spool.py @@ -15,13 +15,24 @@ of its own, removed at interpreter exit. A killed process leaves its directory behind; the next process to spill there removes it: every directory holds a lock file its process keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on -Windows, nothing is swept.) A spool is not a store: nothing in it outlives the run, is +Windows, nothing is swept.) + +Ownership: a spool belongs to one thread (or one event loop) of the process that made it: +it has no lock of its own, and a forked child's copy refuses every use, so a child never +touches its parent's files. Different spools may be used from different threads. + +Rows: tables of one schema with at least one column, in Orcapod's normalized types (large +variants, no views). The byte limit bounds what the spool keeps; a ``take`` holds the rows +asked for, twice while it puts them in order, so a caller bounds what it asks for. + +A spool is not a store: nothing in it outlives the run, is found by a later process as rows, or enters a hash. """ from __future__ import annotations import atexit +import contextlib import os import shutil import tempfile @@ -50,28 +61,39 @@ class _ProcessDirectories: def __init__(self) -> None: self._guard = threading.Lock() - self._pid: int = os.getpid() self._held: dict[str, tuple[str, IO[str]]] = {} + self.root_lock: IO[str] | None = None + """The root's lock file while a directory is made.""" def get(self, root: str) -> str: """This process's directory under ``root``.""" with self._guard: - if self._pid != os.getpid(): - # A forked child: the directories held are its parent's. - self._pid, self._held = os.getpid(), {} if root not in self._held or not os.path.isdir(self._held[root][0]): self._held[root] = _make_process_directory(root) return self._held[root][0] def remove(self) -> None: """Remove this process's directories (at exit).""" - if self._pid != os.getpid(): - return # a forked child holds none of its own for directory, lock in self._held.values(): - shutil.rmtree(directory, ignore_errors=True) + _remove_process_directory(directory) lock.close() self._held = {} + def after_fork_in_child(self) -> None: + """Start empty: the directories are the parent's, and so are the locks. + + The guard may be held by a thread that does not exist in the child. The lock + files are closed, never unlocked: the parent's open files keep them locked, and + the child keeps none of them locked after the parent is gone. + """ + self._guard = threading.Lock() + inherited = [lock for _, lock in self._held.values()] + if self.root_lock is not None: + inherited.append(self.root_lock) + self._held, self.root_lock = {}, None + for lock in inherited: + lock.close() + def _make_process_directory(root: str) -> tuple[str, IO[str]]: """Make this process's directory under ``root``, locked, and sweep abandoned ones. @@ -86,14 +108,31 @@ def _make_process_directory(root: str) -> tuple[str, IO[str]]: name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: - fcntl.flock(root_lock, fcntl.LOCK_EX) - _sweep(root) - directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) - lock = open(os.path.join(directory, _LOCK_NAME), "w") - fcntl.flock(lock, fcntl.LOCK_EX) + _directories.root_lock = root_lock + try: + fcntl.flock(root_lock, fcntl.LOCK_EX) + _sweep(root) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.flock(lock, fcntl.LOCK_EX) + finally: + _directories.root_lock = None return directory, lock +def _remove_process_directory(directory: str) -> None: + """Remove a process's directory, its lock file last. + + Stopped part way, it leaves a directory a later sweep still recognizes. + """ + with contextlib.suppress(OSError): + for name in os.listdir(directory): + if name != _LOCK_NAME: + shutil.rmtree(os.path.join(directory, name), ignore_errors=True) + os.unlink(os.path.join(directory, _LOCK_NAME)) + os.rmdir(directory) + + def _sweep(root: str) -> None: """Remove this user's spool directories under ``root`` that no process holds.""" assert fcntl is not None @@ -104,18 +143,24 @@ def _sweep(root: str) -> None: if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) ] for directory in candidates: - try: + # A directory held by a live process, being removed, or not a spool's is left. + with contextlib.suppress(OSError): if os.stat(directory).st_uid != os.getuid(): continue - with open(os.path.join(directory, _LOCK_NAME)) as lock: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) - shutil.rmtree(directory, ignore_errors=True) - except OSError: - continue # held by a live process, being removed, or not a spool's + try: + with open(os.path.join(directory, _LOCK_NAME)) as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + _remove_process_directory(directory) + except FileNotFoundError: + # Its process was killed before it made the lock file (the root's lock + # is held here, so none is being made): then it is empty. + os.rmdir(directory) _directories = _ProcessDirectories() _ = atexit.register(_directories.remove) +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_directories.after_fork_in_child) def _remove_directory(directory: str, owner: int) -> None: @@ -158,10 +203,12 @@ def __init__( self._memory_bytes: int = memory_bytes self._root: str | None = root self._closed: bool = False + self._owner: int = os.getpid() self._schema: pa.Schema | None = None self._segments: list[_Segment] = [] self._starts: npt.NDArray[np.int64] | None = None self._in_memory: int = 0 + self._discarded: bool = False self._directory: str | None = None self._cleanup: weakref.finalize[..., Any] | None = None # pyright: ignore[reportExplicitAny] # any finalizer self.size: int = 0 @@ -180,19 +227,41 @@ def append(self, table: pa.Table) -> None: Raises: ValueError: If the spool is closed. - OSError: If the rows in memory cannot be written to the local disk. + RuntimeError: In a process other than the one that made the spool. + OSError: If the rows in memory cannot be written to the local disk. The + spool is then as before the call, with no partial file. """ - if self._closed: - raise ValueError("the row spool is closed") + self._require_usable() if not table.num_rows: return + schema, size = self._schema, self.size if self._schema is None: self._schema = table.schema # One chunk that owns its rows: a slice would keep its whole parent alive. - self._add(_Segment(self.size, _owned(table))) + added = _Segment(self.size, _owned(table)) + self._add(added) self.size += table.num_rows if self._in_memory > self._memory_bytes: - self._spill() + try: + self._spill() + except BaseException: + # The new rows are in the last run, so they were not written. + self._segments.remove(added) + self._starts = None + if added.table is not None: + self._in_memory -= added.table.nbytes + self._schema, self.size = schema, size + raise + + def _require_usable(self) -> None: + """Refuse a closed spool, and a forked child's copy of its parent's.""" + if self._owner != os.getpid(): + raise RuntimeError( + "a row spool is used only in the process that made it: this is a " + + "forked child's copy" + ) + if self._closed: + raise ValueError("the row spool is closed") def _add(self, segment: _Segment) -> None: self._segments.append(segment) @@ -207,7 +276,12 @@ def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: Args: rows: Row numbers, at least one, none of them discarded. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. """ + self._require_usable() if self._starts is None: self._starts = np.fromiter( (s.start for s in self._segments), np.int64, len(self._segments) @@ -234,9 +308,67 @@ def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # py if segment.table is not None: return segment.table.take(local) assert segment.path is not None and self._schema is not None + return _wrapped(self._stored(segment).take(local), self._schema) + + @staticmethod + def _stored(segment: _Segment) -> pa.Table: + """A segment's file as a table over its mapping, extension columns as storage. + + The mapping lives as long as a buffer of the table, also after the file is + deleted (POSIX). + """ + assert segment.path is not None with pa.memory_map(segment.path) as mapped: - stored = pa.ipc.open_file(mapped).read_all() - return _wrapped(stored.take(local), self._schema) + return pa.ipc.open_file(mapped).read_all() + + def table(self) -> pa.Table: + """Every row appended, in order, without copying it into memory. + + Rows in files are read through their mappings: a page is read when a value on it + is. The table stays valid after ``close`` and after the spool is gone: the rows' + memory or mapping lives until the table does (on POSIX, where a deleted file + stays mapped). + + Raises: + ValueError: If the spool is closed, a row was discarded, or nothing was ever + appended (the columns are then unknown). + RuntimeError: In a process other than the one that made the spool. + """ + return self.slice(0, self.size) + + def slice(self, start: int, length: int) -> pa.Table: + """``length`` rows from row number ``start`` on, fewer at the end. + + As ``table``: nothing is copied, and the result outlives the spool. + + Args: + start: The first row's number. + length: How many rows. + + Raises: + ValueError: As ``table``; also for a negative ``start`` or ``length``. + RuntimeError: In a process other than the one that made the spool. + """ + self._require_usable() + if start < 0 or length < 0: + raise ValueError(f"a slice of rows from {start}, {length} long") + if self._schema is None: + raise ValueError("nothing was appended to the row spool: no columns yet") + if self._discarded: + raise ValueError("rows of the row spool were discarded: no whole table") + end = min(start + length, self.size) + parts: list[pa.Table] = [] + for segment in self._segments: + first = max(start, segment.start) + last = min(end, segment.start + segment.rows) + if first >= last: + continue + if segment.table is not None: + part = segment.table + else: + part = _wrapped(self._stored(segment), self._schema) + parts.append(part.slice(first - segment.start, last - first)) + return pa.concat_tables(parts) if parts else self._schema.empty_table() def discard(self, rows: npt.NDArray[np.int64]) -> None: """Say that these rows are never fetched again. @@ -245,7 +377,12 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: Args: rows: Row numbers, each discarded once only. + + Raises: + ValueError: If the spool is closed. + RuntimeError: In a process other than the one that made the spool. """ + self._require_usable() if not len(rows): return starts = np.fromiter( @@ -253,6 +390,7 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: ) held_in = np.searchsorted(starts, rows, side="right") - 1 counts = np.bincount(held_in, minlength=len(self._segments)) + self._discarded = True emptied = False for index in np.flatnonzero(counts): segment = self._segments[int(index)] @@ -302,11 +440,16 @@ def _write(self, segment: _Segment) -> str: ) path = os.path.join(self._directory, f"{segment.start}.arrow") table = _as_storage(segment.table) - with ( - pa.OSFile(path, "wb") as sink, - pa.ipc.new_file(sink, table.schema) as writer, - ): - writer.write_table(table) + try: + with ( + pa.OSFile(path, "wb") as sink, + pa.ipc.new_file(sink, table.schema) as writer, + ): + writer.write_table(table) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(path) + raise return path def close(self) -> None: diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py index 848fcb94a..6b7faa775 100644 --- a/tests/test_core/test_row_spool.py +++ b/tests/test_core/test_row_spool.py @@ -3,18 +3,20 @@ from __future__ import annotations import asyncio +import errno import gc import os +import signal import subprocess import sys from datetime import datetime, timezone from pathlib import Path +from typing import Any import numpy as np import pyarrow as pa import pytest -from orcapod.core import row_spool from orcapod.core.row_spool import RowSpool @@ -124,6 +126,66 @@ def test_rows_spilled_after_a_segment_between_them_was_freed(tmp_path: Path) -> spool.close() +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +def test_the_whole_table_and_slices_of_it(tmp_path: Path, memory_bytes: int) -> None: + spool, rows = _filled(tmp_path, [1, 50, 7, 120, 3], memory_bytes) + assert spool.table().equals(rows, check_metadata=True) + for start, length in ((0, 1), (1, 50), (40, 100), (170, 50), (181, 1), (500, 2)): + part = spool.slice(start, length) + assert part.schema.equals(rows.schema, check_metadata=True) + assert part.equals(rows.slice(start, length)) + with pytest.raises(ValueError, match="slice"): + _ = spool.slice(-1, 2) + with pytest.raises(ValueError, match="slice"): + _ = spool.slice(1, -2) + spool.discard(np.array([3])) + with pytest.raises(ValueError, match="discarded"): + _ = spool.table() + spool.close() + with pytest.raises(ValueError, match="closed"): + _ = spool.table() + + +def test_a_spool_nothing_was_appended_to_has_no_table(tmp_path: Path) -> None: + spool = RowSpool(0, str(tmp_path)) + with pytest.raises(ValueError, match="nothing was appended"): + _ = spool.table() + spool.append(_table(0, 2)) + assert spool.slice(0, 0).equals(_table(0, 0)) + + +def test_the_table_is_mapped_and_not_copied(tmp_path: Path) -> None: + spool = RowSpool(0, str(tmp_path)) + for start in range(0, 40_000, 10_000): + spool.append(_table(start, 10_000)) + before = pa.total_allocated_bytes() + table = spool.table() + size = table.nbytes + assert size > 1_000_000 + assert pa.total_allocated_bytes() - before < size / 100 + spool.close() + + +@pytest.mark.skipif(sys.platform == "win32", reason="a mapped file cannot be deleted") +@pytest.mark.parametrize("memory_bytes", [0, 3_000, 10**9]) +@pytest.mark.parametrize("end", ["close", "collect"]) +def test_a_table_outlives_its_spool( + tmp_path: Path, memory_bytes: int, end: str +) -> None: + spool, rows = _filled(tmp_path, [40, 5_000, 40], memory_bytes) + table, part = spool.table(), spool.slice(30, 100) + if end == "close": + spool.close() + del spool + gc.collect() + assert _files(tmp_path) == [] + assert table.equals(rows, check_metadata=True) + table.validate(full=True) + del table + gc.collect() + assert part.equals(rows.slice(30, 100)) + + def test_nothing_is_written_below_the_limit(tmp_path: Path) -> None: spool, _ = _filled(tmp_path, [10, 10], 10**9) assert list(tmp_path.iterdir()) == [] @@ -219,6 +281,7 @@ def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None (held,) = tmp_path.glob("orcapod-spool-*") other = tmp_path / "orcapod-spool-not-ours" # no lock file: left alone other.mkdir() + (other / "file").touch() spool, _ = _filled(tmp_path, [10], 0) assert held.exists() and _files(held) assert other.exists() @@ -228,11 +291,213 @@ def test_a_killed_process_is_swept_and_a_live_one_is_not(tmp_path: Path) -> None assert not held.exists() -def test_a_forked_child_never_removes_its_parents_files(tmp_path: Path) -> None: - # A child inherits its parent's finalizers; the owner check is what stops them. - directory = tmp_path / "spool" - directory.mkdir() - row_spool._remove_directory(str(directory), os.getpid() + 1) # pyright: ignore[reportPrivateUsage] # the owner check itself - assert directory.exists() - row_spool._remove_directory(str(directory), os.getpid()) # pyright: ignore[reportPrivateUsage] # the owner check itself - assert not directory.exists() +_FORK = """ +import os, sys, signal, threading +import numpy as np, pyarrow as pa +from orcapod.core import row_spool +from orcapod.core.row_spool import RowSpool +case, root = sys.argv[1:] +table = pa.table({"x": [1, 2], "y": [3, 4]}) + +def in_child(function): + child = os.fork() + if child == 0: + signal.alarm(10) + try: + function() + except BaseException as error: + print(repr(error), file=sys.stderr, flush=True) + os._exit(1) + os._exit(0) + assert os.waitstatus_to_exitcode(os.waitpid(child, 0)[1]) == 0 + +if case == "guard_held": + # Another thread makes a directory while this one forks. + entered, release = threading.Event(), threading.Event() + def hold(): + with row_spool._directories._guard: + entered.set() + release.wait() + thread = threading.Thread(target=hold, daemon=True) + thread.start() + assert entered.wait(10) + def spill(): + with RowSpool(0, root) as spool: + spool.append(table) + assert spool.take(np.array([1])).equals(table.slice(1, 1)) + try: + in_child(spill) + finally: + release.set() + thread.join() +elif case == "inherited": + spool = RowSpool(0, root) + spool.append(table) + def use(): + for call in ( + lambda: spool.discard(np.array([0, 1])), + lambda: spool.take(np.array([0])), + lambda: spool.append(table), + ): + try: + call() + except RuntimeError as error: + assert "the process that made it" in str(error) + else: + raise AssertionError("a child used its parent's spool") + spool.close() + row_spool._directories.remove() + with RowSpool(0, root) as own: # sweeps, and leaves the parent's + own.append(table) + in_child(use) + assert spool.take(np.array([1, 0])).equals(table.take(pa.array([1, 0]))) + spool.close() +elif case == "outlived": + # A child that outlives its parent does not keep the parent's directory locked. + spool = RowSpool(0, root) + spool.append(table) + ready, wait = os.pipe() + child = os.fork() + if child == 0: + os.close(0) + os.write(wait, b"x") + os.close(1) + os.close(2) + signal.alarm(120) # never left behind + signal.pause() + os.read(ready, 1) + print(child, flush=True) + os.kill(os.getpid(), signal.SIGKILL) +""" + + +def _fork(case: str, root: Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-c", _FORK, case, str(root)], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +@pytest.mark.parametrize("case", ["guard_held", "inherited"]) +def test_a_forked_child_neither_waits_for_nor_touches_its_parents_spools( + tmp_path: Path, case: str +) -> None: + done = _fork(case, tmp_path) + assert done.returncode == 0, done.stderr + # The child ended without its exit handlers (``os._exit``): its own directory is + # left, with no owner, for the next process to sweep. + (left,) = tmp_path.glob("orcapod-spool-*") + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +def test_a_child_that_outlives_its_killed_parent_does_not_stop_the_sweep( + tmp_path: Path, +) -> None: + done = _fork("outlived", tmp_path) + (left,) = tmp_path.glob("orcapod-spool-*") + child = int(done.stdout) + try: + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + finally: + os.kill(child, signal.SIGKILL) + + +@pytest.mark.parametrize("stage", ["write", "close"]) +def test_a_failed_spill_leaves_the_spool_as_it_was( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stage: str +) -> None: + spool, rows = _filled(tmp_path, [40, 10], 1 << 14) + held, size = spool.memory_bytes, spool.size + assert held and _files(tmp_path) == [] + + class Full: + """A file writer that writes some bytes, then finds the disk full.""" + + def __init__(self, sink: Any, schema: pa.Schema) -> None: + self.sink = sink + + def __enter__(self) -> Full: + return self + + def __exit__(self, *exc: object) -> None: + if stage == "close": + raise OSError(errno.ENOSPC, "no space") + + def write_table(self, table: pa.Table) -> None: + self.sink.write(b"part of a file") + if stage == "write": + raise OSError(errno.ENOSPC, "no space") + + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", Full) + for _ in range(2): + with pytest.raises(OSError, match="no space"): + spool.append(_table(50, 5_000)) + assert (spool.memory_bytes, spool.size) == (held, size) + assert _files(tmp_path) == [] + everything = np.arange(50) + assert spool.take(everything).equals(rows.combine_chunks()) + spool.append(_table(50, 5_000)) # the retry: the rows once + assert spool.size == 5_050 + assert spool.take(np.array([5_049, 0, 50])).equals( + _table(0, 5_050).take(pa.array([5_049, 0, 50], pa.int64())) + ) + assert len(_files(tmp_path)) == 1 + spool.close() + + +def test_a_first_append_that_fails_decides_nothing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def full(*args: object) -> None: + raise OSError(errno.ENOSPC, "no space") + + spool = RowSpool(0, str(tmp_path)) + with monkeypatch.context() as patched: + patched.setattr(pa.ipc, "new_file", full) + with pytest.raises(OSError, match="no space"): + spool.append(_table(0, 3)) + other = pa.table({"a": [1, 2], "b": [3, 4]}) # another schema: nothing was held + spool.append(other) + assert spool.take(np.array([1, 0])).equals(other.take(pa.array([1, 0], pa.int64()))) + spool.close() + + +def test_a_closed_spool_refuses_every_use(tmp_path: Path) -> None: + spool, _ = _filled(tmp_path, [10], 0) + spool.close() + with pytest.raises(ValueError, match="closed"): + _ = spool.take(np.array([0])) + with pytest.raises(ValueError, match="closed"): + spool.discard(np.array([0])) + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_process_killed_before_it_locked_its_directory_is_swept( + tmp_path: Path, +) -> None: + left = tmp_path / "orcapod-spool-unlocked" + left.mkdir() + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() + + +@pytest.mark.skipif(sys.platform == "win32", reason="swept through fcntl locks") +def test_a_removal_that_stopped_part_way_is_finished(tmp_path: Path) -> None: + left = tmp_path / "orcapod-spool-partly" + (left / "some-spool").mkdir(parents=True) + (left / "some-spool" / "0.arrow").touch() + (left / "lock").touch() + spool, _ = _filled(tmp_path, [10], 0) + assert not left.exists() + spool.close() From a04b7e47e0efbc894aca94ca4e309f9df43c7b77 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:53:57 -0800 Subject: [PATCH 3/3] fix(core): row spool locks no forked child inherits, and one call at a time across threads (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/row_spool.py | 289 ++++++++++++++++-------------- tests/test_core/test_row_spool.py | 126 ++++++++++++- 2 files changed, 279 insertions(+), 136 deletions(-) diff --git a/src/orcapod/core/row_spool.py b/src/orcapod/core/row_spool.py index 2ac0de2e2..94b3be6f9 100644 --- a/src/orcapod/core/row_spool.py +++ b/src/orcapod/core/row_spool.py @@ -5,21 +5,23 @@ rows by those numbers; ``discard`` says that rows are never fetched again. Format: rows wait in memory until they exceed a byte limit, then become one segment: an -Arrow IPC file of one record batch, uncompressed, read memory-mapped (a mapped page is -the operating system's to drop, not memory this process holds). An extension column is -written as its storage and wrapped again when read, so reading needs no registered type. +Arrow IPC file of one record batch, uncompressed, read memory-mapped. A mapped page is the +operating system's to drop: it counts in a process's resident size while it is there, but +it is no memory of Arrow's or of this process's own. An extension column is written as its +storage and wrapped again when read, so reading needs no registered type. Lifetime: a segment is deleted once every row of it is discarded; a spool's files are removed by ``close`` (a spool is a context manager: normal end, exception and cancellation alike) and when it is collected. A process keeps its spools in one directory of its own, removed at interpreter exit. A killed process leaves its directory behind; the next process to spill there removes it: every directory holds a lock file its process -keeps locked, so a directory whose lock is free has no owner. (Without ``fcntl``, as on -Windows, nothing is swept.) +keeps locked (a POSIX record lock, which a forked child does not inherit), so a directory +whose lock is free has no owner. (Without ``fcntl``, as on Windows, nothing is swept.) -Ownership: a spool belongs to one thread (or one event loop) of the process that made it: -it has no lock of its own, and a forked child's copy refuses every use, so a child never -touches its parent's files. Different spools may be used from different threads. +Ownership: a spool belongs to the process that made it, and any of its threads may use it: +one call at a time, a call after ``close`` refused. What ``table`` and ``slice`` returned +stays readable whatever happens to the spool. A forked child's copy refuses every read and +write, and its ``close`` does nothing, so a child never touches its parent's files. Rows: tables of one schema with at least one column, in Orcapod's normalized types (large variants, no views). The byte limit bounds what the spool keeps; a ``take`` holds the rows @@ -38,6 +40,7 @@ import tempfile import threading import weakref +from collections.abc import Collection from typing import IO, Any, Self import numpy as np @@ -61,15 +64,16 @@ class _ProcessDirectories: def __init__(self) -> None: self._guard = threading.Lock() + # Each root's directory, and its open lock file: never opened again, because + # closing any handle of a file gives up the process's record lock on it. self._held: dict[str, tuple[str, IO[str]]] = {} - self.root_lock: IO[str] | None = None - """The root's lock file while a directory is made.""" def get(self, root: str) -> str: """This process's directory under ``root``.""" with self._guard: if root not in self._held or not os.path.isdir(self._held[root][0]): - self._held[root] = _make_process_directory(root) + own = {os.path.basename(held) for held, _ in self._held.values()} + self._held[root] = _make_process_directory(root, own) return self._held[root][0] def remove(self) -> None: @@ -80,26 +84,24 @@ def remove(self) -> None: self._held = {} def after_fork_in_child(self) -> None: - """Start empty: the directories are the parent's, and so are the locks. + """Start empty: the directories are the parent's, and so are their locks. - The guard may be held by a thread that does not exist in the child. The lock - files are closed, never unlocked: the parent's open files keep them locked, and - the child keeps none of them locked after the parent is gone. + The guard may be held by a thread that does not exist in the child. """ self._guard = threading.Lock() - inherited = [lock for _, lock in self._held.values()] - if self.root_lock is not None: - inherited.append(self.root_lock) - self._held, self.root_lock = {}, None - for lock in inherited: - lock.close() + self._held = {} -def _make_process_directory(root: str) -> tuple[str, IO[str]]: +def _make_process_directory(root: str, own: Collection[str]) -> tuple[str, IO[str]]: """Make this process's directory under ``root``, locked, and sweep abandoned ones. Both happen under one lock of the root, so a sweep never sees a directory that is - made but not yet locked. + made but not yet locked. The locks are record locks: a child forked at any point + holds none of them. + + Args: + root: The directory to make it under. + own: The names of the directories this process holds already. """ os.makedirs(root, exist_ok=True) if fcntl is None: @@ -108,15 +110,11 @@ def _make_process_directory(root: str) -> tuple[str, IO[str]]: name = os.path.join(root, f".{_PREFIX}{os.getuid()}.lock") flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC with os.fdopen(os.open(name, flags, 0o600), "w") as root_lock: - _directories.root_lock = root_lock - try: - fcntl.flock(root_lock, fcntl.LOCK_EX) - _sweep(root) - directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) - lock = open(os.path.join(directory, _LOCK_NAME), "w") - fcntl.flock(lock, fcntl.LOCK_EX) - finally: - _directories.root_lock = None + fcntl.lockf(root_lock, fcntl.LOCK_EX) + _sweep(root, own) + directory = tempfile.mkdtemp(prefix=_PREFIX, dir=root) + lock = open(os.path.join(directory, _LOCK_NAME), "w") + fcntl.lockf(lock, fcntl.LOCK_EX) return directory, lock @@ -133,14 +131,22 @@ def _remove_process_directory(directory: str) -> None: os.rmdir(directory) -def _sweep(root: str) -> None: - """Remove this user's spool directories under ``root`` that no process holds.""" +def _sweep(root: str, own: Collection[str]) -> None: + """Remove this user's spool directories under ``root`` that no process holds. + + Args: + root: The directory to look in. + own: The names of the directories this process holds: its own record locks do + not stop it, so they are left out by name. + """ assert fcntl is not None with os.scandir(root) as entries: candidates = [ entry.path for entry in entries - if entry.name.startswith(_PREFIX) and entry.is_dir(follow_symlinks=False) + if entry.name.startswith(_PREFIX) + and entry.name not in own + and entry.is_dir(follow_symlinks=False) ] for directory in candidates: # A directory held by a live process, being removed, or not a spool's is left. @@ -148,8 +154,8 @@ def _sweep(root: str) -> None: if os.stat(directory).st_uid != os.getuid(): continue try: - with open(os.path.join(directory, _LOCK_NAME)) as lock: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with open(os.path.join(directory, _LOCK_NAME), "r+") as lock: + fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) _remove_process_directory(directory) except FileNotFoundError: # Its process was killed before it made the lock file (the root's lock @@ -204,6 +210,8 @@ def __init__( self._root: str | None = root self._closed: bool = False self._owner: int = os.getpid() + # One call at a time; a call waits for the one before it, ``close`` included. + self._lock = threading.RLock() self._schema: pa.Schema | None = None self._segments: list[_Segment] = [] self._starts: npt.NDArray[np.int64] | None = None @@ -231,35 +239,40 @@ def append(self, table: pa.Table) -> None: OSError: If the rows in memory cannot be written to the local disk. The spool is then as before the call, with no partial file. """ - self._require_usable() - if not table.num_rows: - return - schema, size = self._schema, self.size - if self._schema is None: - self._schema = table.schema - # One chunk that owns its rows: a slice would keep its whole parent alive. - added = _Segment(self.size, _owned(table)) - self._add(added) - self.size += table.num_rows - if self._in_memory > self._memory_bytes: - try: - self._spill() - except BaseException: - # The new rows are in the last run, so they were not written. - self._segments.remove(added) - self._starts = None - if added.table is not None: - self._in_memory -= added.table.nbytes - self._schema, self.size = schema, size - raise - - def _require_usable(self) -> None: - """Refuse a closed spool, and a forked child's copy of its parent's.""" + self._require_owner() + with self._lock: + self._require_usable() + if not table.num_rows: + return + schema, size = self._schema, self.size + if self._schema is None: + self._schema = table.schema + # One chunk that owns its rows: a slice would keep its whole parent alive. + added = _Segment(self.size, _owned(table)) + self._add(added) + self.size += table.num_rows + if self._in_memory > self._memory_bytes: + try: + self._spill() + except BaseException: + # The new rows are in the last run, so they were not written. + self._segments.remove(added) + self._starts = None + if added.table is not None: + self._in_memory -= added.table.nbytes + self._schema, self.size = schema, size + raise + + def _require_owner(self) -> None: + """Refuse a forked child's copy of its parent's spool, before its lock is touched.""" if self._owner != os.getpid(): raise RuntimeError( "a row spool is used only in the process that made it: this is a " + "forked child's copy" ) + + def _require_usable(self) -> None: + """Refuse a closed spool.""" if self._closed: raise ValueError("the row spool is closed") @@ -281,27 +294,29 @@ def take(self, rows: npt.NDArray[np.int64]) -> pa.Table: ValueError: If the spool is closed. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if self._starts is None: - self._starts = np.fromiter( - (s.start for s in self._segments), np.int64, len(self._segments) - ) - held_in = np.searchsorted(self._starts, rows, side="right") - 1 - order = np.argsort(held_in, kind="stable") - sorted_rows, sorted_in = rows[order], held_in[order] - edges = np.flatnonzero(np.diff(sorted_in)) + 1 - parts: list[pa.Table] = [] - for group in np.split(np.arange(len(rows)), edges): - segment = self._segments[int(sorted_in[group[0]])] - local = pa.array(sorted_rows[group] - segment.start, pa.int64()) - parts.append(self._take_from(segment, local)) - if len(parts) == 1: - # One segment: the stable sort changed nothing. - return parts[0].combine_chunks() - taken = pa.concat_tables(parts).combine_chunks() - back = np.empty(len(order), np.int64) - back[order] = np.arange(len(order)) - return taken.take(pa.array(back, pa.int64())).combine_chunks() + self._require_owner() + with self._lock: + self._require_usable() + if self._starts is None: + self._starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(self._starts, rows, side="right") - 1 + order = np.argsort(held_in, kind="stable") + sorted_rows, sorted_in = rows[order], held_in[order] + edges = np.flatnonzero(np.diff(sorted_in)) + 1 + parts: list[pa.Table] = [] + for group in np.split(np.arange(len(rows)), edges): + segment = self._segments[int(sorted_in[group[0]])] + local = pa.array(sorted_rows[group] - segment.start, pa.int64()) + parts.append(self._take_from(segment, local)) + if len(parts) == 1: + # One segment: the stable sort changed nothing. + return parts[0].combine_chunks() + taken = pa.concat_tables(parts).combine_chunks() + back = np.empty(len(order), np.int64) + back[order] = np.arange(len(order)) + return taken.take(pa.array(back, pa.int64())).combine_chunks() def _take_from(self, segment: _Segment, local: pa.Array[Any]) -> pa.Table: # pyright: ignore[reportExplicitAny] # row numbers """Rows of one segment, by their numbers in it.""" @@ -349,26 +364,30 @@ def slice(self, start: int, length: int) -> pa.Table: ValueError: As ``table``; also for a negative ``start`` or ``length``. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if start < 0 or length < 0: - raise ValueError(f"a slice of rows from {start}, {length} long") - if self._schema is None: - raise ValueError("nothing was appended to the row spool: no columns yet") - if self._discarded: - raise ValueError("rows of the row spool were discarded: no whole table") - end = min(start + length, self.size) - parts: list[pa.Table] = [] - for segment in self._segments: - first = max(start, segment.start) - last = min(end, segment.start + segment.rows) - if first >= last: - continue - if segment.table is not None: - part = segment.table - else: - part = _wrapped(self._stored(segment), self._schema) - parts.append(part.slice(first - segment.start, last - first)) - return pa.concat_tables(parts) if parts else self._schema.empty_table() + self._require_owner() + with self._lock: + self._require_usable() + if start < 0 or length < 0: + raise ValueError(f"a slice of rows from {start}, {length} long") + if self._schema is None: + raise ValueError( + "nothing was appended to the row spool: no columns yet" + ) + if self._discarded: + raise ValueError("rows of the row spool were discarded: no whole table") + end = min(start + length, self.size) + parts: list[pa.Table] = [] + for segment in self._segments: + first = max(start, segment.start) + last = min(end, segment.start + segment.rows) + if first >= last: + continue + if segment.table is not None: + part = segment.table + else: + part = _wrapped(self._stored(segment), self._schema) + parts.append(part.slice(first - segment.start, last - first)) + return pa.concat_tables(parts) if parts else self._schema.empty_table() def discard(self, rows: npt.NDArray[np.int64]) -> None: """Say that these rows are never fetched again. @@ -382,27 +401,29 @@ def discard(self, rows: npt.NDArray[np.int64]) -> None: ValueError: If the spool is closed. RuntimeError: In a process other than the one that made the spool. """ - self._require_usable() - if not len(rows): - return - starts = np.fromiter( - (s.start for s in self._segments), np.int64, len(self._segments) - ) - held_in = np.searchsorted(starts, rows, side="right") - 1 - counts = np.bincount(held_in, minlength=len(self._segments)) - self._discarded = True - emptied = False - for index in np.flatnonzero(counts): - segment = self._segments[int(index)] - segment.live -= int(counts[index]) - if not segment.live: - if segment.table is not None: - self._in_memory -= segment.table.nbytes - segment.drop() - emptied = True - if emptied: - self._segments = [s for s in self._segments if s.live] - self._starts = None + self._require_owner() + with self._lock: + self._require_usable() + if not len(rows): + return + starts = np.fromiter( + (s.start for s in self._segments), np.int64, len(self._segments) + ) + held_in = np.searchsorted(starts, rows, side="right") - 1 + counts = np.bincount(held_in, minlength=len(self._segments)) + self._discarded = True + emptied = False + for index in np.flatnonzero(counts): + segment = self._segments[int(index)] + segment.live -= int(counts[index]) + if not segment.live: + if segment.table is not None: + self._in_memory -= segment.table.nbytes + segment.drop() + emptied = True + if emptied: + self._segments = [s for s in self._segments if s.live] + self._starts = None def _spill(self) -> None: """Write the segments in memory to one file, as one segment.""" @@ -453,14 +474,20 @@ def _write(self, segment: _Segment) -> str: return path def close(self) -> None: - """Let every row go and remove the files. Calling it again does nothing.""" - self._closed = True - self._segments = [] - self._starts = None - self._in_memory = 0 - if self._cleanup is not None: - _ = self._cleanup() - self._directory = self._cleanup = None + """Let every row go and remove the files. Calling it again does nothing. + + It waits for a call of another thread to end. In a forked child it does nothing. + """ + if self._owner != os.getpid(): + return + with self._lock: + self._closed = True + self._segments = [] + self._starts = None + self._in_memory = 0 + if self._cleanup is not None: + _ = self._cleanup() + self._directory = self._cleanup = None def __enter__(self) -> Self: return self diff --git a/tests/test_core/test_row_spool.py b/tests/test_core/test_row_spool.py index 6b7faa775..67b69651b 100644 --- a/tests/test_core/test_row_spool.py +++ b/tests/test_core/test_row_spool.py @@ -9,6 +9,9 @@ import signal import subprocess import sys +import threading +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import TimeoutError as FutureTimeout from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -352,6 +355,44 @@ def use(): in_child(use) assert spool.take(np.array([1, 0])).equals(table.take(pa.array([1, 0]))) spool.close() +elif case in ("root_lock", "unpublished"): + # A fork while another thread has just opened the root's lock file, or has made a + # directory and not yet recorded it; then the parent is killed holding the lock. + opened, resume = threading.Event(), threading.Event() + name = "fdopen" if case == "root_lock" else "_make_process_directory" + where = os if case == "root_lock" else row_spool + original = getattr(where, name) + def paused(*args, **kwargs): + result = original(*args, **kwargs) + opened.set() + resume.wait(30) + return result + setattr(where, name, paused) + if case == "root_lock": + import fcntl + locked, take_lock = threading.Event(), fcntl.lockf + def lockf(*args): + take_lock(*args) + locked.set() + threading.Event().wait(30) + fcntl.lockf = lockf + spool = RowSpool(0, root) + threading.Thread(target=spool.append, args=(table,), daemon=True).start() + assert opened.wait(10) + ready, wait = os.pipe() + child = os.fork() + if child == 0: + signal.alarm(120) # never left behind + os.write(wait, b"x") + os.close(1) + os.close(2) + signal.pause() + os.read(ready, 1) + if case == "root_lock": + resume.set() + assert locked.wait(10) + print(child, flush=True) + os.kill(os.getpid(), signal.SIGKILL) elif case == "outlived": # A child that outlives its parent does not keep the parent's directory locked. spool = RowSpool(0, root) @@ -397,15 +438,21 @@ def test_a_forked_child_neither_waits_for_nor_touches_its_parents_spools( @pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") -def test_a_child_that_outlives_its_killed_parent_does_not_stop_the_sweep( - tmp_path: Path, +@pytest.mark.parametrize("case", ["outlived", "root_lock", "unpublished"]) +def test_a_child_that_outlives_its_killed_parent_holds_none_of_its_locks( + tmp_path: Path, case: str ) -> None: - done = _fork("outlived", tmp_path) - (left,) = tmp_path.glob("orcapod-spool-*") + done = _fork(case, tmp_path) + left = list(tmp_path.glob("orcapod-spool-*")) + assert bool(left) == (case != "root_lock") child = int(done.stdout) try: + # Another process spills at once, and sweeps what the killed one left. + other = _child(tmp_path, "exit") + _ = other.communicate(timeout=30) + assert other.returncode == 0 + assert not any(directory.exists() for directory in left) spool, _ = _filled(tmp_path, [10], 0) - assert not left.exists() spool.close() finally: os.kill(child, signal.SIGKILL) @@ -501,3 +548,72 @@ def test_a_removal_that_stopped_part_way_is_finished(tmp_path: Path) -> None: spool, _ = _filled(tmp_path, [10], 0) assert not left.exists() spool.close() + + +def test_a_process_never_sweeps_its_own_directory(tmp_path: Path) -> None: + """Its own record lock would not stop it: also when a root has two names.""" + root, alias = tmp_path / "root", tmp_path / "alias" + root.mkdir() + alias.symlink_to(root, target_is_directory=True) + first, rows = _filled(root, [10], 0) + second, _ = _filled(alias, [10], 0) + assert len(list(root.glob("orcapod-spool-*"))) == 2 + # And the first directory is still locked for every other process. + other = _child(root, "exit") + _ = other.communicate() + assert other.returncode == 0 + assert first.take(np.array([9])).equals(rows.slice(9, 1)) + first.close() + second.close() + + +@pytest.mark.parametrize("read", ["take", "table", "slice"]) +def test_a_close_waits_for_a_read_of_another_thread( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, read: str +) -> None: + spool, rows = _filled(tmp_path, [10, 10], 0) + about_to_map, go_on = threading.Event(), threading.Event() + original = pa.memory_map + + def parked(path: str) -> Any: + about_to_map.set() + assert go_on.wait(10) + return original(path) + + monkeypatch.setattr(pa, "memory_map", parked) + reads: dict[str, Any] = { + "take": lambda: spool.take(np.arange(20)), + "table": spool.table, + "slice": lambda: spool.slice(0, 20), + } + with ThreadPoolExecutor(2) as pool: + result = pool.submit(reads[read]) + assert about_to_map.wait(10) + closed = pool.submit(spool.close) + with pytest.raises(FutureTimeout): + closed.result(timeout=0.1) + go_on.set() + assert result.result(10).equals(rows) + closed.result(10) + assert _files(tmp_path) == [] + with pytest.raises(ValueError, match="closed"): + reads[read]() + + +def test_threads_append_and_read_one_spool(tmp_path: Path) -> None: + spool = RowSpool(1 << 12, str(tmp_path)) + + def work(number: int) -> None: + for i in range(20): + spool.append(pa.table({"a": [number] * 5, "b": [i] * 5})) + rows = np.arange(0, spool.size, 7) + assert spool.take(rows).num_rows == len(rows) + _ = spool.table() + + with ThreadPoolExecutor(4) as pool: + for done in [pool.submit(work, n) for n in range(4)]: + done.result(60) + assert spool.size == spool.table().num_rows == 400 + counts = spool.table().group_by(["a", "b"]).aggregate([([], "count_all")]) + assert set(counts.column("count_all").to_pylist()) == {5} + spool.close()