Metadata-Version: 2.4
Name: leangeo
Version: 3.0.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: grpcio>=1.82.1 ; python_full_version >= '3.10' and extra == 'grpc'
Requires-Dist: protobuf>=7.35.0,<8 ; python_full_version >= '3.10' and extra == 'grpc'
Requires-Dist: fastapi>=0.110 ; extra == 'server'
Requires-Dist: uvicorn[standard]>=0.29 ; extra == 'server'
Requires-Dist: pydantic>=2.8 ; extra == 'server'
Requires-Dist: orjson>=3.9 ; 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: pydantic>=2.8 ; extra == 'test'
Requires-Dist: orjson>=3.9 ; extra == 'test'
Requires-Dist: httpx>=0.27 ; extra == 'test'
Requires-Dist: grpcio>=1.82.1 ; python_full_version >= '3.10' and extra == 'test'
Requires-Dist: grpcio-tools>=1.82.1 ; python_full_version >= '3.10' and extra == 'test'
Requires-Dist: protobuf>=7.35.0,<8 ; python_full_version >= '3.10' and extra == 'test'
Provides-Extra: grpc
Provides-Extra: server
Provides-Extra: test
License-File: LICENSE
Summary: Embedded, persistent geospatial point store (radius, bbox, polygon) with MongoDB-style metadata filters
Author-email: Carlo Moro <cnmoro@gmail.com>
Requires-Python: >=3.8
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/cnmoro/LeanGeo

# LeanGeo

An embedded, persistent store for geographic points with JSON metadata. It answers
radius, bounding-box and polygon queries, MongoDB-style metadata filters, and both
combined. The core is Rust (PyO3); the Python package is `leangeo`, imported as
`leangeo_engine`. REST and gRPC servers ship in the same wheel as optional extras.

```bash
pip install leangeo                 # the library
pip install "leangeo[server]"       # + REST server (leangeo-serve)
pip install "leangeo[grpc]"         # + gRPC server and client (leangeo-grpc)
```

Python 3.8+ (abi3 wheels for Linux x86_64/x86/aarch64/armv7, Windows x64, macOS
x86_64/arm64).

```python
from leangeo_engine import LeanGeoEngine

with LeanGeoEngine("data/geo") as db:
    sp = db.insert(-23.55, -46.63, {"city": "São Paulo", "pop": 12_300_000})
    db.insert_batch([(40.71, -74.00), (51.51, -0.13)],
                    [{"city": "New York", "pop": 8_300_000}, {"city": "London", "pop": 8_900_000}])

    db.query_radius(-23.55, -46.63, 50_000)                        # within 50 km
    db.query_bbox(35.0, -80.0, 45.0, -70.0, filter={"pop": {"$gt": 1_000_000}})
    db.query_polygon([(-47, -24), (-46, -24), (-46, -23), (-47, -23)])  # (lon, lat) vertices
    db.query({"city": {"$in": ["London", "Paris"]}})
    db.delete_by_metadata({"city": "London"})
```

Every result is a dict `{"id": int, "latitude": float, "longitude": float, "metadata": dict}`.

