Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
5296c5d
Read the HTTP contract from the spec, not the server's minor version
ragnorc Nov 25, 2026
87e6b51
Pin omnigraph-server 0.15.0
ragnorc Nov 25, 2026
f43005b
Recognize not_admitted as NotAdmittedError
ragnorc Nov 25, 2026
e1f92dd
Add branches.list_detailed() for GET /branches?detailed=true
ragnorc Nov 25, 2026
2612566
Pass request settings and expose 0.15 read, access and error fields
ragnorc Nov 25, 2026
67f41cc
Test 0.15 features live; document them; add CHANGELOG for 0.15.0
ragnorc Nov 25, 2026
0d63c8d
Keep a server-sent outcome_unknown on every route
ragnorc Nov 25, 2026
a3b2254
Pin omnigraph-server 0.16.0
ragnorc Nov 25, 2026
965f29c
Recognize writer_fenced as WriterFencedError
ragnorc Nov 25, 2026
96b7163
Add og.operations for recorded optimize runs
ragnorc Nov 25, 2026
0a7c8e2
Treat a dry-run merge as a read when its answer is lost
ragnorc Nov 25, 2026
71902d6
Run the live suite against omnigraph-server 0.16.0
ragnorc Nov 25, 2026
4bd5891
Document 0.16 operations, errors and dry runs; add CHANGELOG for 0.16.0
ragnorc Nov 25, 2026
0fce896
Refuse one string as optimize datasets instead of splitting it
ragnorc Nov 25, 2026
3d50a33
Accept only a receipt for the submitted operation
ragnorc Nov 25, 2026
2ccd850
Document operation limits and tracing; name outcomes per dataset
ragnorc Nov 25, 2026
2cd0f75
Require dataset outcomes and cancel an active run live
ragnorc Nov 25, 2026
8f9fc8d
Record the 0.16 receipt, cancel and merge-limit changes in the changelog
ragnorc Nov 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@ for names and shapes.
- The server version lives in `pyproject.toml` `[tool.omnigraph] server-version`. Bumping it:
`scripts/sync_spec.py`, then `scripts/generate.py`, then run the e2e suite against that
release's binaries.
- Versioning: the package's major.minor equals the server's contract (`generate.py --check`
enforces it); bump the patch for an SDK-only fix, the minor only with `server-version`.
- Versioning: the package's major.minor equals the pinned server release's
(`generate.py --check` enforces it); bump the patch for an SDK-only fix, the minor only with
`server-version`. The `Omnigraph-Http-Api` contract is read from the spec, never derived
from the version: servers 0.14 to 0.16 all speak contract 0.14.
- `src/omnigraph/_models.py` and `_version.py` are generated; never edit them by hand.
`scripts/generate.py --check` must pass.
- Public results are the generated `TypedDict`s; do not rename wire fields.
- Public results are the generated `TypedDict`s; do not rename wire fields. Where the spec
leaves an object open (the recorded-operation record), `_operations.py` types it by hand
with the wire names.
- Never add automatic retries. A lost write response is `outcome_unknown`, not a retry signal.
- Runtime dependency: `httpx` only.
- Checks: `uv run pytest`, `uv run mypy`, `uv run ruff check .`, `uv run ruff format --check .`;
Expand Down
94 changes: 94 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Changelog

The package's major.minor follows the `omnigraph-server` release it is generated from; the
patch number is the SDK's own. Every release so far speaks HTTP contract 0.14.

## 0.16.0

Generated from and tested against `omnigraph-server` 0.16.0, which still speaks HTTP contract
0.14. The additions below need server 0.16.

### Added

