Skip to content
Open
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
20 changes: 20 additions & 0 deletions docs/source/tsfile_load.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,26 @@ Map files to splits explicitly:
... )
```

## Streaming remote files

With `tsfile>=2.5.0`, remote files can be read in streaming mode without first
copying the entire file to local storage:

```py
>>> dataset = load_dataset(
... "tsfile",
... data_files="https://example.com/data.tsfile",
... split="train",
... streaming=True,
... )
>>> row = next(iter(dataset))
```

The remote filesystem must support seeking; HTTP servers must support byte-range
requests. Authentication and caching are handled by Hugging Face and fsspec.
Each output row still contains one device's full time series, so streaming does
not make the memory needed for an individual device constant.

## Example dataset on the Hub

A ready-to-use example is available at [`tsfile/lotsa_data`](https://huggingface.co/datasets/tsfile/lotsa_data). Because `.tsfile` files are recognized automatically, you can load it by repository id without specifying `data_files`:
Expand Down
47 changes: 26 additions & 21 deletions src/datasets/packaged_modules/tsfile/tsfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from __future__ import annotations

import datetime as _dt
from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
from typing import Any, Literal, Optional

Expand All @@ -43,6 +44,7 @@
import datasets
from datasets.builder import Key
from datasets.table import table_cast
from datasets.utils.file_utils import is_local_path
from datasets.utils.tqdm import tqdm


Expand Down Expand Up @@ -399,10 +401,10 @@ def _fold_split(self, files, target_schema: pa.Schema):
raise _SkipSplit

readers: dict[str, Any] = {}
try:
with ExitStack() as stack:
for file in files:
try:
readers[file] = self._open_reader(file)
readers[file] = stack.enter_context(self._open_reader(file))
except Exception as e:
if self._should_reraise(file, e):
raise
Expand All @@ -413,12 +415,6 @@ def _fold_split(self, files, target_schema: pa.Schema):
return

yield from self._iter_device_batches(device_index, file_meta, readers, target_schema)
finally:
for reader in readers.values():
try:
reader.close()
except Exception:
pass

def _build_device_index(self, readers: dict):
"""Walk every open reader and build the cross-file device index.
Expand Down Expand Up @@ -722,24 +718,33 @@ def _build_list_array(values: list, list_type: pa.ListType) -> pa.ListArray:
# ----- file / error handling ---------------------------------------

@staticmethod
@contextmanager
def _open_reader(file: str):
"""Open a file as a ``TsFileReader`` after verifying its magic header.
"""Validate the magic header and keep the source alive until its reader closes.

In streaming mode, ``open`` is patched to ``xopen`` and returns a
seekable fsspec file object. TsFile 2.5.0 can read that object directly;
remote URLs must not be passed to the native local-path reader.

The C library's ``TsFileReader`` constructor silently returns an
invalid handle for non-tsfile inputs, and any subsequent call on it
segfaults. The 6-byte ``TsFile`` magic header is checked first to
bail out cleanly.
The magic check also prevents invalid files from reaching native code.
"""
from tsfile import TsFileReader

try:
with open(file, "rb") as fh:
header = fh.read(len(_TSFILE_MAGIC))
except OSError as e:
raise ValueError(f"Cannot open file {file!r}: {e}") from e
if header != _TSFILE_MAGIC:
raise ValueError(f"File {file!r} is not a valid TsFile (bad magic header).")
return TsFileReader(file)
with ExitStack() as stack:
try:
source = stack.enter_context(open(file, "rb"))
header = source.read(len(_TSFILE_MAGIC))
except OSError as e:
raise ValueError(f"Cannot open file {file!r}: {e}") from e
if header != _TSFILE_MAGIC:
raise ValueError(f"File {file!r} is not a valid TsFile (bad magic header).")
if is_local_path(file):
source.close()
reader = TsFileReader(file)
else:
source.seek(0)
reader = TsFileReader(source)
yield stack.enter_context(reader)

@staticmethod
def _require_table_model(file: str, schemas) -> None:
Expand Down
139 changes: 139 additions & 0 deletions tests/packaged_modules/test_tsfile_streaming.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

import io
import os
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import pytest


tsfile = pytest.importorskip("tsfile")

from datasets import load_dataset # noqa: E402
from datasets.packaged_modules.tsfile import tsfile as tsfile_module # noqa: E402
from tests.packaged_modules.test_tsfile import _write_multi_device # noqa: E402


@pytest.fixture
def http_tsfile(tmp_path):
path = tmp_path / "data.tsfile"
_write_multi_device(str(path))
payload = path.read_bytes()
requests = []

class Handler(BaseHTTPRequestHandler):
def do_HEAD(self):
self.respond(send_body=False)

def do_GET(self):
self.respond(send_body=True)

def respond(self, send_body):
start, end = 0, len(payload) - 1
range_header = self.headers.get("Range")
if range_header:
interval = range_header.removeprefix("bytes=")
first, last = interval.split("-", 1)
start = int(first) if first else max(0, len(payload) - int(last))
if first and last:
end = min(int(last), end)
if start > end:
self.send_error(416)
return
status = 206 if range_header else 200
requests.append((self.command, range_header, status, end - start + 1))
self.send_response(status)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(end - start + 1))
if range_header:
self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
self.end_headers()
if send_body:
self.wfile.write(payload[start : end + 1])

def log_message(self, *args):
pass

with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield path, f"http://127.0.0.1:{server.server_port}/data.tsfile", requests
finally:
server.shutdown()
thread.join()


@pytest.mark.parametrize("stop_early", [False, True])
def test_http_streaming_matches_local_and_closes_sources(http_tsfile, monkeypatch, stop_early):
path, url, requests = http_tsfile
expected = list(load_dataset("tsfile", data_files=str(path), split="train", streaming=True))
sources = []
original_reader = tsfile.TsFileReader

def open_reader(source):
# A remote URL must never reach the native local-path reader.
assert not isinstance(source, (str, bytes, os.PathLike))
sources.append(source)
return original_reader(source)

monkeypatch.setattr(tsfile, "TsFileReader", open_reader)
ds = load_dataset(
"tsfile",
data_files=url,
split="train",
streaming=True,
storage_options={"http": {"block_size": 64}},
)
iterator = iter(ds)
try:
actual = [next(iterator)] if stop_early else list(iterator)
finally:
iterator.close()

assert actual == (expected[:1] if stop_early else expected)
assert sources and all(source.closed for source in sources)
assert any(
method == "GET" and range_header and status == 206 and size < path.stat().st_size
for method, range_header, status, size in requests
)


def test_remote_reader_closes_source_on_bad_magic(monkeypatch):
source = io.BytesIO(b"not a TsFile")
monkeypatch.setattr(tsfile_module, "open", lambda *args: source, raising=False)
with pytest.raises(ValueError, match="bad magic header"):
with tsfile_module.TsFile._open_reader("https://example.com/bad.tsfile"):
pytest.fail("An invalid file must not be opened")
assert source.closed


def test_remote_reader_closes_source_on_reader_error(monkeypatch):
source = io.BytesIO(b"TsFile")
monkeypatch.setattr(tsfile_module, "open", lambda *args: source, raising=False)

def fail_reader(source):
raise RuntimeError("Cannot construct reader")

monkeypatch.setattr(tsfile, "TsFileReader", fail_reader)
with pytest.raises(RuntimeError, match="Cannot construct reader"):
with tsfile_module.TsFile._open_reader("https://example.com/bad.tsfile"):
pytest.fail("Reader construction must fail")
assert source.closed