Metadata-Version: 2.4
Name: leanqueue
Version: 0.2.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS
Requires-Dist: orjson
Requires-Dist: grpcio>=1.82.1 ; extra == 'grpc'
Requires-Dist: protobuf>=7.35.0,<8 ; extra == 'grpc'
Requires-Dist: fastapi>=0.110 ; extra == 'server'
Requires-Dist: uvicorn[standard]>=0.29 ; extra == 'server'
Requires-Dist: httpx>=0.27 ; extra == 'server'
Requires-Dist: pydantic>=2.8 ; extra == 'server'
Requires-Dist: pytest>=7.0 ; extra == 'test'
Requires-Dist: psutil>=5.9 ; extra == 'test'
Requires-Dist: fastapi>=0.110 ; extra == 'test'
Requires-Dist: uvicorn[standard]>=0.29 ; extra == 'test'
Requires-Dist: httpx>=0.27 ; extra == 'test'
Requires-Dist: pydantic>=2.8 ; extra == 'test'
Requires-Dist: grpcio>=1.82.1 ; extra == 'test'
Requires-Dist: grpcio-tools==1.82.1 ; extra == 'test'
Requires-Dist: protobuf>=7.35.0,<8 ; extra == 'test'
Provides-Extra: grpc
Provides-Extra: server
Provides-Extra: test
License-File: LICENSE
Summary: Embedded, durable, crash-resistant message queue (Rust core + Python), with optional REST and gRPC servers
Author-email: Carlo Moro <cnmoro@gmail.com>
License: MIT
Requires-Python: >=3.8
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/cnmoro

# LeanQueue

LeanQueue is an embedded, durable message queue for Python with a Rust core. It
works like a small RabbitMQ or SQS queue, but it is a library: every producer and
consumer process opens the same queue directory, and there is no broker process.
If you need network access, the wheel also contains a REST server and a gRPC server
that you can start with one command.

```python
from leanqueuedb import Queue

q = Queue("./jobs")                 # a durable queue in ./jobs/
q.put_json({"task": "resize", "id": 42})

msg = q.get()                       # lease the next message
do_work(msg.json())
msg.ack()                           # remove it permanently
```

- **Durable.** By default a call returns only after its record is on disk (fsync).
- **Crash-safe.** After a crash, the queue opens with every acknowledged operation.
  Damage inside the log stops the open instead of silently dropping data.
- **Multi-process.** Any number of processes on one host can produce and consume
  from one directory. A message is leased to one consumer at a time.
- **At-least-once delivery.** A message that is not acknowledged before its lease
  expires is delivered again.

## Contents