- `og.operations` for recorded operations: `optimize(operation_id, datasets=...,
max_gate_hold_ms=...)`, `get`, `cancel`, and `wait`, which polls the lookup until the record
is terminal. The caller mints the id with `new_operation_id()` and keeps it before
submitting; `optimize` never mints one. `is_terminal()`
and `TERMINAL_STATES` name the final states. `Operation`, `OperationResult`,
`OptimizeOutcome` and `DatasetOutcome` type the record.
- `WriterFencedError`, a `ConflictError`, for the new `writer_fenced` code, with
`writer_fenced` (`current`, `held`, `read` epochs). A refused write is not `outcome_unknown`.
- Types for the `maintain` access action and `WriterFencedOutput`.

### Fixed

- Every operation route accepts only a receipt for the id it was given: a lookup envelope
whose `found` record names that id, or `unknown` where the route can answer it (lookup and
cancel). Anything else raises `ApiContractError`, `outcome_unknown` after a submission or
cancellation. Before, `{}` under HTTP 200 counted as an accepted operation.
- `optimize(datasets="node:Person")` raises `TypeError` instead of sending one key per
character.

### Changed

- A `branches.merge(dry_run=True)` whose answer is lost is no longer `outcome_unknown`: a dry
run is a read, as the 0.16 CLI now reports it. A reply that contradicts the dry run still is.

### Server changes that affect callers

- A graph with no applied policy refuses reads (`ForbiddenError`) unless the server sets
`OMNIGRAPH_ALLOW_READS_WITHOUT_POLICY=1`.
- A request setting above the server's resource budget is refused with `BadRequestError`.
- A conditional mutation that loses a race fails with `PreconditionFailedError`, not a `@card`
violation.
- A Blob write on a recreated branch fails with `ConflictError.read_set_conflict`; an update,
delete or overwrite load overtaken by another commit reruns instead of failing.
- Deployment routes answer a failed control-state read with 503 (retry) or 500, with
`effects: none`, instead of 409.
- A recorded-operation lookup can answer 500 `outcome_unknown` when a settlement write it made
has no definite answer; it is `outcome_unknown`, and retrying the lookup is safe. `cancel`
is best effort and returns a `publishing` operation unchanged.
- A merge refused by its validation limit names the resource
`branch-merge retained validation key bytes` (it was `… delta bytes`) and counts only the
delta's keys. `PayloadTooLargeError.resource_limit` already carries the new name; match on
the code, not the name.

## 0.15.0

Generated from and tested against `omnigraph-server` 0.15.0. Works with any server that
speaks HTTP contract 0.14; the additions below need server 0.15.

### Fixed

- The `Omnigraph-Http-Api` header is read from the server's OpenAPI document instead of being
derived from the server's minor version. Server 0.15 still speaks contract 0.14, so deriving
it would have sent `0.15` and failed every request with `api_contract_mismatch`.
- An error reply that says a write may have taken effect sets `outcome_unknown` on every
route, reads included: code `outcome_unknown` always (whatever its disposition reads), and
otherwise effects `unknown` or `partial`. Before, a GET could never be `outcome_unknown`.

### Added

- `branches.list_detailed()` (`GET /branches?detailed=true`): each readable branch's head,
start (`from`, `from_commit_id`), `created_at` and `updated_at`.
- `NotAdmittedError`, a `ForbiddenError`, for the new `not_admitted` code: a valid OIDC token
whose subject the server does not admit. A refused write is not `outcome_unknown`.
- `settings=` on `query`, `mutate` and `branches.merge`, including the new `change_lineage`
setting.
- Types for `ReadOutput.ranking` (`RankingOutput`, `SearchFunction`, `RankOrder`),
`AccessOutput.client_id` and `LoadSliceExecutedOutput.read_ns`.
- Error detail properties matching the TypeScript SDK: `ConflictError.read_set_conflict`,
`.published_dataset_version_conflict`, `.change_diff_refusal`,
`.full_text_index_rebuild_required`; `GoneError.change_feed_gap`;
`RangeNotSatisfiableError.blob_range`; `FailedDependencyError.external_blob_source`;
`ServiceUnavailableError.recovery_required`.

### Changed

