diff --git a/AGENTS.md b/AGENTS.md index 9b4f891..7e182ea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 .`; diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4c7be91 --- /dev/null +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index c87211e..fe13733 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 @@ -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 @@ -83,6 +112,68 @@ 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`, @@ -90,7 +181,19 @@ Every error is an `OmnigraphError` subclass chosen by status and `code` (`Confli - `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. @@ -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 . ``` diff --git a/pyproject.toml b/pyproject.toml index 2c17272..3888f8b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" @@ -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 = [ diff --git a/scripts/generate.py b/scripts/generate.py index 729b415..6a5e73e 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -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. @@ -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: @@ -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}") @@ -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' ) diff --git a/spec/openapi.json b/spec/openapi.json index 628cb10..ac26ab1 100644 --- a/spec/openapi.json +++ b/spec/openapi.json @@ -7,7 +7,7 @@ "name": "MIT", "identifier": "MIT" }, - "version": "0.14.0" + "version": "0.16.0" }, "paths": { "/.well-known/oauth-protected-resource": { @@ -232,6 +232,27 @@ } } }, + "409": { + "description": "Conflict (code `conflict`), for example a cluster control object whose stored text is corrupt: an applied policy payload that does not match its recorded digest, or a state file that is not valid cluster state; restore the object from a trusted copy. Its bytes failing to decode as text answer 500 instead", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, "412": { "description": "actor_mismatch when Omnigraph-If-Actor names another actor than the credential resolves to", "headers": { @@ -281,7 +302,7 @@ } }, "500": { - "description": "Internal failure (code `internal`) while evaluating deployment access", + "description": "Internal failure (code `internal`) while evaluating deployment access, or a storage read of a cluster control object (the state file, its lock or a catalog payload) that fails the same way on every read, such as bytes that are not text (`effects: none`)", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -302,7 +323,7 @@ } }, "503": { - "description": "Deployment ownership changed during the bounded ledger observation; retry this GET within the caller deadline; graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", + "description": "Deployment ownership changed during the bounded ledger observation; retry this GET within the caller deadline. Also a storage read of a cluster control object (the state file, its lock or a catalog payload) that failed temporarily or for an unknown reason (`effects: none`; retry); graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -555,7 +576,7 @@ } }, "409": { - "description": "", + "description": "Conflict (code `conflict`), including a cluster control object whose stored text is corrupt: a catalog payload that does not match its recorded digest, or a state file that is not valid cluster state; restore the object from a trusted copy. Its bytes failing to decode as text answer 500 instead", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -666,7 +687,7 @@ } }, "500": { - "description": "Internal failure (code `internal`), or unsettled deployment completion (code `outcome_unknown`); reconcile the original deployment identity before submitting another deployment", + "description": "Internal failure (code `internal`), or unsettled deployment completion (code `outcome_unknown`); reconcile the original deployment identity before submitting another deployment. Also, before any effect, a storage read of a cluster control object (the state file, its lock or a catalog payload) that fails the same way on every read, such as bytes that are not text (`effects: none`)", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -687,7 +708,7 @@ } }, "503": { - "description": "; graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", + "description": "Nothing changed: before any effect, a storage read of a cluster control object (the state file, its lock or a catalog payload) that failed temporarily or for an unknown reason (`effects: none`; retry); graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -898,6 +919,27 @@ } } }, + "409": { + "description": "Conflict (code `conflict`), for example a cluster control object whose stored text is corrupt: an applied policy payload that does not match its recorded digest, or a state file that is not valid cluster state; restore the object from a trusted copy. Its bytes failing to decode as text answer 500 instead", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, "412": { "description": "actor_mismatch when Omnigraph-If-Actor names another actor than the credential resolves to", "headers": { @@ -946,8 +988,29 @@ } } }, + "500": { + "description": "Internal failure (code `internal`), or a storage read of a cluster control object (the state file, its lock or a catalog payload) that fails the same way on every read, such as bytes that are not text (`effects: none`)", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, "503": { - "description": "Deployment ownership changed during the bounded ledger observation; retry this GET within the caller deadline; graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", + "description": "Deployment ownership changed during the bounded ledger observation; retry this GET within the caller deadline. Also a storage read of a cluster control object (the state file, its lock or a catalog payload) that failed temporarily or for an unknown reason (`effects: none`; retry); graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -1181,7 +1244,7 @@ } }, "409": { - "description": "", + "description": "Conflict (code `conflict`), including a cluster control object whose stored text is corrupt: a catalog payload that does not match its recorded digest, or a state file that is not valid cluster state; restore the object from a trusted copy. Its bytes failing to decode as text answer 500 instead", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -1292,7 +1355,7 @@ } }, "500": { - "description": "Internal failure (code `internal`) while evaluating deployment access or planning", + "description": "Internal failure (code `internal`) while evaluating deployment access or planning, or a storage read of a cluster control object (the state file, its lock or a catalog payload) that fails the same way on every read, such as bytes that are not text (`effects: none`)", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -1313,7 +1376,7 @@ } }, "503": { - "description": "graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", + "description": "Nothing was planned: a storage read of a cluster control object (the state file, its lock or a catalog payload) that failed temporarily or for an unknown reason (`effects: none`; retry); graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -3937,7 +4000,7 @@ "branches" ], "summary": "List all branches.", - "description": "Returns branch names sorted by name in byte order. Read-only. The GQ statement\n`branch list` on `POST /query` runs the same body.", + "description": "Returns branch names sorted by name in byte order. Read-only. The GQ statement\n`branch list` on `POST /query` runs the same body.\n\n`detailed=true` adds `details`: for each branch the caller may `read`, its\nhead commit, the branch and commit it started from, when it was created,\nand when it last moved. Each listed branch costs a read of its latest\nversion, and of the version it was created from once it has written a\ncommit; no commit history is read.", "operationId": "branchList", "parameters": [ { @@ -3949,6 +4012,15 @@ "type": "string" } }, + { + "name": "detailed", + "in": "query", + "description": "`true` adds `details`: each branch's head, the branch and commit it\nstarted from, when it was created, and when it last moved. Defaults\nto `false`. Reads each listed branch's latest version, and the version\nit was created from once it has written a commit, never its commit\nhistory; the names alone read neither.", + "required": false, + "schema": { + "type": "boolean" + } + }, { "name": "Omnigraph-Http-Api", "in": "header", @@ -3994,7 +4066,7 @@ } }, "400": { - "description": "api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", + "description": "Invalid `detailed`; api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -10713,14 +10785,13 @@ ] } }, - "/graphs/{graph_id}/queries": { - "get": { + "/graphs/{graph_id}/operations/optimize": { + "post": { "tags": [ - "queries" + "operations" ], - "summary": "List the graph's exposed stored queries as a typed tool catalog.", - "description": "Returns every stored query in the `queries:` registry, each\nwith its MCP tool name, read/mutate flag, description/instruction, and\ntyped parameters — enough for a client to register them as tools without\nfetching `.gq` source. Cluster-served graphs have no per-query expose flag,\nso the catalog lists them all. Read-gated; the catalog is graph-wide (branch\nindependent — `read` is authorized against `main`). **Not** Cedar-filtered\nper query yet, so it can list a query whose `invoke_query` the caller\nlacks (a known gap until per-query authorization lands).", - "operationId": "queriesList", + "summary": "Submit a recorded optimize run on the graph's main branch.", + "operationId": "startOptimize", "parameters": [ { "name": "graph_id", @@ -10753,9 +10824,19 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StartOptimizeRequest" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "Stored-query catalog (every stored query, with typed params)", + "description": "The operation is terminal", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -10770,13 +10851,34 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/QueriesCatalogOutput" + "$ref": "#/components/schemas/OperationOutput" + } + } + } + }, + "202": { + "description": "Durably accepted, or still running; look it up by its id until it is terminal", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OperationOutput" } } } }, "400": { - "description": "api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", + "description": "A non-canonical operation_id, or a max_gate_hold_ms above this server's ceiling; api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -10797,7 +10899,7 @@ } }, "401": { - "description": "Unauthorized; unauthorized when no bearer credential is presented or the server refuses it", + "description": "unauthorized when no bearer credential is presented or the server refuses it", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -10824,7 +10926,7 @@ } }, "403": { - "description": "Forbidden", + "description": "", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -10892,6 +10994,48 @@ } } }, + "408": { + "description": "request_timeout when the request body deadline passes before operation admission", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "409": { + "description": "Conflict (code `conflict`): the same id with a different request (`[operation_request_mismatch]`), an id at or before the eviction mark (`[operation_id_expired]`), an outstanding deployment, four unresolved publications, a record from another ledger (`[operation_record_foreign]`), or a state file or operation record whose stored text is corrupt (`[invalid_state_json]`, `[operation_record_invalid]`; bytes that are not text answer 500)", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, "412": { "description": "actor_mismatch when Omnigraph-If-Actor names another actor than the credential resolves to", "headers": { @@ -10913,8 +11057,29 @@ } } }, + "413": { + "description": "payload_too_large when the request body exceeds its route limit before operation admission", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, "429": { - "description": "too_many_requests when server observer, ingress or operation admission capacity is exhausted; honor Retry-After", + "description": "Another operation is active in the maintenance scope, or that scope's admission gate is held across an acceptance; honor `Retry-After`; too_many_requests when server observer, ingress or operation admission capacity is exhausted; honor Retry-After", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -10941,7 +11106,7 @@ } }, "500": { - "description": "Internal failure (code `internal`) before a successful response", + "description": "Internal failure (code `internal`), including a storage read of the cluster state, its lock or the operation record that fails the same way on every read (nothing was accepted), or a record write with no definite answer (code `outcome_unknown`); look the operation up by its id", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -10962,7 +11127,7 @@ } }, "503": { - "description": "graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", + "description": "The routes are not enabled, admission is closed, a storage read of the cluster state, its lock or the operation record failed temporarily or for an unknown reason, or the operation record write was refused; nothing was accepted (a refusal naming an earlier request of unknown outcome clears once a read sees the record change, or, for an unconditional write or a create whose record never appeared, when the server restarts); graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -10996,14 +11161,13 @@ ] } }, - "/graphs/{graph_id}/queries/{query_name}": { - "post": { + "/graphs/{graph_id}/operations/{operation_id}": { + "get": { "tags": [ - "queries" + "operations" ], - "summary": "Invoke a curated, server-side stored query by name.", - "description": "The query source comes from the graph's `queries:` registry, not the\nrequest body — callers send only runtime inputs (`params`, `branch`,\n`snapshot`). Gated by the `invoke_query` Cedar action at the boundary;\na stored *mutation* additionally passes the engine's `change` gate\n(double-gated). An actor **without** `invoke_query` cannot tell a denied\nquery from a missing one — both return the same 404, so the catalog\ncan't be probed without the grant. Once `invoke_query` is held, the\ninner `read`/`change` gate may surface a 403 for an existing query the\nactor can't run (the intended double-gate signal).", - "operationId": "queryInvoke", + "summary": "Look a recorded operation up by its original id, whatever its kind.", + "operationId": "getOperation", "parameters": [ { "name": "graph_id", @@ -11015,9 +11179,9 @@ } }, { - "name": "query_name", + "name": "operation_id", "in": "path", - "description": "Stored query name (the registry key)", + "description": "The id the caller submitted", "required": true, "schema": { "type": "string" @@ -11045,25 +11209,9 @@ } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "oneOf": [ - { - "type": "null" - }, - { - "$ref": "#/components/schemas/InvokeStoredQueryRequest" - } - ] - } - } - } - }, "responses": { "200": { - "description": "Read envelope (ReadOutput) or mutation envelope (ChangeOutput), serialized untagged", + "description": "The operation's record, or `lookup: unknown`", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11078,13 +11226,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/InvokeStoredQueryOutput" + "$ref": "#/components/schemas/OperationOutput" } } } }, "400": { - "description": "Bad request (param type error; snapshot on a stored mutation); api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", + "description": "api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11105,7 +11253,7 @@ } }, "401": { - "description": "Unauthorized; unauthorized when no bearer credential is presented or the server refuses it", + "description": "unauthorized when no bearer credential is presented or the server refuses it", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11132,7 +11280,7 @@ } }, "403": { - "description": "Forbidden (the inner `change` gate for a stored mutation)", + "description": "", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11153,7 +11301,7 @@ } }, "404": { - "description": "Unknown stored query, or `invoke_query` denied — indistinguishable to a caller without the grant; not_found when no graph `graph_id` is served or the caller may not see it, or when no route serves the path", + "description": "not_found when no graph `graph_id` is served or the caller may not see it, or when no route serves the path", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11200,29 +11348,8 @@ } } }, - "408": { - "description": "request_timeout when the request body deadline passes before operation admission", - "headers": { - "Omnigraph-Http-Api": { - "schema": { - "type": "string", - "enum": [ - "0.14" - ] - }, - "description": "Supported OmniGraph HTTP API contract." - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorOutput" - } - } - } - }, "409": { - "description": "Stored mutation write-authority conflict, or a full-text index requires explicit rebuilding (full_text_index_rebuild_required) or has no segment at the snapshot (full_text_index_required); neither is cleared by retrying", + "description": "Conflict (code `conflict`): a record from another ledger at this root, the record changed during resolution, or a state file or operation record whose stored text is corrupt (`[invalid_state_json]`, `[operation_record_invalid]`; bytes that are not text answer 500)", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11263,8 +11390,8 @@ } } }, - "413": { - "description": "Stored keyed mutation exceeds the per-commit entity or byte ceiling; payload_too_large when the request body exceeds its route limit before operation admission", + "429": { + "description": "too_many_requests when server observer, ingress or operation admission capacity is exhausted; honor Retry-After", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11274,6 +11401,12 @@ ] }, "description": "Supported OmniGraph HTTP API contract." + }, + "Retry-After": { + "schema": { + "type": "string" + }, + "description": "Minimum delay before a caller-bounded retry of this refused request; not a scheduled server retry." } }, "content": { @@ -11284,8 +11417,8 @@ } } }, - "424": { - "description": "A stored mutation could not probe or read an allowed external Blob source", + "500": { + "description": "Internal failure (code `internal`), including a storage read of the cluster state, its lock or the operation record that fails the same way on every read (nothing changed), or a resolution write with no definite answer (code `outcome_unknown`); retry the lookup", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11305,8 +11438,8 @@ } } }, - "429": { - "description": "Per-actor admission cap exceeded; honor `Retry-After` header; too_many_requests when server observer, ingress or operation admission capacity is exhausted; honor Retry-After", + "503": { + "description": "The routes are not enabled, a storage read of the cluster state, its lock or the operation record failed temporarily or for an unknown reason, or a record write was refused; nothing changed, retry; graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", "headers": { "Omnigraph-Http-Api": { "schema": { @@ -11331,12 +11464,972 @@ } } } - }, - "500": { - "description": "Internal failure (code `internal`), or unsettled write completion (code `outcome_unknown`); follow the returned disposition before another write", - "headers": { - "Omnigraph-Http-Api": { - "schema": { + } + }, + "security": [ + { + "bearer_token": [] + } + ] + } + }, + "/graphs/{graph_id}/operations/{operation_id}/cancel": { + "post": { + "tags": [ + "operations" + ], + "summary": "Ask a recorded operation to stop at its next safe boundary.", + "operationId": "cancelOperation", + "parameters": [ + { + "name": "graph_id", + "in": "path", + "description": "Graph id to route the request to. The `og_` prefix is reserved for system graphs. `og_catalog` is the built-in, storage-free catalogue: it serves only POST /query and GET /schema with their ordinary response bodies. Its query refuses `branch` and `snapshot`; every other route under /graphs/og_catalog returns 405 `method_not_allowed` before effects.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "operation_id", + "in": "path", + "description": "The id the caller submitted", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "Omnigraph-Http-Api", + "in": "header", + "description": "exactly one Omnigraph-Http-Api header with value 0.14 is required", + "required": true, + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + } + }, + { + "name": "Omnigraph-If-Actor", + "in": "header", + "description": "The actor the caller expects its credential to resolve to. A mismatch is refused with 412 actor_mismatch before graph lookup or effects; a match changes nothing.", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The operation is terminal, unchanged; or `lookup: unknown`", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OperationOutput" + } + } + } + }, + "202": { + "description": "Cancellation requested; a `publishing` operation is unchanged", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OperationOutput" + } + } + } + }, + "400": { + "description": "api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "401": { + "description": "unauthorized when no bearer credential is presented or the server refuses it", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + }, + "WWW-Authenticate": { + "schema": { + "type": "string" + }, + "description": "Bearer challenge (RFC 6750 §3). It carries error=\"invalid_token\" when a presented bearer credential was refused, and resource_metadata naming the OAuth protected-resource metadata when the server has an OIDC resource identity." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "403": { + "description": "", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "404": { + "description": "not_found when no graph `graph_id` is served or the caller may not see it, or when no route serves the path", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "405": { + "description": "method_not_allowed when the path is served, but not with this method", + "headers": { + "Allow": { + "schema": { + "type": "string" + }, + "description": "The methods the path serves." + }, + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "409": { + "description": "Conflict (code `conflict`): a record from another ledger at this root, the record changed during resolution, or a state file or operation record whose stored text is corrupt (`[invalid_state_json]`, `[operation_record_invalid]`; bytes that are not text answer 500)", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "412": { + "description": "actor_mismatch when Omnigraph-If-Actor names another actor than the credential resolves to", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "429": { + "description": "too_many_requests when server observer, ingress or operation admission capacity is exhausted; honor Retry-After", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + }, + "Retry-After": { + "schema": { + "type": "string" + }, + "description": "Minimum delay before a caller-bounded retry of this refused request; not a scheduled server retry." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "500": { + "description": "Internal failure (code `internal`), including a storage read of the cluster state, its lock or the operation record that fails the same way on every read (nothing changed), or a resolution write with no definite answer (code `outcome_unknown`); look the operation up by its id", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "503": { + "description": "The routes are not enabled, a storage read of the cluster state, its lock or the operation record failed temporarily or for an unknown reason, or a record write was refused; nothing changed, retry; graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + }, + "Retry-After": { + "schema": { + "type": "string" + }, + "description": "Minimum delay before a caller-bounded retry of this refused request; not a scheduled server retry." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + } + }, + "security": [ + { + "bearer_token": [] + } + ] + } + }, + "/graphs/{graph_id}/queries": { + "get": { + "tags": [ + "queries" + ], + "summary": "List the graph's exposed stored queries as a typed tool catalog.", + "description": "Returns every stored query in the `queries:` registry, each\nwith its MCP tool name, read/mutate flag, description/instruction, and\ntyped parameters — enough for a client to register them as tools without\nfetching `.gq` source. Cluster-served graphs have no per-query expose flag,\nso the catalog lists them all. Read-gated; the catalog is graph-wide (branch\nindependent — `read` is authorized against `main`). **Not** Cedar-filtered\nper query yet, so it can list a query whose `invoke_query` the caller\nlacks (a known gap until per-query authorization lands).", + "operationId": "queriesList", + "parameters": [ + { + "name": "graph_id", + "in": "path", + "description": "Graph id to route the request to. The `og_` prefix is reserved for system graphs. `og_catalog` is the built-in, storage-free catalogue: it serves only POST /query and GET /schema with their ordinary response bodies. Its query refuses `branch` and `snapshot`; every other route under /graphs/og_catalog returns 405 `method_not_allowed` before effects.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "Omnigraph-Http-Api", + "in": "header", + "description": "exactly one Omnigraph-Http-Api header with value 0.14 is required", + "required": true, + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + } + }, + { + "name": "Omnigraph-If-Actor", + "in": "header", + "description": "The actor the caller expects its credential to resolve to. A mismatch is refused with 412 actor_mismatch before graph lookup or effects; a match changes nothing.", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Stored-query catalog (every stored query, with typed params)", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/QueriesCatalogOutput" + } + } + } + }, + "400": { + "description": "api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "401": { + "description": "Unauthorized; unauthorized when no bearer credential is presented or the server refuses it", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + }, + "WWW-Authenticate": { + "schema": { + "type": "string" + }, + "description": "Bearer challenge (RFC 6750 §3). It carries error=\"invalid_token\" when a presented bearer credential was refused, and resource_metadata naming the OAuth protected-resource metadata when the server has an OIDC resource identity." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "403": { + "description": "Forbidden", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "404": { + "description": "not_found when no graph `graph_id` is served or the caller may not see it, or when no route serves the path", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "405": { + "description": "method_not_allowed when the path is served, but not with this method", + "headers": { + "Allow": { + "schema": { + "type": "string" + }, + "description": "The methods the path serves." + }, + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "412": { + "description": "actor_mismatch when Omnigraph-If-Actor names another actor than the credential resolves to", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "429": { + "description": "too_many_requests when server observer, ingress or operation admission capacity is exhausted; honor Retry-After", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + }, + "Retry-After": { + "schema": { + "type": "string" + }, + "description": "Minimum delay before a caller-bounded retry of this refused request; not a scheduled server retry." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "500": { + "description": "Internal failure (code `internal`) before a successful response", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "503": { + "description": "graph_unavailable for a known graph that is not served, or service_unavailable when server operation admission is closed; honor Retry-After, and reconcile any earlier write before retrying", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + }, + "Retry-After": { + "schema": { + "type": "string" + }, + "description": "Minimum delay before a caller-bounded retry of this refused request; not a scheduled server retry." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + } + }, + "security": [ + { + "bearer_token": [] + } + ] + } + }, + "/graphs/{graph_id}/queries/{query_name}": { + "post": { + "tags": [ + "queries" + ], + "summary": "Invoke a curated, server-side stored query by name.", + "description": "The query source comes from the graph's `queries:` registry, not the\nrequest body — callers send only runtime inputs (`params`, `branch`,\n`snapshot`). Gated by the `invoke_query` Cedar action at the boundary;\na stored *mutation* additionally passes the engine's `change` gate\n(double-gated). An actor **without** `invoke_query` cannot tell a denied\nquery from a missing one — both return the same 404, so the catalog\ncan't be probed without the grant. Once `invoke_query` is held, the\ninner `read`/`change` gate may surface a 403 for an existing query the\nactor can't run (the intended double-gate signal).", + "operationId": "queryInvoke", + "parameters": [ + { + "name": "graph_id", + "in": "path", + "description": "Graph id to route the request to. The `og_` prefix is reserved for system graphs. `og_catalog` is the built-in, storage-free catalogue: it serves only POST /query and GET /schema with their ordinary response bodies. Its query refuses `branch` and `snapshot`; every other route under /graphs/og_catalog returns 405 `method_not_allowed` before effects.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "query_name", + "in": "path", + "description": "Stored query name (the registry key)", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "Omnigraph-Http-Api", + "in": "header", + "description": "exactly one Omnigraph-Http-Api header with value 0.14 is required", + "required": true, + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + } + }, + { + "name": "Omnigraph-If-Actor", + "in": "header", + "description": "The actor the caller expects its credential to resolve to. A mismatch is refused with 412 actor_mismatch before graph lookup or effects; a match changes nothing.", + "required": false, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/InvokeStoredQueryRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "Read envelope (ReadOutput) or mutation envelope (ChangeOutput), serialized untagged", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvokeStoredQueryOutput" + } + } + } + }, + "400": { + "description": "Bad request (param type error; snapshot on a stored mutation); api_contract_mismatch when the required API contract header is missing, duplicated or unsupported", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "401": { + "description": "Unauthorized; unauthorized when no bearer credential is presented or the server refuses it", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + }, + "WWW-Authenticate": { + "schema": { + "type": "string" + }, + "description": "Bearer challenge (RFC 6750 §3). It carries error=\"invalid_token\" when a presented bearer credential was refused, and resource_metadata naming the OAuth protected-resource metadata when the server has an OIDC resource identity." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "403": { + "description": "Forbidden (the inner `change` gate for a stored mutation)", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "404": { + "description": "Unknown stored query, or `invoke_query` denied — indistinguishable to a caller without the grant; not_found when no graph `graph_id` is served or the caller may not see it, or when no route serves the path", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "405": { + "description": "method_not_allowed when the path is served, but not with this method", + "headers": { + "Allow": { + "schema": { + "type": "string" + }, + "description": "The methods the path serves." + }, + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "408": { + "description": "request_timeout when the request body deadline passes before operation admission", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "409": { + "description": "Stored mutation write-authority conflict, or a full-text index requires explicit rebuilding (full_text_index_rebuild_required) or has no segment at the snapshot (full_text_index_required); neither is cleared by retrying", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "412": { + "description": "actor_mismatch when Omnigraph-If-Actor names another actor than the credential resolves to", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "413": { + "description": "Stored keyed mutation exceeds the per-commit entity or byte ceiling; payload_too_large when the request body exceeds its route limit before operation admission", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "424": { + "description": "A stored mutation could not probe or read an allowed external Blob source", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "429": { + "description": "Per-actor admission cap exceeded; honor `Retry-After` header; too_many_requests when server observer, ingress or operation admission capacity is exhausted; honor Retry-After", + "headers": { + "Omnigraph-Http-Api": { + "schema": { + "type": "string", + "enum": [ + "0.14" + ] + }, + "description": "Supported OmniGraph HTTP API contract." + }, + "Retry-After": { + "schema": { + "type": "string" + }, + "description": "Minimum delay before a caller-bounded retry of this refused request; not a scheduled server retry." + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "500": { + "description": "Internal failure (code `internal`), or unsettled write completion (code `outcome_unknown`); follow the returned disposition before another write", + "headers": { + "Omnigraph-Http-Api": { + "schema": { "type": "string", "enum": [ "0.14" @@ -12884,7 +13977,8 @@ "branch_merge", "commit_publish", "commit_drop", - "invoke_query" + "invoke_query", + "maintain" ] }, "AccessOutput": { @@ -12917,6 +14011,13 @@ ], "description": "The branch asked about, when one was." }, + "client_id": { + "type": [ + "string", + "null" + ], + "description": "The OAuth client the credential was issued to, when it is a verified\nOIDC access token. The actor stays the person's principal across\nclients. Opaque text the client chose: render it escaped." + }, "graph_id": { "type": "string" }, @@ -13144,6 +14245,53 @@ } } }, + "BranchDetailOutput": { + "type": "object", + "description": "One live branch as `GET /branches?detailed=true` reports it. `from` and\n`from_commit_id` say where the branch started, as its `POST /branches`\nreceipt did. A branch deleted and created again under the same name is a\nnew lifetime: its start and creation time are the later creation's. The\noptional fields are absent on `main`.", + "required": [ + "name", + "head", + "updated_at" + ], + "properties": { + "created_at": { + "type": [ + "integer", + "null" + ], + "format": "int64", + "description": "When the branch was created, as Unix epoch microseconds recorded to\nthe second.", + "example": 1714000000000000 + }, + "from": { + "type": [ + "string", + "null" + ], + "description": "The branch this one started from, as that branch was named then; it\nmay since have been deleted or recreated." + }, + "from_commit_id": { + "type": [ + "string", + "null" + ], + "description": "The commit the branch started at. A later merge does not move it;\n`GET /branches/merge-base` answers where two branches last met." + }, + "head": { + "$ref": "#/components/schemas/CommitOutput", + "description": "The commit a read of the branch sees: its newest commit, or the commit\nit started at while it has written none." + }, + "name": { + "type": "string" + }, + "updated_at": { + "type": "integer", + "format": "int64", + "description": "When the head last moved, as Unix epoch microseconds: the time of the\nbranch's newest commit, or `created_at` while it has written none.", + "example": 1714000000000000 + } + } + }, "BranchListOutput": { "type": "object", "required": [ @@ -13154,7 +14302,18 @@ "type": "array", "items": { "type": "string" - } + }, + "description": "Every live branch, sorted by name in byte order." + }, + "details": { + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/components/schemas/BranchDetailOutput" + }, + "description": "Present only with `detailed=true`: one entry per branch the caller\nmay `read`, in the order of `branches`. A branch the caller may not\nread is listed in `branches` alone." } } }, @@ -14241,10 +15400,11 @@ }, "ErrorCode": { "type": "string", - "description": "The registry of error codes. A server sends each code under the HTTP statuses named with it; a code without one never appears in an HTTP response.\n\n- `unauthorized` (401): The request carries no credential the server accepts: a bearer token is missing, unknown or expired. Supply one the server is configured to verify.\n- `forbidden` (403): The credential's actor may not do this: policy denies the action, or the action needs a policy permit the server has not been given.\n- `bad_request` (400): The request is malformed or invalid: a body, query string, path parameter or header that does not decode, a query the compiler refuses (see `diagnostic`), or a value refused before any effect.\n- `api_contract_mismatch` (400): The request lacks exactly one `Omnigraph-Http-Api` header naming the contract this server speaks. Authentication and this check precede graph access and effects.\n- `actor_mismatch` (412): The request's `Omnigraph-If-Actor` header names another actor than its credential resolves to. Nothing ran.\n- `outcome_unknown` (500): A write whose completion the server could not settle: it may or may not have published. Read the target before writing again; never replay the write blindly. An MCP write call that was cancelled or passed its deadline answers it too.\n- `precondition_failed` (412): A request precondition no longer holds: the branch head moved past `Omnigraph-If-Graph-Commit` (see `precondition_failure`), or a Blob's `If-Match` names a value the cell no longer holds (a write's `blob_precondition_failure` names the current one). Nothing was written.\n- `recovery_required` (503): An overlapping durable recovery intent must be resolved first; see `recovery_required`.\n- `external_blob_source` (424): An admitted external Blob source could not be probed or read; see `external_blob_source`.\n- `change_feed_gap` (410): Retained history can no longer reconstruct a change continuation; see `change_feed_gap`. Resume from a new baseline.\n- `not_found` (404): The graph, branch, commit, query, entity or route the request names does not exist, or the caller may not learn that it does.\n- `method_not_allowed` (405): The request path is served, but not with the request's method.\n- `request_timeout` (408): The request body did not arrive before its deadline; nothing was admitted.\n- `conflict` (409): The request conflicts with the graph's current state: a concurrent change, an existing id, a merge conflict, an index that must be built first, or a commit that cannot be diffed. The details say which.\n- `branch_start_refusal` (409, 410): `branch create` could not start the branch at the commit `from_commit` named, and nothing was created; see `branch_start_refusal`, whose `not_retained` reason answers 410.\n- `unattached_cannot_publish` (409): The commit is an unattached snapshot, a kind that never publishes. Distinct from `conflict`, the authority-moved refusal of a publishable proposal.\n- `payload_too_large` (413): The request body, or the work it asks for, exceeds a bounded limit; `resource_limit` names the limit when it is the operation's. Split or reduce the request.\n- `unsupported_media_type` (415): The request body's content type is not one the route accepts.\n- `range_not_satisfiable` (416): The requested Blob byte range lies outside the value; see `blob_range`.\n- `too_many_requests` (429): Admission capacity is exhausted: an actor's, the server's, or the MCP endpoint's concurrent tool calls. Nothing started; retry after `Retry-After`.\n- `service_unavailable` (503): Operation admission is closed, or a deployment observation raced an owner change. Nothing started; retry after `Retry-After`, reconciling any earlier write first.\n- `graph_unavailable` (503): A known graph is not being served. The request did not start, so it may be retried once the graph is served again.\n- `internal` (500): The server failed. An error before any write took no effect; see the server log.\n- `cancelled` (no HTTP status): MCP only: the client cancelled a read tool call. A cancelled write answers `outcome_unknown`.\n- `deadline_exceeded` (no HTTP status): MCP only: a read tool call passed its deadline. A write that does answers `outcome_unknown`.\n- `result_too_large` (no HTTP status): MCP only: a tool result exceeds the result limit. Narrow the read.", + "description": "The registry of error codes. A server sends each code under the HTTP statuses named with it; a code without one never appears in an HTTP response.\n\n- `unauthorized` (401): The request carries no credential the server accepts: a bearer token is missing, unknown or expired. Supply one the server is configured to verify.\n- `forbidden` (403): The credential's actor may not do this: policy denies the action, or the action needs a policy permit the server has not been given.\n- `not_admitted` (403): The OIDC access token is valid, but the server admits no principal for its subject. Signing in again issues a token for the same subject and cannot help; the server's operator must admit the identity.\n- `bad_request` (400): The request is malformed or invalid: a body, query string, path parameter or header that does not decode, a query the compiler refuses (see `diagnostic`), or a value refused before any effect.\n- `api_contract_mismatch` (400): The request lacks exactly one `Omnigraph-Http-Api` header naming the contract this server speaks. Authentication and this check precede graph access and effects.\n- `actor_mismatch` (412): The request's `Omnigraph-If-Actor` header names another actor than its credential resolves to. Nothing ran.\n- `outcome_unknown` (500): A write whose completion the server could not settle: it may or may not have published. Read the target before writing again; never replay the write blindly. An MCP write call that was cancelled or passed its deadline answers it too.\n- `precondition_failed` (412): A request precondition no longer holds: the branch head moved past `Omnigraph-If-Graph-Commit` (see `precondition_failure`), or a Blob's `If-Match` names a value the cell no longer holds (a write's `blob_precondition_failure` names the current one). Nothing was written.\n- `recovery_required` (503): An overlapping durable recovery intent must be resolved first; see `recovery_required`.\n- `external_blob_source` (424): An admitted external Blob source could not be probed or read; see `external_blob_source`.\n- `change_feed_gap` (410): Retained history can no longer reconstruct a change continuation; see `change_feed_gap`. Resume from a new baseline.\n- `not_found` (404): The graph, branch, commit, query, entity or route the request names does not exist, or the caller may not learn that it does.\n- `method_not_allowed` (405): The request path is served, but not with the request's method.\n- `request_timeout` (408): The request body did not arrive before its deadline; nothing was admitted.\n- `conflict` (409): The request conflicts with the graph's current state: a concurrent change, an existing id, a merge conflict, an index that must be built first, or a commit that cannot be diffed. The details say which.\n- `branch_start_refusal` (409, 410): `branch create` could not start the branch at the commit `from_commit` named, and nothing was created; see `branch_start_refusal`, whose `not_retained` reason answers 410.\n- `unattached_cannot_publish` (409): The commit is an unattached snapshot, a kind that never publishes. Distinct from `conflict`, the authority-moved refusal of a publishable proposal.\n- `writer_fenced` (409): The branch's writer epoch refused the write: another process claimed the branch, or the serving process holds no claim on it; see `writer_fenced`. Nothing was written.\n- `payload_too_large` (413): The request body, or the work it asks for, exceeds a bounded limit; `resource_limit` names the limit when it is the operation's. Split or reduce the request.\n- `unsupported_media_type` (415): The request body's content type is not one the route accepts.\n- `range_not_satisfiable` (416): The requested Blob byte range lies outside the value; see `blob_range`.\n- `too_many_requests` (429): Admission capacity is exhausted: an actor's, the server's, or the MCP endpoint's concurrent tool calls. Nothing started; retry after `Retry-After`.\n- `service_unavailable` (503): Operation admission is closed, or a deployment observation raced an owner change. Nothing started; retry after `Retry-After`, reconciling any earlier write first.\n- `graph_unavailable` (503): A known graph is not being served. The request did not start, so it may be retried once the graph is served again.\n- `internal` (500): The server failed. An error before any write took no effect; see the server log.\n- `cancelled` (no HTTP status): MCP only: the client cancelled a read tool call. A cancelled write answers `outcome_unknown`.\n- `deadline_exceeded` (no HTTP status): MCP only: a read tool call passed its deadline. A write that does answers `outcome_unknown`.\n- `result_too_large` (no HTTP status): MCP only: a tool result exceeds the result limit. Narrow the read.", "enum": [ "unauthorized", "forbidden", + "not_admitted", "bad_request", "api_contract_mismatch", "actor_mismatch", @@ -14259,6 +15419,7 @@ "conflict", "branch_start_refusal", "unattached_cannot_publish", + "writer_fenced", "payload_too_large", "unsupported_media_type", "range_not_satisfiable", @@ -14460,6 +15621,17 @@ "description": "Set when the request must be split into smaller graph commits. The\nrejected attempt has no durable effect." } ] + }, + "writer_fenced": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/WriterFencedOutput", + "description": "Set with HTTP 409 and `writer_fenced` when the branch's writer epoch\nrefused a publish or a claim. Nothing was written." + } + ] } } }, @@ -14520,7 +15692,7 @@ }, "FullTextIndexRequiredOutput": { "type": "object", - "description": "A full-text call read a declared full-text index that has no segment at\nthe query's snapshot (HTTP 409), so no segment carries its analyzer. This\nis not a retryable conflict: an operator builds the branch's index\n(`omnigraph optimize` on main, `omnigraph rebuild-full-text-indexes\n--branch` elsewhere). Historical snapshots stay unchanged.", + "description": "A full-text call read a declared full-text index that has no segment at\nthe query's snapshot (HTTP 409), so no segment carries its analyzer. This\nis not a retryable conflict: an operator builds the branch's index\n(`omnigraph index build --branch `). Historical snapshots stay\nunchanged.", "required": [ "index" ], @@ -15097,6 +16269,12 @@ "description": "The partition that claimed the slice; which one varies between runs.", "minimum": 0 }, + "read_ns": { + "type": "integer", + "format": "int64", + "description": "Nanoseconds the slice's partition waited for the source's bytes.", + "minimum": 0 + }, "rows": { "type": "integer", "format": "int64", @@ -15186,6 +16364,36 @@ } } }, + "OperationLookup": { + "type": "string", + "enum": [ + "found", + "unknown" + ] + }, + "OperationOutput": { + "type": "object", + "required": [ + "lookup", + "in_progress" + ], + "properties": { + "in_progress": { + "type": "boolean", + "description": "Whether this server is running it now." + }, + "lookup": { + "$ref": "#/components/schemas/OperationLookup" + }, + "operation": { + "type": [ + "object", + "null" + ], + "description": "The operation's record; absent for an `unknown` lookup." + } + } + }, "ParamDescriptor": { "type": "object", "description": "One declared parameter of a stored query, projected for the catalog.", @@ -15434,6 +16642,45 @@ }, "additionalProperties": false }, + "RankOrder": { + "type": "string", + "description": "The direction a ranking's score orders rows.", + "enum": [ + "ascending", + "descending" + ] + }, + "RankingOutput": { + "type": "object", + "description": "The ranking a read ordered its rows by.", + "required": [ + "by", + "order", + "exhaustive", + "score_columns" + ], + "properties": { + "by": { + "$ref": "#/components/schemas/SearchFunction", + "description": "The search function the leading `order` key names." + }, + "exhaustive": { + "type": "boolean", + "description": "Whether no row the search admitted and did not return outranks a\nreturned one. `bm25` scores every match, so it is always exhaustive.\n`nearest` is exhaustive when the run searched every partition of the\nvector index, scored every row flat or returned every row it\nadmitted, and `false` when a probe cap left partitions unsearched, so\na nearer row may exist. `rrf` is exhaustive when its `nearest` arms\nare." + }, + "order": { + "$ref": "#/components/schemas/RankOrder", + "description": "`ascending` for a `nearest` distance (smaller is nearer),\n`descending` for a `bm25` or `rrf` score (larger is more relevant)." + }, + "score_columns": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The returned columns that hold the ranking's own score, in return\norder; empty when the read returns none. A column computed from the\nscore is not one." + } + } + }, "ReadOutput": { "type": "object", "required": [ @@ -15470,6 +16717,17 @@ "query_name": { "type": "string" }, + "ranking": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RankingOutput", + "description": "How the read ordered its rows when its order is a search: the\nsearch function, the direction its score ranks, whether the run's\nsearch was exhaustive, and the returned columns holding the score.\nAbsent when the order is no search." + } + ] + }, "row_count": { "type": "integer", "minimum": 0 @@ -15686,6 +16944,15 @@ } } }, + "SearchFunction": { + "type": "string", + "description": "The search function a ranked read orders by.", + "enum": [ + "nearest", + "bm25", + "rrf" + ] + }, "SettingsRequest": { "type": "object", "description": "The `settings` field of a request: one optional value per `request`-scope\nsetting of the definition, applied to the request's session before the\nsource's own `set` lines, so a `set` line in the request's text overrides\nthe field. An absent field is empty. A `process` setting has no field\nhere, so `{\"stage_write_concurrency\": 64}` is refused as an unknown field.", @@ -15695,6 +16962,15 @@ "description": "the partition cap per index delta of a `nearest` scan; `0` is no cap", "minimum": 0 }, + "change_lineage": { + "type": "string", + "description": "how a graph diff or commit page finds the entities it compares across a window with no adjacent transaction: the exact ordered merge of both versions, the entities paired by stable identity, or both compared", + "enum": [ + "off", + "on", + "verify" + ] + }, "engine": { "type": "string", "description": "the engine a read query runs on; `v2`, the plan runner, is the one value; this setting does not change change-feed or merge execution", @@ -15809,6 +17085,39 @@ } } }, + "StartOptimizeRequest": { + "type": "object", + "description": "`POST /graphs/{graph_id}/operations/optimize`.", + "required": [ + "operation_id" + ], + "properties": { + "datasets": { + "type": [ + "array", + "null" + ], + "items": { + "type": "string" + }, + "description": "Only these datasets, each named by its type key (`node:`,\n`edge:`), in this order." + }, + "max_gate_hold_ms": { + "type": [ + "integer", + "null" + ], + "format": "int64", + "description": "How long writers to main wait at most, within the server's ceiling.", + "minimum": 0 + }, + "operation_id": { + "type": "string", + "description": "A canonical ULID the caller chose; a repeated submission with the same\nrequest answers the existing record." + } + }, + "additionalProperties": false + }, "SuggestionOutput": { "type": "object", "description": "Non-overlapping edits against the original request source.", @@ -15869,6 +17178,36 @@ "minimum": 0 } } + }, + "WriterFencedOutput": { + "type": "object", + "description": "The writer epochs of a publish or claim a claimed branch refused. `held`\nis the serving process's epoch, absent when it holds none; `read` is the\nepoch a refused claim read; `current` is the branch's epoch.", + "required": [ + "current" + ], + "properties": { + "current": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "held": { + "type": [ + "integer", + "null" + ], + "format": "int64", + "minimum": 0 + }, + "read": { + "type": [ + "integer", + "null" + ], + "format": "int64", + "minimum": 0 + } + } } }, "securitySchemes": { @@ -15907,6 +17246,10 @@ "name": "health", "description": "Process health and readiness probes" }, + { + "name": "operations", + "description": "Recorded operations: optimize through the serving owner, looked up and cancelled by id" + }, { "name": "management", "description": "Server graph inventory and OAuth resource metadata" diff --git a/src/omnigraph/__init__.py b/src/omnigraph/__init__.py index 55d487a..b76958f 100644 --- a/src/omnigraph/__init__.py +++ b/src/omnigraph/__init__.py @@ -13,6 +13,7 @@ InternalServerError, MethodNotAllowedError, NetworkError, + NotAdmittedError, NotFoundError, OmnigraphError, PayloadTooLargeError, @@ -23,6 +24,17 @@ TooManyRequestsError, UnauthorizedError, UnsupportedMediaTypeError, + WriterFencedError, +) +from ._operations import ( + TERMINAL_STATES, + DatasetOutcome, + Operation, + OperationResult, + OperationState, + OptimizeOutcome, + is_terminal, + new_operation_id, ) from ._version import HTTP_API_CONTRACT, HTTP_API_CONTRACT_HEADER, SERVER_VERSION @@ -30,10 +42,12 @@ "HTTP_API_CONTRACT", "HTTP_API_CONTRACT_HEADER", "SERVER_VERSION", + "TERMINAL_STATES", "ApiContractError", "BadRequestError", "ConfigurationError", "ConflictError", + "DatasetOutcome", "FailedDependencyError", "ForbiddenError", "GoneError", @@ -41,9 +55,14 @@ "InternalServerError", "MethodNotAllowedError", "NetworkError", + "NotAdmittedError", "NotFoundError", "Omnigraph", "OmnigraphError", + "Operation", + "OperationResult", + "OperationState", + "OptimizeOutcome", "PayloadTooLargeError", "PreconditionFailedError", "RangeNotSatisfiableError", @@ -52,4 +71,7 @@ "TooManyRequestsError", "UnauthorizedError", "UnsupportedMediaTypeError", + "WriterFencedError", + "is_terminal", + "new_operation_id", ] diff --git a/src/omnigraph/_client.py b/src/omnigraph/_client.py index 330332c..65ee0af 100644 --- a/src/omnigraph/_client.py +++ b/src/omnigraph/_client.py @@ -18,8 +18,10 @@ LoadMode, ReadinessOutput, ReadOutput, + SettingsRequest, SnapshotOutput, ) +from ._operations import Operations from ._receipts import valid_mutation_receipt from ._resources import ( Blobs, @@ -41,8 +43,11 @@ def _gq_body( name: str | None, params: dict[str, Any] | None, branch: str | None, + settings: SettingsRequest | None, ) -> dict[str, Any]: body: dict[str, Any] = {"query": query} + if settings is not None: + body["settings"] = settings if name is not None: body["name"] = name if params is not None: @@ -98,6 +103,7 @@ def _init(self, transport: Transport) -> None: self.queries = Queries(transport) self.changes = Changes(transport) self.blobs = Blobs(transport) + self.operations = Operations(transport) @property def base_url(self) -> str: @@ -172,10 +178,20 @@ async def query( params: dict[str, Any] | None = None, branch: str | None = None, snapshot: str | None = None, + settings: SettingsRequest | None = None, if_actor: str | None = None, ) -> ReadOutput: - """Run a GQ read (`POST /query`). `params` keys match `$name` slots.""" - body = _gq_body(query, name=name, params=params, branch=branch) + """Run a GQ read (`POST /query`). `params` keys match `$name` slots. + + A read ordered by `nearest`, `bm25` or `rrf()` reports `ranking`: the + search, its score order, whether it was exhaustive, and the columns + holding the score. `settings` applies request-scope session settings, + such as `{"change_lineage": "verify"}`; a budget above the server's + ceiling is refused with `BadRequestError`. + """ + body = _gq_body( + query, name=name, params=params, branch=branch, settings=settings + ) if snapshot is not None: body["snapshot"] = snapshot return cast( @@ -191,6 +207,7 @@ async def mutate( params: dict[str, Any] | None = None, branch: str | None = None, if_graph_commit: str | None = None, + settings: SettingsRequest | None = None, if_actor: str | None = None, ) -> ChangeOutput: """Run a GQ mutation (`POST /mutate`); its statements publish as one commit. @@ -201,7 +218,9 @@ async def mutate( successful no-op. A branch statement (`branch create|delete|merge …`) names its own branches: send it without `name`, `params`, `branch`. """ - body = _gq_body(query, name=name, params=params, branch=branch) + body = _gq_body( + query, name=name, params=params, branch=branch, settings=settings + ) if if_graph_commit is not None: return cast( ChangeOutput, diff --git a/src/omnigraph/_errors.py b/src/omnigraph/_errors.py index 96afcd0..c4f1a43 100644 --- a/src/omnigraph/_errors.py +++ b/src/omnigraph/_errors.py @@ -8,13 +8,22 @@ import httpx from ._models import ( + BlobRangeOutput, + ChangeDiffRefusalOutput, + ChangeFeedGapOutput, DispositionOutput, ErrorCode, ErrorOutput, + ExternalBlobSourceOutput, + FullTextIndexRebuildRequiredOutput, KeyConflictOutput, MergeConflictOutput, PreconditionFailureOutput, + PublishedDatasetVersionConflictOutput, + ReadSetConflictOutput, + RecoveryRequiredOutput, ResourceLimitOutput, + WriterFencedOutput, ) @@ -90,6 +99,12 @@ class ForbiddenError(OmnigraphError): pass +class NotAdmittedError(ForbiddenError): + """The OIDC token is valid, but the server admits no principal for its + subject (`not_admitted`). Signing in again cannot help; the server's + operator must admit the identity.""" + + class NotFoundError(OmnigraphError): pass @@ -115,10 +130,50 @@ def merge_conflicts(self) -> list[MergeConflictOutput]: def key_conflict(self) -> KeyConflictOutput | None: return self.body.get("key_conflict") if self.body else None + @property + def read_set_conflict(self) -> ReadSetConflictOutput | None: + """A concurrent commit changed what this write read; read again first.""" + return self.body.get("read_set_conflict") if self.body else None + + @property + def published_dataset_version_conflict( + self, + ) -> PublishedDatasetVersionConflictOutput | None: + if not self.body: + return None + return self.body.get("published_dataset_version_conflict") + + @property + def change_diff_refusal(self) -> ChangeDiffRefusalOutput | None: + return self.body.get("change_diff_refusal") if self.body else None + + @property + def full_text_index_rebuild_required( + self, + ) -> FullTextIndexRebuildRequiredOutput | None: + """This conflict needs operator maintenance, not a retry.""" + if not self.body: + return None + return self.body.get("full_text_index_rebuild_required") + + +class WriterFencedError(ConflictError): + """The branch's writer epoch refused this publish or claim + (`writer_fenced`): another process claimed the branch. Nothing was + written. `writer_fenced` names the epochs.""" + + @property + def writer_fenced(self) -> WriterFencedOutput | None: + return self.body.get("writer_fenced") if self.body else None + class GoneError(OmnigraphError): """Retained change history is unavailable; recover through a baseline.""" + @property + def change_feed_gap(self) -> ChangeFeedGapOutput | None: + return self.body.get("change_feed_gap") if self.body else None + class PreconditionFailedError(OmnigraphError): """A stale graph-head precondition, an actor mismatch, or a failed Blob If-Match.""" @@ -135,11 +190,15 @@ def resource_limit(self) -> ResourceLimitOutput | None: class RangeNotSatisfiableError(OmnigraphError): - pass + @property + def blob_range(self) -> BlobRangeOutput | None: + return self.body.get("blob_range") if self.body else None class FailedDependencyError(OmnigraphError): - pass + @property + def external_blob_source(self) -> ExternalBlobSourceOutput | None: + return self.body.get("external_blob_source") if self.body else None class TooManyRequestsError(OmnigraphError): @@ -151,7 +210,9 @@ class InternalServerError(OmnigraphError): class ServiceUnavailableError(OmnigraphError): - pass + @property + def recovery_required(self) -> RecoveryRequiredOutput | None: + return self.body.get("recovery_required") if self.body else None class GraphUnavailableError(ServiceUnavailableError): @@ -196,6 +257,7 @@ class ConfigurationError(OmnigraphError): "graph_unavailable": GraphUnavailableError, "unauthorized": UnauthorizedError, "forbidden": ForbiddenError, + "not_admitted": NotAdmittedError, "not_found": NotFoundError, "method_not_allowed": MethodNotAllowedError, "conflict": ConflictError, @@ -210,6 +272,7 @@ class ConfigurationError(OmnigraphError): "request_timeout": RequestTimeoutError, "branch_start_refusal": ConflictError, "unattached_cannot_publish": ConflictError, + "writer_fenced": WriterFencedError, "payload_too_large": PayloadTooLargeError, "unsupported_media_type": UnsupportedMediaTypeError, "range_not_satisfiable": RangeNotSatisfiableError, @@ -219,6 +282,22 @@ class ConfigurationError(OmnigraphError): } +def error_class(status: int, code: str | None) -> type[OmnigraphError]: + """The status picks the class; a code's class replaces it when it refines + it (a subclass, such as `GraphUnavailableError` for a 503 or + `NotAdmittedError` for a 403). A code alone decides only when the status + has no class of its own.""" + if code == "api_contract_mismatch": + return ApiContractError + by_status = _BY_STATUS.get(status) + by_code = _BY_CODE.get(code) if code else None + if by_status is None: + return by_code or InternalServerError + if by_code is not None and issubclass(by_code, by_status): + return by_code + return by_status + + def error_body(parsed: Any) -> ErrorOutput | None: """The parsed body when it is the server's error envelope, else `None`.""" if not isinstance(parsed, dict): @@ -235,26 +314,32 @@ def error_body(parsed: Any) -> ErrorOutput | None: return cast(ErrorOutput, parsed) +def server_outcome_unknown(parsed: Any) -> bool | None: + """Whether an error reply says a write may have taken effect, on any + route. Code `outcome_unknown` always does, whatever its disposition reads + (a recorded-operation lookup can leave a settlement write in doubt), and + a valid disposition otherwise decides. `None` when the reply says + neither, so the route decides.""" + if isinstance(parsed, dict) and parsed.get("code") == "outcome_unknown": + return True + body = error_body(parsed) + return None if body is None else body["disposition"]["effects"] != "none" + + def from_response( response: httpx.Response, - body: ErrorOutput | None, + parsed: Any, *, method: str, url: str, may_write: bool, ) -> OmnigraphError: + """The error for a non-success reply. `parsed` is its JSON, if any; + `may_write` is the route's answer, used only when the reply does not say.""" + body = error_body(parsed) code = body["code"] if body else None - if code == "graph_unavailable": - cls: type[OmnigraphError] = GraphUnavailableError - elif code == "api_contract_mismatch": - cls = ApiContractError - else: - cls = ( - _BY_STATUS.get(response.status_code) - or (_BY_CODE.get(code) if code else None) - or InternalServerError - ) - effects = body["disposition"]["effects"] if body else None + cls = error_class(response.status_code, code) + unknown = server_outcome_unknown(parsed) return cls( body["error"] if body else f"HTTP {response.status_code}", status=response.status_code, @@ -265,5 +350,5 @@ def from_response( body=body, response=response, request_dispatched=True, - outcome_unknown=may_write and effects != "none", + outcome_unknown=may_write if unknown is None else unknown, ) diff --git a/src/omnigraph/_models.py b/src/omnigraph/_models.py index 736ae39..97c6eca 100644 --- a/src/omnigraph/_models.py +++ b/src/omnigraph/_models.py @@ -18,6 +18,7 @@ 'commit_publish', 'commit_drop', 'invoke_query', + 'maintain', ] @@ -31,6 +32,7 @@ class AccessOutput(TypedDict): actions: list[AccessAction] actor_id: NotRequired[str | None] branch: NotRequired[str | None] + client_id: NotRequired[str | None] graph_id: str graph_wide: list[AccessAction] target_branch: NotRequired[str | None] @@ -95,10 +97,6 @@ class BranchDeleteOutput(TypedDict): uri: str -class BranchListOutput(TypedDict): - branches: list[str] - - BranchMergeOutcome = Literal['already_up_to_date', 'fast_forward', 'merged'] @@ -318,6 +316,7 @@ class DispositionOutput(TypedDict): ErrorCode = Literal[ 'unauthorized', 'forbidden', + 'not_admitted', 'bad_request', 'api_contract_mismatch', 'actor_mismatch', @@ -332,6 +331,7 @@ class DispositionOutput(TypedDict): 'conflict', 'branch_start_refusal', 'unattached_cannot_publish', + 'writer_fenced', 'payload_too_large', 'unsupported_media_type', 'range_not_satisfiable', @@ -377,8 +377,8 @@ class FullTextIndexRequiredOutput(TypedDict): A full-text call read a declared full-text index that has no segment at the query's snapshot (HTTP 409), so no segment carries its analyzer. This is not a retryable conflict: an operator builds the branch's index - (`omnigraph optimize` on main, `omnigraph rebuild-full-text-indexes - --branch` elsewhere). Historical snapshots stay unchanged. + (`omnigraph index build --branch `). Historical snapshots stay + unchanged. """ index: str @@ -483,6 +483,7 @@ class LoadSliceExecutedOutput(TypedDict): elapsed_compute_ns: int end_ns: int partition: int + read_ns: NotRequired[int] rows: int slice: int start_ns: int @@ -520,6 +521,15 @@ class MergeConflictOutput(TypedDict): type_name: str +OperationLookup = Literal['found', 'unknown'] + + +class OperationOutput(TypedDict): + in_progress: bool + lookup: OperationLookup + operation: NotRequired[dict[str, Any] | None] + + ParamKind = Literal[ 'string', 'bool', @@ -575,6 +585,9 @@ class PublishedDatasetVersionConflictOutput(TypedDict): type_name: str +RankOrder = Literal['ascending', 'descending'] + + class ReadPageOutput(TypedDict): """ The page state a `branch diff` answer carries: the exact commits it @@ -640,6 +653,9 @@ class ResourceLimitOutput(TypedDict): resource: str +SearchFunction = Literal['nearest', 'bm25', 'rrf'] + + class SettingsRequest(TypedDict): """ The `settings` field of a request: one optional value per `request`-scope @@ -650,6 +666,7 @@ class SettingsRequest(TypedDict): """ ann_nprobes: NotRequired[int] + change_lineage: NotRequired[Literal['off', 'on', 'verify']] engine: NotRequired[Literal['v2']] history_release_bytes: NotRequired[int] load_source_max_bytes: NotRequired[int] @@ -675,6 +692,16 @@ class SnapshotOutput(TypedDict): internal_schema_version: int +class StartOptimizeRequest(TypedDict): + """ + `POST /graphs/{graph_id}/operations/optimize`. + """ + + datasets: NotRequired[list[str]] + max_gate_hold_ms: NotRequired[int | None] + operation_id: str + + class SystemColumnsOutput(TypedDict): """ A graph's system column spellings (see `SchemaOutput::system_columns`). @@ -695,6 +722,18 @@ class TextEditOutput(TypedDict): start: int +class WriterFencedOutput(TypedDict): + """ + The writer epochs of a publish or claim a claimed branch refused. `held` + is the serving process's epoch, absent when it holds none; `read` is the + epoch a refused claim read; `current` is the branch's epoch. + """ + + current: int + held: NotRequired[int | None] + read: NotRequired[int | None] + + class BlobSelectorOutput(TypedDict): """ One logical graph Blob cell. @@ -723,6 +762,31 @@ class BlobWriteOutput(TypedDict): size: NotRequired[int | None] +""" +One live branch as `GET /branches?detailed=true` reports it. `from` and + `from_commit_id` say where the branch started, as its `POST /branches` + receipt did. A branch deleted and created again under the same name is a + new lifetime: its start and creation time are the later creation's. The + optional fields are absent on `main`. +""" +BranchDetailOutput = TypedDict( + 'BranchDetailOutput', + { + 'created_at': NotRequired[int | None], + 'from': NotRequired[str | None], + 'from_commit_id': NotRequired[str | None], + 'head': CommitOutput, + 'name': str, + 'updated_at': int, + }, +) + + +class BranchListOutput(TypedDict): + branches: list[str] + details: NotRequired[list[BranchDetailOutput]] + + class BranchMergeRequest(TypedDict): as_commit: NotRequired[bool] delete_branch: NotRequired[bool] @@ -941,11 +1005,23 @@ class QueryRequest(TypedDict): snapshot: NotRequired[str | None] +class RankingOutput(TypedDict): + """ + The ranking a read ordered its rows by. + """ + + by: SearchFunction + exhaustive: bool + order: RankOrder + score_columns: list[str] + + class ReadOutput(TypedDict): columns: NotRequired[list[str]] graph_commit_id: NotRequired[str | None] page: NotRequired[ReadPageOutput | None] query_name: str + ranking: NotRequired[RankingOutput | None] row_count: int rows: Any target: ReadTargetOutput @@ -1053,6 +1129,7 @@ class ErrorOutput(TypedDict): read_set_conflict: NotRequired[ReadSetConflictOutput | None] recovery_required: NotRequired[RecoveryRequiredOutput | None] resource_limit: NotRequired[ResourceLimitOutput | None] + writer_fenced: NotRequired[WriterFencedOutput | None] class LoadExecutedOutput(TypedDict): diff --git a/src/omnigraph/_operations.py b/src/omnigraph/_operations.py new file mode 100644 index 0000000..518256f --- /dev/null +++ b/src/omnigraph/_operations.py @@ -0,0 +1,278 @@ +"""Recorded operations (server 0.16+): submit, look up, cancel and wait. + +A cluster server with `OMNIGRAPH_OPERATION_ROUTES=true` runs `optimize` on a +graph's `main` as a recorded operation, tracked by an id the caller chose. +Every route needs the `maintain` action on `main`. + +The spec leaves the operation record an open object; the `TypedDict`s here +describe the record as server 0.16 writes it, with its wire names. A later +server may add fields. +""" + +from __future__ import annotations + +import asyncio +import os +import time +from collections.abc import Sequence +from typing import Any, Literal, NotRequired, TypedDict, cast +from urllib.parse import quote + +from ._models import OperationLookup +from ._transport import Transport + +OperationState = Literal[ + "accepted", + "running", + "publishing", + "succeeded", + "failed", + "cancelled", + "interrupted", + "unsettled", +] + +#: States an operation never leaves. `unsettled` means its publication can no +#: longer be answered (the graph was deleted while it was in doubt). +TERMINAL_STATES: frozenset[str] = frozenset( + {"succeeded", "failed", "cancelled", "interrupted", "unsettled"} +) + + +def is_terminal(state: str) -> bool: + """Whether an operation in `state` is finished.""" + return state in TERMINAL_STATES + + +_CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" + + +def new_operation_id() -> str: + """A fresh canonical ULID to submit an operation under. + + Mint it, keep it, then submit: after a lost response, look the same id + up instead of submitting again. + """ + value = (time.time_ns() // 1_000_000) << 80 | int.from_bytes(os.urandom(10)) + return "".join(_CROCKFORD[(value >> shift) & 31] for shift in range(125, -1, -5)) + + +class OptimizeRequestRecord(TypedDict): + """The request an operation was submitted with.""" + + kind: Literal["optimize"] + datasets: NotRequired[list[str]] + max_gate_hold_ms: NotRequired[int] + + +class DatasetOutcome(TypedDict): + """One dataset's outcome in an optimize run.""" + + type_key: str + #: `optimized`, `unchanged`, `deferred` or `failed`. + outcome: str + #: Why a `deferred` dataset was not started, or `index_failed` on an + #: `optimized` one whose index work failed after its compaction committed. + reason: NotRequired[str] + detail: NotRequired[str] + fragments_removed: int + fragments_added: int + duration_ms: int + source_bytes: NotRequired[int] + + +class TailOutcome(TypedDict): + """An outcome after the graph commit; it never fails the operation.""" + + outcome: str + detail: NotRequired[str] + + +class OptimizeOutcome(TypedDict): + kind: Literal["optimize"] + start_at: NotRequired[str] + #: At most 1,024 datasets, in visit order. + datasets: NotRequired[list[DatasetOutcome]] + #: Datasets beyond the listed ones, counted by `outcome` or + #: `outcome:reason` (for example `deferred:gate_hold_limit`). + more_datasets: NotRequired[dict[str, int]] + resume_at: NotRequired[str] + configuration_clear: NotRequired[TailOutcome] + artifact: NotRequired[TailOutcome] + + +class ResolutionProgress(TypedDict): + """Where a `publishing` operation's history walk stands.""" + + cursor: NotRequired[str] + visited: int + + +class OperationTimings(TypedDict, total=False): + queued_ms: int + gate_hold_ms: int + compute_ms: int + + +class Operation(TypedDict): + """A recorded operation, with the server's field names.""" + + operation_id: str + request_digest: str + graph: str + schema_identity_domain: str + settlement_branch: str + request: OptimizeRequestRecord + principal: str + accepted_at: str + state: OperationState + nonce: NotRequired[str] + input_commit: NotRequired[str] + input_manifest_version: NotRequired[int] + published_commit: NotRequired[str] + resolution: NotRequired[ResolutionProgress] + outcome: OptimizeOutcome + timings: OperationTimings + reason: NotRequired[str] + + +class OperationResult(TypedDict): + """A submission, lookup or cancellation answer. `lookup: "unknown"` has no + `operation`; it does not prove the operation never ran, and is never a + reason to resubmit the same work under the same id.""" + + lookup: OperationLookup + in_progress: bool + operation: NotRequired[Operation | None] + + +def valid_receipt(reply: Any, operation_id: str, *, unknown_allowed: bool) -> bool: + """Whether `reply` is a receipt for `operation_id`: a lookup envelope with + a boolean `in_progress` whose `found` record names that id and carries a + state and an outcome, or an `unknown` lookup where the route can answer one + (lookup and cancel; a submission always identifies its record). The one + check every operation route applies.""" + if not isinstance(reply, dict) or not isinstance(reply.get("in_progress"), bool): + return False + lookup, record = reply.get("lookup"), reply.get("operation") + if lookup == "unknown": + return unknown_allowed and record is None + return ( + lookup == "found" + and isinstance(record, dict) + and record.get("operation_id") == operation_id + and isinstance(record.get("state"), str) + and isinstance(record.get("outcome"), dict) + ) + + +class Operations: + """`og.operations`: recorded operations on the client's graph.""" + + def __init__(self, transport: Transport) -> None: + self._t = transport + + async def optimize( + self, + operation_id: str, + *, + datasets: Sequence[str] | None = None, + max_gate_hold_ms: int | None = None, + if_actor: str | None = None, + ) -> OperationResult: + """Submit an optimize run of `main` under `operation_id`, a canonical + ULID from `new_operation_id()`. + + `datasets` limits the run to these type keys (`node:Person`, + `edge:Knows`), in order; `max_gate_hold_ms` bounds how long writers to + `main` wait, within the server's ceiling. The answer is the record: + accepted or running (HTTP 202), or terminal (200). While the server's + record still holds the id (it keeps the 32 newest terminal + operations), the same id with the same request (same graph lifetime, + branch, request and principal: the request digest) returns that record + without running again; an evicted id is refused as expired, and the + same id with another request is a `ConflictError`. After an + `outcome_unknown` error, look the id up with `get`. + """ + body: dict[str, Any] = {"operation_id": operation_id} + if isinstance(datasets, str): + # A str is a Sequence[str] of characters; sending it would record + # one dataset key per character under this id. + raise TypeError("datasets must be a list of type keys, not one string") + if datasets is not None: + body["datasets"] = list(datasets) + if max_gate_hold_ms is not None: + body["max_gate_hold_ms"] = max_gate_hold_ms + return await self._receipt( + "POST", "/operations/optimize", operation_id, False, body, if_actor + ) + + async def get( + self, operation_id: str, *, if_actor: str | None = None + ) -> OperationResult: + """Look an operation up by its id, whatever its kind. A lookup may + settle a publication in doubt, so it can raise `outcome_unknown`; + retrying the lookup is safe.""" + return await self._receipt( + "GET", f"/operations/{quote(operation_id, safe='')}", operation_id, True, + None, if_actor, + ) # fmt: skip + + async def cancel( + self, operation_id: str, *, if_actor: str | None = None + ) -> OperationResult: + """Ask an operation to stop at its next safe boundary; best effort. + + A terminal, unknown or `publishing` operation is returned unchanged and + no cancellation is requested for it. An `accepted` or `running` one is + asked to stop: it ends `cancelled`, or `succeeded`, usually with a + `reason` saying the cancellation arrived late. omnigraph-server 0.16.0 + gives no reason when the cancel lands as the run finishes, so read + the terminal record (`wait`) to know whether it was cancelled.""" + return await self._receipt( + "POST", f"/operations/{quote(operation_id, safe='')}/cancel", + operation_id, True, None, if_actor, + ) # fmt: skip + + async def _receipt( + self, + method: str, + path: str, + operation_id: str, + unknown_allowed: bool, + body: dict[str, Any] | None, + if_actor: str | None, + ) -> OperationResult: + """Send one operation request and accept only a receipt for its id. + An invalid reply is an `ApiContractError`: outcome unknown after a + submission or cancellation, which may have written, and certain after + a lookup.""" + reply = await self._t.request(method, path, body=body, if_actor=if_actor) + if not valid_receipt(reply, operation_id, unknown_allowed=unknown_allowed): + raise self._t.invalid_response( + method, path, f"invalid receipt for operation {operation_id}" + ) + return cast(OperationResult, reply) + + async def wait( + self, + operation_id: str, + *, + interval: float = 1.0, + if_actor: str | None = None, + ) -> OperationResult: + """Look the operation up every `interval` seconds until it is terminal + or the lookup answers `unknown`, and return that answer. + + Only the read route is called, and an error ends the wait: nothing is + retried, though retrying a lookup is always safe. Bound the wait with + `asyncio.timeout(...)`; ending the wait does not stop the operation, + which keeps running on the server (use `cancel`). + """ + while True: + result = await self.get(operation_id, if_actor=if_actor) + operation = result.get("operation") + if operation is None or is_terminal(operation["state"]): + # A valid receipt has no record only when lookup is unknown. + return result + await asyncio.sleep(interval) diff --git a/src/omnigraph/_resources.py b/src/omnigraph/_resources.py index 8e15c3f..395795f 100644 --- a/src/omnigraph/_resources.py +++ b/src/omnigraph/_resources.py @@ -14,6 +14,7 @@ BlobWriteOutput, BranchCreateOutput, BranchDeleteOutput, + BranchListOutput, BranchMergeOutput, ChangeFeedOutput, ChangeOutput, @@ -30,6 +31,7 @@ QueriesCatalogOutput, ReadOutput, SchemaOutput, + SettingsRequest, ) from ._receipts import valid_merge from ._transport import Transport @@ -51,6 +53,23 @@ async def list(self, *, if_actor: str | None = None) -> builtins.list[str]: r = await self._t.request("GET", "/branches", if_actor=if_actor) return builtins.list(r["branches"]) + async def list_detailed(self, *, if_actor: str | None = None) -> BranchListOutput: + """Every branch name, and `details` for each branch this credential may + read: its head commit, where it started, and when it was created and + last moved (server 0.15+). `details` follows the order of `branches`; a + branch the caller may not read appears in `branches` alone. + + A reply without `details` raises `ApiContractError`. + """ + r = await self._t.request( + "GET", "/branches", query={"detailed": "true"}, if_actor=if_actor + ) + if not isinstance(r, dict) or not isinstance(r.get("details"), builtins.list): + raise self._t.invalid_response( + "GET", "/branches", "branch listing without details" + ) + return cast(BranchListOutput, r) + async def create( self, name: str, @@ -82,6 +101,7 @@ async def merge( as_commit: bool = False, delete_branch: bool = False, dry_run: bool = False, + settings: SettingsRequest | None = None, if_actor: str | None = None, ) -> BranchMergeOutput: """Merge `source` into `target`. @@ -89,7 +109,8 @@ async def merge( Returns this merge's exact commit, or `commit: None` when already up to date. With `delete_branch`, a deletion can fail after a merge that landed; inspect `branch_deleted` and `branch_delete_error_details`. - Never retry an uncertain merge blindly. + Never retry an uncertain merge blindly. A `dry_run` is a read: it + reports the outcome the merge would have now and writes nothing. """ body: dict[str, Any] = {"source": source, "target": target} if as_commit: @@ -98,8 +119,12 @@ async def merge( body["delete_branch"] = True if dry_run: body["dry_run"] = True + if settings is not None: + body["settings"] = settings + # A dry run writes nothing, so a lost answer has no effects; a reply + # that says it ran no dry run still leaves effects unknown below. result = await self._t.request( - "POST", "/branches/merge", body=body, if_actor=if_actor + "POST", "/branches/merge", body=body, if_actor=if_actor, read_only=dry_run ) if not valid_merge( result, diff --git a/src/omnigraph/_transport.py b/src/omnigraph/_transport.py index 17d7699..e7361c9 100644 --- a/src/omnigraph/_transport.py +++ b/src/omnigraph/_transport.py @@ -19,7 +19,6 @@ ConfigurationError, NetworkError, OmnigraphError, - error_body, from_response, ) from ._version import HTTP_API_CONTRACT, HTTP_API_CONTRACT_HEADER @@ -118,9 +117,13 @@ async def request( headers: Mapping[str, str] | None = None, if_actor: str | None = None, accepted_statuses: Sequence[int] = (), + read_only: bool = False, ) -> Any: """Send one request and return its parsed JSON body. A missing or - invalid body never acknowledges a write.""" + invalid body never acknowledges a write. + + `read_only` marks a request that cannot write although its route can + (a dry-run merge): losing its answer leaves no outcome unknown.""" response = await self.send( method, path, @@ -131,6 +134,7 @@ async def request( headers=headers, if_actor=if_actor, accepted_statuses=accepted_statuses, + read_only=read_only, ) try: if not response.content: @@ -145,7 +149,7 @@ async def request( url=self.url(path), response=response, request_dispatched=True, - outcome_unknown=may_write(method, path), + outcome_unknown=not read_only and may_write(method, path), ) from None async def send( @@ -160,6 +164,7 @@ async def send( headers: Mapping[str, str] | None = None, if_actor: str | None = None, accepted_statuses: Sequence[int] = (), + read_only: bool = False, ) -> httpx.Response: """Send one request and read its whole body.""" async with self.stream( @@ -172,11 +177,12 @@ async def send( headers=headers, if_actor=if_actor, accepted_statuses=accepted_statuses, + read_only=read_only, ) as response: try: await response.aread() except httpx.TransportError as e: - raise self._transport_error(method, path, e) from e + raise self._transport_error(method, path, e, read_only) from e return response @contextlib.asynccontextmanager @@ -192,6 +198,7 @@ async def stream( headers: Mapping[str, str] | None = None, if_actor: str | None = None, accepted_statuses: Sequence[int] = (), + read_only: bool = False, ) -> AsyncIterator[httpx.Response]: """Send one request and yield the response with its body unread, once its status and contract header passed. Closing the context closes the @@ -223,7 +230,7 @@ async def stream( if content_type is not None: sent["Content-Type"] = content_type params = {k: v for k, v in (query or {}).items() if v is not None} - writes = may_write(method, path) + writes = not read_only and may_write(method, path) request = self._client.build_request( method, url, content=content, headers=sent, params=params ) @@ -236,7 +243,7 @@ async def stream( url=url, ) from e except httpx.TransportError as e: - raise self._transport_error(method, path, e) from e + raise self._transport_error(method, path, e, read_only) from e try: if not path.startswith(_OAUTH_PREFIX) and response.headers.get_list( HTTP_API_CONTRACT_HEADER @@ -250,7 +257,9 @@ async def stream( code="api_contract_mismatch", response=response, request_dispatched=True, - outcome_unknown=writes, + # A reply outside the contract cannot confirm that a + # read-only request (a dry run) was treated as one. + outcome_unknown=may_write(method, path), ) if ( not response.is_success @@ -264,7 +273,7 @@ async def stream( parsed = None raise from_response( response, - error_body(parsed), + parsed, method=method, url=url, may_write=writes, @@ -274,19 +283,22 @@ async def stream( await response.aclose() def _transport_error( - self, method: str, path: str, error: httpx.TransportError + self, method: str, path: str, error: httpx.TransportError, read_only: bool ) -> NetworkError: return NetworkError( "HTTP transport failed after dispatch; reconcile writes before retrying", method=method, url=self.url(path), request_dispatched=True, - outcome_unknown=may_write(method, path), + outcome_unknown=not read_only and may_write(method, path), ) def invalid_response( self, method: str, path: str, message: str, status: int = 200 ) -> ApiContractError: + """A reply that contradicts its request. It is judged by the route, not + by what was asked: a dry-run merge whose reply says it ran no dry run + may have merged.""" return ApiContractError( f"{message}; effects are unknown; reconcile before retrying", status=status, diff --git a/src/omnigraph/_version.py b/src/omnigraph/_version.py index d467cb2..e07fa4e 100644 --- a/src/omnigraph/_version.py +++ b/src/omnigraph/_version.py @@ -1,5 +1,5 @@ """Generated by scripts/generate.py. Do not edit by hand.""" -SERVER_VERSION = "0.14.0" +SERVER_VERSION = "0.16.0" HTTP_API_CONTRACT = "0.14" HTTP_API_CONTRACT_HEADER = "Omnigraph-Http-Api" diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 983488e..dc5dbcc 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -1,16 +1,17 @@ -"""Live tests against `omnigraph-server` 0.14.0. +"""Live tests against the pinned `omnigraph-server` release (`SERVER_VERSION`). Set `OMNIGRAPH_TEST_SERVER=1` and `OMNIGRAPH_BIN_DIR` to a directory holding the release's `omnigraph` and `omnigraph-server`. The fixture bootstraps a one-graph cluster on a local `file://` root and boots the server with a bearer -token and a policy that grants the test actor the data-plane actions. +token and a policy that grants the test actor the data-plane actions and +`maintain`, with the recorded-operation routes enabled. """ from __future__ import annotations +import asyncio import json import os -import re import socket import subprocess import time @@ -22,12 +23,16 @@ import pytest from omnigraph import ( + SERVER_VERSION, + BadRequestError, ConflictError, NotFoundError, Omnigraph, PayloadTooLargeError, PreconditionFailedError, UnauthorizedError, + is_terminal, + new_operation_id, ) pytestmark = pytest.mark.skipif( @@ -54,6 +59,16 @@ edge WorksAt: Person -> Company { role: String? } + +node Spot { + slug: String @key + at: Vector(2) +} + +node Counter { + name: String @key + n: U64 +} """ POLICY = f"""\ version: 1 @@ -63,7 +78,7 @@ - id: rw allow: actors: {{ group: sdk }} - actions: [read, change, export] + actions: [read, change, export, maintain] branch_scope: any - id: branches allow: @@ -106,25 +121,33 @@ def server(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Server]: (bundle / "g.pg").write_text(SCHEMA) (bundle / "graph.policy.yaml").write_text(POLICY) env = {**os.environ, "OMNIGRAPH_HOME": str(work / "home")} - r = subprocess.run( + subprocess.run( [str(bin_dir / "omnigraph"), "cluster", "apply", "--target", f"file://{root}", "--config", str(bundle), "--as", ACTOR, "--json"], capture_output=True, text=True, env=env, check=True, ) # fmt: skip - lock = re.search(r"Admission lock: (\S+);", r.stderr) - assert lock, r.stderr - subprocess.run( - [str(bin_dir / "omnigraph"), "--target", f"file://{root}", "cluster", - "force-unlock", lock.group(1)], - capture_output=True, env=env, check=True, + # 0.16 releases the lock after a converged direct apply; an older CLI + # leaves it held. Unlock only what `cluster status` still reports. + status = subprocess.run( + [str(bin_dir / "omnigraph"), "cluster", "status", "--target", f"file://{root}", + "--json"], + capture_output=True, text=True, env=env, check=True, ) # fmt: skip + lock = json.loads(status.stdout).get("lock_id") + if lock: + subprocess.run( + [str(bin_dir / "omnigraph"), "--target", f"file://{root}", "cluster", + "force-unlock", lock], + capture_output=True, env=env, check=True, + ) # fmt: skip token = os.urandom(12).hex() port = _free_port() proc = subprocess.Popen( [str(bin_dir / "omnigraph-server"), "--cluster", f"file://{root}", "--bind", f"127.0.0.1:{port}"], stdout=(work / "server.log").open("wb"), stderr=subprocess.STDOUT, - env={**env, "OMNIGRAPH_SERVER_BEARER_TOKENS_JSON": json.dumps({ACTOR: token})}, + env={**env, "OMNIGRAPH_SERVER_BEARER_TOKENS_JSON": json.dumps({ACTOR: token}), + "OMNIGRAPH_OPERATION_ROUTES": "true"}, ) # fmt: skip base = f"http://127.0.0.1:{port}" deadline = time.monotonic() + 30 @@ -157,7 +180,7 @@ async def og(server: Server) -> AsyncIterator[Omnigraph]: async def test_probes(og: Omnigraph) -> None: - assert (await og.health())["version"] == "0.14.0" + assert (await og.health())["version"] == SERVER_VERSION assert (await og.readiness())["ready"] is True @@ -303,3 +326,176 @@ async def test_blob_put_get_clear(og: Omnigraph) -> None: assert head.status_code == 200 and head.headers.get("ETag") cleared = await og.blobs.clear(**sel) assert cleared["commit"] is not None + + +async def test_branch_list_detailed(og: Omnigraph) -> None: + await og.branches.create("sdk_detail") + await og.mutate( + INSERT_PERSON, params={"n": "detail", "c": None}, branch="sdk_detail" + ) + listed = await og.branches.list_detailed() + assert "sdk_detail" in listed["branches"] + details = {d["name"]: d for d in listed["details"]} + assert [d["name"] for d in listed["details"]] == [ + b for b in listed["branches"] if b in details + ] + branch = details["sdk_detail"] + assert branch.get("from") == "main" and branch.get("from_commit_id") + assert branch["head"]["graph_commit_id"] != branch.get("from_commit_id") + assert branch["updated_at"] >= (branch.get("created_at") or 0) + assert "from" not in details["main"] or details["main"].get("from") is None + await og.branches.delete("sdk_detail") + + +async def test_ranked_read_reports_ranking(og: Omnigraph) -> None: + await og.mutate( + 'query s() { insert Spot { slug: "near", at: [0.0, 0.0] } ' + 'insert Spot { slug: "far", at: [5.0, 5.0] } }' + ) + read = await og.query( + "query n($v: Vector(2)) { match { $s: Spot } " + "return { $s.slug, nearest($s.at, $v) as dist } " + "order { nearest($s.at, $v) } limit 2 }", + params={"v": [0.1, 0.1]}, + ) + assert [r["s.slug"] for r in read["rows"]] == ["near", "far"] + ranking = read.get("ranking") + assert ranking is not None, read + assert ranking["by"] == "nearest" and ranking["order"] == "ascending" + assert ranking["score_columns"] == ["dist"] + assert ranking["exhaustive"] is True + + +U64_MAX = 2**64 - 1 + + +@pytest.mark.parametrize("value", [U64_MAX, str(U64_MAX)], ids=["number", "string"]) +async def test_u64_parameter_above_i64_max_binds(og: Omnigraph, value: object) -> None: + name = f"max-{type(value).__name__}" + await og.mutate( + "query c($k: String, $n: U64) { insert Counter { name: $k, n: $n } }", + params={"k": name, "n": value}, + ) + read = await og.query( + "query r($n: U64) { match { $c: Counter { n: $n } } return { $c.name, $c.n } }", + params={"n": value}, + ) + assert {"c.name": name, "c.n": U64_MAX} in read["rows"], read["rows"] + + +async def test_access_reports_maintain_and_no_oauth_client(og: Omnigraph) -> None: + access = await og.access(branch="main") + assert "maintain" in access["actions"] + assert access.get("client_id") is None # a static token has no OAuth client + + +async def test_dry_run_merge_reports_without_writing(og: Omnigraph) -> None: + await og.branches.create("sdk_dry") + await og.mutate(INSERT_PERSON, params={"n": "dry", "c": None}, branch="sdk_dry") + head = (await og.query(COUNT))["graph_commit_id"] + preview = await og.branches.merge("sdk_dry", dry_run=True) + assert preview["dry_run"] is True and preview["commit"] is None + assert preview["outcome"] in ("fast_forward", "merged") + assert (await og.query(COUNT))["graph_commit_id"] == head + await og.branches.delete("sdk_dry") + + +async def test_recorded_optimize_submit_wait_lookup_cancel(og: Omnigraph) -> None: + await og.mutate(INSERT_PERSON, params={"n": "opt", "c": None}) + op_id = new_operation_id() + submitted = await og.operations.optimize(op_id, max_gate_hold_ms=30_000) + assert submitted["lookup"] == "found" + op = submitted.get("operation") + assert op is not None and op["operation_id"] == op_id + assert op["request"]["kind"] == "optimize" + + # The same id and request answers the existing record, starting nothing. + again = await og.operations.optimize(op_id, max_gate_hold_ms=30_000) + again_op = again.get("operation") + assert again_op is not None and again_op["accepted_at"] == op["accepted_at"] + + async with asyncio.timeout(120): + done = await og.operations.wait(op_id, interval=0.2) + final = done.get("operation") + assert final is not None and final["state"] == "succeeded", final + assert is_terminal(final["state"]) and done["in_progress"] is False + # A full run reports every dataset of the schema, under `datasets`. + datasets = final["outcome"].get("datasets") + assert datasets, final + keys = {d["type_key"] for d in datasets} + assert {"node:Person", "node:Company", "edge:WorksAt"} <= keys, keys + for dataset in datasets: + assert dataset["outcome"] in ("optimized", "unchanged", "deferred", "failed") + + # Cancelling a terminal operation leaves it unchanged. + cancelled = await og.operations.cancel(op_id) + cancelled_op = cancelled.get("operation") + assert cancelled_op is not None and cancelled_op["state"] == "succeeded" + + # The same id with another request is refused, not run. + with pytest.raises(ConflictError) as info: + await og.operations.optimize(op_id, datasets=["node:Person"]) + assert info.value.outcome_unknown is False + + +async def test_a_run_limited_to_one_dataset_reports_exactly_it(og: Omnigraph) -> None: + op_id = new_operation_id() + await og.operations.optimize(op_id, datasets=["node:Person"]) + async with asyncio.timeout(120): + done = await og.operations.wait(op_id, interval=0.05) + op = done.get("operation") + assert op is not None and op["request"].get("datasets") == ["node:Person"] + assert [d["type_key"] for d in op["outcome"].get("datasets", [])] == ["node:Person"] + + +async def test_cancelling_an_active_run(og: Omnigraph) -> None: + # A fixture run takes milliseconds, so cancel concurrently with the + # submission: the first cancel that finds the record meets it accepted or + # running unless the run already ended. Retry until one meets an active + # run, then check the terminal record. + for _ in range(50): + op_id = new_operation_id() + submit = asyncio.create_task(og.operations.optimize(op_id)) + while True: + reply = await og.operations.cancel(op_id) + if reply["lookup"] == "found": + break + await submit + cancel = reply.get("operation") + assert cancel is not None + if is_terminal(cancel["state"]): + continue + async with asyncio.timeout(120): + done = await og.operations.wait(op_id, interval=0.02) + op = done.get("operation") + assert op is not None + if cancel["state"] == "publishing": + # No cancellation is requested once publishing; it finishes. + assert op["state"] == "succeeded" + elif op["state"] == "cancelled": + assert "published_commit" not in op + assert "cancelled by" in op.get("reason", "") + else: + # omnigraph 0.16.0 settles a run's cancellation when it builds the + # run's report, but keeps the record running until it writes the + # terminal record; a cancel in that window is answered 202 and + # the run ends succeeded with no reason. A reason, when present, + # says the cancellation arrived late. + assert op["state"] == "succeeded" + reason = op.get("reason") + assert reason is None or "a cancellation arrived after" in reason + return + pytest.fail("no cancel met an active run in 50 attempts") + + +async def test_unknown_operation_lookup(og: Omnigraph) -> None: + looked = await og.operations.get(new_operation_id()) + assert looked["lookup"] == "unknown" and looked.get("operation") is None + waited = await og.operations.wait(new_operation_id(), interval=0) + assert waited["lookup"] == "unknown" + + +async def test_non_canonical_operation_id_is_refused(og: Omnigraph) -> None: + with pytest.raises(BadRequestError) as info: + await og.operations.optimize("not-a-ulid") + assert info.value.outcome_unknown is False diff --git a/tests/test_generate.py b/tests/test_generate.py new file mode 100644 index 0000000..8a24e72 --- /dev/null +++ b/tests/test_generate.py @@ -0,0 +1,55 @@ +"""The generator reads the HTTP contract from the spec, not the release number.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) + +import generate + + +def _op(*values: str) -> dict[str, Any]: + return { + "parameters": [ + {"name": "graph_id", "in": "path", "schema": {"type": "string"}}, + { + "name": "Omnigraph-Http-Api", + "in": "header", + "schema": {"type": "string", "enum": list(values)}, + }, + ] + } + + +def test_contract_is_the_header_enum_not_the_release() -> None: + spec = { + "info": {"version": "0.16.0"}, + "paths": {"/a": {"get": _op("0.14")}, "/b": {"post": _op("0.14")}}, + } + assert generate.http_api_contract(spec) == "0.14" + + +@pytest.mark.parametrize( + "paths", + [ + {"/a": {"get": _op("0.14")}, "/b": {"get": _op("0.15")}}, + {"/a": {"get": _op("0.14", "0.15")}}, + {"/a": {"get": {"parameters": []}}}, + ], +) +def test_contract_must_be_one_value(paths: dict[str, Any]) -> None: + with pytest.raises(SystemExit): + generate.http_api_contract({"paths": paths}) + + +def test_pinned_spec_contract_matches_generated_version() -> None: + from omnigraph import HTTP_API_CONTRACT + + spec = json.loads(generate.SPEC.read_text()) + assert generate.http_api_contract(spec) == HTTP_API_CONTRACT diff --git a/tests/test_operations.py b/tests/test_operations.py new file mode 100644 index 0000000..3771b71 --- /dev/null +++ b/tests/test_operations.py @@ -0,0 +1,287 @@ +"""Recorded operations against a mocked server.""" + +from __future__ import annotations + +import asyncio +import json +import re +import time +from typing import Any + +import httpx +import pytest + +import omnigraph +from omnigraph import Omnigraph, is_terminal, new_operation_id + +CONTRACT = {"Omnigraph-Http-Api": "0.14"} +OP_ID = "01JC0000000000000000000000" + + +def _record(state: str, **extra: Any) -> dict[str, Any]: + return { + "operation_id": OP_ID, "request_digest": "sha256:x", "graph": "g", + "schema_identity_domain": "d", "settlement_branch": "main", + "request": {"kind": "optimize"}, "principal": "act", "accepted_at": "t", + "state": state, "outcome": {"kind": "optimize"}, "timings": {}, **extra, + } # fmt: skip + + +class Server: + def __init__(self, *answers: tuple[int, Any]) -> None: + self.answers = list(answers) + self.requests: list[httpx.Request] = [] + + def __call__(self, request: httpx.Request) -> httpx.Response: + if request.method == "HEAD": + return httpx.Response(200, headers=CONTRACT) + self.requests.append(request) + status, body = self.answers.pop(0) + return httpx.Response(status, json=body, headers=CONTRACT) + + +def _client(server: Server) -> Omnigraph: + return Omnigraph( + "http://og.test", graph_id="g", transport=httpx.MockTransport(server) + ) + + +def test_new_operation_id_is_a_canonical_ulid() -> None: + before = time.time_ns() // 1_000_000 + ids = {new_operation_id() for _ in range(64)} + after = time.time_ns() // 1_000_000 + assert len(ids) == 64 + crockford = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" + for op_id in ids: + assert re.fullmatch(r"[0-7][0-9A-HJKMNP-TV-Z]{25}", op_id), op_id + stamp = 0 + for ch in op_id[:10]: + stamp = stamp * 32 + crockford.index(ch) + assert before <= stamp <= after + + +@pytest.mark.parametrize( + ("state", "terminal"), + [("accepted", False), ("running", False), ("publishing", False), + ("succeeded", True), ("failed", True), ("cancelled", True), + ("interrupted", True), ("unsettled", True)], +) # fmt: skip +def test_terminal_states(state: str, terminal: bool) -> None: + assert is_terminal(state) is terminal + + +async def test_optimize_submits_the_callers_id_and_returns_202_record() -> None: + server = Server((202, {"lookup": "found", "in_progress": True, + "operation": _record("accepted")})) # fmt: skip + async with _client(server) as og: + out = await og.operations.optimize( + OP_ID, datasets=["node:Person"], max_gate_hold_ms=30_000 + ) + (req,) = server.requests + assert req.method == "POST" + assert req.url.path == "/graphs/g/operations/optimize" + assert json.loads(req.content) == { + "operation_id": OP_ID, "datasets": ["node:Person"], "max_gate_hold_ms": 30_000, + } # fmt: skip + op = out.get("operation") + assert out["lookup"] == "found" and op is not None and op["state"] == "accepted" + + +async def test_optimize_sends_only_the_id_by_default() -> None: + server = Server((200, {"lookup": "found", "in_progress": False, + "operation": _record("succeeded")})) # fmt: skip + async with _client(server) as og: + await og.operations.optimize(OP_ID) + assert json.loads(server.requests[0].content) == {"operation_id": OP_ID} + + +async def test_optimize_refuses_one_string_as_datasets_before_sending() -> None: + server = Server() + async with _client(server) as og: + with pytest.raises(TypeError, match="list of type keys"): + await og.operations.optimize(OP_ID, datasets="node:Person") + assert server.requests == [] + + +async def test_lost_submission_is_outcome_unknown_and_not_retried() -> None: + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "HEAD": + return httpx.Response(200, headers=CONTRACT) + raise httpx.ReadError("reset", request=request) + + calls: list[httpx.Request] = [] + + def counting(request: httpx.Request) -> httpx.Response: + if request.method != "HEAD": + calls.append(request) + return handler(request) + + async with Omnigraph( + "http://og.test", graph_id="g", transport=httpx.MockTransport(counting) + ) as og: + with pytest.raises(omnigraph.NetworkError) as info: + await og.operations.optimize(OP_ID) + assert info.value.outcome_unknown is True + assert len(calls) == 1 + + +async def test_get_and_cancel_routes() -> None: + server = Server( + (200, {"lookup": "unknown", "in_progress": False}), + ( + 202, + {"lookup": "found", "in_progress": True, "operation": _record("running")}, + ), + ) + async with _client(server) as og: + looked = await og.operations.get(OP_ID) + cancelled = await og.operations.cancel(OP_ID) + assert [(r.method, r.url.path) for r in server.requests] == [ + ("GET", f"/graphs/g/operations/{OP_ID}"), + ("POST", f"/graphs/g/operations/{OP_ID}/cancel"), + ] + assert looked["lookup"] == "unknown" and "operation" not in looked + assert cancelled["in_progress"] is True + + +async def test_a_refused_cancel_is_not_outcome_unknown() -> None: + server = Server((503, {"error": "[state_read_error] x", "code": "service_unavailable", + "disposition": {"effects": "none", "action": "retry"}})) # fmt: skip + async with _client(server) as og: + with pytest.raises(omnigraph.ServiceUnavailableError) as info: + await og.operations.cancel(OP_ID) + assert info.value.outcome_unknown is False + + +async def test_wait_polls_the_lookup_until_terminal() -> None: + outcome = {"kind": "optimize", "datasets": [ + {"type_key": "node:Person", "outcome": "optimized", "reason": "index_failed", + "detail": "boom", "fragments_removed": 2, "fragments_added": 1, + "duration_ms": 5}], "more_datasets": {"deferred:gate_hold_limit": 3}} # fmt: skip + server = Server( + (200, {"lookup": "found", "in_progress": True, "operation": _record("running")}), + (200, {"lookup": "found", "in_progress": True, + "operation": _record("publishing")}), + (200, {"lookup": "found", "in_progress": False, + "operation": _record("succeeded", published_commit="c9", + outcome=outcome)}), + ) # fmt: skip + async with _client(server) as og: + out = await og.operations.wait(OP_ID, interval=0) + assert [r.method for r in server.requests] == ["GET"] * 3 + op = out.get("operation") + assert op is not None and op["state"] == "succeeded" + assert op["outcome"].get("more_datasets") == {"deferred:gate_hold_limit": 3} + assert op["outcome"].get("datasets", [])[0].get("reason") == "index_failed" + + +async def test_wait_stops_at_an_unknown_lookup() -> None: + server = Server((200, {"lookup": "unknown", "in_progress": False})) + async with _client(server) as og: + out = await og.operations.wait(OP_ID, interval=0) + assert out["lookup"] == "unknown" and len(server.requests) == 1 + + +async def test_wait_does_not_retry_an_error() -> None: + server = Server( + (200, {"lookup": "found", "in_progress": True, "operation": _record("running")}), + (500, {"error": "x", "code": "internal", + "disposition": {"effects": "none", "action": "retry"}}), + ) # fmt: skip + async with _client(server) as og: + with pytest.raises(omnigraph.InternalServerError): + await og.operations.wait(OP_ID, interval=0) + assert len(server.requests) == 2 + + +async def test_wait_is_bounded_by_the_caller() -> None: + running = {"lookup": "found", "in_progress": True, "operation": _record("running")} + server = Server(*[(200, running)] * 1000) + async with _client(server) as og: + with pytest.raises(TimeoutError): + async with asyncio.timeout(0.05): + await og.operations.wait(OP_ID, interval=0.01) + + +_ROUTES: list[tuple[str, Any, bool, bool]] = [ + # name, call, may write (an invalid reply is outcome unknown), unknown allowed + ("optimize", lambda og: og.operations.optimize(OP_ID), True, False), + ("get", lambda og: og.operations.get(OP_ID), False, True), + ("cancel", lambda og: og.operations.cancel(OP_ID), True, True), +] +_FOREIGN = "01JC9999999999999999999999" +_INVALID: list[tuple[str, Any]] = [ + ("an empty object", {}), + ("another operation's record", + {"lookup": "found", "in_progress": False, + "operation": {**_record("succeeded"), "operation_id": _FOREIGN}}), + ("found without a record", {"lookup": "found", "in_progress": False}), + ("a record without a state", + {"lookup": "found", "in_progress": False, + "operation": {"operation_id": OP_ID, "outcome": {}}}), + ("no in_progress", {"lookup": "found", "operation": _record("succeeded")}), +] # fmt: skip + + +@pytest.mark.parametrize( + ("call", "writes", "reply"), + [(c, w, r) for _, c, w, _ in _ROUTES for _, r in _INVALID], + ids=[f"{n}-{d}" for n, _, _, _ in _ROUTES for d, _ in _INVALID], +) +async def test_a_route_refuses_a_reply_that_is_not_its_receipt( + call: Any, writes: bool, reply: Any +) -> None: + server = Server((200, reply)) + async with _client(server) as og: + with pytest.raises(omnigraph.ApiContractError) as info: + await call(og) + assert info.value.request_dispatched is True + assert info.value.outcome_unknown is writes + assert len(server.requests) == 1 + + +@pytest.mark.parametrize( + ("call", "unknown_allowed"), + [(c, u) for _, c, _, u in _ROUTES], + ids=[n for n, _, _, _ in _ROUTES], +) +async def test_unknown_is_a_receipt_only_where_the_route_can_answer_it( + call: Any, unknown_allowed: bool +) -> None: + server = Server((200, {"lookup": "unknown", "in_progress": False})) + async with _client(server) as og: + if unknown_allowed: + assert (await call(og))["lookup"] == "unknown" + else: + with pytest.raises(omnigraph.ApiContractError) as info: + await call(og) + assert info.value.outcome_unknown is True + + +async def test_wait_stops_at_an_invalid_receipt() -> None: + server = Server((200, {"lookup": "found", "in_progress": True})) + async with _client(server) as og: + with pytest.raises(omnigraph.ApiContractError) as info: + await og.operations.wait(OP_ID, interval=0) + assert info.value.outcome_unknown is False + + +async def test_a_lookup_that_leaves_a_settlement_write_in_doubt_is_uncertain() -> None: + doubt = (500, {"error": "resolution write in doubt; retry the lookup", + "code": "outcome_unknown", + "disposition": {"effects": "none", "action": "reconcile"}}) # fmt: skip + server = Server(doubt, doubt) + async with _client(server) as og: + for call in (og.operations.get, og.operations.wait): + with pytest.raises(omnigraph.InternalServerError) as info: + await call(OP_ID) + assert info.value.code == "outcome_unknown" + assert info.value.outcome_unknown is True + + +def test_dataset_outcomes_are_exported_under_their_dataset_name() -> None: + # 0.16 (omnigraph 9575c176) names a run's outcomes per dataset, not table. + assert "DatasetOutcome" in omnigraph.__all__ + assert "TableOutcome" not in omnigraph.__all__ + hints = omnigraph.OptimizeOutcome.__annotations__["datasets"] + assert "DatasetOutcome" in str(hints) diff --git a/tests/test_transport.py b/tests/test_transport.py index cbf129d..dc5d2a1 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -135,6 +135,12 @@ async def test_graph_scoped_call_without_graph_id_is_refused_before_sending() -> (413, "payload_too_large", PayloadTooLargeError), (503, "graph_unavailable", GraphUnavailableError), (400, "api_contract_mismatch", ApiContractError), + (403, "forbidden", omnigraph.ForbiddenError), + (403, "not_admitted", omnigraph.NotAdmittedError), + # A code's class never overrides a status it does not refine. + (409, "not_admitted", ConflictError), + (418, "not_admitted", omnigraph.NotAdmittedError), + (409, "writer_fenced", omnigraph.WriterFencedError), ], ) async def test_errors_map_to_classes( @@ -172,8 +178,33 @@ async def test_write_outcome_follows_effects(effects: str, unknown: bool) -> Non assert info.value.outcome_unknown is unknown -async def test_a_read_error_is_never_outcome_unknown() -> None: - rec = Recorder(lambda r: _error(400, "bad_request", "unknown")) +@pytest.mark.parametrize( + ("status", "code", "effects", "unknown"), + [ + (403, "not_admitted", "none", False), + (403, "forbidden", "none", False), + (409, "writer_fenced", "none", False), + (409, "writer_fenced", "partial", True), + (500, "outcome_unknown", "unknown", True), + (503, "service_unavailable", "none", False), + ], +) +async def test_refused_write_disposition_without_retries( + status: int, code: str, effects: str, unknown: bool +) -> None: + rec = Recorder(lambda r: _error(status, code, effects)) + async with _client(rec) as og: + with pytest.raises(omnigraph.OmnigraphError) as info: + await og.mutate('query a() { insert A { k: "x" } }') + assert info.value.code == code + assert info.value.outcome_unknown is unknown + assert len(rec.data_requests) == 1 + + +async def test_a_read_refusal_the_server_calls_certain_is_not_outcome_unknown() -> None: + # A read is uncertain only when the server says so (see + # test_a_read_keeps_the_servers_word_on_uncertainty). + rec = Recorder(lambda r: _error(400, "bad_request", "none")) async with _client(rec) as og: with pytest.raises(omnigraph.BadRequestError) as info: await og.query("query q() { match { $a: A } return { $a.k } }") @@ -259,3 +290,213 @@ def test_base_url_must_be_a_plain_server_root() -> None: for bad in ("ftp://x", "http://u:p@x", "http://x?q=1", "http://x#f"): with pytest.raises(ConfigurationError): Omnigraph(bad) + + +def _commit(cid: str, branch: str | None = None) -> dict[str, Any]: + return {"graph_commit_id": cid, "graph_manifest_version": 3, + "graph_branch": branch, "kind": "published", "published": True} # fmt: skip + + +async def test_branch_list_detailed_asks_for_details() -> None: + body = { + "branches": ["feature", "main", "secret"], + "details": [ + {"name": "feature", "head": _commit("c2", "feature"), "from": "main", + "from_commit_id": "c1", "created_at": 1714000000000000, + "updated_at": 1714000001000000}, + {"name": "main", "head": _commit("c1"), "updated_at": 1714000000000000}, + ], + } # fmt: skip + rec = Recorder(lambda r: _json(200, body)) + async with _client(rec) as og: + out = await og.branches.list_detailed() + (req,) = rec.data_requests + assert req.method == "GET" and req.url.params["detailed"] == "true" + assert out["branches"] == ["feature", "main", "secret"] + assert [d["name"] for d in out["details"]] == ["feature", "main"] + assert out["details"][0]["from"] == "main" + + +async def test_branch_list_detailed_without_details_is_a_contract_error() -> None: + rec = Recorder(lambda r: _json(200, {"branches": ["main"]})) + async with _client(rec) as og: + with pytest.raises(ApiContractError) as info: + await og.branches.list_detailed() + assert info.value.outcome_unknown is False + + +async def test_ranked_read_reports_its_ranking() -> None: + body = { + "query_name": "q", "target": {"branch": "main"}, "row_count": 1, + "rows": [{"d.slug": "a", "score": 1.5}], "columns": ["d.slug", "score"], + "ranking": {"by": "bm25", "order": "descending", "exhaustive": True, + "score_columns": ["score"]}, + } # fmt: skip + rec = Recorder(lambda r: _json(200, body)) + async with _client(rec) as og: + out = await og.query("query q($t: String) { ... }", params={"t": "x"}) + ranking = out.get("ranking") + assert ranking is not None + assert ranking["by"] == "bm25" and ranking["order"] == "descending" + assert ranking["score_columns"] == ["score"] + + +async def test_access_reports_the_oauth_client() -> None: + body = {"graph_id": "g", "actor_id": "principal:p", "client_id": "studio", + "actions": ["read"], "graph_wide": ["read"]} # fmt: skip + rec = Recorder(lambda r: _json(200, body)) + async with _client(rec) as og: + out = await og.access() + assert out.get("client_id") == "studio" + + +async def test_settings_travel_in_query_mutate_and_merge_bodies() -> None: + def data(request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("/branches/merge"): + return _json(200, {"source": "s", "target": "main", "dry_run": True, + "outcome": "fast_forward", "commit": None}) # fmt: skip + if request.url.path.endswith("/mutate"): + return _json( + 200, {"affected_nodes": 0, "affected_edges": 0, "commit": None} + ) + return _json(200, {"query_name": "q", "target": {}, "row_count": 0, "rows": []}) + + rec = Recorder(data) + settings: Any = {"change_lineage": "verify"} + async with _client(rec) as og: + await og.query("query q() { ... }", settings=settings) + await og.mutate("query m() { ... }", settings=settings) + await og.branches.merge("s", dry_run=True, settings=settings) + bodies = [json.loads(r.content) for r in rec.data_requests] + assert [b["settings"] for b in bodies] == [settings] * 3 + + +@pytest.mark.parametrize( + ("status", "code", "field", "cls", "accessor"), + [ + (409, "conflict", "read_set_conflict", ConflictError, "read_set_conflict"), + (409, "conflict", "published_dataset_version_conflict", ConflictError, + "published_dataset_version_conflict"), + (409, "conflict", "change_diff_refusal", ConflictError, "change_diff_refusal"), + (409, "conflict", "full_text_index_rebuild_required", ConflictError, + "full_text_index_rebuild_required"), + (410, "change_feed_gap", "change_feed_gap", omnigraph.GoneError, + "change_feed_gap"), + (416, "range_not_satisfiable", "blob_range", + omnigraph.RangeNotSatisfiableError, "blob_range"), + (424, "external_blob_source", "external_blob_source", + omnigraph.FailedDependencyError, "external_blob_source"), + (503, "recovery_required", "recovery_required", + omnigraph.ServiceUnavailableError, "recovery_required"), + ], +) # fmt: skip +async def test_error_details_are_exposed( + status: int, code: str, field: str, cls: type[Exception], accessor: str +) -> None: + detail = {"marker": field} + rec = Recorder(lambda r: _error(status, code, "none", **{field: detail})) + async with _client(rec) as og: + with pytest.raises(cls) as info: + await og.schema.get() + assert getattr(info.value, accessor) == detail + + +@pytest.mark.parametrize( + ("body", "status", "unknown"), + [ + # code outcome_unknown wins over any disposition it carries + ({"error": "resolution write in doubt", "code": "outcome_unknown", + "disposition": {"effects": "none", "action": "reconcile"}}, 500, True), + ({"error": "in doubt", "code": "outcome_unknown"}, 500, True), + ({"error": "in doubt", "code": "internal", + "disposition": {"effects": "unknown", "action": "reconcile"}}, 500, True), + ({"error": "half", "code": "conflict", + "disposition": {"effects": "partial", "action": "refresh"}}, 409, True), + ({"error": "retry", "code": "service_unavailable", + "disposition": {"effects": "none", "action": "retry"}}, 503, False), + ("gateway timeout", 500, False), + ], +) # fmt: skip +async def test_a_read_keeps_the_servers_word_on_uncertainty( + body: Any, status: int, unknown: bool +) -> None: + rec = Recorder(lambda r: _json(status, body)) + async with _client(rec) as og: + with pytest.raises(omnigraph.OmnigraphError) as info: + await og.snapshot() + assert info.value.status == status + assert info.value.outcome_unknown is unknown + assert len(rec.data_requests) == 1 + + +async def test_a_write_without_a_valid_body_stays_uncertain() -> None: + rec = Recorder( + lambda r: httpx.Response(502, content=b"bad gateway", headers=CONTRACT) + ) + async with _client(rec) as og: + with pytest.raises(omnigraph.OmnigraphError) as info: + await og.mutate('query q() { insert A { k: "x" } }') + assert info.value.outcome_unknown is True + + +async def test_writer_fenced_names_the_epochs() -> None: + fenced = {"current": 7, "held": 6} + rec = Recorder(lambda r: _error(409, "writer_fenced", "none", writer_fenced=fenced)) + async with _client(rec) as og: + with pytest.raises(omnigraph.WriterFencedError) as info: + await og.mutate('query a() { insert A { k: "x" } }') + err = info.value + assert isinstance(err, ConflictError) + assert err.writer_fenced == fenced + assert err.outcome_unknown is False + assert len(rec.data_requests) == 1 + + +def _lost(request: httpx.Request) -> httpx.Response: + raise httpx.ReadError("connection reset", request=request) + + +@pytest.mark.parametrize(("dry_run", "unknown"), [(True, False), (False, True)]) +async def test_a_lost_dry_run_merge_has_no_effects( + dry_run: bool, unknown: bool +) -> None: + rec = Recorder(_lost) + async with _client(rec) as og: + with pytest.raises(NetworkError) as info: + await og.branches.merge("s", dry_run=dry_run) + assert info.value.outcome_unknown is unknown + assert len(rec.data_requests) == 1 + + +async def test_an_interrupted_dry_run_reply_has_no_effects() -> None: + rec = Recorder(lambda r: httpx.Response(200, content=b"{trunc", headers=CONTRACT)) + async with _client(rec) as og: + with pytest.raises(NetworkError) as info: + await og.branches.merge("s", dry_run=True) + assert info.value.outcome_unknown is False + + +@pytest.mark.parametrize( + "reply", + [ + _merge("fast_forward", _commit("c1")), # it merged + {**_merge("fast_forward", None), "dry_run": True, "branch_deleted": True}, + ], +) +async def test_a_reply_contradicting_the_dry_run_is_outcome_unknown( + reply: dict[str, Any], +) -> None: + rec = Recorder(lambda r: _json(200, reply)) + async with _client(rec) as og: + with pytest.raises(ApiContractError) as info: + await og.branches.merge("s", dry_run=True) + assert info.value.outcome_unknown is True + + +async def test_a_dry_run_reply_without_the_contract_is_outcome_unknown() -> None: + # Only a reply inside the contract confirms the server ran a dry run. + rec = Recorder(lambda r: httpx.Response(200, json=_merge("fast_forward", None))) + async with _client(rec) as og: + with pytest.raises(ApiContractError) as info: + await og.branches.merge("s", dry_run=True) + assert info.value.outcome_unknown is True diff --git a/uv.lock b/uv.lock index 3d477d3..581c7cc 100644 --- a/uv.lock +++ b/uv.lock @@ -621,7 +621,7 @@ wheels = [ [[package]] name = "omnigraph" -version = "0.14.0" +version = "0.16.0" source = { editable = "." } dependencies = [ { name = "httpx" },