- [Install](#install)
- [Concepts](#concepts)
- [API](#api)
- [Durability modes](#durability-modes)
- [Crashes and damaged files](#crashes-and-damaged-files)
- [Processes, threads and fork](#processes-threads-and-fork)
- [Compaction](#compaction)
- [Leases and clocks](#leases-and-clocks)
- [Servers](#servers)
- [Environment variables](#environment-variables)
- [Limits](#limits)
- [Performance](#performance)
- [Upgrading from 0.1.0](#upgrading-from-010)
- [Caveats](#caveats)
- [Development](#development)

## Install

```bash
pip install leanqueue                    # the library
pip install "leanqueue[server]"          # + REST server (FastAPI, uvicorn)
pip install "leanqueue[server,grpc]"     # + gRPC server
```

Wheels are built for Linux (x86_64, x86, aarch64, armv7), Windows (x64) and macOS
(x86_64, arm64), for CPython 3.8 and later (abi3). The only runtime dependency of the
library is `orjson`.

## Concepts

- A **queue** is a directory. The directory holds one append-only log file,
  `queue.log`.
- `put()` appends a message and returns its **sequence id** (`seq`), a number that
  increases and is never reused. You use it to acknowledge the message.
- `get()` **leases** the next ready message for `lease_ms` milliseconds. During the
  lease, no other consumer receives the message.
- `ack()` removes the message permanently. `nack(requeue=True)` makes it ready
  again; `nack(requeue=False)` drops it (dead-letters it).
- If the lease expires before an ack or nack (for example, because the consumer
  crashed), the message becomes ready again and is delivered again.
- `deliveries` counts how many times a message was leased. It is durable. Use it to
  find poison messages.

## API

### `Queue(path, sync_interval_ms=0, default_lease_ms=30_000, auto_compact_bytes=64 MiB)`

| Parameter | Meaning |
|---|---|
| `path` | Directory of the queue (created if missing), or `":memory:"` for a queue with no files that only this process can use. |
| `sync_interval_ms` | `0` (default): fsync before each call returns. A positive value: fsync in the background within this many milliseconds. See [Durability modes](#durability-modes). |
| `default_lease_ms` | Lease length when `get()` does not give one. |
| `auto_compact_bytes` | Minimum log size for automatic compaction. `0` turns automatic compaction off. See [Compaction](#compaction). |

**Produce**

```python
seq  = q.put(b"bytes")            # also accepts str, bytearray, memoryview
seq  = q.put_json({"any": "object"})
seqs = q.put_many([b"a", b"b"])   # one write and one fsync for the whole batch
seqs = q.put_many_json([{...}, {...}])
```

**Consume**

```python
msg  = q.get()                                    # None if nothing is ready
msg  = q.get(block=True, timeout=5.0, poll_interval=0.05, lease_ms=60_000)
msgs = q.get_many(100, lease_ms=None)             # up to 100 messages

for msg in q.consume(timeout=1.0):    # ack after the loop body, nack(requeue) if it raises
    handle(msg)

with q.transaction() as msg:          # ack on success, nack on an exception
    if msg is not None:
        handle(msg)
```

A `Message` has `seq`, `body` (bytes), `deliveries`, `enqueued_at_ms`,
`enqueued_at` (UTC `datetime`), `text()`, `json()`, `is_json()`, `ack()`,
`nack(requeue=True)`, `extend_lease(lease_ms=None)` and `settled`.

**Settle**

```python
q.ack(seq)                     # -> bool: True if the message existed
q.ack_many(seqs)               # -> int: how many existed
q.nack(seq, requeue=True)
q.nack_many(seqs, requeue=True)
q.extend_lease(seq, lease_ms=None)        # only for a message that is in flight
q.extend_lease_many(seqs, lease_ms=None)
```

**Inspect and maintain**

```python
q.available()                 # messages ready now
q.in_flight()                 # messages leased and not expired
len(q)                        # same as available()
q.message_state(seq)          # None, or {"state": "ready"|"in_flight", "deliveries": n, "lease_until_ms": t}
q.message_states(seqs)
q.stats()                     # counters, sizes, durability and compaction state
q.flush()                     # fsync everything written so far
q.compact()                   # rewrite the log without settled messages
q.compaction_errors()         # errors of recent background compactions
q.purge()                     # delete every message
q.verify_integrity()          # read and check the whole log; changes nothing
q.close()                     # fsync, stop background work, release the files
q.closed
```

`close()` can be called more than once. After it, every operation raises
`QueueClosedError`. A `Queue` is also closed when the last reference to it goes away
and when the interpreter exits. `Queue` works as a context manager.

`stats()` returns `ready`, `in_flight`, `total`, `enqueued_total`, `acked_total`,
`requeued_total`, `dead_total` (the four totals count records in the current log, so
they restart after a compaction), `next_seq`, `live_bytes`, `log_bytes`,
`generation`, `persistent`, `format_version`, `sync_interval_ms`, `unsynced_bytes`,
`durability_failed`, `compacting`, `compactions`, `compaction_failures`,
`last_compaction_ms`, `last_compaction_stall_ms` and `reclaimed_bytes`.

### `Broker(root, **queue_defaults)`

A set of named queues under one directory.

```python
broker = Broker("./broker", sync_interval_ms=5)
broker.queue("emails").put_json({"to": "a@b.c"})   # opened (and created) on first use
broker.queue_names()          # ['emails']
broker.has_queue("emails")
broker.stats()                # {name: stats}
broker.delete_queue("emails") # close it and delete its directory
broker.close()
```

A queue name has 1 to 255 characters from `A-Z a-z 0-9 - _ .`, and cannot be `.` or
`..`. A name that resolves outside the root (through a symbolic link) is refused.
Before you delete a queue, stop the other processes that use it.

### Exceptions

All are importable from `leanqueuedb` (and `leanqueue`).

| Exception | Base | When |
|---|---|---|
| `CorruptionError` | `OSError` | The log is damaged in a way that recovery must not repair silently. See [docs/RECOVERY.md](docs/RECOVERY.md). |
| `UnsupportedFormatError` | `OSError` | A newer release wrote the log. |
| `DurabilityError` | `OSError` | An fsync failed. The handle refuses more writes. |
| `QueueClosedError` | `ValueError` | An operation on a closed queue. |
| `TimeoutError` | built-in | The cross-process lock was not acquired in time. |
| `ValueError` | built-in | A body larger than `MAX_BODY_BYTES`, an empty path, an invalid queue name. |

## Durability modes

**Strict (default, `sync_interval_ms=0`).** Each call that changes the queue
(`put`, `get`, `ack`, `nack`, `extend_lease`) returns only after its record is
fsynced. When several threads write at the same time, they share one fsync: records
are appended under the lock, the fsync runs after the lock is released, and one
fsync covers all records written before it (group commit). LeanQueue uses
`fdatasync` on Linux.

**Interval (`sync_interval_ms > 0`).** A call returns when its record is in the
operating system's page cache. A background thread (one per process) fsyncs each
queue within `sync_interval_ms` of its first unsynced write, even if no other write
comes. If the process crashes, nothing is lost, because the kernel still has the
data. If the machine loses power, the writes of at most the last interval can be
lost. Batch calls (`put_many`, `get_many`, `ack_many`, `nack_many`,
`extend_lease_many`) always fsync before they return, in both modes.

If an fsync fails (EIO, ENOSPC), LeanQueue does not retry it: the kernel can have
dropped the data already. The handle raises `DurabilityError` for every later write.
Close it and open the queue again.

## Crashes and damaged files

- Every change is written to the log before it changes the in-memory state.
- When a queue opens, it replays the log. A last record that a crash or a power
  failure cut off (nothing intact after it) is removed, and a copy is kept as
  `queue.log.torn-<ms>-<offset>` (the newest 8 are kept). If the copy cannot be
  written, nothing is removed and the open fails. Nothing that was acknowledged is
  lost.
- Damage with intact records after it, or below the last fsynced position (the
  "durable mark", raised after each fsync), is treated as corruption of
  acknowledged data: the open fails with `CorruptionError` and the file is not
  changed. 0.1.0 removed everything from the first bad byte to the end. This
  includes a zero-filled hole that a power failure can leave in un-fsynced data
  (interval mode); salvage skips just the hole.
- A log with a format version above 1 is refused with `UnsupportedFormatError`.
- `verify_integrity()` checks the whole log without changing it.
- `LEANQUEUE_ALLOW_LOG_SKIP=1` opens a damaged log, skips the damaged ranges, keeps
  the original as `queue.log.corrupt-<ms>` and rewrites the log.

[docs/RECOVERY.md](docs/RECOVERY.md) has the details and a procedure.

## Processes, threads and fork

- **Use a local filesystem on one host.** The lock is `flock` (Linux, macOS) or
  `LockFileEx` (Windows). On NFS or SMB these locks and fsync are not reliable, so two
  hosts could lease the same message. For several hosts, run the [servers](#servers)
  on the host that has the data.
- **Many processes.** Each operation takes the cross-process lock, reads the records
  that other processes appended, and appends its own. An `fstat` of the log (and,
  after a write, an 8-byte read of the replacement counter in `.compact_lock`) shows
  if there are new records or if another process replaced the file. When the link
  count or the counter changed, the path is also checked by device and inode, so a
  hard link to the old file (a backup made with `cp -al`, for example) does not hide
  a replacement. A message is leased to one consumer at a time.
  When no other process has changed the log, `get()` on an empty queue and the
  read-only calls (`available`, `in_flight`, `stats`, `message_state`) do not take
  the lock at all.
- **Lock timeout.** A process waits at most `LEANQUEUE_PROC_LOCK_TIMEOUT_MS` (30 s)
  for the lock, then raises `TimeoutError`. The operating system releases the lock of
  a process that dies, so a crash never leaves a stale lock.
- **Threads.** A `Queue` is safe to use from many threads. All waiting, I/O and
  fsync happens with the GIL released, so a queue that waits for another process
  does not stop the other Python threads.
- **fork.** A forked child can use the `Queue` objects it inherited (with
  `os.fork()` or the `fork` start method of `multiprocessing`). Before the fork,
  LeanQueue waits for operations in progress to finish. In the child it replaces the
  internal locks, closes every inherited lock descriptor (also one that another
  thread was opening at the moment of the fork) and reopens the files. A
  child therefore never releases the parent's lock, and it cannot keep the lock of a
  parent that died. `spawn` workers open the queue themselves, as usual.
- **Mixed releases.** Do not run 0.1.0 and 0.2.0 processes on the same queue at the
  same time: stop the 0.1.0 processes, then start 0.2.0. 0.1.0 can hand out message
  ids twice when it compacts (and on Windows the releases do not even share a lock).
  0.2.0 warns when it sees a 0.1.0 compaction and protects the ids it issues itself,
  but not ids issued by 0.1.0. A queue written by either release opens in the other.

## Compaction

The log grows with every operation. Compaction writes a new log with only the
messages that are not settled, and replaces the old log with one rename.

- **Automatic.** A background thread compacts when the log is at least
  `auto_compact_bytes` (64 MiB by default) and less than half of it is live
  messages. LeanQueue checks this after acks and drops, when a queue opens, and every
  30 seconds. A failure is shown in `compaction_errors()` and the next attempt waits
  60 seconds, doubling up to one hour.
- **Producers and consumers keep running.** The lock is held only at the start (to
  list the live messages) and at the end (to copy the records written meanwhile and
  rename). In 0.1.0 every operation in every process waited for the whole rewrite.
  The other processes then read the new log once (without holding the lock).
- **One at a time.** `.compact_lock` lets only one process compact a queue at a time.
  `q.compact()` waits for a compaction in another process; the automatic one does not.
- **Safe at any point.** A crash before the rename leaves the old log, which is
  complete. A crash after it leaves the new log, which is complete and fsynced. The
  next open deletes a leftover temporary file. Compaction checks the CRC of each record
  it copies and stops if one is damaged.
- **Free space.** It needs free disk space for the live messages. It checks this
  before it starts.

## Leases and clocks

Lease deadlines are written to the log as wall-clock times (milliseconds since the
Unix epoch), because other processes and later runs must honour them. Within one
process, the clock that LeanQueue uses never goes back. If the system clock jumps
forward, leases expire early and messages are delivered again (at-least-once still
holds). If it jumps back, leases granted before the jump last longer. A lease that
was active when a process crashed is still active after the restart, until it
expires. Use a shorter `default_lease_ms` if you want faster redelivery after a crash,
and `extend_lease()` for long tasks.

## Servers

```bash
pip install "leanqueue[server,grpc]"
LEANQUEUE_DATA_DIR=/var/lib/leanqueue leanqueue-serve          # REST on 127.0.0.1:8004
LEANQUEUE_DATA_DIR=/var/lib/leanqueue leanqueue-grpc           # gRPC on 127.0.0.1:50054
```

Both servers use the same `Broker` operations: declare, list and delete queues;
publish one or many messages; get with a lease (with an optional long poll); ack,
nack and extend; message states; stats; purge. The gRPC server also has `Consume`, a
server stream that keeps at most `prefetch` unsettled messages, and requeues the
ones still leased to it when the stream ends. A queue must be declared before use.

The servers listen on loopback by default. On another address the REST server needs
`LEANQUEUE_API_TOKEN` (bearer token), and the gRPC server needs TLS
(`LEANQUEUE_GRPC_TLS_CERT`, `LEANQUEUE_GRPC_TLS_KEY`) and the token, unless you set
`LEANQUEUE_ALLOW_INSECURE=1`. Request sizes, batch sizes, prefetch and wait times have
limits. [CLIENT.md](CLIENT.md) describes the endpoints, the limits and their
variables, and has client examples. On SIGTERM the servers close the queues, which
fsyncs them.

## Environment variables

Library (read once per process):

| Variable | Default | Meaning |
|---|---|---|
| `LEANQUEUE_PROC_LOCK_TIMEOUT_MS` | `30000` | Maximum wait for the cross-process lock. |
| `LEANQUEUE_MAX_BODY_BYTES` | `536870891` (512 MiB − 21) | Largest message body. It can only be lowered. |
| `LEANQUEUE_FLUSHER_TICK_MS` | `20` | How often the background thread checks for writes to fsync (interval mode). |
| `LEANQUEUE_MAINTENANCE_INTERVAL_MS` | `30000` | How often it checks if a queue needs compaction. |
| `LEANQUEUE_ALLOW_LOG_SKIP` | off | Open a damaged log by skipping the damage. For recovery only. |
| `LEANQUEUE_FAIL_STAGE`, `LEANQUEUE_FAIL_AFTER` | off | Fault injection for tests: kill the process at a named point. |

The server variables are in [CLIENT.md](CLIENT.md).

## Limits

- One message body: 512 MiB − 21 bytes (`leanqueue.MAX_BODY_BYTES`). A larger body
  raises `ValueError`, and a batch with one is written not at all.
- Memory: about 100 bytes per live message (bodies stay on disk and are read on
  demand through a memory map). Billions of unconsumed messages do not fit.
- One host, local filesystem.
- Order: messages are delivered in `seq` order, but redeliveries and concurrent
  consumers mean there is no strict global FIFO.

## Performance

Measured on Linux (ext4 on a SATA disk, 16 cores, shared machine) with
`bench/ab_bench.py`: the published 0.1.0 wheel (A) against this release (B), 5
rounds, A/B/A interleaved, medians. "A/A" is the difference between the two A runs
and shows the noise. Bodies are 100 bytes.

| Scenario | 0.1.0 (A) | 0.2.0 (B) | B vs A | A/A |
|---|---|---|---|---|
| `put` strict (fsync each), ops/s | 680 | 701 | 1.01x | 3.4% |
| `get`+`ack` strict, ops/s | 335 | 357 | 1.05x | 4.8% |
| `put` p50 / p99 strict, µs | 1337 / 2645 | 1334 / 2147 | 1.00x / 1.08x | 0.2% / 0.8% |
| `get`+`ack` p50 / p99 strict, µs | 2686 / 5441 | 2667 / 5632 | 1.01x / 0.89x | 0.3% / 4.2% |
| `put` interval (50 ms), ops/s | 90 760 | 183 500 | 2.04x | 0.9% |
| `put` p50 / p99 interval, µs | 9.5 / 16.1 | 4.9 / 10.6 | 1.94x / 1.65x | 0.1% / 2.5% |
| `get`+`ack` interval, ops/s | 52 500 | 102 500 | 1.90x | 3.1% |
| `get`+`ack` p50 / p99 interval, µs | 17.0 / 25.5 | 9.4 / 17.1 | 1.80x / 1.48x | 0.0% / 0.9% |
| `put_many(100)` strict, msgs/s | 48 520 | 58 370 | 1.25x | 0.9% |
| `put_many(100)` interval, msgs/s | 50 640 | 58 140 | 1.13x | 3.1% |
| `get_many(100)`+`ack_many`, msgs/s | 11 710 | 32 730 | 2.76x | noisy (fsync) |
| 4 producer + 4 consumer processes, batches of 50, strict, msgs/s | 8 892 | 30 330 | 3.46x | 1.9% |
| 4 + 4 processes, single ops, interval 20 ms, msgs/s | 12 320 | 37 400 | 3.18x | 5.6% |
| Open a 170 MB log (1 M messages, 300 k live), s | 1.07 | 0.71 | 1.52x | 1.1% |
| Compact that log, s | 0.263 | 0.232 | 1.13x | 4.6% |
| Compaction stall seen by another process, s | 0.517 | 0.214 | 2.41x | 1.1% |

The interval single-operation rows and the 4 + 4 single-op row come from a later
5-round run on the final code (`--only put_interval,getack_interval,latency_interval,
mp_single_interval`). The strict single-operation rows come from a separate 9-round run (`--only
put_durable,getack_durable,latency_durable`); the p99 of strict `get`+`ack` is inside
the noise of the disk.

Strict-mode single operations are limited by the disk's fsync time in both releases.
The gains there come with several threads or processes (group commit). Compaction
stall is the longest gap between two `put` calls of another process while one
process compacts a 170 MB log with 300 000 live messages; in 0.1.0 it equals the
whole rewrite, in 0.2.0 it is mostly the other process reading the new log.

## Upgrading from 0.1.0

The on-disk format did not change. 0.2.0 opens 0.1.0 queues without a migration, and
0.1.0 can open queues written by 0.2.0. What changed in behaviour:

- **Bug fixes.** Delivery counts were read as 0 after a reopen, after reading other
  processes' records and after a compaction (the records were correct; the reader
  was wrong). Bodies larger than the record limit were accepted and then lost with
  every record after them on the next open. Sequence ids restarted at 0 after
  `purge()` and after compacting and reopening an empty queue.
- **Damage inside the log** raises `CorruptionError` instead of truncating the log.
- **`close()` is final.** 0.1.0 only flushed, and the queue continued to work.
- **Interval mode** fsyncs in the background within the interval. 0.1.0 waited for
  the next write.
- **Expired leases** become ready in memory. 0.1.0 wrote a Requeue record for each
  one, also from `available()`.
- **Compaction** runs in the background and does not stop other operations.
- **New:** `nack_many`, `extend_lease_many`, `message_state(s)`, `compaction_errors`,
  `closed`, `Broker.delete_queue/has_queue/stats`, the exceptions above, the servers.

## Caveats

- A damaged **last** record (nothing intact after it) looks the same as a write that
  a crash interrupted, so it is removed (with a copy kept) unless it lies below the
  durable mark. The mark can be behind the log (it is raised after each fsync but
  not fsynced itself, and 0.1.0 never raises it), so a damaged last record that was
  fsynced is sometimes removed this way.
- An interrupted write of a message body that holds a log segment, cut exactly at
  one of its record boundaries, fails the open (salvage recovers it).
- On Linux and macOS, a process detects that another process replaced the log
  with one `fstat`, a read of 8 bytes and, when those show a change, a `stat` of
  the path. Not covered: a 0.1.0 process compacting while a hard link to the log is
  created, both between two operations of a 0.2.0 process (which then writes to
  the old file).
- After another process compacts a queue, each process reads the new log once.
  That takes time in proportion to the live messages, and this process's next
  operation waits for it.
- Windows and macOS builds are compiled and smoke-tested in CI, but the crash,
  fork and multi-process tests run on Linux.

## Development

```bash
python -m venv .venv && . .venv/bin/activate
pip install maturin pytest psutil "leanqueue[server,grpc]" "grpcio-tools==1.82.1"
maturin build --release -o dist && pip install --force-reinstall dist/*.whl
cargo test --release
cd /tmp && python -m pytest /path/to/LeanQueue/tests
python bench/ab_bench.py --a /venv-0.1.0/bin/python --b .venv/bin/python --work /tmp/lqbench
```

`tests/test_compat_published.py` needs an interpreter with leanqueue 0.1.0:
set `LEANQUEUE_PUBLISHED_PYTHON`, or `LEANQUEUE_COMPAT_INSTALL=1` to install it into
a temporary venv. Regenerate the gRPC stubs with `python scripts/gen_grpc.py`
(grpcio-tools 1.82.1).

## License

MIT. See [LICENSE](LICENSE).