- An error's class is chosen by one rule: the status picks the class, and the code's class
replaces it when it is a subclass of it.
- `U64` parameters above `i64::MAX` now bind on the server; Python sends them exactly.

## 0.14.0

First release, for `omnigraph-server` 0.14.
119 changes: 111 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# omnigraph

Async Python client for the [Omnigraph](https://github.com/ModernRelay/omnigraph) HTTP API,
contract **0.14**. It mirrors the TypeScript SDK
generated from `omnigraph-server` **0.16.0** (HTTP contract **0.14**). It mirrors the TypeScript SDK
[`@modernrelay/omnigraph`](https://github.com/ModernRelay/omnigraph-ts): the same routes, the
same contract checks, and the same error model, with Python names.

Expand Down Expand Up @@ -33,11 +33,16 @@ never retries.

## Versions

The package's major.minor is the HTTP contract it speaks: `omnigraph` 0.14.x talks to
`omnigraph-server` 0.14.x and refuses any other contract. The patch number is the SDK's own,
for fixes that change nothing on the wire, so `omnigraph` 0.14.1 does not mean server 0.14.1.
Upgrade the server and this package together when the minor changes, and pin
`omnigraph>=0.14,<0.15` to follow SDK fixes for one contract.
The package's major.minor is the `omnigraph-server` release it is generated from and tested
against: `omnigraph` 0.14.x is built from server 0.14. The patch number is the SDK's own, for
fixes that change nothing on the wire, so `omnigraph` 0.14.1 does not mean server 0.14.1.
`SERVER_VERSION` names the exact server release.

The HTTP contract is a separate, slower-moving number: `HTTP_API_CONTRACT` is read from the
pinned server's OpenAPI document, and the client refuses a server that speaks another one.
Server releases that keep the wire contract keep its value, so a newer server on the same
contract accepts this client; routes and fields added in a later release need that release.
Pin `omnigraph>=0.14,<0.15` to follow SDK fixes for one server minor.

## Write and verify

Expand All @@ -63,6 +68,30 @@ merged = await og.branches.merge("review", delete_branch=True)
Merge and mutation receipts are validated; a receipt that does not name the requested
operation raises `ApiContractError`.

`og.branches.list_detailed()` adds `details` to the listing: for each branch the credential
may read, its head commit, the branch and commit it started from, and when it was created and
last moved (server 0.15+).

## Ranked reads, settings, and parameters

A read ordered by `nearest`, `bm25` or `rrf()` reports how it ranked its rows:

```python
read = await og.query(
"query near($v: Vector(2)) { match { $s: Spot } return { $s.slug, nearest($s.at, $v) as dist } "
"order { nearest($s.at, $v) } limit 10 }",
params={"v": [0.1, 0.2]},
)
read[
"ranking"
] # {"by": "nearest", "order": "ascending", "exhaustive": True, "score_columns": ["dist"]}
```

`query`, `mutate` and `branches.merge` take `settings`, the request's session settings (for
example `{"change_lineage": "verify"}`). A resource budget above the server's ceiling is refused
with `BadRequestError`. A `U64` parameter carries its whole range, up to `2**64 - 1`; Python
integers are sent exactly.

## Streams, loads, feeds, and blobs

```python
Expand All @@ -83,14 +112,88 @@ await og.queries.invoke("people", params={"name": "Ada"})
Ordinary JSON requests are limited to 1 MiB by the server; bulk loads go through
`load_ndjson`.

## Recorded operations

A cluster server started with `OMNIGRAPH_OPERATION_ROUTES=true` runs `optimize` on a graph's
`main` while it serves, as a recorded operation tracked by an id the caller chose (server
0.16+; every route needs the `maintain` action on `main`):

```python
from omnigraph import new_operation_id

op_id = new_operation_id() # keep it: after a lost response, look it up, never resubmit
await og.operations.optimize(op_id, datasets=["node:Person"], max_gate_hold_ms=30_000)
# A timeout ends the wait, not the run: it keeps going on the server.
async with asyncio.timeout(600):
done = await og.operations.wait(op_id)
operation = done.get("operation")
if done["lookup"] == "unknown" or operation is None:
... # the record no longer holds the id; never resubmit the same work under it
elif operation["state"] == "succeeded":
for dataset in operation["outcome"].get("datasets", []):
print(dataset["type_key"], dataset["outcome"], dataset.get("reason"))
```

`get` and `wait` answer `lookup: "unknown"` for an id the record does not hold; that does not
prove the operation never ran. Resubmitting an id returns its record only while the server's
record still holds it (the 32 newest terminal operations) and the request is the same; an
evicted id is refused as expired. Every reply must be a receipt for the id, or the call raises
`ApiContractError`. `wait` polls only the lookup and lets any error end the wait; retrying a
lookup is always safe, a 500 `outcome_unknown` included (a lookup can settle a publication in
doubt). `cancel` is best effort: an `accepted` or `running` run may still end `succeeded`
(with a late-cancellation `reason`, or with none when the cancel lands as the run finishes on
server 0.16.0), and a `publishing` run is returned unchanged. Only `cancelled` means it
stopped.
A succeeded run may still have deferred or failed datasets: read
`operation["outcome"]["datasets"]`. The record's types (`Operation`, `OperationResult`) are
written by hand from the server's record, which the OpenAPI document leaves open.

A merge with `dry_run=True` is a read: a lost answer is not `outcome_unknown`, while a reply
that contradicts the dry run is.

## Tracing

The server reads W3C `traceparent` and `tracestate`. The client takes an
`httpx.AsyncBaseTransport`, so add the headers with one that wraps the default:

```python
class Traced(httpx.AsyncBaseTransport):
def __init__(self, inner: httpx.AsyncBaseTransport) -> None:
self._inner = inner

async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
request.headers["traceparent"] = current_traceparent() # from your tracer
return await self._inner.handle_async_request(request)

async def aclose(self) -> None:
await self._inner.aclose()


og = Omnigraph(
url, graph_id="g", token=TOKEN, transport=Traced(httpx.AsyncHTTPTransport())
)
```

## Errors

Every error is an `OmnigraphError` subclass chosen by status and `code` (`ConflictError`,
`PreconditionFailedError`, `PayloadTooLargeError`, `GraphUnavailableError`, ...). Each carries:

- `disposition`: the server's `effects` (`none`, `partial`, `unknown`) and next `action`;
- `request_dispatched`: whether the request may have reached the server;
- `outcome_unknown`: a write may have taken effect — reconcile before retrying.
- `outcome_unknown`: a write may have taken effect — reconcile before retrying. The server's
word decides on any route, reads included; only a reply without one falls back to the route.

A code's class refines its status's: `NotAdmittedError` is the `ForbiddenError` for an OIDC
identity the server does not admit (signing in again will not help; the operator must admit
it), and `GraphUnavailableError` is the `ServiceUnavailableError` for a graph that is not
served. `WriterFencedError` is the `ConflictError` for a branch another process claimed
(`writer_fenced` names the epochs; nothing was written). Error details are properties: `ConflictError.merge_conflicts`, `.key_conflict`,
`.read_set_conflict`, `PreconditionFailedError.precondition_failure`,
`PayloadTooLargeError.resource_limit`, `GoneError.change_feed_gap`, and so on.

A graph with no applied policy refuses every action, reads included, with `ForbiddenError`
(server 0.16; `OMNIGRAPH_ALLOW_READS_WITHOUT_POLICY=1` restores reads for static tokens).

The token never appears in a `repr` or an error message.

Expand All @@ -105,7 +208,7 @@ Bundles are opaque here, as in the TypeScript SDK; for operator work use
```sh
uv sync
uv run pytest # unit tests (mocked transport)
OMNIGRAPH_TEST_SERVER=1 OMNIGRAPH_BIN_DIR=/path/to/v0.14.0 uv run pytest tests/test_e2e.py
OMNIGRAPH_TEST_SERVER=1 OMNIGRAPH_BIN_DIR=/path/to/v0.16.0 uv run pytest tests/test_e2e.py
uv run python scripts/generate.py --check # generated files match spec/openapi.json
uv run mypy && uv run ruff check . && uv run ruff format --check .
```
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "omnigraph"
version = "0.14.0"
version = "0.16.0"
description = "Python client for the Omnigraph HTTP API"
readme = "README.md"
license = "MIT"
Expand All @@ -21,7 +21,7 @@ Issues = "https://github.com/ModernRelay/omnigraph/issues"
[tool.omnigraph]
# The server release this SDK is generated from and tested against. The SDK
# minor tracks the server minor; `spec/openapi.json` is that release's file.
server-version = "0.14.0"
server-version = "0.16.0"

[dependency-groups]
dev = [
Expand Down
38 changes: 30 additions & 8 deletions scripts/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
MODELS = ROOT / "src" / "omnigraph" / "_models.py"
VERSION = ROOT / "src" / "omnigraph" / "_version.py"

HEADER_NAME = "Omnigraph-Http-Api"

HEADER = '''\
"""Wire models generated from spec/openapi.json. Do not edit by hand.

Expand All @@ -37,13 +39,32 @@ def server_version() -> str:
return str(_pyproject()["tool"]["omnigraph"]["server-version"])


def check_package_version(contract: str) -> None:
"""The package's major.minor is the HTTP contract it speaks; its patch
number is the SDK's own, for fixes that change nothing on the wire."""
def check_package_version(release: str) -> None:
"""The package's major.minor is the server release it is generated from;
its patch number is the SDK's own, for fixes that change nothing on the
wire."""
version = str(_pyproject()["project"]["version"])
m = re.match(r"(\d+)\.(\d+)", version)
if m is None or f"{m.group(1)}.{m.group(2)}" != contract:
sys.exit(f"package version {version} must start with contract {contract}")
if m is None or f"{m.group(1)}.{m.group(2)}" != release:
sys.exit(f"package version {version} must start with server {release}")


def http_api_contract(spec: dict[str, Any]) -> str:
"""The `Omnigraph-Http-Api` value the spec requires: the one enum value of
that header parameter, the same on every operation that declares it. A
server release does not change it unless the wire contract changes, so it
is read here, never derived from the release number."""
values: set[tuple[str, ...]] = set()
for item in spec["paths"].values():
for op in item.values():
if not isinstance(op, dict):
continue
for param in op.get("parameters", []):
if param.get("in") == "header" and param.get("name") == HEADER_NAME:
values.add(tuple(param["schema"]["enum"]))
if len(values) != 1 or len(next(iter(values))) != 1:
sys.exit(f"spec must require one {HEADER_NAME} value, found {sorted(values)}")
return next(iter(values))[0]


def render_models() -> str:
Expand Down Expand Up @@ -80,7 +101,8 @@ def render_models() -> str:


def render_version() -> str:
spec_version = json.loads(SPEC.read_text())["info"]["version"]
spec = json.loads(SPEC.read_text())
spec_version = spec["info"]["version"]
pinned = server_version()
if spec_version != pinned:
sys.exit(f"spec/openapi.json is {spec_version}, pyproject pins {pinned}")
Expand All @@ -89,8 +111,8 @@ def render_version() -> str:
return (
'"""Generated by scripts/generate.py. Do not edit by hand."""\n\n'
f'SERVER_VERSION = "{pinned}"\n'
f'HTTP_API_CONTRACT = "{major}.{minor}"\n'
'HTTP_API_CONTRACT_HEADER = "Omnigraph-Http-Api"\n'
f'HTTP_API_CONTRACT = "{http_api_contract(spec)}"\n'
f'HTTP_API_CONTRACT_HEADER = "{HEADER_NAME}"\n'
)


Expand Down
Loading
Loading