Skip to main content

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.

python -m pip install batchanchor

Or install the wheel from the source bundle:

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

Start in six lines

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

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.

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

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

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

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
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

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.

Metadata

Release files for batchanchor 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for batchanchor 0.1.0
File Size Uploaded Provenance Actions
batchanchor-0.1.0.tar.gz 17.6 kB Without provenance Details for batchanchor-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for batchanchor 0.1.0
File Interpreter ABI Platform Actions
batchanchor-0.1.0-py3-none-any.whl Python 3 none any Details for batchanchor-0.1.0-py3-none-any.whl

Total release size: 29.1 kB

Release files / batchanchor-0.1.0.tar.gz

Download URL batchanchor-0.1.0.tar.gz
Size 17.6 kB
Tags Source
SHA-256 checksum
How to use checksums
96d938f260cab97fe9c3a363d88cd0f2a0f3ceff9aca167153938c745407d70c
BLAKE2b-256 checksum
How to use checksums
5d38c82eb32dfb40c588c2ed74e7c041a123aa7336c9506042de6d87eaddc994
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.14

Release files / batchanchor-0.1.0-py3-none-any.whl

Download URL batchanchor-0.1.0-py3-none-any.whl
Size 11.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dd859b7d76d7ab539242e8dac2dd6b108e7f822d9e5a228e5cb3acb4480a3904
BLAKE2b-256 checksum
How to use checksums
83668e73a469d25fd4339c3918fa56d482207a6a3d89782c6a68c6aa1835d38e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.14

Security for batchanchor 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page