Metadata-Version: 2.4
Name: batchanchor
Version: 0.1.0
Summary: Resumable Python batch jobs with SQLite checkpoints and bounded concurrency.
Author: Abhimanyu Nair
License-Expression: MIT
Keywords: batch,checkpoint,resume,sqlite,retry,etl
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: build>=1; extra == "dev"
Requires-Dist: twine>=5; extra == "dev"
Dynamic: license-file

# BatchAnchor

**Your batch job stopped at item 8,412. Start it again. Keep the work already done.**

BatchAnchor adds durable checkpoints to ordinary Python functions. It uses a local SQLite file and has **zero runtime dependencies**. No worker service or cloud account is required.

Good for API enrichment, document processing or repeatable data transformations. It works with your existing synchronous Python code.

## Install

Requires Python 3.10 or later.

```sh
python -m pip install batchanchor
```

Or install the wheel from the source bundle:

```sh
python -m pip install dist/batchanchor-0.1.0-py3-none-any.whl
```

## Start in six lines

```python
from batchanchor import Batch

batch = Batch("progress.db", namespace="enrichment-v1")

def enrich(row):
    return {"id": row["id"], "normalized": row["name"].strip().lower()}

rows = [{"id": 1, "name": "  Abhi "}, {"id": 2, "name": " Ada "}]
for result in batch.run(enrich, rows, workers=8):
    print(result.unwrap())
```

Run the same script again. Completed inputs are loaded from disk instead of calling `enrich` again. New inputs are processed. Previously failed or interrupted inputs are attempted again.

## Why use it?

- **Resume after a crash.** Each successful result commits independently.
- **Bounded concurrency.** At most twice the worker count of input entries is buffered.
- **Deduplication.** Identical successful inputs execute once per namespace.
- **Retries you control.** Choose exception types and exponential backoff with full jitter.
- **One shared rate limit.** Limit attempt starts across the worker threads.
- **Inspect without rerunning.** View counts or export records as JSONL.
- **Portable results.** Strict JSON serialization; no pickle execution.

## Retry temporary failures

```python
for result in batch.run(
    enrich, rows, workers=8,
    retries=3, backoff=0.5, max_backoff=20,
    retry_on=(TimeoutError, ConnectionError), rate=5,
):
    if result.ok:
        print(result.value)
    else:
        print(result.key, result.error)
```

The default is **zero retries**, since repeating side effects can be unsafe. `retries=3` means up to four attempts per item in this invocation. Errors are yielded as `Result` objects; use `unwrap()` to raise on an error. Serialization failures are never retried within the invocation. A callback raising `BaseException`, such as `KeyboardInterrupt`, aborts the run.

The rate is attempt starts per second, including retries. It does not interpret HTTP headers or enforce remote server quotas. Use your HTTP client's request timeout. Python threads cannot forcibly stop a blocked request.

## Cache identity matters

Every input is serialized canonically and hashed with SHA-256. Dictionary key order does not affect identity. Integers and floats remain distinct keys. List order matters.

**Namespace is required.** Change it when you change the function, model, prompt or relevant upstream data. BatchAnchor does not infer code or environment changes.

```python
batch = Batch("progress.db", namespace="summaries-model-v2-prompt-v3")
results = batch.run(enrich, rows, key=lambda row: str(row["id"]))
```

A custom key reused with different input raises `InputConflict`; it never silently returns an old answer. This check applies across restarts. Separate namespaces allow separate transformations in one database.

## Results

| Field | Meaning |
| --- | --- |
| `index` | Zero-based position in the current input stream |
| `key` | Input hash or custom key |
| `value` | JSON result, or `None` on failure |
| `error` | Exception type and message, or `None` |
| `ok` | Whether the result succeeded |
| `attempts` | Cumulative attempts recorded for this key |
| `cached` | Whether this outcome was loaded from a prior successful checkpoint |

Results are yielded in input order. Worker threads commit in completion order, so a slow first input does not prevent other completed results being saved. Duplicate entries in the active window share a future; their `cached` field describes that shared computation. Failed duplicate inputs may run again after leaving the active window.

## Stream large datasets

```python
import json
from batchanchor import Batch

batch = Batch("records.db", namespace="normalize-v1")
with open("input.jsonl", encoding="utf-8") as source:
    rows = (json.loads(line) for line in source if line.strip())
    for result in batch.run(lambda row: {"id": row["id"]}, rows):
        if not result.ok:
            print(result.error)
```

Memory use is bounded by the worker window and item sizes, unless you call `list()` on the results. Each individual input and output must fit in memory. SQLite storage grows with unique inputs.

## Stop early safely

```python
from contextlib import closing

with closing(batch.run(enrich, rows)) as results:
    for result in results:
        print(result.value)
        break
```

Closing cancels queued work where possible and waits for running callbacks before releasing the database lock. Some work beyond the last yielded item may complete and be checkpointed. Merely keeping an unclosed iterator after `break` can retain the lock.

## CLI and inspection

```sh
batchanchor stats progress.db --namespace enrichment-v1
batchanchor export progress.db --namespace enrichment-v1 --status done > results.jsonl
batchanchor export progress.db --namespace enrichment-v1 --status failed > failures.jsonl
```

```python
print(batch.stats())
for record in batch.records(status="failed"):
    print(record["input"], record["error"])
```

Exports are in key order, one record per unique key. They include input data and exception messages, so handle them with the same care as the source dataset.

## Guarantees and boundaries

This is an initial **alpha release**, not a distributed workflow platform.

- A result committed to SQLite is reused when its namespace and input match.
- An operation that finishes externally but crashes before its checkpoint commits can run again. This is **at-least-once execution**, not exactly once. Use idempotency keys for external writes. Do not use retries blindly for payments or non-idempotent actions.
- One active run owns a database at a time, even across processes. SQLite releases the separate lock-file transaction when a process dies. Other runs fail with `BusyError`; stats and exports remain available. Do not delete or move the database or its lock file during a run.
- Use a local filesystem with reliable SQLite locking. Network shares and distributed workers are outside the supported scope.
- The database stores inputs and outputs unencrypted. Exceptions may contain sensitive information. There is no telemetry or automatic network activity.
- Use strict JSON values: `None`, booleans, finite numbers, strings, lists or dictionaries with string keys. Convert dates and custom objects explicitly. Tuples are rejected to avoid type changes after resume.
- Threads primarily help I/O workloads. CPU-heavy work, async-native functions, DAGs and schedules are outside this release's scope.
- Retry/backoff happens inside worker threads. A slow input can delay ordered delivery and limit throughput.
- `running` records may represent interrupted attempts. They are automatically retried when that input is presented again. Callers must replay the source; the library does not regenerate missing input streams.
- Callbacks must be safe for concurrent invocation. Give each callback its own mutable client when the underlying client is not thread-safe.

## Development

```sh
python -m pip install -e '.[dev]'
python -m pytest -q
python -m build
python -m twine check dist/*
```

Tests include a subprocess killed during real work, then a fresh process resuming from its SQLite checkpoint. CI is configured for Python 3.10 through 3.14 on Linux, macOS and Windows. Configured CI platforms are not a claim that those jobs have run.

See `PUBLISHING.md` for releasing under your own PyPI account. MIT licensed. Created for Abhimanyu Nair.