Contents: [API](#api) · [Filters](#filters) · [Durability](#durability-and-recovery) ·
[Concurrency](#threads-processes-and-fork) · [Compaction](#compaction) ·
[Configuration](#configuration) · [Servers](#servers) · [Limits](#limits) ·
[Performance](#performance) · [Upgrading from 2.x](#upgrading-from-2x) ·
[Caveats](#caveats)

## API

`LeanGeoEngine(path=None, capacity=10000, thread_safe=False, install_signal_handlers=False, *, wal_sync_interval_ms=None, auto_compact=True)`

- `path`: a directory. Each collection is a set of files `<path>/<collection>.*` (see
  [docs/RECOVERY.md](docs/RECOVERY.md)). `None` keeps everything in temporary files that
  are deleted at close.
- `capacity`: initial size hint (points) for a new collection's files. Files grow as needed.
- `thread_safe`: accepted for compatibility. In 3.x every engine is safe for threads and
  for several processes; it still requires `path`.
- `install_signal_handlers`: SIGINT/SIGTERM handlers that exit through normal interpreter
  shutdown (so `with` blocks unwind and `atexit` closes the engine). They chain to the
  handlers that were installed before. Off by default: a library should not take signals.
- `wal_sync_interval_ms`, `auto_compact`: see [Durability](#durability-and-recovery) and
  [Compaction](#compaction).

Every method takes `collection="default"`. Collection names: letters, digits, `-`, `_`
and `.`, not starting with `.`, at most 220 bytes. They are file names inside `path`;
anything that could leave the directory is refused. (A 2.x collection whose existing
name breaks the rule still opens, with a `DeprecationWarning`.)

| Method | Returns | Notes |
|---|---|---|
| `insert(lat, lon, metadata, skip_index=None, collection=)` | `int` id | Ids are assigned in order, never change and are never reused. `skip_index` is accepted and ignored. |
| `insert_batch(points, metadata, skip_index=None, collection=)` | `list[int]` | `points` = `[(lat, lon), ...]`. Atomic: all points or none, also across a crash. One fsync for the batch. |
| `query_radius(lat, lon, radius_meters, filter=None, collection=, limit=None)` | rows | Great-circle (haversine) distance on a sphere of radius 6,371 km. |
| `query_bbox(min_lat, min_lon, max_lat, max_lon, filter=None, collection=, limit=None)` | rows | `min_lon > max_lon` crosses the antimeridian. Longitudes outside ±180 are wrapped, a span ≥ 360° covers everything, latitudes are clamped to ±90. |
| `query_polygon(coordinates, filter=None, collection=, limit=None)` | rows | Vertices are `(longitude, latitude)` (GeoJSON order). Planar containment: split a polygon that crosses the antimeridian. Fewer than 3 vertices returns `[]`. |
| `query(filter=None, limit=None, collection=)` | rows | `None`/`{}` = every point. |
| `exists(filter, collection=)` | `bool` | |
| `count(collection=)` / `len(engine)` | `int` | Live points. |
| `delete_by_metadata(filter, collection=)` | `int` deleted | Refuses filters that would delete everything (see [Deletes](#deletes)). |
| `clear(collection=)` | `int` deleted | Deletes every point. |
| `compact(collection=)` | `int` reclaimed | Reclaims deleted points now (also automatic). Ids do not change. |
| `slot_stats(collection=)` | `(slots, live)` | `slots - live` = deleted points not yet reclaimed. |
| `compaction_errors(collection=)` | `list[str]` | Errors of background compactions. |
| `verify_integrity(collection=, flush=False)` | `{"ok", "errors"}` | Recomputes the CRC32 of every committed region. `flush=True` checkpoints first. |
| `verify_all(flush=False)` | `{collection: report}` | Open collections. |
| `persist_all()` | | Checkpoints every open collection. |
| `list_collections()` | `list[str]` | |
| `close_collection(collection=)` | `bool` | Checkpoints and releases one collection's handle; it reopens on next use. Operations already running on it finish or are retried on the reopened handle. |
| `create_collection(collection)` | `bool` | Only needed for a NEW dotted name over a store upgraded from 2.x (see "Upgrading from 2.x"). |
| `register_2x_alias(collection)` | `None` | Records a 2.x dotted name as an alias of its upgraded stem, so writes through it go to the stem. |
| `close()` | | Stops background work, checkpoints, releases files. Idempotent. Any later call raises `ClosedError`. |

`limit=None` returns every match; spatial queries stop collecting at `limit`. Every read also takes keyword `max_result_bytes`: rows stop being added (before any is built) once their metadata JSON plus 64 bytes per row would exceed it; `leangeo_engine.last_read_truncated()` says whether the last read on the calling thread stopped there. Result order:
spatial queries follow the grid; `query()` returns ascending ids when it returns all
matches. Reads of a collection that does not exist return nothing and do not create it.

Metadata is a dict with string keys and JSON values. Key order is preserved. `date` and
`datetime` values are stored as Unix seconds (a naive datetime is read as UTC). NaN and
infinity are stored as `null`, a tuple as a list, an integer beyond 64 bits as its decimal
text. Other types (sets, bytes, objects) raise `TypeError`.

Exceptions (importable from `leangeo_engine`):

- `InvalidInputError` — bad coordinates, filter, metadata, collection name or limit.
  Subclass of `ValueError` and `RuntimeError` (2.x raised `RuntimeError`).
- `StorageError` — I/O failure, on-disk corruption, a handle poisoned by a failed fsync.
  Subclass of `OSError` and `RuntimeError`.
- `ClosedError` — the engine was closed. Subclass of `RuntimeError`.
- `TypeError` — an unsupported metadata value type.

The native class `leangeo_engine.leangeo.PyGeoDB(path=None, capacity=10000, wal_sync_interval_ms=None, auto_compact=True)`
is one collection; the engine is a directory of them. `leangeo_engine.validate_filter(f)`
checks a filter without a store.

## Filters

LeanGeo implements the filter language shared by the Lean* engines (LeanVec, LeanText):
[docs/filters.md](docs/filters.md). In short:

```python
{"lang": "en", "year": {"$gte": 2020, "$lt": 2025}}        # keys are ANDed
{"$or": [{"a": 1}, {"b": {"$exists": False}}]}
{"tags": "x"}                                               # matches an array containing "x"
{"$nor": [...]}, {"$not": {...}}, {"f": {"$not": {"$gt": 5}}}
```

Operators: `$and $or $nor $not` (top level), `$eq $ne $gt $gte $lt $lte $in $nin $exists $not`
(per field). `null` and a missing field are the same. Numbers compare by value (`1 == 1.0`,
integers exactly beyond 2^53); strings, numbers and booleans never equal one another. An
array matches when one element does; `$ne`/`$nin`/`$not` are the exact negations. The
range operators of one condition form one interval that ONE element must satisfy. A
malformed filter raises `InvalidInputError` instead of matching anything: an unknown
operator, `{}` as a condition, a non-number range bound, a non-boolean `$exists`, NaN or
infinity, an integer past 64 bits.

LeanGeo differs from the shared document in two places, both kept from 2.x:

- An array or object used as an equality value (`{"tags": ["a", "b"]}`,
  `{"addr": {"city": "NYC"}}`, or inside `$eq`/`$ne`/`$in`/`$nin`) compares the whole
  stored value exactly. The shared contract refuses these.
- `id` and `_id` are ordinary metadata fields. The point id is the `id` key of each result
  row, outside `metadata`; there is no filter on it.

Field names are top-level keys: `{"a.b": 1}` names a field called `"a.b"`.

### Deletes

`delete_by_metadata` deletes exactly what the same filter reads, but refuses (raises
`InvalidInputError`, deletes nothing):

- a filter that matches every point whatever the data: `None`, `{}`, `{"$and": []}`,
  `{"f": {"$nin": []}}`, `{"$or": [{}]}`, the negation of a contradiction, ...;
- a filter that matches every point because it tests a field no point has (a misspelled
  name such as `{"stauts": None}`);

Use `clear()` to delete everything. The analysis is the same code LeanVec and LeanText run.

### Indexes

Equality-type operators are answered from an inverted index (roaring bitmaps per field and
value, element-wise for arrays, plus a presence bitmap per field); numeric ranges from a
bit-sliced index. Both are built on the first query that needs them and maintained on
writes. A field with more than 1,000 distinct values keeps only its presence bitmap; its
equality filters scan. Anything an index cannot decide is checked against the stored
JSON. A spatial query with a selective filter starts from the index; otherwise from the
grid.

## Durability and recovery

Each collection has a write-ahead log. A write is appended to the log under the
collection's lock, applied, and then made durable:

- `wal_sync_interval_ms=None` or `0` (default): the call returns after the log record is
  fsynced. Concurrent writers share fsyncs (group commit): with N threads writing, one
  fsync covers everything appended while the previous one ran.
- `wal_sync_interval_ms=N > 0`: the call returns without waiting; a background thread (one
  per process) fsyncs within N ms. A crash (power loss) may lose the last N ms of
  acknowledged writes. A process crash loses nothing: the data is in the page cache.

An `insert_batch` is one logical log record: after a crash it is entirely present or
entirely absent.

Checkpoints commit the log into the data files and reset the log: when the log exceeds
clamp(8 MiB, 5% of the collection, 128 MiB) (`LEANGEO_CHECKPOINT_BYTES` overrides), on
`persist_all()`, `close()` and at interpreter exit. The commit point is the atomic rename
of a small manifest that records the length and CRC32 of every data file. Committed bytes
are never rewritten.

At open, every committed region is verified against its CRC32 and the log is replayed. A
torn last record (a crash during an append: a short frame) is dropped. Damage anywhere
else, including a complete last record that fails its CRC, refuses the open with
`StorageError` instead of serving or silently discarding data. A failed fsync poisons the
handle until reopen; the write that saw it raised, but its record may survive (outcome
unknown: check before retrying). A checkpoint that fails automatically after a successful
write does not fail that write; it is recorded in `compaction_errors()` and retried. Details and what to do: [docs/RECOVERY.md](docs/RECOVERY.md).

## Threads, processes and fork

- Threads: one engine can be shared. Reads run in parallel and release the GIL; writes to
  one collection are serialized. Readers copy result rows out of storage under a short
  lock and build them after releasing it, so a heavy query does not block writers for
  long.
- Processes: any number of processes can open the same directory, with or without
  `thread_safe`. Writes are serialized by an advisory file lock (`flock`; `LockFileEx` on
  Windows). Every write bumps a shared counter (`<collection>.epoch`, memory-mapped); a
  process that sees a new value catches up before its next read or write: it replays the
  new log records, adopts a peer's checkpoint, or reopens after a peer's compaction. A
  writer that crashed without bumping the counter is detected from the log length and the
  manifest's identity.
- `fork()`: a child process reopens persistent collections on first use (it never touches
  the parent's locks, files or threads). An in-memory engine stays readable in the child,
  but writes raise. The low-level `PyGeoDB` raises `StorageError` in a child; open a new one.

`LEANGEO_PROC_LOCK_TIMEOUT_MS` (default 0 = wait forever) bounds the wait for another
process's lock.

## Compaction

A delete only marks points. With `auto_compact=True` (default) a background thread
compacts a collection when deleted points reach both 256 (`LEANGEO_COMPACT_MIN_DELETED`)
and 20% of its slots (`LEANGEO_COMPACT_RATIO`). It is checked after deletes and at open.
`compact()` runs one now.

A compaction copies the live points into a new generation of files while reads and
writes continue: it holds the collection's lock only to start (a snapshot) and to finish
(copy what changed meanwhile, commit by renaming the manifest, swap). Ids do not change.
One compaction runs per collection across all processes. A failure leaves the previous
generation in place, is recorded in `compaction_errors()`, and is retried after a backoff
(1 minute, doubling to 1 hour). `close()` cancels a running compaction.

After a compaction the metadata indexes are rebuilt by the next filtered query (a
background compaction rebuilds them itself).

## Configuration

| Variable | Default | Meaning |
|---|---|---|
| `LEANGEO_CHECKPOINT_BYTES` | clamp(8 MiB, 5% of store, 128 MiB) | Log size that triggers a checkpoint |
| `LEANGEO_COMPACT_MIN_DELETED` | 256 | Deleted points before auto-compaction |
| `LEANGEO_COMPACT_RATIO` | 0.2 | Deleted share of slots before auto-compaction |
| `LEANGEO_PROC_LOCK_TIMEOUT_MS` | 0 (wait) | Cross-process lock wait limit |
| `LEANGEO_MAX_METADATA_BYTES` | 16 MiB (may only be lowered) | Largest metadata document of one point |
| `LEANGEO_MAX_WAL_BYTES` | 16 GiB | Refuse to open a log larger than this |
| `LEANGEO_WAL_FLUSHER_TICK_MS` | 20 | Tick of the bounded-delay flusher thread |
| `LEANGEO_ALLOW_WAL_CORRUPTION` | unset | `1` = salvage a log damaged mid-file by discarding from the damage on (loud) |
| `LEANGEO_FAIL_STAGE`, `LEANGEO_FAIL_MODE` | unset | Fault injection for the crash tests |

Server variables are in [CLIENT.md](CLIENT.md).

## Servers

`leangeo-serve` (REST, FastAPI) and `leangeo-grpc` (gRPC) serve one data directory. They
bind 127.0.0.1 by default; a non-loopback address needs a bearer token
(`LEANGEO_API_TOKEN`), and gRPC also TLS, unless `LEANGEO_ALLOW_INSECURE=1`. Requests are
size-checked before parsing, results are capped by a memory-aware budget, and errors map to
HTTP / gRPC status codes. Endpoints, limits, the Python client (`leangeo_server.client.LeanGeoClient`)
and all settings: [CLIENT.md](CLIENT.md).

The REST check is made on the address each request actually reached, not on settings: a
REST server reached on a non-loopback address without `LEANGEO_API_TOKEN` answers 403
(except `/health`) however it was started (`uvicorn leangeo_server.serve:app --host
0.0.0.0` included). Set `LEANGEO_ALLOW_INSECURE=1` only on a trusted network.

## Limits

- Points per collection: 4,294,967,295 slots (deleted points use slots until compacted).
- Metadata per point: 16 MiB of JSON, nesting depth 100.
- Filters: nesting depth 64.
- Coordinates: latitude in [-90, 90], longitude in [-180, 180], finite. NaN/infinity are
  refused.
- A batch is split into 32 MiB log records internally; there is no batch size limit
  besides memory.

## Performance

Measured on this repository's machine (16 cores, SATA SSD where fsync takes ~1.3 ms),
release 3.0.0 against the published 2.1.12, paired and interleaved, 5 rounds, medians, with
an A/A control (2.1.12 run twice) for the noise floor. Store of 1,000,000 points spread
over Brazil, metadata `{"cat": 1 of 20, "val": int, "name": str, "w": float}`. Script:
[bench/ab_vs_published.py](bench/ab_vs_published.py).

| Workload | 2.1.12 | 3.0.0 | 3.0 / 2.1 | A/A |
|---|---:|---:|---:|---:|
| open + count (1M points) | 569.1 ms | 204.4 ms | 0.36 | 1.01 |
| bbox, small area | 0.015 ms | 0.012 ms | 0.78 | 1.04 |
| bbox, large area (277k hits) | 507.6 ms | 479.0 ms | 0.94 | 1.03 |
| radius 5 km | 0.014 ms | 0.011 ms | 0.81 | 0.99 |
| radius 800 km | 224.3 ms | 196.2 ms | 0.88 | 1.00 |
| polygon, small | 0.015 ms | 0.012 ms | 0.83 | 0.99 |
| polygon, large | 487.4 ms | 453.3 ms | 0.93 | 0.96 |
| first filtered query (builds the index) | 974.2 ms | 937.7 ms | 0.96 | 0.99 |
| filter `{"cat": "c3"}`, limit 100 | 0.843 ms | 0.128 ms | 0.15 | 0.96 |
| filter `{"cat": "c3"}`, all 50k rows | 82.9 ms | 74.2 ms | 0.89 | 1.03 |
| range filter (2k rows) | 15.5 ms | 4.6 ms | 0.29 | 1.03 |
| `exists` (hit / miss) | 0.640 / 0.012 ms | 0.005 / 0.002 ms | 0.01 / 0.13 | 1.03 / 1.00 |
| bbox + filter | 57.5 ms | 43.9 ms | 0.76 | 1.01 |
| radius 50 km + filter | 0.447 ms | 0.110 ms | 0.25 | 1.03 |
| `count()` | 1.0 µs | 0.4 µs | 0.36 | 1.00 |
| single insert, durable (per op) | 2.98 ms | 2.98 ms | 1.00 | 1.05 |
| single insert, in-memory (per op) | 9 µs | 2 µs | 0.25 | 1.00 |
| `insert_batch` 100k points | 602 ms | 441 ms | 0.73 | 0.99 |
| `insert_batch` 1k points | 21.4 ms | 6.3 ms | 0.29 | 1.04 |
| delete 5% (5k of 100k) | 35.2 ms | 13.9 ms | 0.39 | 0.98 |
| delete one point | 22.9 ms | 13.2 ms | 0.58 | 0.99 |
| `compact()` 100k, 25% deleted (15 rounds) | 60.7 ms | 53.7 ms | 0.88 | 1.02 |
| `thread_safe=True`: filtered query | 0.149 ms | 0.062 ms | 0.42 | 0.97 |
| `thread_safe=True`: radius query | 0.076 ms | 0.021 ms | 0.27 | 0.98 |
| `thread_safe=True`: insert (per op) | 6.63 ms | 2.88 ms | 0.43 | 0.91 |
| 4 threads inserting (per op) | 12.3 ms | 1.33 ms | 0.11 | 0.80 |

Ratios below 1 mean 3.0 is faster; the A/A column (2.1.12 against itself) shows how much a
ratio can move by noise alone. Durable single inserts are bound by one fsync (~1.3 ms
here) in both versions; concurrent writers share fsyncs in 3.0. Under a concurrent heavy
reader (tests/test_p7_concurrency.py: 20,000 inserts while another thread runs large
filtered bbox queries) 2.1.12 needs ~96 s and 3.0 ~0.4 s, because 3.0 builds result rows
after releasing the storage lock.

## Upgrading from 2.x

**Stop every 2.x process using a store before opening it with 3.0 (no rolling
upgrades).** A 2.x process that already has the store open does not see 3.0's writes and
would rewrite the manifest in its own format, dropping them; on Linux 3.0 detects such a
process and refuses to upgrade.

3.0 opens 2.x stores in place (including un-checkpointed log records, 2.x tombstones and
compacted generations) and keeps their ids. **Opening a 2.x collection with 3.0 upgrades
it at once**: 3.0 replays the 2.x log, checkpoints, and writes the 3.x manifest before it
appends anything, so a 2.x release never sees a 3.x log record. From then on **2.x refuses
to open the collection** (a fresh 2.x open fails closed). There is no downgrade;
keep a backup if you may need one.

A collection whose name contains a dot and that 3.0 **created** (`x.y` -> files `x.y.*`)
is invisible to 2.x: 2.x looks for `x.*` and, if no store `x` exists there, creates an
empty one instead of refusing. This cannot be prevented from the 3.x side without
breaking a legitimate collection `x`. Do not point 2.x at a directory 3.0 has written to.
Dotted names over a store upgraded from 2.x. 2.x stored a collection `v1.2` as `v1.*`,
so `v1.2` and `v1` were the same data, and nothing on disk says which dotted names were
used. After the upgrade (marker `v1.from2x`):

- **Reads** through any dotted name that has no files of its own (`count("v1.2")`) see
  `v1`, as in 2.x.
- **Writes** through such a name (`insert`, `insert_batch`, `delete_by_metadata`, `clear`,
  `compact`) are allowed only if the name is recorded as a 2.x alias. It is recorded
  automatically when the upgrade happened through that name; otherwise call
  `register_2x_alias("v1.2")`. An unrecorded name raises `InvalidInputError` naming both
  options, so data is never silently split into a new store or wiped through an alias.
- **New** dotted collections there need `create_collection("v1.bak")`, which gives them
  their own files (`v1.bak.*`). `clear("v1.bak")` then only touches `v1.bak`.

`list_collections()` lists an alias once, under the stem. Dotted names over a store 3.x
created have no such rules: they get their own files on first write.

Behaviour changes:

- `delete_by_metadata(None)` / `({})` and other match-everything filters raise
  `InvalidInputError` instead of deleting everything. Use `clear()`.
- Filters follow the shared contract: `{"f": None}` and `{"f": {"$ne": ...}}` treat null and
  missing alike; `1` equals `1.0`; `{"tags": "x"}` matches arrays containing `"x"`; range
  bounds must be numbers (2.x matched nothing for `{"f": {"$gt": "a"}}`; 3.0 raises);
  `{"f": {}}`, NaN operands and unknown operators raise. New: `$nor`, `$exists`,
  field-level `$not`, `$in` with a single value.
- Ids no longer change on compaction (2.x renumbered them).
- Invalid query coordinates raise `InvalidInputError` (NaN, `min_lat > max_lat`, a negative
  radius, polygon vertices outside the valid range). Bounding-box longitudes outside ±180
  are wrapped (2.x silently missed points).
- Radius queries no longer miss points in the outer 0.11% of the radius.
- Collection names are validated (no path separators or traversal). A dotted name gets its
  own files (2.x shared them with the name before the dot; existing 2.x data stays where
  it is).
- Calling a method after `close()` raises `ClosedError` (2.x silently reopened).
- Polygons over gRPC and the Python client use `(longitude, latitude)` like the library
  (the 2.x gRPC server swapped the axes). See [CLIENT.md](CLIENT.md).
- `skip_index` is ignored (it was in 2.x as well).
- Servers: the default bind is `127.0.0.1` (2.x: `0.0.0.0`). A non-loopback bind needs a
  bearer token (`LEANGEO_API_TOKEN`) or an explicit `LEANGEO_ALLOW_INSECURE=1`; gRPC on a
  non-loopback address also needs TLS. REST rejects unknown fields and query parameters
  with 422, and uses 413 (body too large), 429 (over capacity), 500 (storage error) and
  503 (unavailable) where 2.x answered 400 to every error. `/insert_batch` is one atomic
  write. See [CLIENT.md](CLIENT.md).
- `start_time`, `last_access_time`, `collection_locks`, `version_trackers` and
  `local_versions` still exist on the engine for code that reads them, but 3.x does not
  use them (the maps stay empty): locking and change detection are native.
- `limit` accepts any non-negative int (a value past 64 bits means no limit); a negative
  or non-int limit raises `InvalidInputError`.
- The gRPC extra (`leangeo[grpc]`) needs Python 3.10 or later (grpcio 1.82, protobuf 7);
  the library and the REST server support Python 3.8+.
- Metadata keys keep their insertion order in results.

## Caveats

- Polygon containment is planar in longitude/latitude, not geodesic.
- Radius queries use a spherical Earth (6,371 km); the error against WGS84 is up to ~0.5%.
- There is no nearest-neighbour or sort-by-distance query, and no stored geometry other
  than points.
- Windows: cross-process locking uses `LockFileEx` through `fs2`; the full test suite runs
  on Linux only.
- An in-memory engine (`path=None`) uses temporary files in the system temp directory.

## Development

```bash
python -m venv .venv && . .venv/bin/activate
pip install maturin && maturin develop --release
pip install pytest psutil fastapi "uvicorn[standard]" httpx "grpcio>=1.82.1" "protobuf>=7.35,<8"
cargo test --release
cd /tmp && python -m pytest /path/to/LeanGeo/tests          # run from outside the checkout
LEANGEO_PUBLISHED_PYTHON=/path/to/venv-with-leangeo-2.1.12/bin/python python -m pytest ...  # + format compatibility
python scripts/gen_grpc.py --check                         # stubs (grpcio-tools==1.82.1)
```

Benchmarks are in `bench/`, ad-hoc diagnostic scripts in `scripts/diagnostics/`; neither
is collected by pytest.

## License

MIT

