Metadata-Version: 2.2
Name: sackli
Version: 0.2.8
Summary: A format for storing a sequence of byte-array records
Author-Email: Charlie Beattie <cbeattie@google.com>, Lucas Beyer <lucasb.eyer.be@gmail.com>, =?utf-8?q?Augustin_=C5=BD=C3=ADdek?= <augustinzidek@google.com>, Nicolas Porcel <nicolasporcel@google.com>
Maintainer: Lucas Beyer
License: 
                                          Apache License
                                    Version 2.0, January 2004
                                 http://www.apache.org/licenses/
         
            TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
         
            1. Definitions.
         
               "License" shall mean the terms and conditions for use, reproduction,
               and distribution as defined by Sections 1 through 9 of this document.
         
               "Licensor" shall mean the copyright owner or entity authorized by
               the copyright owner that is granting the License.
         
               "Legal Entity" shall mean the union of the acting entity and all
               other entities that control, are controlled by, or are under common
               control with that entity. For the purposes of this definition,
               "control" means (i) the power, direct or indirect, to cause the
               direction or management of such entity, whether by contract or
               otherwise, or (ii) ownership of fifty percent (50%) or more of the
               outstanding shares, or (iii) beneficial ownership of such entity.
         
               "You" (or "Your") shall mean an individual or Legal Entity
               exercising permissions granted by this License.
         
               "Source" form shall mean the preferred form for making modifications,
               including but not limited to software source code, documentation
               source, and configuration files.
         
               "Object" form shall mean any form resulting from mechanical
               transformation or translation of a Source form, including but
               not limited to compiled object code, generated documentation,
               and conversions to other media types.
         
               "Work" shall mean the work of authorship, whether in Source or
               Object form, made available under the License, as indicated by a
               copyright notice that is included in or attached to the work
               (an example is provided in the Appendix below).
         
               "Derivative Works" shall mean any work, whether in Source or Object
               form, that is based on (or derived from) the Work and for which the
               editorial revisions, annotations, elaborations, or other modifications
               represent, as a whole, an original work of authorship. For the purposes
               of this License, Derivative Works shall not include works that remain
               separable from, or merely link (or bind by name) to the interfaces of,
               the Work and Derivative Works thereof.
         
               "Contribution" shall mean any work of authorship, including
               the original version of the Work and any modifications or additions
               to that Work or Derivative Works thereof, that is intentionally
               submitted to Licensor for inclusion in the Work by the copyright owner
               or by an individual or Legal Entity authorized to submit on behalf of
               the copyright owner. For the purposes of this definition, "submitted"
               means any form of electronic, verbal, or written communication sent
               to the Licensor or its representatives, including but not limited to
               communication on electronic mailing lists, source code control systems,
               and issue tracking systems that are managed by, or on behalf of, the
               Licensor for the purpose of discussing and improving the Work, but
               excluding communication that is conspicuously marked or otherwise
               designated in writing by the copyright owner as "Not a Contribution."
         
               "Contributor" shall mean Licensor and any individual or Legal Entity
               on behalf of whom a Contribution has been received by Licensor and
               subsequently incorporated within the Work.
         
            2. Grant of Copyright License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               copyright license to reproduce, prepare Derivative Works of,
               publicly display, publicly perform, sublicense, and distribute the
               Work and such Derivative Works in Source or Object form.
         
            3. Grant of Patent License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               (except as stated in this section) patent license to make, have made,
               use, offer to sell, sell, import, and otherwise transfer the Work,
               where such license applies only to those patent claims licensable
               by such Contributor that are necessarily infringed by their
               Contribution(s) alone or by combination of their Contribution(s)
               with the Work to which such Contribution(s) was submitted. If You
               institute patent litigation against any entity (including a
               cross-claim or counterclaim in a lawsuit) alleging that the Work
               or a Contribution incorporated within the Work constitutes direct
               or contributory patent infringement, then any patent licenses
               granted to You under this License for that Work shall terminate
               as of the date such litigation is filed.
         
            4. Redistribution. You may reproduce and distribute copies of the
               Work or Derivative Works thereof in any medium, with or without
               modifications, and in Source or Object form, provided that You
               meet the following conditions:
         
               (a) You must give any other recipients of the Work or
                   Derivative Works a copy of this License; and
         
               (b) You must cause any modified files to carry prominent notices
                   stating that You changed the files; and
         
               (c) You must retain, in the Source form of any Derivative Works
                   that You distribute, all copyright, patent, trademark, and
                   attribution notices from the Source form of the Work,
                   excluding those notices that do not pertain to any part of
                   the Derivative Works; and
         
               (d) If the Work includes a "NOTICE" text file as part of its
                   distribution, then any Derivative Works that You distribute must
                   include a readable copy of the attribution notices contained
                   within such NOTICE file, excluding those notices that do not
                   pertain to any part of the Derivative Works, in at least one
                   of the following places: within a NOTICE text file distributed
                   as part of the Derivative Works; within the Source form or
                   documentation, if provided along with the Derivative Works; or,
                   within a display generated by the Derivative Works, if and
                   wherever such third-party notices normally appear. The contents
                   of the NOTICE file are for informational purposes only and
                   do not modify the License. You may add Your own attribution
                   notices within Derivative Works that You distribute, alongside
                   or as an addendum to the NOTICE text from the Work, provided
                   that such additional attribution notices cannot be construed
                   as modifying the License.
         
               You may add Your own copyright statement to Your modifications and
               may provide additional or different license terms and conditions
               for use, reproduction, or distribution of Your modifications, or
               for any such Derivative Works as a whole, provided Your use,
               reproduction, and distribution of the Work otherwise complies with
               the conditions stated in this License.
         
            5. Submission of Contributions. Unless You explicitly state otherwise,
               any Contribution intentionally submitted for inclusion in the Work
               by You to the Licensor shall be under the terms and conditions of
               this License, without any additional terms or conditions.
               Notwithstanding the above, nothing herein shall supersede or modify
               the terms of any separate license agreement you may have executed
               with Licensor regarding such Contributions.
         
            6. Trademarks. This License does not grant permission to use the trade
               names, trademarks, service marks, or product names of the Licensor,
               except as required for reasonable and customary use in describing the
               origin of the Work and reproducing the content of the NOTICE file.
         
            7. Disclaimer of Warranty. Unless required by applicable law or
               agreed to in writing, Licensor provides the Work (and each
               Contributor provides its Contributions) on an "AS IS" BASIS,
               WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
               implied, including, without limitation, any warranties or conditions
               of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
               PARTICULAR PURPOSE. You are solely responsible for determining the
               appropriateness of using or redistributing the Work and assume any
               risks associated with Your exercise of permissions under this License.
         
            8. Limitation of Liability. In no event and under no legal theory,
               whether in tort (including negligence), contract, or otherwise,
               unless required by applicable law (such as deliberate and grossly
               negligent acts) or agreed to in writing, shall any Contributor be
               liable to You for damages, including any direct, indirect, special,
               incidental, or consequential damages of any character arising as a
               result of this License or out of the use or inability to use the
               Work (including but not limited to damages for loss of goodwill,
               work stoppage, computer failure or malfunction, or any and all
               other commercial damages or losses), even if such Contributor
               has been advised of the possibility of such damages.
         
            9. Accepting Warranty or Additional Liability. While redistributing
               the Work or Derivative Works thereof, You may choose to offer,
               and charge a fee for, acceptance of support, warranty, indemnity,
               or other liability obligations and/or rights consistent with this
               License. However, in accepting such obligations, You may act only
               on Your own behalf and on Your sole responsibility, not on behalf
               of any other Contributor, and only if You agree to indemnify,
               defend, and hold each Contributor harmless for any liability
               incurred by, or claims asserted against, such Contributor by reason
               of your accepting any such warranty or additional liability.
         
            END OF TERMS AND CONDITIONS
         
            APPENDIX: How to apply the Apache License to your work.
         
               To apply the Apache License to your work, attach the following
               boilerplate notice, with the fields enclosed by brackets "[]"
               replaced with your own identifying information. (Don't include
               the brackets!)  The text should be enclosed in the appropriate
               comment syntax for the file format. We also recommend that a
               file or class name and description of purpose be included on the
               same "printed page" as the copyright notice for easier
               identification within third-party archives.
         
            Copyright [yyyy] [name of copyright owner]
         
            Licensed 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.
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: File Formats
Classifier: Topic :: Scientific/Engineering
Project-URL: Homepage, https://github.com/lucasb-eyer/sackli
Project-URL: Bug Tracker, https://github.com/lucasb-eyer/sackli/issues
Project-URL: Upstream, https://github.com/google-deepmind/bagz
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown

# Säckli

This is a friendly fork of [bagz](https://github.com/google-deepmind/bagz).

Additions so far:
- Merge some PRs such as [S3 support PR by @KefanXIAO](https://github.com/google-deepmind/bagz/pull/5) and [compile fixes](https://github.com/google-deepmind/bagz/pull/4).
- Add `access_pattern` and `cache_policy` reader hints:
    - On POSIX filesystems, this can add `mmap` hints or use `pread`-based no-cache reads to optimize for random access and larger-than-RAM data.
    - On Linux, support `O_DIRECT` for even better reading of random access and larger-than-RAM data.
    - On macOS, support `F_NOCACHE`, `MAP_NOCACHE`, and `madvise`-based cache hints on Apple silicon.
- Make it compatible to Python versions past 3.13.
- Make it compatible with free-threading (nogil) Python.
- Add macOS support and wheels.
- Add CI, stress-tests and automatic wheel releases to PyPI for Linux x86_64 and macOS arm64 (macOS 14+).

Versioning of this fork is detached from the original bagz library at the point it was forked (v0.2.0).

## Overview

*Säckli* is a format for storing a sequence of byte-array records.
It supports per-record compression and fast index-based lookup.
All indexing is zero based.

## Installation

The recommended installation on Linux and Mac is via the pre-built wheels on PyPI.
PyPI currently ships Linux x86_64 wheels and macOS arm64 wheels for macOS 14+:

```sh
uv pip install sackli
```

If you want to build locally to work on this, just `uv pip install .`.
However, building can be slow because of GCS and S3 support;
to skip both of these dependencies for much faster builds, you can do:

```sh
CMAKE_ARGS="-DSACKLI_ENABLE_GCS=OFF -DSACKLI_ENABLE_S3=OFF" uv pip install .
```

## Python API

### Python Reader

Reader for reading a single or sharded Säckli file-set.

```python
from collections.abc import Sequence, Iterable

import sackli
import numpy as np

# Säckli Readers support random access. The order of elements within a Säckli
# file is the order in which they are written. Records are returned as `bytes`
# objects.
data = sackli.Reader('/path/to/data.bagz')

# Säckli Readers can be configured like this - here we require that the file was
# written with separate limits.
data_separate_limits = sackli.Reader('/path/to/data.bagz', sackli.Reader.Options(
    limits_placement=sackli.LimitsPlacement.SEPARATE,
))

# Säckli Readers are Sequences and support slicing, iterating, etc.
assert isinstance(data, Sequence)

# Säckli Readers have a length.
assert len(data) > 10

# Can access record by row-index.
fifth_value: bytes = data[5]

# Can slice.
data_from_5: sackli.Reader = data[5:]

# Slices are still Readers.
assert isinstance(data_from_5, sackli.Reader)

assert data_from_5[0] == fifth_value

# Can access records by multiple row-indices.
fourth, second, tenth = data.read_indices([4, 2, 10])
assert fourth == data[4]
assert second == data[2]
assert tenth == data[10]

# Can iterate records.
for record in data:
  do_something_else(record)

# Can read all records. This eager version can be faster than iteration.
all_records = data.read()

# Can iterate sub-range of records.
for record in data[4:9]:
  do_something_else(record)

# Can read a sub-range of records. This eager form can be faster than
# iteration.
sub_range = data[4:9].read()

# Can use an infinite iterator as source of indices. (Reads ahead in parallel.)
def my_generator(size: int) -> Iterable[int]:
  rng = np.random.default_rng(42)
  while True:
    yield rng.integers(size).item()

data_iter: Iterable[bytes] = data.read_indices_iter(my_generator(len(data)))
for i in range(10):
  random_item: bytes = next(data_iter)
```

#### Python Reader - `Index` and `MultiIndex`

You can use `Index` to find the first index of a record and `MultiIndex` to find
all instances of an item.

```python
keys = sackli.Reader('/path/to/keys.bag')
# Get the index of the first occurrence of key.
index = sackli.Index(keys)
key_index: int = index[b'example_key']

# Get all occurrences of key.
multi_index = sackli.MultiIndex(keys)
all_indices: list[int] = multi_index[b'example_key']
```

### Python Writer

For writing a single Säckli file.

Example:

```python
import sackli

# Compression is selected based on the file extension:
# `.bagz` will use Zstandard compression with default settings.
# `.bag` will use no compression.
with sackli.Writer('/path/to/data.bagz') as writer:
  for d in generate_records():
    writer.write(d)

# Adjust compression level explicitly.
# Note this will no longer use the extension to detemine whether to compress.
with sackli.Writer(
    '/path/to/data.bagz',
    sackli.Writer.Options(
        compression=sackli.CompressionZstd(level=3)
    ),
) as writer:
  for d in generate_records():
    writer.write(d)
```

## Options

### Reader Options

`sackli.Reader.Options` has these optional arguments.

*   `compression`: Can be one of:
    *   `sackli.CompressionAutoDetect()`: Default - Uses extension whether to
        compress. (`.bagz` - Compressed (ZStandard), `.bag` - Uncompressed)
    *   `sackli.CompressionNone()`: Records are not decompressed.
    *   `sackli.CompressionZstd()`: Records are decompressed using Zstandard.
*   `limits_placement`: Can be one of:
    *   `sackli.LimitsPlacement.TAIL`: Default- Reads limits from a tail of file.
    *   `sackli.LimitsPlacement.SEPARATE`: Reads limits from a separate file.
*   `limits_storage`: Can be one of:
    *   `sackli.LimitsStorage.ON_DISK`: Default - Reads limits from disk for each
        read.
    *   `sackli.LimitsStorage.IN_MEMORY`: Reads all limits from disk in one go.
*   `access_pattern`: Can be one of:
    *   `sackli.AccessPattern.SYSTEM`: Default - no specific hint to the OS.
    *   `sackli.AccessPattern.RANDOM`: Hints that you read entries in random order.
    *   `sackli.AccessPattern.SEQUENTIAL`: Hints that you read entries roughly sequentially.
*   `cache_policy`: Can be one of:
    *   `sackli.CachePolicy.SYSTEM`: Default - no specific hint to the OS.
    *   `sackli.CachePolicy.DROP_AFTER_READ`: Reads data in such a way that the OS
        is unlikely to hold any of it in cache. For POSIX filesystems, this means
        using OS-specific no-cache hints: Linux uses `pread` with
        `posix_fadvise`, while macOS uses `MAP_NOCACHE` plus `madvise` for
        mmap-backed reads and `F_NOCACHE` for streaming reads.
        This is more efficient when you read more data than your RAM before doing
        any repeats (ie when an epoch is larger than RAM).
    *   `sackli.CachePolicy.DIRECT_IO`: Uses `O_DIRECT` on Linux and `F_NOCACHE`
        on macOS to read records. This is the most aggressive os-cache avoidance
        option and can be best for random reads on huge data with rare re-reads.
        Linux uses `STATX_DIOALIGN` if supported, otherwise probes from a conservative
        page-aligned starting point derived from file/filesystem metadata.
        For the unaligned tail, it does a one-time standard read at init.
*   `max_parallelism`: Default number of threads when reading many records.
*   `sharding_layout`: Can be one of:
    *   `sackli.ShardingLayout.CONCATENATED`: Default - See [Sharding](#sharding)
    *   `sackli.ShardingLayout.INTERLEAVED`: See [Sharding](#sharding)

`access_pattern` and `cache_policy` are currently interpreted only for local
POSIX files and influence OS-level behaviour on page cache and cache lines.

For tail-formatted files, non-default POSIX record-cache policies open a second
POSIX read handle to the same file so limits metadata reads keep the default
cache policy.

### Writer Options

`sackli.Writer.Options` has these optional arguments.

*   `compression`: Can be one of:
    *   `sackli.CompressionAutoDetect()`: Default - Uses extension whether to
        compress. (`.bagz` - Compressed (Zstandard), `.bag` - Uncompressed)
    *   `sackli.CompressionNone()`: Records are not compressed.
    *   `sackli.CompressionZstd(level = 3)`: Records are compressed using
        Zstandard the level of the compression can be specified.
*   `limits_placement`: Can be one of:
    *   `sackli.LimitsPlacement.TAIL`: Default - Writes limits to a tail of file.
    *   `sackli.LimitsPlacement.SEPARATE`: Writes limits to a separate file.

## Sharding

An ordered collection of Säckli-formatted files ("shards") may be opened together
and indexed via a single `global-index`. The `global-index` is mapped to a
`shard` and an index within that shard (`shard-index`) in one of two ways:

1.  **Concatenated** (default). Indexing is equivalent to the records in each
    Säckli-formatted shard being concatenated into a single sequence of records.

    Example:

    When opening four Säckli-formatted files with sizes `[8, 4, 0, 5]`, the
    `global-index` with range `[0, 17)` (shown as the table entries) maps to
    `shard` and `shard-index` like this:

    ```
                   | shard-index
    shard          |  0  1  2  3  4  5  6  7
    -------------- | -----------------------
    00000-of-00004 |  0  1  2  3  4  5  6  7
    00001-of-00004 |  8  9 10 11
    00002-of-00004 |
    00003-of-00004 | 12 13 14 15 16
    ```

    Mappings

    `global-index` | `shard`          | `shard-index`
    -------------: | :--------------: | -------------
    `0`            | `00000-of-00004` | `0`
    `1`            | `00000-of-00004` | `1`
    `2`            | `00000-of-00004` | `2`
    ...            | ...              | ...
    `8`            | `00001-of-00004` | `0`
    `9`            | `00001-of-00004` | `1`
    ...            | ...              | ...
    `15`           | `00003-of-00004` | `3`
    `16`           | `00003-of-00004` | `4`

2.  **Interleaved** where the global-index is interleaved in a round-robin
    manner across all the shards.

    Example:

    When opening three Säckli-formatted files with sizes `[6, 6, 5]`, the
    `global-index` with range `[0, 17)` (shown as the table entries) maps to
    `shard` and `shard-index` like this:

    ```
                   |  shard-index
    shard          |  0  1  2  3  4  5
    -------------- | -----------------
    00000-of-00003 |  0  3  6  9 12 15
    00001-of-00003 |  1  4  7 10 13 16
    00002-of-00003 |  2  5  8 11 14
    ```

    Mappings

    `global-index` | `shard`          | `shard-index`
    -------------: | :--------------: | -------------
    `0`            | `00000-of-00003` | `0`
    `1`            | `00001-of-00003` | `0`
    `2`            | `00002-of-00003` | `0`
    ...            | ...              | ...
    `6`            | `00000-of-00003` | `2`
    `7`            | `00001-of-00003` | `2`
    `8`            | `00002-of-00003` | `2`
    ...            | ...              | ...
    `15`           | `00000-of-00003` | `5`
    `16`           | `00001-of-00003` | `5`

## Apache Beam Support

Säckli also provides Apache Beam connectors for reading and writing Säckli files in
Beam pipelines.

Ensure you have Apache Beam installed.
```sh
uv pip install apache_beam
```

### Säckli Source

```python
import apache_beam as beam
from sackli.beam import sacklio
import tensorflow as tf

with beam.Pipeline() as pipeline:
  examples = (
      pipeline
      | 'ReadData' >> sacklio.ReadFromSackli('/path/to/your/data@*.bagz')
      | 'Decode' >> beam.Map(tf.train.Example.FromString)
  )
  # Continue your pipeline.
```

#### Säckli Sink

```python
from sackli.beam import sacklio
import tensorflow as tf

def create_tf_example(data):
  # Replace with your actual feature creation logic.
  feature = {
      'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[data])),
  }
  return tf.train.Example(features=tf.train.Features(feature=feature))

with beam.Pipeline() as pipeline:
  data = [b'record1', b'record2', b'record3']

  examples = (
      pipeline
      | 'CreateData' >> beam.Create(data)
      | 'Encode' >> beam.Map(lambda x: create_tf_example(x).SerializeToString())
      | 'WriteData' >> sacklio.WriteToSackli('/path/to/output/data@*.bagz')
  )
```

## Cloud Storage

Säckli supports POSIX file-systems, Google Cloud Storage (GCS), and Amazon S3.
These can be enabled or disabled at compile-time, but the PyPI-deployed wheels
have support for both built-in.

### GCS authentication

These examples assume you have the gcloud CLI installed.

```sh
gcloud config set project your-project-name
gcloud auth application-default login
```

### S3 authentication

Authentication uses the standard AWS credential chain (environment variables,
`~/.aws/credentials`, IAM roles, etc.).

```sh
aws configure
```

### Paths

Use the `gs:` and `s3:` file-system prefixes in paths.

```python
import pathlib
import sackli

# This may freeze if you have not configured the GCS project.
gcs_reader = sackli.Reader('gs://your-bucket-name/your-file.bagz')
s3_reader = sackli.Reader('s3://your-bucket-name/your-file.bagz')

# Path supports a leading slash to work well with pathlib.
gcs_bucket = pathlib.Path('/gs://your-bucket-name')
gcs_reader = sackli.Reader(gcs_bucket / 'your-file.bagz')

s3_bucket = pathlib.Path('/s3://your-bucket-name')
s3_reader = sackli.Reader(s3_bucket / 'your-file.bagz')
```

## Säckli/Bagz file format

For now, Säckli still preserves exactly the Bagz file format.
However, this is not guaranteed to remain the case.

The Bagz file format has two parts: the `records` section and the `limits`
section.

*   The `records` section consists of the concatenation of all (possibly
    compressed) records. (There are no additional bytes inside or between
    records, and records are not aligned in any way.)
*   The `limits` section is a dense array of the end-offsets of each record in
    order, encoded in little-endian 64-bit unsigned integers.

These can be stored as *tail-limits* in one file, where the `limits` section is
appended to the `records` section, or as *separate-limits*, where they are
stored in separate files.

### Tail-limits example

Given a Bagz-formatted file with the following 3 uncompressed records:

Records  |
-------- |
`abcdef` |
`123`    |
`catcat` |

The raw bytes of the Bagz-formatted file corresponding to the records above:

```
0x61 a 0x62 b 0x63 c 0x64 d 0x65 e 0x66 f
0x31 1 0x32 2 0x33 3
0x63 c 0x61 a 0x74 t 0x63 c 0x61 a 0x74 t
0x06   0x00   0x00   0x00   0x00   0x00   0x00   0x00  # 6 byte offset
0x09   0x00   0x00   0x00   0x00   0x00   0x00   0x00  # 9 byte offset
0x0f   0x00   0x00   0x00   0x00   0x00   0x00   0x00  # 15 byte offset
```

The last 8 bytes represent the end-offset of the last record. This is also the
start of the `limits` section. Therefore reading the last 8 bytes will directly
tell you the offset of the `records`/`limits` boundary.
