Object storage (altar.storage)¶
altar.storage defines the location-neutral Storage contract and local, HTTPS, and fsspec (GCS, S3, Azure, Hugging Face) file adapters.
Maturity: 6 Stable, 2 Provisional (8 exports total). Related guides: Data locations and connections · Stores, details, and artifacts.
Summary¶
Functions¶
| Symbol | Description | Maturity |
|---|---|---|
get_storage_registry |
Return the shared registry of storage adapters. | Stable |
Classes and contracts¶
| Symbol | Description | Maturity |
|---|---|---|
FsspecStorage |
A Storage over fsspec that picks a filesystem from each path's URI scheme. |
Stable |
HttpsStorage |
A read-only Storage for files published over HTTP(S), using only the standard library. |
Stable |
LocalStorage |
A Storage implementation backed by the local filesystem. |
Stable |
PublishedFile |
A file Storage.publish_parts published, with what Storage.verify_published checks it against. |
Provisional |
Storage |
A backend-independent interface for reading and writing files. | Stable |
StoredFile |
A stored file as Storage.describe_file reports it, without reading its bytes. |
Provisional |
TextWriter |
An async context manager for writing a text file through a Storage. |
Stable |
Functions API¶
Object storage: the Storage contract and its local, fsspec and HTTPS adapters.
Storage-adapter authors, and the stores, sources and exports that read and write files through an adapter, import
these names from :mod:altar.storage, the supported import path. The modules under altar.plugins that define
them are not public API. Adapters register under the altar.storages entry-point group, which
get_storage_registry reads.
Storage is the contract. LocalStorage implements it on the local filesystem, FsspecStorage over fsspec,
choosing a filesystem from each path's URI scheme (gs:// and the others fsspec knows), and HttpsStorage
read-only over HTTP(S). TextWriter is the async context manager Storage.open_text_writer returns.
PublishedFile is provisional and listed in __provisional__: it is the file the optional, provisional
Storage.publish_parts publishes from a warehouse export's parts, which Storage.verify_published and
Storage.describe_published check and describe. StoredFile is provisional too: it is what the optional,
provisional Storage.describe_file reports of a file another process wrote, such as a warehouse export's shard,
without reading it; Storage.open_reader, which reads part of a file, is provisional as well.
get_storage_registry
¶
get_storage_registry() -> PluginRegistry[type[Storage]]
Return the shared registry of storage adapters.
Classes and contracts API¶
Object storage: the Storage contract and its local, fsspec and HTTPS adapters.
Storage-adapter authors, and the stores, sources and exports that read and write files through an adapter, import
these names from :mod:altar.storage, the supported import path. The modules under altar.plugins that define
them are not public API. Adapters register under the altar.storages entry-point group, which
get_storage_registry reads.
Storage is the contract. LocalStorage implements it on the local filesystem, FsspecStorage over fsspec,
choosing a filesystem from each path's URI scheme (gs:// and the others fsspec knows), and HttpsStorage
read-only over HTTP(S). TextWriter is the async context manager Storage.open_text_writer returns.
PublishedFile is provisional and listed in __provisional__: it is the file the optional, provisional
Storage.publish_parts publishes from a warehouse export's parts, which Storage.verify_published and
Storage.describe_published check and describe. StoredFile is provisional too: it is what the optional,
provisional Storage.describe_file reports of a file another process wrote, such as a warehouse export's shard,
without reading it; Storage.open_reader, which reads part of a file, is provisional as well.
FsspecStorage
¶
FsspecStorage(
logger: Logger | None = None,
*,
storage_options: Mapping[str, Any] | None = None,
connection: Connection | None = None,
fsync: bool = False,
)
Bases: Storage
A Storage over fsspec that picks a filesystem from each path's URI scheme.
Every operation runs in a worker thread, so a slow object store does not stall the event loop. Uploads and
as_local_file stream through fsspec's put_file and get_file rather than holding the object in
memory. Local writes and uploads use LocalStorage: they create parent directories and replace files
atomically, preserving the previous complete file and cleaning up temporary files if interrupted or
cancelled. Local destinations that are symbolic links are replaced, leaving the link target unchanged;
uploading a file onto itself (including a symbolic or hard link) is a no-op. Remote writes retain their
provider's semantics.
Two upload behaviors apply to local destinations only. A local upload copies the source's permission bits
and modification time. An upload to an existing local directory writes the file at
<directory>/<source name>. A remote upload writes the object at dest_path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logger
|
Logger | None
|
The logger for this adapter; defaults to this module's logger. |
None
|
storage_options
|
Mapping[str, Any] | None
|
Keyword arguments for every non-local filesystem this instance opens, such as
|
None
|
connection
|
Connection | None
|
A |
None
|
fsync
|
bool
|
Whether a local write or upload syncs the new file and its directory to disk before it returns,
as |
False
|
from_options
classmethod
¶
from_options(
options: Mapping[str, Any],
*,
connection: Connection | None = None,
context: AdapterContext,
) -> Self
Build the storage from [storage] options, reading through the connection the section names.
upload_from_local_file
async
¶
Stream a local file to dest_path; a local destination that is the source file is left alone.
A *.gz object on gs:// is uploaded as Content-Type: application/gzip (gcsfs would guess the type
of the text inside), and never with a Content-Encoding, which would make GCS decompress it on download.
list_files
async
¶
Return every file under prefix, at any depth, sorted, as URIs of the prefix's own scheme.
describe_file
async
¶
describe_file(path: str) -> StoredFile
Describe a local file or a remote object from its metadata, without reading it. Provisional.
A local path is described as LocalStorage.describe_file describes it. A remote object's size is its
filesystem's info, and so are a gs:// object's generation and base64 CRC32C, which gcsfs reports
from the object's metadata; another filesystem's generation and crc32c are reported when its
info has them. A path that is not a file raises FileNotFoundError.
open_reader
async
¶
Open a local file in place, or a remote object as the filesystem's file, read with ranged requests.
Provisional.
publish_parts
async
¶
publish_parts(
parts_prefix: str,
destination: str,
*,
expected_rows: int,
fields: int,
) -> PublishedFile
Publish the export parts under parts_prefix as one new file, on the local disk or in a GCS bucket.
Provisional. Local paths publish as LocalStorage.publish_parts does, and the result's uri is
destination as given. On gs:// the parts and destination must be in one bucket. The parts are
listed with their generations, read pinned to them, and composed server side into destination. Up to 32
parts compose straight into it. More are composed 32 at a time into temporary objects named
<destination>.compose-*, which compose into destination and are removed afterwards. The result's
generation and crc32c are the published object's. Its size and CRC32C must equal the bytes read, or the
object is deleted and ValueError raised. The gs:// path goes through google-cloud-storage
(pip install "altar[gcs]") with the project, credentials and endpoint of the gcsfs filesystem this storage
opens. A gs:// filesystem other than gcsfs, and every other protocol, raises
CapabilityNotSupported. See Storage.publish_parts for the rules the parts must meet.
verify_published
async
¶
verify_published(published: PublishedFile) -> None
Check a file publish_parts published: a local file's SHA-256, a GCS object's generation and CRC32C.
Provisional. Every other protocol raises CapabilityNotSupported.
describe_published
async
¶
describe_published(
uri: str, *, expected_rows: int, fields: int
) -> PublishedFile | None
Describe the file at uri as publish_parts would have: a local file, or a GCS object.
Provisional. A local path is described as LocalStorage.describe_published describes it. A gs://
object is read once, pinned to its generation and as stored, and the result's generation and crc32c are
the object's. The result's uri is uri as given. Every other protocol raises CapabilityNotSupported.
compose_gzip_files
async
¶
compose_gzip_files(
sources: Sequence[str],
destination: str,
*,
overwrite: bool = True,
) -> StoredFile
Compose sources in order into destination: locally or via server-side GCS 32-ary tree compose.
Provisional. On gs:// / gcs://, all sources and destination must live in the same bucket; zero bytes
pass through Python, GCS compose mutates source shard metadata in place (content_encoding=None,
content_type="application/gzip" via blob.patch()) before composing so raw gzip concatenation is accepted
without transparent decompression, and temporary .compose-* intermediates are deleted in finally:.
open_writer
async
¶
Stream a write to path, committed whole on a clean exit and not at all when the block raises.
A local path is written as LocalStorage.open_writer writes it, beside the destination and renamed. On an
object store that commits a written file only when it is closed (gs://, s3://, az:// and their
aliases), the bytes stream through the provider's own file: on GCS a resumable upload in blocks of 5 MiB,
the object visible only once it is finalized. A block that raises or is cancelled discards the file instead
of closing it, which cancels the upload, so local disk holds nothing and memory one block. A *.gz
object on gs:// is written as Content-Type: application/gzip, with no content encoding. Any other
protocol, such as memory://, whose files may show their bytes before they are closed, spools to a
local temporary file and uploads it (Storage.open_writer).
as_local_file
async
¶
Yield a local path for path; a remote object is streamed to a temporary file, removed on exit.
A local path is yielded as it is, without a copy. The temporary name keeps the object's suffix, so a
reader that chooses a decoder from the extension (.gz, .h5) still works.
HttpsStorage
¶
Bases: Storage
A read-only Storage for files published over HTTP(S), using only the standard library.
A path is an absolute https:// (or http://) URL, such as a model release on a public file server.
No provider SDK or credential is involved, so this is the adapter for resources whose location is a plain
URL. Every write raises CapabilityNotSupported: a web server is not a place Altar writes results, and an
adapter that quietly dropped writes would be worse than one that refuses them. Reads run in a worker
thread so a long download does not stall the event loop. Redirects are followed, and a server that
answers HEAD with 405 or 501 is probed with a one-byte ranged GET instead.
open_writer
async
¶
Refuse before anything is written, rather than spool a file the upload would then refuse.
as_local_file
async
¶
Stream the file to a temporary path and yield it; the temporary file is removed on exit.
The temporary name keeps the URL's suffix, so a reader that chooses a decoder from the extension
(.gz, .h5) still works.
LocalStorage
¶
Bases: Storage
A Storage implementation backed by the local filesystem.
Every method takes a bare filesystem path or a file: URI for this machine (file:///abs/path), so a
location written by another component or a run spec as a URI works unchanged. A file:// URI that names
another host raises ValueError.
Every write streams into a temporary file in the destination's directory and renames it to the destination.
A reader sees either the previous file or the complete new one. A write that fails or is cancelled removes
its temporary file and leaves the previous file in place. Temporary file names start with .altar-tmp-. A
destination that is a symbolic link is replaced by the new file, and the link's target is left unchanged.
Writes run in a worker thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logger
|
Logger | None
|
The logger for this adapter; defaults to this module's logger. |
None
|
fsync
|
bool
|
Whether to sync each new file and its directory to disk before a write returns. Without it, a power loss or operating-system crash can lose a write that already returned, but never leaves a partial file under the final name. Off by default: a lost staged input with a digest fails its check, and a lost output is produced again. Syncing a 3 GB file adds several seconds. |
False
|
upload_from_local_file
async
¶
Copy a local file to the destination path, with its permission bits and timestamps.
The copy is a new, independent file, so a later change to either file leaves the other unchanged.
When the source and destination are already the same file, this returns without doing anything. That
case arises with the local backend when storage and the compute volume are the same directory. The
check compares the files themselves. A file: URI, another spelling of the path, a symbolic link, or a
hard link to the source all count as the same file. A destination that is an existing directory receives
the file under the source's name.
read_csv
async
¶
read_csv(
path: str,
delimiter: str = "\t",
fieldnames: list[str] | None = None,
) -> list[dict[str, Any]]
Read the delimited file directly from disk, skipping the in-memory text round-trip.
write_csv
async
¶
Write the rows to disk a chunk at a time instead of rendering the whole file in memory first.
as_local_file
async
¶
Yield the file's filesystem path, since the file is already on the local disk.
list_files
async
¶
Return every file under the local directory prefix, at any depth, sorted; [] when there is none.
describe_file
async
¶
describe_file(path: str) -> StoredFile
Return the local file's size; a local file has no generation or store checksum. Provisional.
open_reader
async
¶
Open the local file in place for reading. Provisional.
publish_parts
async
¶
publish_parts(
parts_prefix: str,
destination: str,
*,
expected_rows: int,
fields: int,
) -> PublishedFile
Concatenate the export parts in the local directory parts_prefix into a new file at destination.
Provisional. Every file under the directory, at any depth, counts as an object under the prefix. The parts
stream through validation into a temporary file beside destination, which is then hard-linked to
destination, so the link fails rather than replace a file that is already there. A part whose size,
modification time or inode changes while it is read restarts the read. The result's uri is destination
as given, and its generation and crc32c are None. With fsync, the file and its directory are synced
before this returns. See Storage.publish_parts for the rules the parts must meet.
verify_published
async
¶
verify_published(published: PublishedFile) -> None
Hash the file at published.uri again and compare its size and SHA-256 with published.
Provisional. Raises FileNotFoundError when the file is gone and ValueError when its bytes differ.
describe_published
async
¶
describe_published(
uri: str, *, expected_rows: int, fields: int
) -> PublishedFile | None
Read the local file at uri once and describe it, or return None when there is no file there.
Provisional. The result's uri is uri as given, and its generation and crc32c are None. See
Storage.describe_published for the rules the file must meet.
compose_gzip_files
async
¶
compose_gzip_files(
sources: Sequence[str],
destination: str,
*,
overwrite: bool = True,
) -> StoredFile
Stream the raw bytes of sources in order into destination atomically. Provisional.
open_writer
async
¶
Write into a temporary file beside path and rename it to path on a clean exit, like every write.
A block that raises or is cancelled removes the temporary file and leaves path as it was. With fsync,
the file and its directory are synced before the block returns.
PublishedFile
dataclass
¶
PublishedFile(
*,
uri: str,
size: int,
sha256: str,
row_count: int,
generation: str | None,
crc32c: str | None,
)
A file Storage.publish_parts published, with what Storage.verify_published checks it against.
Provisional.
Attributes:
| Name | Type | Description |
|---|---|---|
uri |
str
|
The published file. |
size |
int
|
Its size in bytes. |
sha256 |
str
|
The |
row_count |
int
|
The rows it holds. |
generation |
str | None
|
The object version that was published, where the store versions objects, as GCS does.
|
crc32c |
str | None
|
The store's own checksum of the object, in the store's encoding (on GCS, the base64 CRC32C), where
the store keeps one. |
Storage
¶
Bases: ABC
A backend-independent interface for reading and writing files.
Subclasses implement the file operations against a specific backend, such as the local disk or GCS.
Each subclass sets name to its registry key ("local", "gcs", and so on), which is how a caller
looks the adapter up in the altar.storage registry.
from_options
classmethod
¶
from_options(
options: Mapping[str, Any],
*,
connection: Connection | None = None,
context: AdapterContext,
) -> Self
Build this storage from a run spec's [storage] options and the connection it names.
The default passes the options to the constructor and refuses a connection (construct). A storage that
reads through a connection, as FsspecStorage does, overrides it.
read_text
abstractmethod
async
¶
Read a text file and return its contents as a string.
read_binary
abstractmethod
async
¶
Read a file and return its contents as bytes.
write_text
abstractmethod
async
¶
Write a string to a text file.
write_binary
abstractmethod
async
¶
Write bytes to a file.
exists
abstractmethod
async
¶
Return whether a file exists at the given path.
upload_from_local_file
abstractmethod
async
¶
Copy a file from the local disk into storage by streaming it.
Use this for large files. It streams the upload rather than reading the whole file into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
local_path
|
str
|
Path to the local file to upload. |
required |
dest_path
|
str
|
Destination path in storage. |
required |
as_local_file
abstractmethod
async
¶
Yield a local filesystem path for a stored file, for the duration of the context.
Local storage yields the path unchanged. Remote storage downloads the file to a temporary path and yields that; the temporary file is removed when the context exits.
Usage
async with storage.as_local_file(path) as local_path: with open(local_path) as f: # Process file
open_writer
async
¶
Open path for a streamed write and yield a synchronous binary file to write it through.
The object is committed whole or not at all. When the block exits cleanly, path holds every byte written,
in order; when the block raises or is cancelled, nothing is committed and an object already at path is
left as it was. The file's write may block on an upload, so call it off the event loop
(asyncio.to_thread), one call at a time. A *.gz object is stored as gzip bytes, never with a content
encoding.
The default spools the bytes to a temporary file under TMPDIR and uploads it with
upload_from_local_file on a clean exit, so local disk holds the whole object once. A backend that can
stream an upload, or write beside the destination and rename, overrides it.
list_files
async
¶
Return the path of every file under the directory prefix, at any depth, sorted.
An optional capability, for a caller that must find and remove files it did not name itself, such as the
shards a warehouse export wrote. A prefix with no files returns []. The default raises
CapabilityNotSupported.
describe_file
async
¶
describe_file(path: str) -> StoredFile
Return the size of the file at path and, where the store keeps them, its version and checksum.
Provisional. An optional capability, for a caller that records files another process wrote, such as the
shards of a warehouse export, without reading them. Raises FileNotFoundError when path holds no file.
The result's uri is path as given. The default raises CapabilityNotSupported. LocalStorage reports a
local file's size; FsspecStorage reports a local file's or a remote object's size, and a gs://
object's generation and CRC32C.
open_reader
async
¶
Open path for reading and yield a seekable binary file, for a caller that reads only part of it.
Provisional. A Parquet footer, for example, is read with a seek near the file's end. The file's read
and seek may block on the network, so call them off the event loop (asyncio.to_thread). The default
yields the copy as_local_file makes, so a remote object is downloaded whole once; LocalStorage opens the
file in place, and FsspecStorage reads a remote object with ranged requests.
publish_parts
async
¶
publish_parts(
parts_prefix: str,
destination: str,
*,
expected_rows: int,
fields: int,
) -> PublishedFile
Publish the export parts under parts_prefix as one new file at destination, and describe it.
Provisional. An optional capability, for a warehouse export that writes one table as numbered parts, such
as BigQuery's EXPORT DATA with uri='gs://bucket/export/part-*.tsv'. The published file holds the
bytes of every part, in part order, with nothing added or removed.
The parts must be headerless, uncompressed TSV. Every object under parts_prefix must be named
part-<digits> with one shared extension, numbered from 0 with no gap. Every row must have exactly
fields tab-separated fields and end with a newline, and the parts together must hold exactly
expected_rows rows. Any other object under the prefix, a missing part, a malformed row or a different
row count raises ValueError, and nothing is published. Each part is read pinned to what the listing
recorded of it, since an exporter can rewrite a part after it reports that it is done. A part that changes
after the listing named it restarts the read from a new listing, at most PUBLISH_READ_ATTEMPTS times.
The publish never replaces a file. When destination already holds exactly the bytes this call read, as
it does after an earlier call whose answer was lost, that file is returned. When it holds anything else,
FileExistsError is raised. destination must not be under parts_prefix. Pass the result to
verify_published to check later that the file is unchanged.
The default raises CapabilityNotSupported. LocalStorage publishes local paths, and FsspecStorage
publishes local paths and gs:// objects.
verify_published
async
¶
verify_published(published: PublishedFile) -> None
Check that published.uri still holds exactly the file publish_parts returned as published.
Provisional. Raises FileNotFoundError when the file is gone and ValueError when it has changed. Where the
store versions its objects, as GCS does, the check compares the version, size and the store's checksum.
Elsewhere it compares the size and SHA-256 of the bytes. The default raises CapabilityNotSupported.
describe_published
async
¶
describe_published(
uri: str, *, expected_rows: int, fields: int
) -> PublishedFile | None
Describe the file already at uri as publish_parts would have, or return None when there is none.
Provisional. An optional capability, for a caller about to export and publish a table that first asks
whether an earlier run already published it, so a run repeated after a lost answer returns that file
instead of exporting again. A second export can split the rows into parts differently, so its bytes can
differ, and publish_parts would refuse to replace the first file.
The file is read once and must meet the rules publish_parts applies to the parts: every row has exactly
fields tab-separated fields and ends with a newline, and there are exactly expected_rows rows. A file
that breaks them raises ValueError. The result's uri is uri as given, and it can be passed to
verify_published. The default raises CapabilityNotSupported. LocalStorage describes local paths, and
FsspecStorage local paths and gs:// objects.
compose_gzip_files
async
¶
compose_gzip_files(
sources: Sequence[str],
destination: str,
*,
overwrite: bool = True,
) -> StoredFile
Concatenate one or more stored gzip files in order into destination and describe the result.
Provisional. RFC 1952 permits valid gzip members to be concatenated byte-for-byte into a single gzip stream.
On GCS (FsspecStorage), this runs server-side 32-ary tree compose with zero bytes passing through Python,
clearing content_encoding = None and setting content_type = "application/gzip" on shards and the composed
object, and deleting temporary .compose-* objects in finally:. On LocalStorage, the raw bytes of
sources stream in order into an atomic replacement at destination. Raises ValueError when sources is
empty, FileNotFoundError when a source is missing, and FileExistsError when overwrite=False and
destination already exists.
read_csv
async
¶
read_csv(
path: str,
delimiter: str = "\t",
fieldnames: list[str] | None = None,
) -> list[dict[str, Any]]
Read a delimited file and return one dict per row, keyed by column name.
write_csv
async
¶
Write a list of rows to a delimited file.
open_text_reader
async
¶
Read a text file and return its contents as an in-memory file object.
open_text_writer
¶
open_text_writer(path: str) -> TextWriter
Return a context manager for writing text to a file (see TextWriter).
StoredFile
dataclass
¶
A stored file as Storage.describe_file reports it, without reading its bytes.
Provisional.
Attributes:
| Name | Type | Description |
|---|---|---|
uri |
str
|
The file, as the caller named it. |
size |
int
|
Its size in bytes. |
generation |
str | None
|
The object version, where the store versions objects, as GCS does. |
crc32c |
str | None
|
The store's own checksum of the object, in the store's encoding (on GCS, the base64 CRC32C), where
the store keeps one. |
TextWriter
¶
TextWriter(storage: Storage, path: str)
An async context manager for writing a text file through a Storage.
Writes made inside the block go to an in-memory buffer. When the block exits without an error, the
buffer is flushed to the file with Storage.write_text. Because that flush is awaited, the writer
only supports async with.