diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 34dd9c6..d4ecfa5 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -8,11 +8,11 @@ # CI fails if this file drifts from its source, and rejects PRs that # edit this file directly without also editing the yml. -* @aaltshuler +* @ragnorc -crates/** @aaltshuler -docs/** @aaltshuler @ragnorc -README.md @aaltshuler @ragnorc -AGENTS.md @aaltshuler @ragnorc -CLAUDE.md @aaltshuler @ragnorc -SECURITY.md @aaltshuler @ragnorc +crates/** @ragnorc +docs/** @ragnorc +README.md @ragnorc +AGENTS.md @ragnorc +CLAUDE.md @ragnorc +SECURITY.md @ragnorc diff --git a/.github/branch-protection.json b/.github/branch-protection.json index 61b7d33..7ca46b9 100644 --- a/.github/branch-protection.json +++ b/.github/branch-protection.json @@ -7,8 +7,8 @@ "Check AGENTS.md Links", "Test Workspace", "Test omnigraph-server --features aws", - "CODEOWNERS / drift", - "CODEOWNERS / noedit" + "CODEOWNERS matches source", + "CODEOWNERS not hand-edited" ] }, "enforce_admins": false, diff --git a/.github/codeowners-roles.yml b/.github/codeowners-roles.yml index 9fdc8e5..c5e36a9 100644 --- a/.github/codeowners-roles.yml +++ b/.github/codeowners-roles.yml @@ -19,18 +19,15 @@ roles: engineering: description: > All production code under crates/**. Engine, CLI, server, - compiler. Single owner; review must come from this person. + compiler. members: - - aaltshuler + - ragnorc docs: description: > Documentation under docs/**, plus repo-level docs (README.md, - AGENTS.md, CLAUDE.md symlink, SECURITY.md). Either named member - can approve; both are listed so reviews can route to whoever is - available. + AGENTS.md, CLAUDE.md symlink, SECURITY.md). members: - - aaltshuler - ragnorc # Path → role mapping. GitHub CODEOWNERS uses "last match wins" diff --git a/.github/scripts/render-codeowners.py b/.github/scripts/render-codeowners.py index f243d0c..5e96545 100755 --- a/.github/scripts/render-codeowners.py +++ b/.github/scripts/render-codeowners.py @@ -1,10 +1,14 @@ #!/usr/bin/env python3 -"""Render .github/CODEOWNERS from .github/codeowners-roles.yml. +"""Render .github/CODEOWNERS and the ownership tables in +docs/dev/codeowners.md from .github/codeowners-roles.yml. -The yml is the source of truth — editing CODEOWNERS directly is -rejected by CI (see .github/workflows/codeowners.yml). This script -expands the role-based yml into the flat path→owners format GitHub -expects. +The yml is the source of truth. This script expands the role-based yml +into (1) the flat path→owners format GitHub expects in +`.github/CODEOWNERS`, and (2) the "who owns what" markdown tables spliced +between the generated-region markers in `docs/dev/codeowners.md`. Both are +derived artifacts; CI re-renders them on every PR (see +.github/workflows/codeowners.yml) and auto-commits the result on same-repo +PRs, so the source of truth and the human-readable view never drift. Usage: python3 .github/scripts/render-codeowners.py @@ -16,6 +20,7 @@ Exits non-zero on: one owner; otherwise CODEOWNERS would assign nobody and GitHub would silently fall back to "no required reviewer", which defeats the purpose). + - Missing generated-region markers in docs/dev/codeowners.md. """ from __future__ import annotations @@ -34,6 +39,13 @@ except ImportError: REPO_ROOT = Path(__file__).resolve().parents[2] SOURCE = REPO_ROOT / ".github" / "codeowners-roles.yml" OUTPUT = REPO_ROOT / ".github" / "CODEOWNERS" +DOCS = REPO_ROOT / "docs" / "dev" / "codeowners.md" + +# The "who owns what" tables in docs/dev/codeowners.md are spliced between +# these markers so the human-readable view never drifts from the source of +# truth. Edit codeowners-roles.yml and re-render — never the table by hand. +DOCS_BEGIN = "" +DOCS_END = "" BANNER = """\ # AUTOGENERATED from .github/codeowners-roles.yml. Do not edit by hand. @@ -75,6 +87,62 @@ def owners_for(role_names: list[str], roles: dict) -> list[str]: return seen +def _oneline(text: str) -> str: + """Collapse a folded/multi-line YAML description into one cell of text.""" + return " ".join((text or "").split()) + + +def ownership_tables(spec: dict, roles: dict) -> str: + """Render the human-readable "who owns what" markdown — a path→owners + table (the operative view at PR time, in last-match-wins order with the + catch-all first) plus a role→members table. Spliced into the docs between + the markers so it is always current with the source of truth.""" + out: list[str] = [] + + out.append("**Path → owners** (GitHub applies *last match wins*; the `*` " + "catch-all is listed first and is overridden by the specific " + "patterns below it):") + out.append("") + out.append("| Path | Owners | Role(s) |") + out.append("|---|---|---|") + if "default" in spec: + owners = " ".join(owners_for(spec["default"], roles)) + out.append(f"| `*` | {owners} | {', '.join(spec['default'])} |") + for pattern, role_names in (spec.get("paths") or {}).items(): + owners = " ".join(owners_for(role_names, roles)) + out.append(f"| `{pattern}` | {owners} | {', '.join(role_names)} |") + out.append("") + + out.append("**Roles**:") + out.append("") + out.append("| Role | Members | Description |") + out.append("|---|---|---|") + for name, role in roles.items(): + members = " ".join(f"@{m}" for m in (role.get("members") or [])) + out.append(f"| `{name}` | {members} | {_oneline(role.get('description', ''))} |") + out.append("") + + return "\n".join(out) + + +def splice_docs(table_md: str) -> None: + """Replace the region between DOCS_BEGIN/DOCS_END in the docs file with the + freshly generated tables, leaving surrounding prose untouched.""" + if not DOCS.exists(): + sys.exit(f"error: docs file not found: {DOCS}") + text = DOCS.read_text() + if DOCS_BEGIN not in text or DOCS_END not in text: + sys.exit( + f"error: ownership markers not found in {DOCS.relative_to(REPO_ROOT)}. " + f"Add the lines:\n {DOCS_BEGIN}\n {DOCS_END}\n" + f"around the generated table region." + ) + head, rest = text.split(DOCS_BEGIN, 1) + _, tail = rest.split(DOCS_END, 1) + new = f"{head}{DOCS_BEGIN}\n\n{table_md}\n{DOCS_END}{tail}" + DOCS.write_text(new) + + def main() -> int: if not SOURCE.exists(): sys.exit(f"error: source file not found: {SOURCE}") @@ -127,6 +195,9 @@ def main() -> int: OUTPUT.write_text(rendered) print(f"wrote {OUTPUT.relative_to(REPO_ROOT)}") + + splice_docs(ownership_tables(spec, roles)) + print(f"updated {DOCS.relative_to(REPO_ROOT)}") return 0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3dc2e80..5b7b7b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -111,6 +111,18 @@ jobs: - name: Verify AGENTS.md ↔ docs/ cross-links run: bash scripts/check-agents-md.sh + entrypoint_test: + name: Container Entrypoint + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout source + uses: actions/checkout@v5.0.1 + + - name: Verify omnigraph-server entrypoint arg composition + run: sh docker/entrypoint_test.sh + test: name: Test Workspace needs: classify_changes @@ -249,6 +261,63 @@ jobs: if: needs.classify_changes.outputs.run_full_ci == 'true' run: cargo test --locked -p omnigraph-server --features aws + test_windows_binaries: + name: Test Windows release binaries + needs: classify_changes + runs-on: windows-latest + timeout-minutes: 75 + permissions: + contents: read + env: + CARGO_TERM_COLOR: always + steps: + - name: Skip for text-only changes + if: needs.classify_changes.outputs.run_full_ci != 'true' + run: Write-Host "Text-only change detected; skipping Windows binary build." + + - name: Checkout source + if: needs.classify_changes.outputs.run_full_ci == 'true' + uses: actions/checkout@v5.0.1 + + - name: Install system dependencies + if: needs.classify_changes.outputs.run_full_ci == 'true' + run: choco install protoc -y + + - name: Install Rust stable + if: needs.classify_changes.outputs.run_full_ci == 'true' + uses: dtolnay/rust-toolchain@stable + with: + toolchain: stable + + - name: Cache Rust build data + if: needs.classify_changes.outputs.run_full_ci == 'true' + uses: Swatinem/rust-cache@v2 + with: + workspaces: | + . -> target + key: windows-release-binaries + + - name: Build Windows binaries + if: needs.classify_changes.outputs.run_full_ci == 'true' + run: cargo build --release --locked -p omnigraph-cli -p omnigraph-server + + - name: Smoke test Windows binaries + if: needs.classify_changes.outputs.run_full_ci == 'true' + run: | + & ./target/release/omnigraph.exe version + & ./target/release/omnigraph-server.exe --help + + - name: Check PowerShell installer syntax + if: needs.classify_changes.outputs.run_full_ci == 'true' + run: | + $tokens = $null + $errors = $null + [System.Management.Automation.Language.Parser]::ParseFile("scripts/install.ps1", [ref]$tokens, [ref]$errors) | Out-Null + if ($errors.Count -gt 0) { + $errors | Format-List + exit 1 + } + rustfs_integration: name: RustFS S3 Integration needs: diff --git a/.github/workflows/codeowners.yml b/.github/workflows/codeowners.yml index 19d5835..75b3515 100644 --- a/.github/workflows/codeowners.yml +++ b/.github/workflows/codeowners.yml @@ -1,19 +1,24 @@ name: CODEOWNERS +# Runs on EVERY pull request (no paths filter). The two jobs below are +# required status checks on `main`; a path-filtered required check never +# reports for PRs outside the filter and leaves them permanently "pending" +# (the trap that forced admin-override merges). Always-run + cheap +# short-circuit is what keeps them honest. on: pull_request: - paths: - - '.github/codeowners-roles.yml' - - '.github/CODEOWNERS' - - '.github/scripts/render-codeowners.py' - - '.github/workflows/codeowners.yml' workflow_dispatch: -# Read-only; we never push from this workflow. +# `drift` auto-commits the regenerated artifacts back to same-repo PR +# branches, so it needs write access. permissions: - contents: read + contents: write jobs: + # NOTE: the job `name:` values below ("CODEOWNERS matches source" / + # "CODEOWNERS not hand-edited") ARE the status-check contexts that + # .github/branch-protection.json must list verbatim. Renaming a job here + # is a branch-protection change — update the JSON and re-apply. drift: name: CODEOWNERS matches source runs-on: ubuntu-latest @@ -28,19 +33,56 @@ jobs: - name: Install PyYAML run: pip install pyyaml - - name: Re-render CODEOWNERS + - name: Re-render CODEOWNERS + ownership docs run: python3 .github/scripts/render-codeowners.py - - name: Reject drift + # Same-repo PR: push the regenerated artifacts back so contributors + # never have to run the script locally. Mirrors the openapi.json + # auto-commit in ci.yml (separate shallow clone of the head branch so + # the pushed commit carries only the regenerated files). + - name: Commit regenerated artifacts to PR branch + if: | + github.event_name == 'pull_request' && + github.event.pull_request.head.repo.full_name == github.repository + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - if ! git diff --quiet .github/CODEOWNERS; then - echo "::error::.github/CODEOWNERS is out of sync with .github/codeowners-roles.yml." - echo "::error::Run \`python3 .github/scripts/render-codeowners.py\` locally and commit the result." + if git diff --quiet -- .github/CODEOWNERS docs/dev/codeowners.md; then + echo "CODEOWNERS and ownership docs already in sync." + exit 0 + fi + tmp=$(mktemp -d) + git clone --depth 1 --branch "${{ github.head_ref }}" \ + "https://x-access-token:${GITHUB_TOKEN}@github.com/${{ github.repository }}.git" \ + "$tmp" + cp .github/CODEOWNERS "$tmp/.github/CODEOWNERS" + cp docs/dev/codeowners.md "$tmp/docs/dev/codeowners.md" + cd "$tmp" + if git diff --quiet -- .github/CODEOWNERS docs/dev/codeowners.md; then + echo "Head branch already matches; nothing to push." + exit 0 + fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add .github/CODEOWNERS docs/dev/codeowners.md + git commit -m "chore: regenerate CODEOWNERS + ownership docs" + git push + + # Fork PR / workflow_dispatch: cannot push back, so enforce drift + # strictly. The contributor runs the script and commits the result. + - name: Verify in sync (forks / manual runs) + if: | + !(github.event_name == 'pull_request' && + github.event.pull_request.head.repo.full_name == github.repository) + run: | + if ! git diff --quiet -- .github/CODEOWNERS docs/dev/codeowners.md; then + echo "::error::Generated CODEOWNERS / ownership docs are out of sync with .github/codeowners-roles.yml." + echo "::error::Run \`python3 .github/scripts/render-codeowners.py\` and commit the result." echo "--- diff ---" - git --no-pager diff .github/CODEOWNERS + git --no-pager diff -- .github/CODEOWNERS docs/dev/codeowners.md exit 1 fi - echo "CODEOWNERS is in sync with its source." + echo "Generated artifacts are in sync with their source." noedit: name: CODEOWNERS not hand-edited @@ -52,6 +94,8 @@ jobs: fetch-depth: 0 - name: Reject hand-edits to generated file + # Only meaningful for PRs (needs a base to diff against). + if: github.event_name == 'pull_request' run: | base="origin/${{ github.base_ref }}" git fetch origin "${{ github.base_ref }}" --quiet diff --git a/.github/workflows/publish-crates.yml b/.github/workflows/publish-crates.yml index d7f783f..9484b98 100644 --- a/.github/workflows/publish-crates.yml +++ b/.github/workflows/publish-crates.yml @@ -80,8 +80,15 @@ jobs: version=$(cargo metadata --format-version=1 --no-deps \ | jq -r --arg c "$crate" '.packages[] | select(.name==$c) | .version') + # crates.io API requires a User-Agent header — without it the + # API responds 403 and the skip check below would silently + # fall through to a real publish attempt that errors with + # "already exists on crates.io index" when re-running after a + # partial publish. Send a UA naming the workflow. local current - current=$(curl -fsSL "https://crates.io/api/v1/crates/${crate}" \ + current=$(curl -fsSL \ + -A 'ModernRelay-omnigraph-ci (https://github.com/ModernRelay/omnigraph)' \ + "https://crates.io/api/v1/crates/${crate}" \ | jq -r '.crate.max_version' || echo "") if [[ "$current" == "$version" ]]; then @@ -90,10 +97,28 @@ jobs: fi echo "==> publishing ${crate} ${version} (current crates.io: ${current:-none})" - cargo publish -p "$crate" --locked + # Defense in depth: if the skip check missed an existing + # version (e.g. crates.io API hiccup), cargo publish errors + # with "already exists on crates.io index". Treat that as + # success so the workflow can be re-run idempotently. + local output + if ! output=$(cargo publish -p "$crate" --locked 2>&1); then + echo "$output" + if echo "$output" | grep -q "already exists on crates.io"; then + echo "==> ${crate} ${version} was already published; treating as success" + return 0 + fi + return 1 + fi + echo "$output" } + # Order matters: each crate must precede anything that depends on it. + # omnigraph-compiler and omnigraph-policy have no internal deps; + # omnigraph-engine depends on both; server depends on engine + the + # two leaf crates; cli depends on everything. publish_if_new omnigraph-compiler + publish_if_new omnigraph-policy publish_if_new omnigraph-engine publish_if_new omnigraph-server publish_if_new omnigraph-cli diff --git a/.github/workflows/release-edge.yml b/.github/workflows/release-edge.yml index 6147646..3996e65 100644 --- a/.github/workflows/release-edge.yml +++ b/.github/workflows/release-edge.yml @@ -43,6 +43,8 @@ jobs: asset_name: omnigraph-linux-x86_64 - runner: macos-14 asset_name: omnigraph-macos-arm64 + - runner: windows-latest + asset_name: omnigraph-windows-x86_64 env: CARGO_TERM_COLOR: always steps: @@ -59,6 +61,10 @@ jobs: if: runner.os == 'macOS' run: brew install protobuf + - name: Install Windows dependencies + if: runner.os == 'Windows' + run: choco install protoc -y + - name: Install Rust stable uses: dtolnay/rust-toolchain@stable with: @@ -73,7 +79,8 @@ jobs: - name: Build release binaries run: cargo build --release --locked -p omnigraph-cli -p omnigraph-server - - name: Package release archive + - name: Package Unix release archive + if: runner.os != 'Windows' run: | mkdir -p release install -m 0755 target/release/omnigraph release/omnigraph @@ -81,6 +88,22 @@ jobs: tar -C release -czf "${{ matrix.asset_name }}.tar.gz" omnigraph omnigraph-server shasum -a 256 "${{ matrix.asset_name }}.tar.gz" > "${{ matrix.asset_name }}.sha256" + - name: Package Windows release archive + if: runner.os == 'Windows' + run: | + New-Item -ItemType Directory -Force -Path release | Out-Null + Copy-Item target/release/omnigraph.exe release/omnigraph.exe + Copy-Item target/release/omnigraph-server.exe release/omnigraph-server.exe + Compress-Archive -Path release/omnigraph.exe, release/omnigraph-server.exe -DestinationPath "${{ matrix.asset_name }}.zip" -Force + $hash = (Get-FileHash "${{ matrix.asset_name }}.zip" -Algorithm SHA256).Hash.ToLowerInvariant() + "$hash ${{ matrix.asset_name }}.zip" | Out-File -FilePath "${{ matrix.asset_name }}.sha256" -Encoding ascii + New-Item -ItemType Directory -Force -Path verify | Out-Null + Expand-Archive -Path "${{ matrix.asset_name }}.zip" -DestinationPath verify -Force + $items = Get-ChildItem -Path verify -File + if ($items.Count -ne 2 -or !(Test-Path verify/omnigraph.exe) -or !(Test-Path verify/omnigraph-server.exe)) { + throw "Windows release archive is missing expected binaries" + } + - name: Publish edge release assets uses: softprops/action-gh-release@v2.5.0 with: @@ -91,5 +114,22 @@ jobs: body: | Rolling prerelease from `${{ github.sha }}`. files: | - ${{ matrix.asset_name }}.tar.gz - ${{ matrix.asset_name }}.sha256 + ${{ matrix.asset_name }}.* + + smoke_windows_installer: + name: Smoke Windows installer + needs: build_release + runs-on: windows-latest + permissions: + contents: read + steps: + - name: Checkout source + uses: actions/checkout@v5.0.1 + + - name: Install from edge release + run: ./scripts/install.ps1 -ReleaseChannel edge -InstallDir "$env:RUNNER_TEMP/omnigraph-bin" + + - name: Smoke installed binaries + run: | + & "$env:RUNNER_TEMP/omnigraph-bin/omnigraph.exe" version + & "$env:RUNNER_TEMP/omnigraph-bin/omnigraph-server.exe" --help diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e7fc75f..a265c40 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,6 +20,8 @@ jobs: asset_name: omnigraph-linux-x86_64 - runner: macos-14 asset_name: omnigraph-macos-arm64 + - runner: windows-latest + asset_name: omnigraph-windows-x86_64 env: CARGO_TERM_COLOR: always steps: @@ -36,6 +38,10 @@ jobs: if: runner.os == 'macOS' run: brew install protobuf + - name: Install Windows dependencies + if: runner.os == 'Windows' + run: choco install protoc -y + - name: Install Rust stable uses: dtolnay/rust-toolchain@stable with: @@ -50,7 +56,8 @@ jobs: - name: Build release binaries run: cargo build --release --locked -p omnigraph-cli -p omnigraph-server - - name: Package release archive + - name: Package Unix release archive + if: runner.os != 'Windows' run: | mkdir -p release install -m 0755 target/release/omnigraph release/omnigraph @@ -58,12 +65,27 @@ jobs: tar -C release -czf "${{ matrix.asset_name }}.tar.gz" omnigraph omnigraph-server shasum -a 256 "${{ matrix.asset_name }}.tar.gz" > "${{ matrix.asset_name }}.sha256" + - name: Package Windows release archive + if: runner.os == 'Windows' + run: | + New-Item -ItemType Directory -Force -Path release | Out-Null + Copy-Item target/release/omnigraph.exe release/omnigraph.exe + Copy-Item target/release/omnigraph-server.exe release/omnigraph-server.exe + Compress-Archive -Path release/omnigraph.exe, release/omnigraph-server.exe -DestinationPath "${{ matrix.asset_name }}.zip" -Force + $hash = (Get-FileHash "${{ matrix.asset_name }}.zip" -Algorithm SHA256).Hash.ToLowerInvariant() + "$hash ${{ matrix.asset_name }}.zip" | Out-File -FilePath "${{ matrix.asset_name }}.sha256" -Encoding ascii + New-Item -ItemType Directory -Force -Path verify | Out-Null + Expand-Archive -Path "${{ matrix.asset_name }}.zip" -DestinationPath verify -Force + $items = Get-ChildItem -Path verify -File + if ($items.Count -ne 2 -or !(Test-Path verify/omnigraph.exe) -or !(Test-Path verify/omnigraph-server.exe)) { + throw "Windows release archive is missing expected binaries" + } + - name: Publish GitHub release assets uses: softprops/action-gh-release@v2.5.0 with: files: | - ${{ matrix.asset_name }}.tar.gz - ${{ matrix.asset_name }}.sha256 + ${{ matrix.asset_name }}.* update_homebrew_tap: name: Update Homebrew tap @@ -99,6 +121,31 @@ jobs: run: | ./scripts/update-homebrew-formula.sh "${GITHUB_REF_NAME}" homebrew-tap/Formula/omnigraph.rb + # Diagnostic only: brew is not on PATH on the ubuntu runner by default, so + # set it up explicitly. Both this setup and the audit below are best-effort + # canaries, not gates — continue-on-error on each keeps a failed/flaky brew + # (the action is pinned to a moving @master ref) from skipping the actual + # tap publish below. The formula is correct by construction + # (update-homebrew-formula.sh), so brew tooling must never block the push. + - name: Set up Homebrew + if: env.HOMEBREW_TAP_SKIP != '1' + continue-on-error: true + uses: Homebrew/actions/setup-homebrew@master + + - name: Audit generated formula + if: env.HOMEBREW_TAP_SKIP != '1' + continue-on-error: true + run: | + # Audit the checked-out tap by name (brew audit rejects bare paths + # and needs tap context). Symlink the checkout into Homebrew's Taps + # tree so `modernrelay/tap/omnigraph` resolves to it. Offline audit + # (no --online) keeps it deterministic; it still catches the + # ComponentsOrder/structure class of problems. + tap_dir="$(brew --repository)/Library/Taps/modernrelay/homebrew-tap" + mkdir -p "$(dirname "$tap_dir")" + ln -sfn "$PWD/homebrew-tap" "$tap_dir" + brew audit --strict modernrelay/tap/omnigraph + - name: Commit and push formula update if: env.HOMEBREW_TAP_SKIP != '1' working-directory: homebrew-tap @@ -113,3 +160,22 @@ jobs: git add Formula/omnigraph.rb git commit -m "Update Omnigraph formula to ${GITHUB_REF_NAME}" git push origin HEAD:main + + smoke_windows_installer: + name: Smoke Windows installer + needs: build_release + if: startsWith(github.ref, 'refs/tags/v') + runs-on: windows-latest + permissions: + contents: read + steps: + - name: Checkout source + uses: actions/checkout@v5.0.1 + + - name: Install from tagged release + run: ./scripts/install.ps1 -Version "$env:GITHUB_REF_NAME" -InstallDir "$env:RUNNER_TEMP/omnigraph-bin" + + - name: Smoke installed binaries + run: | + & "$env:RUNNER_TEMP/omnigraph-bin/omnigraph.exe" version + & "$env:RUNNER_TEMP/omnigraph-bin/omnigraph-server.exe" --help diff --git a/.gitignore b/.gitignore index 919d9d8..2248d5a 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ __pycache__/ *.pyc demo/*.omni/ .omnigraph-rustfs-demo/ +/docs/internal # Local-only working files (not for the public repo) .claude/ diff --git a/AGENTS.md b/AGENTS.md index 6e45aa7..b876749 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # OmniGraph — Agent Guide -This file is the always-on map for AI coding agents (Claude Code, Codex, Cursor, Cline) working in this repo. It is loaded into context on every turn, so it stays as a **map plus the rules and invariants that need to be in scope at all times** — the encyclopedia content lives under [`docs/`](docs/). When you need depth, follow a pointer. +This file is the always-on map for AI coding agents (Claude Code, Codex, Cursor, Cline) working in this codebase. It is loaded into context on every turn, so it stays as a **map plus the rules and invariants that need to be in scope at all times** — the encyclopedia content lives under [`docs/`](docs/). When you need depth, follow a pointer. **Required reading every session, every change:** @@ -16,8 +16,8 @@ Tools that support `@`-imports (Claude Code) auto-include all three files via th `CLAUDE.md` is a symlink to this file — there is exactly one source of truth. Edit `AGENTS.md`. -**Version surveyed:** 0.4.2 -**Workspace crates:** `omnigraph-compiler`, `omnigraph` (engine), `omnigraph-cli`, `omnigraph-server` +**Version surveyed:** 0.6.1 +**Workspace crates:** `omnigraph-compiler`, `omnigraph` (engine), `omnigraph-policy`, `omnigraph-cli`, `omnigraph-server` **Storage substrate:** Lance 6.x (columnar, versioned, branchable) **License:** MIT **Toolchain:** Rust stable, edition 2024 @@ -33,7 +33,7 @@ OmniGraph is a typed property-graph engine built as a coordination layer over ma - **Multi-modal querying**: vector ANN (`nearest`), full-text (`search`/`fuzzy`/`match_text`/`bm25`), Reciprocal Rank Fusion (`rrf`), and graph traversal (`Expand`, anti-join `not { … }`) in one runtime. - **Branches and commits across the whole graph**: Git-style — every successful publish appends to a commit DAG; merges are three-way at the row level. - **Atomic per-query writes**: `mutate_as` and `load` accumulate insert/update batches into an in-memory `MutationStaging.pending` per touched table; one `stage_*` + `commit_staged` per table runs at end-of-query, then `ManifestBatchPublisher::publish` commits the manifest atomically with per-table `expected_table_versions` CAS. A mid-query failure leaves Lance HEAD untouched on staged tables — no drift, no run state machine, no staging branches. Deletes still inline-commit; D₂ at parse time prevents inserts/updates and deletes from coexisting in one query. -- **HTTP server**: Axum + utoipa OpenAPI, bearer auth (SHA-256 hashed, optional AWS Secrets Manager). Cedar policy enforcement is engine-wide — every `_as` writer calls `Omnigraph::enforce(action, scope, actor)`, so HTTP, CLI, and embedded SDK consumers all hit the same gate. +- **HTTP server**: Axum + utoipa OpenAPI, bearer auth (SHA-256 hashed, optional AWS Secrets Manager). Cedar policy enforcement is engine-wide — every `_as` writer calls `Omnigraph::enforce(action, scope, actor)`, so HTTP, CLI, and embedded SDK consumers all hit the same gate. **Two modes** (v0.6.0+): single-graph (legacy flat routes) and multi-graph (`/graphs/{graph_id}/...` cluster routes + read-only `GET /graphs` enumeration). Per-graph + server-level Cedar policies. Runtime add/remove (`POST /graphs`, `DELETE /graphs/{id}`) is not exposed — operators edit `omnigraph.yaml` and restart. - **CLI** driven by a single `omnigraph.yaml`; multi-format output (json/jsonl/csv/kv/table). Throughout the docs, capabilities are split into **L1 — Inherited from Lance** vs **L2 — Added by OmniGraph**. @@ -50,7 +50,7 @@ CLI (omnigraph) HTTP Server (omnigraph-server, Axum) omnigraph-compiler ── Pest grammars, catalog, IR, lowering, lint, migration plan │ ▼ - omnigraph (engine) ── ManifestRepo, CommitGraph, RunRegistry, GraphIndex (CSR/CSC), exec + omnigraph (engine) ── ManifestCoordinator, CommitGraph, RunRegistry, GraphIndex (CSR/CSC), exec │ ▼ Lance 6.x ── columnar Arrow, fragments, per-dataset versions/branches, indexes @@ -81,7 +81,7 @@ Full diagram and concurrency model: [docs/dev/architecture.md](docs/dev/architec | Embeddings (compiler + engine clients, env vars, `@embed`) | [docs/user/embeddings.md](docs/user/embeddings.md) | | Branches, commit graph, snapshots, system branches | [docs/user/branches-commits.md](docs/user/branches-commits.md) | | Transactions and atomicity (per-query atomic; branches as multi-query transactions) | [docs/user/transactions.md](docs/user/transactions.md) | -| Direct-publish writes (the former Run state machine, now demoted to publisher CAS) | [docs/dev/runs.md](docs/dev/runs.md) | +| Direct-publish write path (staging, D2, recovery sidecars; the former Run state machine) | [docs/dev/writes.md](docs/dev/writes.md) | | Three-way merge and conflict kinds | [docs/dev/merge.md](docs/dev/merge.md) | | Diff / change feed (`diff_between`, `diff_commits`) | [docs/user/changes.md](docs/user/changes.md) | | Query execution, mutation execution, bulk loader, `load` vs `ingest` | [docs/dev/execution.md](docs/dev/execution.md) | @@ -164,38 +164,64 @@ If a proposal fits one of these, the burden is on the proposer to justify why th --- +## Build, test, lint + +Rust stable workspace (edition 2024). `protoc` is a build dependency (`brew install protobuf` / `apt-get install protobuf-compiler libprotobuf-dev`). **Crate dir ≠ package name** for the engine: the directory is `crates/omnigraph` but its Cargo package is `omnigraph-engine` (use that in `-p`). The CLI binary built from `omnigraph-cli` is named `omnigraph`. + +```bash +cargo build --workspace --locked # build everything +cargo test --workspace --locked # the canonical CI gate (matches CI exactly) +cargo run -p omnigraph-cli -- # run the `omnigraph` CLI from source +cargo run -p omnigraph-server -- --bind 0.0.0.0:8080 # run the server from source + +# Run one crate / one test file / one test fn +cargo test -p omnigraph-engine --test traversal # one integration-test file (see docs/dev/testing.md) +cargo test -p omnigraph-engine --test writes concurrent # one test fn by name substring +cargo test -p omnigraph-engine some_inline_test -- --nocapture # show stdout + +# Feature-gated suites (each is its own job in CI, not part of the default run) +cargo test -p omnigraph-engine --features failpoints --test failpoints # fault injection +cargo build -p omnigraph-server --features aws # AWS Secrets Manager bearer-token source +``` + +S3-backed tests (`s3_storage`, and the S3 paths in server/CLI system tests) **skip** unless `OMNIGRAPH_S3_TEST_BUCKET` + `AWS_*` (incl. `AWS_ENDPOINT_URL_S3` for non-AWS) are set; CI runs them against containerized RustFS. `scripts/local-rustfs-bootstrap.sh` stands up a local S3 environment. + +CI does **not** run `clippy` or `rustfmt` as gates — but `cargo test --workspace --locked` is the exact gate, so run it before pushing. Two non-test CI checks: `scripts/check-agents-md.sh` (doc cross-link integrity — run it after moving/renaming docs) and OpenAPI drift (`crates/omnigraph-server/tests/openapi.rs` regenerates `openapi.json`; set `OMNIGRAPH_UPDATE_OPENAPI=1` to update the checked-in copy when a server/API change is intentional). + +--- + ## Quick-reference flows ```bash -# Initialize an S3-backed repo -omnigraph init --schema ./schema.pg s3://my-bucket/repo.omni +# Initialize an S3-backed graph +omnigraph init --schema ./schema.pg s3://my-bucket/graph.omni # Bulk load -omnigraph load --data ./seed.jsonl --mode overwrite s3://my-bucket/repo.omni +omnigraph load --data ./seed.jsonl --mode overwrite s3://my-bucket/graph.omni # Branch + ingest a review batch -omnigraph branch create --from main review/2026-04-25 s3://my-bucket/repo.omni -omnigraph ingest --branch review/2026-04-25 --data ./batch.jsonl s3://my-bucket/repo.omni +omnigraph branch create --from main review/2026-04-25 s3://my-bucket/graph.omni +omnigraph ingest --branch review/2026-04-25 --data ./batch.jsonl s3://my-bucket/graph.omni # Run a hybrid (vector + BM25) query omnigraph read --query ./queries.gq --name find_similar \ - --params '{"q":"trends in AI safety"}' --format table s3://my-bucket/repo.omni + --params '{"q":"trends in AI safety"}' --format table s3://my-bucket/graph.omni # Plan + apply schema migration -omnigraph schema plan --schema ./next.pg s3://my-bucket/repo.omni -omnigraph schema apply --schema ./next.pg s3://my-bucket/repo.omni --json +omnigraph schema plan --schema ./next.pg s3://my-bucket/graph.omni +omnigraph schema apply --schema ./next.pg s3://my-bucket/graph.omni --json # Merge review branch back -omnigraph branch merge review/2026-04-25 --into main s3://my-bucket/repo.omni +omnigraph branch merge review/2026-04-25 --into main s3://my-bucket/graph.omni # Compact + GC (preview, then confirm) -omnigraph optimize s3://my-bucket/repo.omni -omnigraph cleanup --keep 10 --older-than 7d s3://my-bucket/repo.omni -omnigraph cleanup --keep 10 --older-than 7d --confirm s3://my-bucket/repo.omni +omnigraph optimize s3://my-bucket/graph.omni +omnigraph cleanup --keep 10 --older-than 7d s3://my-bucket/graph.omni +omnigraph cleanup --keep 10 --older-than 7d --confirm s3://my-bucket/graph.omni # Stand up the HTTP server (token from env) OMNIGRAPH_SERVER_BEARER_TOKEN=xxxx \ - omnigraph-server s3://my-bucket/repo.omni --bind 0.0.0.0:8080 + omnigraph-server s3://my-bucket/graph.omni --bind 0.0.0.0:8080 # Cedar policy explain omnigraph policy explain --actor act-alice --action change --branch main @@ -211,7 +237,7 @@ omnigraph policy explain --actor act-alice --action change --branch main | Per-dataset versioning + time travel | ✅ | `snapshot_at_version`, `entity_at`, snapshot-pinned reads across many tables | | Per-dataset branches | ✅ | **Graph-level** branches (atomic across all sub-tables), lazy fork, system branch filtering | | Atomic single-dataset commits | ✅ | **Multi-table publish via three layers**, NOT a single Lance primitive: (1) per-table Lance `commit_staged` for the data write, (2) `__manifest` row-level CAS via `ManifestBatchPublisher` for cross-table ordering, (3) the open-time recovery sweep for the residual gap between (1) and (2). All three layers ship; the four migrated writers (`MutationStaging::finalize`, `schema_apply`, `branch_merge`, `ensure_indices`) write a `__recovery/{ulid}.json` sidecar before Phase B and delete it after Phase C. The next `Omnigraph::open` (gated on `OpenMode::ReadWrite`) runs the sweep in `db/manifest/recovery.rs`: classify, decide all-or-nothing per sidecar, roll forward via single `ManifestBatchPublisher::publish` or roll back via `Dataset::restore`, and record an audit row in `_graph_commit_recoveries.lance` (queryable via `omnigraph commit list --filter actor=omnigraph:recovery`). Continuous in-process recovery (no restart needed between Phase B failure and recovery) is the goal of a future background reconciler. Engine writes route through a sealed `TableStorage` trait exposing `stage_*` + `commit_staged` as the canonical staged-write surface; documented inline-commit residuals (`delete_where`, `create_vector_index`, plus legacy `append_batch` / `merge_insert_batches` / `overwrite_batch` / `create_*_index`) remain on the trait until upstream Lance ships a public two-phase API ([#6658](https://github.com/lance-format/lance/issues/6658), [#6666](https://github.com/lance-format/lance/issues/6666)) and the migration of every call site completes. | -| Compaction (`compact_files`) | ✅ | `omnigraph optimize` orchestrates over all node/edge tables, bounded concurrency | +| Compaction (`compact_files`) | ✅ | `omnigraph optimize` orchestrates over all node/edge tables, bounded concurrency; **skips blob-bearing tables** (reported via `TableOptimizeStats.skipped`, not silent), gated on `LANCE_SUPPORTS_BLOB_COMPACTION` until the upstream blob-v2 compaction-decode bug is fixed (see [docs/dev/invariants.md](docs/dev/invariants.md) Known Gaps) | | Cleanup (`cleanup_old_versions`) | ✅ | `omnigraph cleanup` with `--keep` / `--older-than` policy | | BTREE / inverted (FTS) / vector indexes | ✅ | `ensure_indices` builds them on every relevant column; idempotent; lazy across branches | | `merge_insert` upsert | ✅ | `LoadMode::Merge`, mutation `update`/`insert`/`delete` lowering | @@ -222,12 +248,12 @@ omnigraph policy explain --actor act-alice --action change --branch main | Schema language | — | `.pg` + Pest grammar + catalog + interfaces + constraints + annotations | | Query language | — | `.gq` + Pest grammar + IR + lowering + linter | | Schema migration planning | — | `plan_schema_migration` + `apply_schema` step types + `__schema_apply_lock__` | -| Commit graph (DAG) across whole repo | — | `_graph_commits.lance` with linear + merge parents, ULID ids, actor map | +| Commit graph (DAG) across whole graph | — | `_graph_commits.lance` with linear + merge parents, ULID ids, actor map | | Per-query atomic writes | — | In-memory `MutationStaging.pending` accumulator + `stage_*` / `commit_staged` per touched table at end-of-query + publisher CAS via `commit_with_expected` (single manifest commit per `mutate_as` / `load`); D₂ parse-time rule keeps inserts/updates and deletes from mixing | | Three-way row-level merge | — | `OrderedTableCursor` + `StagedTableWriter`, structured `MergeConflictKind` | | Change feeds | — | `diff_between` / `diff_commits` with manifest fast path + ID streaming | -| Cedar policy | — | 8 actions, branch / target_branch / protected scopes, validate/test/explain CLI. **Engine-wide enforcement** (MR-722): every `_as` writer (`apply_schema_as`, `mutate_as`, `load_as`, `ingest_as`, `branch_create_as` / `branch_create_from_as`, `branch_delete_as`, `branch_merge_as`) calls `Omnigraph::enforce(action, scope, actor)` — HTTP, CLI, embedded SDK all hit the same gate. | -| HTTP server | — | Axum, OpenAPI via utoipa, bearer auth (SHA-256, AWS Secrets Manager option), `authorize_request` at the HTTP boundary (resolves bearer→actor, applies admission control), NDJSON streaming export | +| Cedar policy | — | Per-graph actions plus server-scoped actions (see [docs/user/policy.md](docs/user/policy.md) for the current list), branch / target_branch / protected scopes, validate/test/explain CLI. **Engine-wide enforcement** (MR-722): every `_as` writer (`apply_schema_as`, `mutate_as`, `load_as`, `ingest_as`, `branch_create_as` / `branch_create_from_as`, `branch_delete_as`, `branch_merge_as`) calls `Omnigraph::enforce(action, scope, actor)` — HTTP, CLI, embedded SDK all hit the same gate. | +| HTTP server | — | Axum, OpenAPI via utoipa, bearer auth (SHA-256, AWS Secrets Manager option), `authorize_request` at the HTTP boundary (resolves bearer→actor, applies admission control), NDJSON streaming export, **multi-graph mode (v0.6.0+) with cluster routes + read-only `GET /graphs` enumeration + per-graph + server-level Cedar policies. Add/remove graphs by editing `omnigraph.yaml` and restarting.** | | CLI with config | — | `omnigraph.yaml`, aliases, multi-format output (json/jsonl/csv/kv/table) | | Audit / actor tracking | — | `_as` write APIs + actor map in commit graph | | Local RustFS bootstrap | — | `scripts/local-rustfs-bootstrap.sh` one-shot S3-backed dev environment | diff --git a/Cargo.lock b/Cargo.lock index fcc2d7d..3223b9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4543,7 +4543,7 @@ dependencies = [ [[package]] name = "omnigraph-cli" -version = "0.4.2" +version = "0.6.1" dependencies = [ "assert_cmd", "clap", @@ -4565,7 +4565,7 @@ dependencies = [ [[package]] name = "omnigraph-compiler" -version = "0.4.2" +version = "0.6.1" dependencies = [ "ahash", "arrow-array", @@ -4586,7 +4586,7 @@ dependencies = [ [[package]] name = "omnigraph-engine" -version = "0.4.2" +version = "0.6.1" dependencies = [ "arc-swap", "arrow-array", @@ -4627,7 +4627,7 @@ dependencies = [ [[package]] name = "omnigraph-policy" -version = "0.4.2" +version = "0.6.1" dependencies = [ "cedar-policy", "clap", @@ -4640,8 +4640,9 @@ dependencies = [ [[package]] name = "omnigraph-server" -version = "0.4.2" +version = "0.6.1" dependencies = [ + "arc-swap", "async-trait", "aws-config", "aws-sdk-secretsmanager", @@ -4655,6 +4656,7 @@ dependencies = [ "omnigraph-compiler", "omnigraph-engine", "omnigraph-policy", + "regex", "serde", "serde_json", "serde_yaml", @@ -4662,6 +4664,7 @@ dependencies = [ "sha2", "subtle", "tempfile", + "thiserror", "tokio", "tower", "tower-http", diff --git a/README.md b/README.md index bf884af..0f6ebea 100644 --- a/README.md +++ b/README.md @@ -5,33 +5,35 @@ [![Crates.io](https://img.shields.io/crates/v/omnigraph-cli.svg)](https://crates.io/crates/omnigraph-cli) [![CI](https://github.com/ModernRelay/omnigraph/actions/workflows/ci.yml/badge.svg)](https://github.com/ModernRelay/omnigraph/actions/workflows/ci.yml) -**Object-storage native graph engine with git-style workflows. Designed for agents as first-class operators.** +**Lakehouse native graph engine built for context assembly** -Branch, commit, and merge typed graph data like source code. Multi-modal, self-hosted, open source. +Omnigraph acts as operational state & coordination layer for agents -Built on Rust, Arrow, DataFusion and Lance. - -Join the [Omnigraph Slack community](https://join.slack.com/t/omnigraphworkspace/shared_invite/zt-3wfpglyxj-lHvJGhuySPfqLtN35uJZNw) - -## Use Cases - -- Company brains / [Second brains](https://github.com/ModernRelay/omnigraph-cookbooks/tree/main/second-brain) -- Context graphs -- Backbone for multi-agent research -- Incident response graphs -- Compliance & audit graphs -- Enterprise knowledge systems - -## Capabilities - -- Typed schema, typed queries, and typed mutations +- Git-style versioning & branching +- Multimodal retrieval (graph+vector/fts+filters) optimized for context assembly +- Object storage native (S3, RustFS) - Native blob-as-data support (docs, images, videos, etc) -- Schema-as-code, query validation and linting -- Git-style graph workflows: branches, commits, merges, and transactional runs -- Local, on-prem & cloud S3-native storage with snapshot-pinned reads -- Graph traversal + text, fuzzy, BM25, vector, and RRF search in one runtime -- Policy-as-code for server-side access control -- Single CLI for multiple deployments +- VPC, On-prem, hybrid deployment +- [`Lance`](https://github.com/lance-format/lance) format as open storage layer + +| AS CODE | What it means | +|---|---| +| **Schema AS CODE** | Typed `.pg` schemas, planned, applied, enforced | +| **Context AS CODE** | Linted queries & agentic nudges, versioned and reusable | +| **Security AS CODE** | Cedar policies enforced server-side on every mutation | +| **Dashboards AS CODE** | Declarative views & controls over the graph *(coming)* | + +## Core Use Cases + +| Use case | What it's for +|---|---| +| **Company brain** | Org knowledge unified into one queryable graph | +| **Context graph** | Decision traces and codified tribal knowledge | +| **Agentic memory** | Durable, versioned memory for long-running agents | +| **Dev graph** | Issues & dependency model for coding agents | +| **R&D data layer** | Experiments & trials data written into branches | +| **ML workflows** | Versioned, branchable graphs for training & eval | +| **Karpathy's LLM wiki** | A living, agent-updatable knowledge base | ## Quick Install @@ -60,7 +62,7 @@ curl -fsSL https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/ That bootstrap: - starts RustFS on `127.0.0.1:9000` -- creates a bucket and S3-backed repo +- creates a bucket and S3-backed graph - loads the checked-in context fixture - launches `omnigraph-server` on `127.0.0.1:8080` @@ -69,8 +71,8 @@ Docker must be installed and running first. The RustFS bootstrap prefers the rolling `edge` binaries and only falls back to source builds when release assets are unavailable. -If a previous run left objects under the same repo prefix but did not finish -initializing the repo, rerun with `RESET_REPO=1` or set `PREFIX` to a new +If a previous run left objects under the same graph prefix but did not finish +initializing the graph, rerun with `RESET_REPO=1` or set `PREFIX` to a new value. ## Common Commands @@ -78,20 +80,37 @@ value. The same URI works for local paths, `s3://…`, or `http://host:port`. ```bash -omnigraph init --schema ./schema.pg ./repo.omni -omnigraph load --data ./data.jsonl ./repo.omni -omnigraph read --query ./queries.gq --name get_person --params '{"name":"Alice"}' ./repo.omni -omnigraph change --query ./queries.gq --name insert_person --params '{"name":"Mina"}' ./repo.omni -omnigraph branch create --from main feature-x ./repo.omni -omnigraph branch merge feature-x --into main ./repo.omni +omnigraph init --schema ./schema.pg ./graph.omni +omnigraph load --data ./data.jsonl ./graph.omni +omnigraph read --query ./queries.gq --name get_person --params '{"name":"Alice"}' ./graph.omni +omnigraph change --query ./queries.gq --name insert_person --params '{"name":"Mina"}' ./graph.omni +omnigraph branch create --from main feature-x ./graph.omni +omnigraph branch merge feature-x --into main ./graph.omni ``` -See [docs/user/cli.md](docs/user/cli.md) for schema apply, snapshots, ingest, runs, and policy commands. +See [docs/user/cli.md](docs/user/cli.md) for schema apply, snapshots, ingest, commits, and policy commands. + +## Clients + +For programmatic access to a running `omnigraph-server`: + +- **TypeScript SDK** — [`@modernrelay/omnigraph`](https://www.npmjs.com/package/@modernrelay/omnigraph) ([source](https://github.com/ModernRelay/omnigraph-ts/tree/main/packages/sdk)). Instance-per-client, typed errors, camelCase types, async-iterator streaming export. + + ```bash + npm install @modernrelay/omnigraph + ``` + +- **Model Context Protocol server** — [`@modernrelay/omnigraph-mcp`](https://www.npmjs.com/package/@modernrelay/omnigraph-mcp) ([source](https://github.com/ModernRelay/omnigraph-ts/tree/main/packages/mcp)). Bridges Omnigraph to LLM hosts (Claude Desktop, Claude Code, …) over stdio. Exposes tools and resources for schema, branches, queries, mutations, ingest, and bundles curated best-practices guidance from the cookbook. + + ```bash + npm install -g @modernrelay/omnigraph-mcp + ``` + +Both packages are versioned in lockstep with `omnigraph-server` on major.minor: `@modernrelay/omnigraph@X.Y.*` targets `omnigraph-server@X.Y.*`. See [`ModernRelay/omnigraph-ts`](https://github.com/ModernRelay/omnigraph-ts) for the monorepo. ## Docs - [Install guide](docs/user/install.md) -- [CLI guide](docs/user/cli.md) - [Deployment guide](docs/user/deployment.md) ## Build And Test @@ -113,8 +132,8 @@ Notes: - `crates/omnigraph-compiler`: shared schema/query parser, typechecker, catalog, and IR lowering - `crates/omnigraph`: storage/runtime, branching, merge, change detection, and query execution -- `crates/omnigraph-cli`: CLI for init/load/ingest/read/change/branch/snapshot/export/policy operations -- `crates/omnigraph-server`: Axum HTTP server for remote reads, changes, ingest, export, branches, commits, and runs +- `crates/omnigraph-cli`: CLI for graph lifecycle (init/load/ingest), query/mutate, branch/commit/merge, schema/lint, snapshot/export, policy, and maintenance (optimize/cleanup) +- `crates/omnigraph-server`: Axum HTTP server for remote reads, changes, ingest, export, branches, and commits ## Contributing diff --git a/crates/omnigraph-cli/Cargo.toml b/crates/omnigraph-cli/Cargo.toml index fb232eb..641068e 100644 --- a/crates/omnigraph-cli/Cargo.toml +++ b/crates/omnigraph-cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-cli" -version = "0.4.2" +version = "0.6.1" edition = "2024" description = "CLI for the Omnigraph graph database." license = "MIT" @@ -13,10 +13,10 @@ name = "omnigraph" path = "src/main.rs" [dependencies] -omnigraph = { package = "omnigraph-engine", path = "../omnigraph", version = "0.4.2" } -omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.4.2" } -omnigraph-policy = { path = "../omnigraph-policy", version = "0.4.2" } -omnigraph-server = { path = "../omnigraph-server", version = "0.4.2" } +omnigraph = { package = "omnigraph-engine", path = "../omnigraph", version = "0.6.1" } +omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.1" } +omnigraph-policy = { path = "../omnigraph-policy", version = "0.6.1" } +omnigraph-server = { path = "../omnigraph-server", version = "0.6.1" } clap = { workspace = true } color-eyre = { workspace = true } serde = { workspace = true } diff --git a/crates/omnigraph-cli/src/main.rs b/crates/omnigraph-cli/src/main.rs index ac21e7b..29b55c4 100644 --- a/crates/omnigraph-cli/src/main.rs +++ b/crates/omnigraph-cli/src/main.rs @@ -1,3 +1,4 @@ +use std::ffi::OsString; use std::fs; use std::io::{self, Write}; use std::path::Path; @@ -8,6 +9,7 @@ use clap::{Arg, ArgAction, Args, CommandFactory, FromArgMatches, Parser, Subcomm use color_eyre::eyre::{Result, bail}; use omnigraph::db::{Omnigraph, ReadTarget, SnapshotId}; use omnigraph::loader::LoadMode; +use omnigraph::storage::normalize_root_uri; use omnigraph_compiler::query::parser::parse_query; use omnigraph_compiler::schema::parser::parse_schema; use omnigraph_compiler::{ @@ -17,14 +19,16 @@ use omnigraph_compiler::{ }; use omnigraph_server::api::{ BranchCreateOutput, BranchCreateRequest, BranchDeleteOutput, BranchListOutput, - BranchMergeOutput, BranchMergeRequest, ChangeOutput, ChangeRequest, CommitListOutput, - CommitOutput, ErrorOutput, ExportRequest, IngestOutput, IngestRequest, ReadOutput, ReadRequest, - SchemaApplyOutput, SchemaApplyRequest, SchemaOutput, SnapshotOutput, SnapshotTableOutput, - commit_output, ingest_output, read_output, schema_apply_output, snapshot_payload, + BranchMergeOutput, BranchMergeRequest, ChangeOutput, CommitListOutput, CommitOutput, + ErrorOutput, ExportRequest, GraphListResponse, IngestOutput, IngestRequest, ReadOutput, + ReadRequest, SchemaApplyOutput, SchemaApplyRequest, SchemaOutput, SnapshotOutput, + SnapshotTableOutput, commit_output, ingest_output, read_output, schema_apply_output, + snapshot_payload, }; +use omnigraph_server::queries::{QueryRegistry, check, format_check_breakages}; use omnigraph_server::{ AliasCommand, OmnigraphConfig, PolicyAction, PolicyDecision, PolicyEngine, PolicyRequest, - PolicyTestConfig, ReadOutputFormat, load_config, + PolicyTestConfig, ReadOutputFormat, graph_resource_id_for_selection, load_config, }; use reqwest::Method; use reqwest::header::AUTHORIZATION; @@ -66,16 +70,23 @@ enum Command { Version, /// Generate, clean, or refresh explicit seed embeddings Embed(EmbedArgs), - /// Initialize a new repo from a schema + /// Initialize a new graph from a schema Init { #[arg(long)] schema: PathBuf, - /// Repo URI (local path or s3://) + /// Graph URI (local path or s3://) uri: String, + /// Overwrite existing schema artifacts at the URI. Without + /// this flag, init refuses to touch a URI that already holds + /// `_schema.pg`, `_schema.ir.json`, or `__schema_state.json` + /// — closes the re-init footgun (MR-668 follow-up). With the + /// flag, the operator opts in to destructive semantics. + #[arg(long)] + force: bool, }, - /// Load data into a repo + /// Load data into a graph Load { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -92,7 +103,7 @@ enum Command { }, /// Ingest data into a reviewable named branch Ingest { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -119,14 +130,39 @@ enum Command { #[command(subcommand)] command: SchemaCommand, }, - /// Query validation and linting - Query { - #[command(subcommand)] - command: QueryCommand, + /// Validate queries against a schema (offline) or repo (repo-backed). + /// + /// Canonical name is `lint` (matches the `omnigraph_compiler::lint` + /// module and the `OG-XXX-NNN` lint-code vocabulary). Replaces the + /// deprecated `omnigraph query lint` / `omnigraph query check` / + /// `omnigraph check` invocations — each is kept as an argv-level + /// shim that prints a one-line stderr warning and rewrites to + /// `omnigraph lint`. Aliases are deliberately *not* exposed via + /// clap's `visible_alias` because that would advertise two + /// equivalent canonical names, which agents emit interchangeably + /// (see MR-981). + Lint { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + query: PathBuf, + #[arg(long)] + schema: Option, + #[arg(long)] + json: bool, }, - /// Show repo snapshot + /// Operate on the server-side stored-query registry (`queries:`). + Queries { + #[command(subcommand)] + command: QueriesCommand, + }, + /// Show graph snapshot Snapshot { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -139,7 +175,7 @@ enum Command { }, /// Export a full graph snapshot as JSONL Export { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -159,9 +195,14 @@ enum Command { #[command(subcommand)] command: CommitCommand, }, - /// Execute a read query against a branch or snapshot - Read { - /// Repo URI + /// Execute a read query against a branch or snapshot. + /// + /// Canonical read endpoint. The previous name `omnigraph read` is + /// kept as a visible alias and prints a one-line deprecation warning + /// when used. Pairs with `omnigraph mutate` on the write side. + #[command(visible_alias = "read")] + Query { + /// Graph URI #[arg(long)] uri: Option, #[arg(hide = true)] @@ -170,10 +211,13 @@ enum Command { target: Option, #[arg(long)] config: Option, - #[arg(long)] + #[arg(long, conflicts_with_all = ["query", "query_string"])] alias: Option, - #[arg(long)] + #[arg(long, conflicts_with_all = ["alias", "query_string"])] query: Option, + /// Inline GQ source — alternative to `--query ` and `--alias `. + #[arg(short = 'e', long = "query-string", value_name = "GQ", conflicts_with_all = ["query", "alias"])] + query_string: Option, #[arg(long)] name: Option, #[command(flatten)] @@ -189,9 +233,14 @@ enum Command { #[arg()] alias_args: Vec, }, - /// Execute a graph change query against a branch - Change { - /// Repo URI + /// Execute a graph mutation query against a branch. + /// + /// Canonical mutation endpoint. The previous name `omnigraph change` + /// is kept as a visible alias and prints a one-line deprecation + /// warning when used. Pairs with `omnigraph query` on the read side. + #[command(visible_alias = "change")] + Mutate { + /// Graph URI #[arg(long)] uri: Option, #[arg(hide = true)] @@ -200,10 +249,13 @@ enum Command { target: Option, #[arg(long)] config: Option, - #[arg(long)] + #[arg(long, conflicts_with_all = ["query", "query_string"])] alias: Option, - #[arg(long)] + #[arg(long, conflicts_with_all = ["alias", "query_string"])] query: Option, + /// Inline GQ source — alternative to `--query ` and `--alias `. + #[arg(short = 'e', long = "query-string", value_name = "GQ", conflicts_with_all = ["query", "alias"])] + query_string: Option, #[arg(long)] name: Option, #[command(flatten)] @@ -220,9 +272,9 @@ enum Command { #[command(subcommand)] command: PolicyCommand, }, - /// Compact small Lance fragments in every table of the repo + /// Compact small Lance fragments in every table of the graph Optimize { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -231,9 +283,9 @@ enum Command { #[arg(long)] json: bool, }, - /// Remove old Lance versions from every table of the repo (destructive) + /// Remove old Lance versions from every table of the graph (destructive) Cleanup { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -253,13 +305,40 @@ enum Command { #[arg(long)] json: bool, }, + /// Manage graphs on a multi-graph server (MR-668) + Graphs { + #[command(subcommand)] + command: GraphsCommand, + }, +} + +/// Operations on the graph registry of a multi-graph server (MR-668). +/// +/// All operations target a remote multi-graph server URL (http:// or +/// https://). Local-URI invocations return a clear error. To add or +/// remove graphs, operators edit `omnigraph.yaml` directly and restart +/// the server — runtime mutation is not exposed in v0.6.0. +#[derive(Debug, Subcommand)] +enum GraphsCommand { + /// List every graph registered with the multi-graph server. + List { + /// Remote server URL (e.g. `https://server.example.com`). + #[arg(long)] + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + json: bool, + }, } #[derive(Debug, Subcommand)] enum BranchCommand { /// Create a new branch Create { - /// Repo URI + /// Graph URI #[arg(long)] uri: Option, #[arg(long)] @@ -274,7 +353,7 @@ enum BranchCommand { }, /// List branches List { - /// Repo URI + /// Graph URI #[arg(long)] uri: Option, #[arg(long)] @@ -286,7 +365,7 @@ enum BranchCommand { }, /// Delete a branch Delete { - /// Repo URI + /// Graph URI #[arg(long)] uri: Option, #[arg(long)] @@ -299,7 +378,7 @@ enum BranchCommand { }, /// Merge a source branch into a target branch Merge { - /// Repo URI + /// Graph URI #[arg(long)] uri: Option, #[arg(long)] @@ -318,7 +397,7 @@ enum BranchCommand { enum SchemaCommand { /// Plan a schema migration against the accepted persisted schema Plan { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -336,7 +415,7 @@ enum SchemaCommand { }, /// Apply a supported schema migration Apply { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -361,7 +440,7 @@ enum SchemaCommand { /// Show the current accepted schema source #[command(alias = "get")] Show { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -373,30 +452,11 @@ enum SchemaCommand { } #[derive(Debug, Subcommand)] -enum QueryCommand { - /// Validate queries and report higher-level drift warnings - #[command(visible_alias = "check")] - Lint { - /// Repo URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - query: PathBuf, - #[arg(long)] - schema: Option, - #[arg(long)] - json: bool, - }, -} -#[derive(Debug, Subcommand)] enum CommitCommand { /// List graph commits List { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, @@ -409,7 +469,7 @@ enum CommitCommand { }, /// Show a graph commit Show { - /// Repo URI + /// Graph URI #[arg(long)] uri: Option, #[arg(long)] @@ -449,6 +509,35 @@ enum PolicyCommand { }, } +#[derive(Debug, Subcommand)] +enum QueriesCommand { + /// Type-check the stored-query registry against the live schema. + /// + /// Distinct from `omnigraph lint` (which lints one `.gq` file): + /// this validates the whole `queries:` registry — opening the graph + /// to read its schema and confirming every stored query still + /// type-checks. Exits non-zero on any breakage. + Validate { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + json: bool, + }, + /// List the registered stored queries (name, MCP exposure, params). + List { + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + json: bool, + }, +} + #[derive(Debug, Args, Clone)] struct ParamsArgs { #[arg(long, conflicts_with = "params_file")] @@ -582,7 +671,7 @@ fn finish_query_lint(output: &QueryLintOutput, json: bool) -> Result<()> { Ok(()) } -fn ensure_local_repo_parent(uri: &str) -> Result<()> { +fn ensure_local_graph_parent(uri: &str) -> Result<()> { if !uri.contains("://") { fs::create_dir_all(uri)?; } @@ -690,25 +779,66 @@ fn load_cli_config(config_path: Option<&PathBuf>) -> Result { Ok(config) } -fn resolve_policy_engine(config: &OmnigraphConfig) -> Result { - let policy_file = config - .resolve_policy_file() - .ok_or_else(|| color_eyre::eyre::eyre!("policy.file must be set in omnigraph.yaml"))?; - PolicyEngine::load(&policy_file, &policy_repo_id(config)) +#[derive(Debug, Clone)] +struct ResolvedCliGraph { + uri: String, + selected: Option, + graph_id: String, + policy_file: Option, + is_remote: bool, } -/// Open a local-URI repo and, when `policy.file` is configured in -/// `omnigraph.yaml`, install the resolved `PolicyEngine` on the engine -/// handle so every direct-engine write goes through -/// `Omnigraph::enforce(...)` (MR-722). Without a configured policy this -/// is identical to a bare `Omnigraph::open`. -/// -/// Returns owned `Omnigraph`; chained on top of `Omnigraph::open(...)`'s -/// existing future to keep call sites narrow. -async fn open_local_db_with_policy(uri: &str, config: &OmnigraphConfig) -> Result { - let db = Omnigraph::open(uri).await?; - if config.resolve_policy_file().is_some() { - let engine = Arc::new(resolve_policy_engine(config)?); +impl ResolvedCliGraph { + fn selected(&self) -> Option<&str> { + self.selected.as_deref() + } +} + +struct ResolvedPolicyContext { + policy_file: PathBuf, + graph_id: String, +} + +fn resolve_policy_context(config: &OmnigraphConfig) -> Result { + let selected = config.resolve_policy_tooling_graph_selection()?; + let policy_file = config + .resolve_policy_file_for(selected) + .ok_or_else(|| { + color_eyre::eyre::eyre!( + "policy.file or graphs..policy.file must be set in omnigraph.yaml" + ) + })?; + let graph_id = match selected { + Some(name) => graph_resource_id_for_selection(Some(name), ""), + None => graph_resource_id_for_selection(None, "default"), + }; + Ok(ResolvedPolicyContext { + policy_file, + graph_id, + }) +} + +fn resolve_policy_engine(context: &ResolvedPolicyContext) -> Result { + PolicyEngine::load_graph(&context.policy_file, &context.graph_id) +} + +fn resolve_policy_engine_for_graph(graph: &ResolvedCliGraph) -> Result { + let policy_file = graph.policy_file.as_ref().ok_or_else(|| { + color_eyre::eyre::eyre!( + "policy.file or graphs..policy.file must be set in omnigraph.yaml" + ) + })?; + PolicyEngine::load_graph(policy_file, &graph.graph_id) +} + +/// Open a local graph and install the policy resolved for the same graph +/// identity that produced the URI. A named graph uses +/// `graphs..policy.file`; an explicit positional URI is anonymous and +/// uses the legacy top-level `policy.file`. +async fn open_local_db_with_policy(graph: &ResolvedCliGraph) -> Result { + let db = Omnigraph::open(&graph.uri).await?; + if graph.policy_file.is_some() { + let engine = Arc::new(resolve_policy_engine_for_graph(graph)?); Ok(db.with_policy(engine as Arc)) } else { Ok(db) @@ -721,29 +851,20 @@ async fn open_local_db_with_policy(uri: &str, config: &OmnigraphConfig) -> Resul /// policy is configured and this returns `None`, the engine-layer /// footgun guard intentionally denies — silent bypass via "I forgot the /// actor" is what the guard prevents. -fn resolve_cli_actor<'a>( - cli_as: Option<&'a str>, - config: &'a OmnigraphConfig, -) -> Option<&'a str> { +fn resolve_cli_actor<'a>(cli_as: Option<&'a str>, config: &'a OmnigraphConfig) -> Option<&'a str> { cli_as.or(config.cli.actor.as_deref()) } -fn resolve_policy_tests_path(config: &OmnigraphConfig) -> Result { - config.resolve_policy_tests_file().ok_or_else(|| { - color_eyre::eyre::eyre!( - "policy.tests.yaml requires policy.file to be set in omnigraph.yaml" - ) - }) +fn resolve_policy_tests_path(context: &ResolvedPolicyContext) -> PathBuf { + context.policy_file.with_file_name("policy.tests.yaml") } -fn policy_repo_id(config: &OmnigraphConfig) -> String { - if let Some(name) = &config.project.name { - return name.clone(); +fn normalize_policy_graph_uri(uri: &str) -> Result { + if is_remote_uri(uri) { + Ok(uri.trim_end_matches('/').to_string()) + } else { + Ok(normalize_root_uri(uri)?) } - config - .resolve_target_uri(None, None, config.server_graph_name()) - .or_else(|_| config.resolve_target_uri(None, None, config.cli_graph_name())) - .unwrap_or_else(|_| "default".to_string()) } fn resolve_remote_bearer_token( @@ -827,6 +948,47 @@ fn resolve_uri( config.resolve_target_uri(cli_uri, cli_target, config.cli_graph_name()) } +fn resolve_cli_graph( + config: &OmnigraphConfig, + cli_uri: Option, + cli_target: Option<&str>, +) -> Result { + let selected = if cli_uri.is_some() { + None + } else { + cli_target + .map(str::to_string) + .or_else(|| config.cli_graph_name().map(str::to_string)) + }; + config.resolve_graph_selection(selected.as_deref())?; + let uri = resolve_uri(config, cli_uri, cli_target)?; + let normalized_uri = normalize_policy_graph_uri(&uri)?; + let graph_id = graph_resource_id_for_selection(selected.as_deref(), &normalized_uri); + Ok(ResolvedCliGraph { + graph_id, + is_remote: is_remote_uri(&uri), + policy_file: config.resolve_policy_file_for(selected.as_deref()), + selected, + uri, + }) +} + +fn resolve_local_graph( + config: &OmnigraphConfig, + cli_uri: Option, + cli_target: Option<&str>, + operation: &str, +) -> Result { + let graph = resolve_cli_graph(config, cli_uri, cli_target)?; + if graph.is_remote { + bail!( + "{} is only supported against local graph URIs in this milestone", + operation + ); + } + Ok(graph) +} + /// Parse a Go-style compact duration: `7d`, `24h`, `30m`, `90s`, or a plain /// integer as seconds. Used by the `cleanup --older-than` flag. fn parse_duration_arg(s: &str) -> Result { @@ -834,8 +996,15 @@ fn parse_duration_arg(s: &str) -> Result { if s.is_empty() { bail!("duration is empty"); } - let (num_part, unit) = match s.char_indices().rev().find(|(_, c)| c.is_ascii_alphabetic()) { - Some((i, _)) => (&s[..i + 1 - s[i..].chars().next().unwrap().len_utf8()], &s[i..]), + let (num_part, unit) = match s + .char_indices() + .rev() + .find(|(_, c)| c.is_ascii_alphabetic()) + { + Some((i, _)) => ( + &s[..i + 1 - s[i..].chars().next().unwrap().len_utf8()], + &s[i..], + ), None => (s, ""), }; let n: u64 = num_part @@ -858,14 +1027,7 @@ fn resolve_local_uri( cli_target: Option<&str>, operation: &str, ) -> Result { - let uri = resolve_uri(config, cli_uri, cli_target)?; - if is_remote_uri(&uri) { - bail!( - "{} is only supported against local repo URIs in this milestone", - operation - ); - } - Ok(uri) + Ok(resolve_local_graph(config, cli_uri, cli_target, operation)?.uri) } fn resolve_branch( @@ -906,7 +1068,9 @@ fn resolve_query_path( .map(PathBuf::from) .or_else(|| alias_query.map(PathBuf::from)) .ok_or_else(|| { - color_eyre::eyre::eyre!("exactly one of --query or --alias must be provided") + color_eyre::eyre::eyre!( + "exactly one of --query, --query-string, or --alias must be provided" + ) }) .and_then(|query_path| config.resolve_query_path(&query_path)) } @@ -914,8 +1078,15 @@ fn resolve_query_path( fn resolve_query_source( config: &OmnigraphConfig, explicit_query: Option<&PathBuf>, + inline_query: Option<&str>, alias_query: Option<&str>, ) -> Result { + if let Some(inline) = inline_query { + if inline.trim().is_empty() { + bail!("--query-string must not be empty"); + } + return Ok(inline.to_string()); + } Ok(fs::read_to_string(resolve_query_path( config, explicit_query, @@ -1117,9 +1288,7 @@ fn render_schema_plan_step(step: &SchemaMigrationStep) -> String { type_name, drop_mode_label(*mode), ), - SchemaMigrationStep::UnsupportedChange { - entity, reason, .. - } => { + SchemaMigrationStep::UnsupportedChange { entity, reason, .. } => { // When a schema-lint code is attached, render code + tier // so operators see at-a-glance the kind of risk (destructive // / validated / safe) — not just the rule identifier. @@ -1303,12 +1472,12 @@ fn print_commit_human(commit: &CommitOutput) { println!("created_at: {}", commit.created_at); } -fn print_policy_explain(decision: &PolicyDecision, request: &PolicyRequest) { +fn print_policy_explain(decision: &PolicyDecision, actor_id: &str, request: &PolicyRequest) { println!( "decision: {}", if decision.allowed { "allow" } else { "deny" } ); - println!("actor: {}", request.actor_id); + println!("actor: {}", actor_id); println!("action: {}", request.action); if let Some(branch) = &request.branch { println!("branch: {}", branch); @@ -1529,10 +1698,10 @@ async fn execute_query_lint( )); } - let has_repo_target = + let has_graph_target = cli_uri.is_some() || cli_target.is_some() || config.cli_graph_name().is_some(); - if !has_repo_target { - bail!("query lint requires --schema or a resolvable repo target"); + if !has_graph_target { + bail!("query lint requires --schema or a resolvable graph target"); } let uri = resolve_local_uri(config, cli_uri, cli_target, "query lint")?; @@ -1541,10 +1710,252 @@ async fn execute_query_lint( &db.catalog(), &query_source, query_path, - QueryLintSchemaSource::repo(uri), + QueryLintSchemaSource::graph(uri), )) } +#[derive(serde::Serialize)] +struct QueriesIssue { + query: String, + message: String, +} + +#[derive(serde::Serialize)] +struct QueriesValidateOutput { + ok: bool, + breakages: Vec, + warnings: Vec, +} + +#[derive(serde::Serialize)] +struct QueriesParam { + name: String, + #[serde(rename = "type")] + type_name: String, + nullable: bool, +} + +#[derive(serde::Serialize)] +struct QueriesListItem { + name: String, + mcp_expose: bool, + tool_name: Option, + mutation: bool, + params: Vec, +} + +#[derive(serde::Serialize)] +struct QueriesListOutput { + queries: Vec, +} + +/// Resolve the selected graph to `(local URI, registry selection)` from one +/// precedence, so a command's schema and its stored-query registry can never +/// come from different graphs. A **positional URI is anonymous** (top-level +/// registry, ignoring the configured default graph); otherwise `--target` +/// or the configured `cli.graph` names the graph (its per-graph block). +/// Mirrors the server's single-mode identity rule. +fn resolve_selected_graph( + config: &OmnigraphConfig, + cli_uri: Option, + cli_target: Option<&str>, + operation: &str, +) -> Result<(String, Option)> { + let graph = resolve_local_graph(config, cli_uri, cli_target, operation)?; + Ok((graph.uri, graph.selected)) +} + +/// Load the stored-query registry for an already-resolved graph selection +/// (`None` = anonymous → top-level; `Some(name)` = that graph's block). +fn load_registry_or_report( + config: &OmnigraphConfig, + selected: Option<&str>, +) -> Result { + QueryRegistry::load(config, config.query_entries_for(selected)).map_err(|errors| { + color_eyre::eyre::eyre!( + "stored-query registry failed to load:\n {}", + errors + .iter() + .map(|e| e.to_string()) + .collect::>() + .join("\n ") + ) + }) +} + +fn graph_query_registry_names(config: &OmnigraphConfig) -> Vec<&str> { + config + .graphs + .iter() + .filter_map(|(name, graph)| (!graph.queries.is_empty()).then_some(name.as_str())) + .collect() +} + +fn resolve_registry_selection_for_list( + config: &OmnigraphConfig, + target: Option<&str>, +) -> Result> { + let selected = target + .map(str::to_string) + .or_else(|| config.cli_graph_name().map(str::to_string)); + if let Some(name) = selected.as_deref() { + config.resolve_graph_selection(Some(name))?; + return Ok(selected); + } + + if !config.query_entries().is_empty() { + return Ok(None); + } + + let graph_names = graph_query_registry_names(config); + if graph_names.is_empty() { + return Ok(None); + } + + bail!( + "stored-query registries are configured for graph{} {} but no graph was selected. Pass `--target {}` or set `cli.graph`.", + if graph_names.len() == 1 { "" } else { "s" }, + graph_names.join(", "), + graph_names[0], + ) +} + +fn validate_registry_for_catalog( + registry: &QueryRegistry, + catalog: &omnigraph_compiler::catalog::Catalog, + label: &str, +) -> omnigraph::error::Result<()> { + let report = check(registry, catalog); + if report.has_breakages() { + return Err(omnigraph::error::OmniError::manifest( + format_check_breakages(label, &report), + )); + } + Ok(()) +} + +async fn execute_queries_validate( + uri: Option, + target: Option, + config_path: Option<&PathBuf>, + json: bool, +) -> Result<()> { + let config = load_cli_config(config_path)?; + // One selection drives both the schema URI and the registry, so a + // positional URI and a `--target` can't validate different graphs. + let (uri, selected) = + resolve_selected_graph(&config, uri, target.as_deref(), "queries validate")?; + let registry = load_registry_or_report(&config, selected.as_deref())?; + let db = Omnigraph::open(&uri).await?; + let report = check(®istry, &db.catalog()); + + let output = QueriesValidateOutput { + ok: !report.has_breakages(), + breakages: report + .breakages + .iter() + .map(|b| QueriesIssue { + query: b.query.clone(), + message: b.message.clone(), + }) + .collect(), + warnings: report + .warnings + .iter() + .map(|w| QueriesIssue { + query: w.query.clone(), + message: w.message.clone(), + }) + .collect(), + }; + + if json { + print_json(&output)?; + } else { + if output.breakages.is_empty() { + println!( + "OK {} stored quer{} type-check against the schema", + registry.len(), + if registry.len() == 1 { "y" } else { "ies" } + ); + } + for issue in &output.breakages { + println!("ERROR query '{}': {}", issue.query, issue.message); + } + for issue in &output.warnings { + println!("WARN query '{}': {}", issue.query, issue.message); + } + } + + if report.has_breakages() { + io::stdout().flush()?; + std::process::exit(1); + } + Ok(()) +} + +fn execute_queries_list( + target: Option, + config_path: Option<&PathBuf>, + json: bool, +) -> Result<()> { + let config = load_cli_config(config_path)?; + let selected = resolve_registry_selection_for_list(&config, target.as_deref())?; + let registry = load_registry_or_report(&config, selected.as_deref())?; + + let output = QueriesListOutput { + queries: registry + .iter() + .map(|q| QueriesListItem { + name: q.name.clone(), + mcp_expose: q.expose, + tool_name: q.tool_name.clone(), + mutation: q.is_mutation(), + params: q + .decl + .params + .iter() + .map(|p| QueriesParam { + name: p.name.clone(), + type_name: p.type_name.clone(), + nullable: p.nullable, + }) + .collect(), + }) + .collect(), + }; + + if json { + print_json(&output)?; + } else if output.queries.is_empty() { + println!("(no stored queries registered)"); + } else { + for q in &output.queries { + let kind = if q.mutation { "mutation" } else { "read" }; + let params = q + .params + .iter() + .map(|p| { + format!( + "${}: {}{}", + p.name, + p.type_name, + if p.nullable { "?" } else { "" } + ) + }) + .collect::>() + .join(", "); + let mcp = if q.mcp_expose { + format!(" [mcp: {}]", q.tool_name.as_deref().unwrap_or(&q.name)) + } else { + String::new() + }; + println!("{kind} {}({params}){mcp}", q.name); + } + } + Ok(()) +} + async fn execute_read( uri: &str, query_source: &str, @@ -1591,7 +2002,7 @@ async fn execute_read_remote( } async fn execute_change( - uri: &str, + graph: &ResolvedCliGraph, query_source: &str, query_name: Option<&str>, branch: &str, @@ -1601,7 +2012,7 @@ async fn execute_change( ) -> Result { let (selected_name, query_params) = select_named_query(query_source, query_name)?; let params = query_params_from_json(&query_params, params_json)?; - let db = open_local_db_with_policy(uri, config).await?; + let db = open_local_db_with_policy(graph).await?; let actor = resolve_cli_actor(cli_as_actor, config); let result = db .mutate_as(branch, query_source, &selected_name, ¶ms, actor) @@ -1615,6 +2026,33 @@ async fn execute_change( }) } +/// Build the JSON body for `POST /change` using the legacy wire shape. +/// +/// `ChangeRequest`'s Rust field names are now `query` / `name` (the canonical +/// wire shape going forward), but old `omnigraph-server` builds still require +/// the legacy `query_source` / `query_name` keys on `/change`. Hand-rolling +/// the JSON with the legacy names keeps a newer CLI talking to an older +/// server intact -- the same byte-stability contract we apply to +/// `execute_read_remote` against `/read`. +fn legacy_change_request_body( + query_source: &str, + query_name: Option<&str>, + branch: &str, + params_json: Option<&Value>, +) -> Value { + let mut body = serde_json::json!({ + "query_source": query_source, + "branch": branch, + }); + if let Some(name) = query_name { + body["query_name"] = Value::String(name.to_string()); + } + if let Some(params) = params_json { + body["params"] = params.clone(); + } + body +} + async fn execute_change_remote( client: &reqwest::Client, uri: &str, @@ -1628,12 +2066,12 @@ async fn execute_change_remote( client, Method::POST, remote_url(uri, "/change"), - Some(serde_json::to_value(ChangeRequest { - query_source: query_source.to_string(), - query_name: query_name.map(ToOwned::to_owned), - params: params_json.cloned(), - branch: Some(branch.to_string()), - })?), + Some(legacy_change_request_body( + query_source, + query_name, + branch, + params_json, + )), bearer_token, ) .await @@ -1688,10 +2126,74 @@ async fn execute_export_remote_to_writer( Ok(()) } +/// Rewrite deprecated CLI invocations into their canonical form. +/// +/// The current rename pass moves four subcommands: +/// - `omnigraph read` -> `omnigraph query` (clap `visible_alias` handles parsing; we warn) +/// - `omnigraph change` -> `omnigraph mutate` (clap `visible_alias` handles parsing; we warn) +/// - `omnigraph check` -> `omnigraph lint` (rewrite required; no visible_alias by design) +/// - `omnigraph query lint` -> `omnigraph lint` (rewrite required; `query` is now the read-runner) +/// - `omnigraph query check` -> `omnigraph lint` (rewrite required) +/// +/// `check` is *not* a clap visible_alias on `lint` even though they're +/// semantically equivalent. Visible aliases create two canonical names +/// that agents emit interchangeably depending on training-data drift +/// (see MR-981 §6 for the policy). The argv-shim + stderr warning +/// pattern preserves back-compat for human users while pointing every +/// caller at the single canonical name in `--help`. +/// +/// Returns the (possibly rewritten) argv that clap should parse. +fn rewrite_deprecated_argv(args: Vec) -> Vec { + if args.len() >= 3 { + let sub = args[1].to_str(); + let sub2 = args[2].to_str(); + if sub == Some("query") && matches!(sub2, Some("lint") | Some("check")) { + let suffix = sub2.unwrap(); + eprintln!( + "warning: `omnigraph query {suffix}` is deprecated; use `omnigraph lint` instead" + ); + // Drop the leading `query` token AND normalize `check` -> `lint`. + // `check` is no longer a clap visible_alias (MR-981 §6), so the + // rewritten argv must reach the canonical `lint` subcommand + // directly. Result for `omnigraph query check --query foo.gq`: + // `omnigraph lint --query foo.gq`. + let mut out = Vec::with_capacity(args.len() - 1); + out.push(args[0].clone()); + out.push(OsString::from("lint")); + out.extend(args[3..].iter().cloned()); + return out; + } + } + if let Some(sub) = args.get(1).and_then(|s| s.to_str()) { + match sub { + "read" => eprintln!( + "warning: `omnigraph read` is deprecated; use `omnigraph query` instead" + ), + "change" => eprintln!( + "warning: `omnigraph change` is deprecated; use `omnigraph mutate` instead" + ), + "check" => { + eprintln!( + "warning: `omnigraph check` is deprecated; use `omnigraph lint` instead" + ); + // Rewrite the top-level subcommand to `lint`; pass through the rest. + let mut out = Vec::with_capacity(args.len()); + out.push(args[0].clone()); + out.push(OsString::from("lint")); + out.extend(args[2..].iter().cloned()); + return out; + } + _ => {} + } + } + args +} + #[tokio::main] async fn main() -> Result<()> { color_eyre::install()?; let cli = { + let raw_args = rewrite_deprecated_argv(std::env::args_os().collect()); let matches = Cli::command() .arg( Arg::new("version") @@ -1700,7 +2202,7 @@ async fn main() -> Result<()> { .action(ArgAction::Version) .help("Print version"), ) - .get_matches(); + .get_matches_from(raw_args); Cli::from_arg_matches(&matches)? }; let http_client = build_http_client()?; @@ -1716,10 +2218,15 @@ async fn main() -> Result<()> { print_embed_human(&output); } } - Command::Init { schema, uri } => { + Command::Init { schema, uri, force } => { let schema_source = fs::read_to_string(&schema)?; - ensure_local_repo_parent(&uri)?; - Omnigraph::init(&uri, &schema_source).await?; + ensure_local_graph_parent(&uri)?; + Omnigraph::init_with_options( + &uri, + &schema_source, + omnigraph::db::InitOptions { force }, + ) + .await?; scaffold_config_if_missing(&uri)?; println!("initialized {}", uri); } @@ -1733,9 +2240,10 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = resolve_local_uri(&config, uri, target.as_deref(), "load")?; + let graph = resolve_local_graph(&config, uri, target.as_deref(), "load")?; + let uri = graph.uri.clone(); let branch = resolve_branch(&config, branch, None, "main"); - let db = open_local_db_with_policy(&uri, &config).await?; + let db = open_local_db_with_policy(&graph).await?; let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); let result = db .load_file_as(&branch, &data.to_string_lossy(), mode.into(), actor) @@ -1776,10 +2284,11 @@ async fn main() -> Result<()> { let config = load_cli_config(config.as_ref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; - let uri = resolve_uri(&config, uri, target.as_deref())?; + let graph = resolve_cli_graph(&config, uri, target.as_deref())?; + let uri = graph.uri.clone(); let branch = resolve_branch(&config, branch, None, "main"); let from = resolve_branch(&config, from, None, "main"); - let payload = if is_remote_uri(&uri) { + let payload = if graph.is_remote { let data = fs::read_to_string(&data)?; remote_json::( &http_client, @@ -1795,7 +2304,7 @@ async fn main() -> Result<()> { ) .await? } else { - let db = open_local_db_with_policy(&uri, &config).await?; + let db = open_local_db_with_policy(&graph).await?; let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); let result = db .ingest_file_as( @@ -1826,9 +2335,10 @@ async fn main() -> Result<()> { let config = load_cli_config(config.as_ref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; - let uri = resolve_uri(&config, uri, target.as_deref())?; + let graph = resolve_cli_graph(&config, uri, target.as_deref())?; + let uri = graph.uri.clone(); let from = resolve_branch(&config, from, None, "main"); - let payload = if is_remote_uri(&uri) { + let payload = if graph.is_remote { remote_json::( &http_client, Method::POST, @@ -1841,7 +2351,7 @@ async fn main() -> Result<()> { ) .await? } else { - let db = open_local_db_with_policy(&uri, &config).await?; + let db = open_local_db_with_policy(&graph).await?; let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); db.branch_create_from_as(ReadTarget::branch(&from), &name, actor) .await?; @@ -1867,8 +2377,9 @@ async fn main() -> Result<()> { let config = load_cli_config(config.as_ref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; - let uri = resolve_uri(&config, uri, target.as_deref())?; - let payload = if is_remote_uri(&uri) { + let graph = resolve_cli_graph(&config, uri, target.as_deref())?; + let uri = graph.uri.clone(); + let payload = if graph.is_remote { remote_json::( &http_client, Method::GET, @@ -1901,8 +2412,9 @@ async fn main() -> Result<()> { let config = load_cli_config(config.as_ref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; - let uri = resolve_uri(&config, uri, target.as_deref())?; - let payload = if is_remote_uri(&uri) { + let graph = resolve_cli_graph(&config, uri, target.as_deref())?; + let uri = graph.uri.clone(); + let payload = if graph.is_remote { remote_json::( &http_client, Method::DELETE, @@ -1912,7 +2424,7 @@ async fn main() -> Result<()> { ) .await? } else { - let db = open_local_db_with_policy(&uri, &config).await?; + let db = open_local_db_with_policy(&graph).await?; let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); db.branch_delete_as(&name, actor).await?; BranchDeleteOutput { @@ -1938,9 +2450,10 @@ async fn main() -> Result<()> { let config = load_cli_config(config.as_ref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; - let uri = resolve_uri(&config, uri, target.as_deref())?; + let graph = resolve_cli_graph(&config, uri, target.as_deref())?; + let uri = graph.uri.clone(); let into = resolve_branch(&config, into, None, "main"); - let payload = if is_remote_uri(&uri) { + let payload = if graph.is_remote { remote_json::( &http_client, Method::POST, @@ -1953,7 +2466,7 @@ async fn main() -> Result<()> { ) .await? } else { - let db = open_local_db_with_policy(&uri, &config).await?; + let db = open_local_db_with_policy(&graph).await?; let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); let outcome = db.branch_merge_as(&source, &into, actor).await?; BranchMergeOutput { @@ -2088,9 +2601,10 @@ async fn main() -> Result<()> { let config = load_cli_config(config.as_ref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; - let uri = resolve_uri(&config, uri, target.as_deref())?; + let graph = resolve_cli_graph(&config, uri, target.as_deref())?; + let uri = graph.uri.clone(); let schema_source = fs::read_to_string(&schema)?; - let output = if is_remote_uri(&uri) { + let output = if graph.is_remote { // MR-694 PR B: SchemaApplyRequest gained an // allow_data_loss field so Hard-mode drops are no // longer CLI-only. The previous bail is gone; the @@ -2108,13 +2622,22 @@ async fn main() -> Result<()> { ) .await? } else { - let db = open_local_db_with_policy(&uri, &config).await?; + let db = open_local_db_with_policy(&graph).await?; let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); + let registry = load_registry_or_report(&config, graph.selected())?; + let registry = (!registry.is_empty()).then_some(registry); + let label = graph.selected().unwrap_or(&uri).to_string(); let result = db - .apply_schema_as( + .apply_schema_as_with_catalog_check( &schema_source, omnigraph::db::SchemaApplyOptions { allow_data_loss }, actor, + |catalog| { + if let Some(registry) = registry.as_ref() { + validate_registry_for_catalog(registry, catalog, &label)?; + } + Ok(()) + }, ) .await?; schema_apply_output(&uri, result) @@ -2157,20 +2680,35 @@ async fn main() -> Result<()> { } } }, - Command::Query { command } => match command { - QueryCommand::Lint { + Command::Lint { + uri, + target, + config, + query, + schema, + json, + } => { + let config = load_cli_config(config.as_ref())?; + let output = + execute_query_lint(&config, uri, target.as_deref(), schema.as_ref(), &query) + .await?; + finish_query_lint(&output, json)?; + } + Command::Queries { command } => match command { + QueriesCommand::Validate { uri, target, config, - query, - schema, json, } => { - let config = load_cli_config(config.as_ref())?; - let output = - execute_query_lint(&config, uri, target.as_deref(), schema.as_ref(), &query) - .await?; - finish_query_lint(&output, json)?; + execute_queries_validate(uri, target, config.as_ref(), json).await?; + } + QueriesCommand::List { + target, + config, + json, + } => { + execute_queries_list(target, config.as_ref(), json)?; } }, Command::Snapshot { @@ -2242,13 +2780,14 @@ async fn main() -> Result<()> { .await?; } } - Command::Read { + Command::Query { uri, legacy_uri, target, config, alias, query, + query_string, name, params, branch, @@ -2257,8 +2796,8 @@ async fn main() -> Result<()> { json, alias_args, } => { - if alias.is_some() == query.is_some() { - bail!("exactly one of --alias or --query must be provided"); + if alias.is_none() && query.is_none() && query_string.is_none() { + bail!("exactly one of --query, --query-string, or --alias must be provided"); } let config = load_cli_config(config.as_ref())?; @@ -2277,10 +2816,12 @@ async fn main() -> Result<()> { .as_deref() .or_else(|| alias_config.and_then(|alias| alias.graph.as_deref())); let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target_name)?; - let uri = resolve_uri(&config, uri, target_name)?; + let graph = resolve_cli_graph(&config, uri, target_name)?; + let uri = graph.uri.clone(); let query_source = resolve_query_source( &config, query.as_ref(), + query_string.as_deref(), alias_config.map(|a| a.query.as_str()), )?; let params_json = merged_params_json( @@ -2298,7 +2839,7 @@ async fn main() -> Result<()> { alias_config.and_then(|alias| alias.branch.clone()), )?; let query_name = name.or_else(|| alias_config.and_then(|alias| alias.name.clone())); - let output = if is_remote_uri(&uri) { + let output = if graph.is_remote { execute_read_remote( &http_client, &uri, @@ -2327,21 +2868,22 @@ async fn main() -> Result<()> { ); print_read_output(&output, format, &config)?; } - Command::Change { + Command::Mutate { uri, legacy_uri, target, config, alias, query, + query_string, name, params, branch, json, alias_args, } => { - if alias.is_some() == query.is_some() { - bail!("exactly one of --alias or --query must be provided"); + if alias.is_none() && query.is_none() && query_string.is_none() { + bail!("exactly one of --query, --query-string, or --alias must be provided"); } let config = load_cli_config(config.as_ref())?; @@ -2360,10 +2902,12 @@ async fn main() -> Result<()> { .as_deref() .or_else(|| alias_config.and_then(|alias| alias.graph.as_deref())); let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target_name)?; - let uri = resolve_uri(&config, uri, target_name)?; + let graph = resolve_cli_graph(&config, uri, target_name)?; + let uri = graph.uri.clone(); let query_source = resolve_query_source( &config, query.as_ref(), + query_string.as_deref(), alias_config.map(|a| a.query.as_str()), )?; let params_json = merged_params_json( @@ -2381,7 +2925,7 @@ async fn main() -> Result<()> { "main", ); let query_name = name.or_else(|| alias_config.and_then(|alias| alias.name.clone())); - let output = if is_remote_uri(&uri) { + let output = if graph.is_remote { execute_change_remote( &http_client, &uri, @@ -2394,7 +2938,7 @@ async fn main() -> Result<()> { .await? } else { execute_change( - &uri, + &graph, &query_source, query_name.as_deref(), &branch, @@ -2413,20 +2957,19 @@ async fn main() -> Result<()> { Command::Policy { command } => match command { PolicyCommand::Validate { config } => { let config = load_cli_config(config.as_ref())?; - let engine = resolve_policy_engine(&config)?; - let policy_file = config - .resolve_policy_file() - .expect("policy file should exist after resolve_policy_engine"); + let context = resolve_policy_context(&config)?; + let engine = resolve_policy_engine(&context)?; println!( "policy valid: {} [{} actors]", - policy_file.display(), + context.policy_file.display(), engine.known_actor_count() ); } PolicyCommand::Test { config } => { let config = load_cli_config(config.as_ref())?; - let engine = resolve_policy_engine(&config)?; - let tests_path = resolve_policy_tests_path(&config)?; + let context = resolve_policy_context(&config)?; + let engine = resolve_policy_engine(&context)?; + let tests_path = resolve_policy_tests_path(&context); let tests = PolicyTestConfig::load(&tests_path)?; engine.run_tests(&tests)?; println!("policy tests passed: {} cases", tests.cases.len()); @@ -2439,15 +2982,15 @@ async fn main() -> Result<()> { target_branch, } => { let config = load_cli_config(config.as_ref())?; - let engine = resolve_policy_engine(&config)?; + let context = resolve_policy_context(&config)?; + let engine = resolve_policy_engine(&context)?; let request = PolicyRequest { - actor_id: actor, action, branch, target_branch, }; - let decision = engine.authorize(&request)?; - print_policy_explain(&decision, &request); + let decision = engine.authorize(&actor, &request)?; + print_policy_explain(&decision, &actor, &request); } }, Command::Optimize { @@ -2468,18 +3011,19 @@ async fn main() -> Result<()> { "fragments_removed": s.fragments_removed, "fragments_added": s.fragments_added, "committed": s.committed, + "skipped": s.skipped.map(|r| r.as_str()), })).collect::>(), }); print_json(&value)?; } else { println!("optimize {} — {} tables", uri, stats.len()); for s in &stats { - if s.committed { + if let Some(reason) = s.skipped { + println!(" {:<40} skipped ({reason})", s.table_key); + } else if s.committed { println!( " {:<40} frags {} → {} ✓", - s.table_key, - s.fragments_removed + s.fragments_added - s.fragments_added, - s.fragments_added + s.table_key, s.fragments_removed, s.fragments_added ); } else { println!(" {:<40} no-op", s.table_key); @@ -2499,17 +3043,16 @@ async fn main() -> Result<()> { let config = load_cli_config(config.as_ref())?; let uri = resolve_uri(&config, uri, target.as_deref())?; - let older_than_dur = older_than - .as_deref() - .map(parse_duration_arg) - .transpose()?; + let older_than_dur = older_than.as_deref().map(parse_duration_arg).transpose()?; if keep.is_none() && older_than_dur.is_none() { bail!("cleanup requires at least one of --keep or --older-than"); } let policy_desc = match (keep, older_than_dur) { - (Some(k), Some(d)) => format!("keep {} versions, remove anything older than {:?}", k, d), + (Some(k), Some(d)) => { + format!("keep {} versions, remove anything older than {:?}", k, d) + } (Some(k), None) => format!("keep {} versions", k), (None, Some(d)) => format!("remove anything older than {:?}", d), _ => unreachable!(), @@ -2539,22 +3082,70 @@ async fn main() -> Result<()> { "table_key": s.table_key, "bytes_removed": s.bytes_removed, "old_versions_removed": s.old_versions_removed, + "error": s.error, })).collect::>(), }); print_json(&value)?; } else { let total_bytes: u64 = stats.iter().map(|s| s.bytes_removed).sum(); let total_versions: u64 = stats.iter().map(|s| s.old_versions_removed).sum(); + let failed: Vec<&str> = stats + .iter() + .filter(|s| s.error.is_some()) + .map(|s| s.table_key.as_str()) + .collect(); println!( "cleanup {} ({}) — removed {} versions ({} bytes) across {} tables", uri, policy_desc, total_versions, total_bytes, - stats.len() + stats.len() - failed.len() ); + if !failed.is_empty() { + println!( + " {} table(s) failed and will be retried on the next cleanup: {}", + failed.len(), + failed.join(", ") + ); + } } } + Command::Graphs { command } => match command { + GraphsCommand::List { + uri, + target, + config, + json, + } => { + let config = load_cli_config(config.as_ref())?; + let bearer_token = + resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; + let uri = resolve_uri(&config, uri, target.as_deref())?; + if !is_remote_uri(&uri) { + bail!( + "`omnigraph graphs list` requires a remote multi-graph server URL \ + (http:// or https://). To enumerate local graphs, read `omnigraph.yaml` \ + directly." + ); + } + let payload = remote_json::( + &http_client, + Method::GET, + remote_url(&uri, "/graphs"), + None, + bearer_token.as_deref(), + ) + .await?; + if json { + print_json(&payload)?; + } else { + for entry in payload.graphs { + println!("{}\t{}", entry.graph_id, entry.uri); + } + } + } + }, } Ok(()) } @@ -2564,14 +3155,63 @@ mod tests { use std::fs; use super::{ - DEFAULT_BEARER_TOKEN_ENV, apply_bearer_token, bearer_token_from_env_file, load_cli_config, - load_env_file_into_process, normalize_bearer_token, parse_env_assignment, - resolve_remote_bearer_token, + DEFAULT_BEARER_TOKEN_ENV, apply_bearer_token, bearer_token_from_env_file, + legacy_change_request_body, load_cli_config, load_env_file_into_process, + normalize_bearer_token, parse_env_assignment, resolve_policy_context, + resolve_cli_graph, resolve_remote_bearer_token, }; use omnigraph_server::load_config; use reqwest::header::AUTHORIZATION; + use serde_json::json; use tempfile::tempdir; + #[test] + fn legacy_change_request_body_uses_legacy_field_names() { + // `execute_change_remote` hits `POST /change`, which old + // `omnigraph-server` builds deserialize as `ChangeRequest` with + // **required** `query_source` and optional `query_name` keys. + // Newer servers accept both spellings via serde alias, but a + // newer CLI must still emit the legacy keys on the wire so it + // can talk to an old server during a rolling upgrade. + let body = legacy_change_request_body( + "query insert_person($n: String) { insert Person { name: $n } }", + Some("insert_person"), + "main", + Some(&json!({ "n": "Alice" })), + ); + assert_eq!( + body["query_source"].as_str(), + Some("query insert_person($n: String) { insert Person { name: $n } }"), + ); + assert_eq!(body["query_name"].as_str(), Some("insert_person")); + assert_eq!(body["branch"].as_str(), Some("main")); + assert_eq!(body["params"]["n"].as_str(), Some("Alice")); + // Crucially, the **new** field names must NOT appear -- old + // servers would silently treat them as unknown fields and then + // fail on missing required `query_source`. + assert!( + body.get("query").is_none(), + "legacy /change body must not carry the renamed `query` key; got {body}" + ); + assert!( + body.get("name").is_none(), + "legacy /change body must not carry the renamed `name` key; got {body}" + ); + } + + #[test] + fn legacy_change_request_body_omits_optional_fields_when_unset() { + let body = legacy_change_request_body( + "query find() { match { $p: Person } return { $p.name } }", + None, + "main", + None, + ); + assert_eq!(body["branch"].as_str(), Some("main")); + assert!(body.get("query_name").is_none()); + assert!(body.get("params").is_none()); + } + #[test] fn apply_bearer_token_adds_header_when_configured() { let client = reqwest::Client::new(); @@ -2778,4 +3418,150 @@ graphs: } } } + + #[test] + fn graph_identity_resolve_policy_context_named_cli_graph_uses_graph_key_not_project_name_or_uri() { + let temp = tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +project: + name: misleading-project +graphs: + local: + uri: /tmp/local-policy-graph.omni + policy: + file: ./policy.yaml +cli: + graph: local +"#, + ) + .unwrap(); + + let config = load_config(Some(&config_path)).unwrap(); + let context = resolve_policy_context(&config).unwrap(); + assert_eq!(context.graph_id, "local"); + } + + #[test] + fn graph_identity_resolve_policy_context_server_graph_uses_graph_key_when_cli_graph_absent() { + let temp = tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +project: + name: misleading-project +graphs: + local: + uri: /tmp/local-policy-graph.omni + policy: + file: ./server-policy.yaml +server: + graph: local +"#, + ) + .unwrap(); + + let config = load_config(Some(&config_path)).unwrap(); + let context = resolve_policy_context(&config).unwrap(); + assert_eq!(context.graph_id, "local"); + assert!(context.policy_file.ends_with("server-policy.yaml")); + } + + #[test] + fn graph_identity_resolve_policy_context_anonymous_uses_top_level_default_identity() { + let temp = tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +project: + name: misleading-project +graphs: + local: + uri: /tmp/local-policy-graph.omni +policy: + file: ./top-policy.yaml +"#, + ) + .unwrap(); + + let config = load_config(Some(&config_path)).unwrap(); + let context = resolve_policy_context(&config).unwrap(); + assert_eq!(context.graph_id, "default"); + assert!(context.policy_file.ends_with("top-policy.yaml")); + } + + #[test] + fn graph_identity_resolve_cli_graph_named_target_uses_graph_key_not_project_name_or_uri() { + let temp = tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +project: + name: misleading-project +graphs: + prod: + uri: s3://bucket/prod-graph/ + policy: + file: ./prod-policy.yaml +"#, + ) + .unwrap(); + + let config = load_config(Some(&config_path)).unwrap(); + let graph = resolve_cli_graph(&config, None, Some("prod")).unwrap(); + assert_eq!(graph.selected(), Some("prod")); + assert_eq!(graph.graph_id, "prod"); + assert_eq!(graph.uri, "s3://bucket/prod-graph/"); + } + + #[test] + fn graph_identity_resolve_cli_graph_positional_uri_uses_anonymous_normalized_uri() { + let temp = tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +project: + name: misleading-project +graphs: + local: + uri: /tmp/configured-graph.omni + policy: + file: ./policy.yaml +cli: + graph: local +"#, + ) + .unwrap(); + + let config = load_config(Some(&config_path)).unwrap(); + let local_graph_path = temp.path().join("explicit-graph.omni"); + let local_graph = resolve_cli_graph( + &config, + Some(format!("file://{}", local_graph_path.display())), + None, + ) + .unwrap(); + assert_eq!(local_graph.selected(), None); + assert_eq!( + local_graph.graph_id, + local_graph_path.to_string_lossy().as_ref() + ); + assert_eq!(local_graph.policy_file, None); + + let s3_graph = resolve_cli_graph( + &config, + Some("s3://bucket/anonymous-graph/".to_string()), + None, + ) + .unwrap(); + assert_eq!(s3_graph.selected(), None); + assert_eq!(s3_graph.graph_id, "s3://bucket/anonymous-graph"); + assert_eq!(s3_graph.policy_file, None); + } } diff --git a/crates/omnigraph-cli/tests/cli.rs b/crates/omnigraph-cli/tests/cli.rs index 137f469..9682d9a 100644 --- a/crates/omnigraph-cli/tests/cli.rs +++ b/crates/omnigraph-cli/tests/cli.rs @@ -48,9 +48,9 @@ cases: expect: deny "#; -fn manifest_dataset_version(repo: &std::path::Path) -> u64 { +fn manifest_dataset_version(graph: &std::path::Path) -> u64 { tokio::runtime::Runtime::new().unwrap().block_on(async { - Omnigraph::open(repo.to_string_lossy().as_ref()) + Omnigraph::open(graph.to_string_lossy().as_ref()) .await .unwrap() .snapshot_of(ReadTarget::branch("main")) @@ -67,7 +67,7 @@ fn write_policy_config_fixture(root: &std::path::Path) -> (std::path::PathBuf, s &config, r#" project: - name: policy-test-repo + name: policy-test-graph policy: file: ./policy.yaml "#, @@ -221,26 +221,26 @@ fn embed_seed_preserves_non_entity_rows() { } #[test] -fn init_creates_repo_successfully_on_missing_local_directory() { +fn init_creates_graph_successfully_on_missing_local_directory() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema = fixture("test.pg"); - let output = output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&repo)); + let output = output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&graph)); let stdout = stdout_string(&output); assert!(stdout.contains("initialized")); - assert!(repo.join("_schema.pg").exists()); - assert!(repo.join("__manifest").exists()); + assert!(graph.join("_schema.pg").exists()); + assert!(graph.join("__manifest").exists()); assert!(temp.path().join("omnigraph.yaml").exists()); } #[test] fn schema_plan_json_reports_supported_additive_change() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("next.pg"); - init_repo(&repo); + init_graph(&graph); let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( " age: I32?\n}", @@ -255,7 +255,7 @@ fn schema_plan_json_reports_supported_additive_change() { .arg("--schema") .arg(&schema_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); @@ -270,9 +270,9 @@ fn schema_plan_json_reports_supported_additive_change() { #[test] fn schema_plan_json_reports_unsupported_type_change() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("breaking.pg"); - init_repo(&repo); + init_graph(&graph); let breaking_schema = fs::read_to_string(fixture("test.pg")) .unwrap() @@ -286,7 +286,7 @@ fn schema_plan_json_reports_unsupported_type_change() { .arg("--schema") .arg(&schema_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); @@ -303,9 +303,9 @@ fn schema_plan_json_reports_unsupported_type_change() { #[test] fn schema_apply_json_applies_supported_migration() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("next.pg"); - init_repo(&repo); + init_graph(&graph); let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( " age: I32?\n}", @@ -320,7 +320,7 @@ fn schema_apply_json_applies_supported_migration() { .arg("--schema") .arg(&schema_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); @@ -330,7 +330,7 @@ fn schema_apply_json_applies_supported_migration() { let db = tokio::runtime::Runtime::new() .unwrap() - .block_on(Omnigraph::open(repo.to_string_lossy().as_ref())) + .block_on(Omnigraph::open(graph.to_string_lossy().as_ref())) .unwrap(); assert!( db.catalog().node_types["Person"] @@ -342,9 +342,9 @@ fn schema_apply_json_applies_supported_migration() { #[test] fn schema_apply_human_reports_noop() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = fixture("test.pg"); - init_repo(&repo); + init_graph(&graph); let output = output_success( cli() @@ -352,7 +352,7 @@ fn schema_apply_human_reports_noop() { .arg("apply") .arg("--schema") .arg(&schema_path) - .arg(&repo), + .arg(&graph), ); let stdout = stdout_string(&output); @@ -363,9 +363,9 @@ fn schema_apply_human_reports_noop() { #[test] fn schema_apply_json_renames_type_and_updates_snapshot() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("rename.pg"); - init_repo(&repo); + init_graph(&graph); let renamed_schema = fs::read_to_string(fixture("test.pg")) .unwrap() @@ -384,14 +384,14 @@ fn schema_apply_json_renames_type_and_updates_snapshot() { .arg("--schema") .arg(&schema_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["applied"], true); let db = tokio::runtime::Runtime::new() .unwrap() - .block_on(Omnigraph::open(repo.to_string_lossy().as_ref())) + .block_on(Omnigraph::open(graph.to_string_lossy().as_ref())) .unwrap(); let snapshot = tokio::runtime::Runtime::new() .unwrap() @@ -404,9 +404,9 @@ fn schema_apply_json_renames_type_and_updates_snapshot() { #[test] fn schema_apply_json_renames_property_and_updates_catalog() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("rename-property.pg"); - init_repo(&repo); + init_graph(&graph); let renamed_schema = fs::read_to_string(fixture("test.pg")) .unwrap() @@ -420,14 +420,14 @@ fn schema_apply_json_renames_property_and_updates_catalog() { .arg("--schema") .arg(&schema_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["applied"], true); let db = tokio::runtime::Runtime::new() .unwrap() - .block_on(Omnigraph::open(repo.to_string_lossy().as_ref())) + .block_on(Omnigraph::open(graph.to_string_lossy().as_ref())) .unwrap(); let person = &db.catalog().node_types["Person"]; assert!(person.properties.contains_key("years")); @@ -437,12 +437,12 @@ fn schema_apply_json_renames_property_and_updates_catalog() { #[test] fn schema_apply_json_adds_index_for_existing_property() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("index.pg"); - init_repo(&repo); + init_graph(&graph); let before_index_count = tokio::runtime::Runtime::new().unwrap().block_on(async { - let db = Omnigraph::open(repo.to_string_lossy().as_ref()) + let db = Omnigraph::open(graph.to_string_lossy().as_ref()) .await .unwrap(); let snapshot = db.snapshot_of(ReadTarget::branch("main")).await.unwrap(); @@ -462,13 +462,13 @@ fn schema_apply_json_adds_index_for_existing_property() { .arg("--schema") .arg(&schema_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["applied"], true); let after_index_count = tokio::runtime::Runtime::new().unwrap().block_on(async { - let db = Omnigraph::open(repo.to_string_lossy().as_ref()) + let db = Omnigraph::open(graph.to_string_lossy().as_ref()) .await .unwrap(); let snapshot = db.snapshot_of(ReadTarget::branch("main")).await.unwrap(); @@ -481,9 +481,9 @@ fn schema_apply_json_adds_index_for_existing_property() { #[test] fn schema_apply_rejects_unsupported_plan() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("breaking.pg"); - init_repo(&repo); + init_graph(&graph); let breaking_schema = fs::read_to_string(fixture("test.pg")) .unwrap() @@ -496,7 +496,7 @@ fn schema_apply_rejects_unsupported_plan() { .arg("apply") .arg("--schema") .arg(&schema_path) - .arg(&repo), + .arg(&graph), ); let stderr = String::from_utf8_lossy(&output.stderr); assert!(stderr.contains("changing property type")); @@ -505,9 +505,9 @@ fn schema_apply_rejects_unsupported_plan() { #[test] fn schema_apply_rejects_when_non_main_branch_exists() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("next.pg"); - init_repo(&repo); + init_graph(&graph); output_success( cli() .arg("branch") @@ -515,7 +515,7 @@ fn schema_apply_rejects_when_non_main_branch_exists() { .arg("--from") .arg("main") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("feature"), ); @@ -531,10 +531,10 @@ fn schema_apply_rejects_when_non_main_branch_exists() { .arg("apply") .arg("--schema") .arg(&schema_path) - .arg(&repo), + .arg(&graph), ); let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("schema apply requires a repo with only main")); + assert!(stderr.contains("schema apply requires a graph with only main")); } #[test] @@ -631,12 +631,208 @@ query list_people() { assert_eq!(stdout_string(&lint_output), stdout_string(&check_output)); } +/// `omnigraph lint` is the canonical top-level lint command after the +/// query/mutate rename. `omnigraph query lint` and `omnigraph query check` +/// are kept as deprecated argv shims (warning + rewrite). All three must +/// produce identical stdout output. #[test] -fn query_lint_can_use_local_repo_via_positional_uri() { +fn lint_top_level_matches_deprecated_query_lint_output() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let schema_path = temp.path().join("schema.pg"); let query_path = temp.path().join("queries.gq"); - init_repo(&repo); + write_file( + &schema_path, + r#" +node Person { + name: String +} +"#, + ); + write_query_file( + &query_path, + r#" +query list_people() { + match { $p: Person } + return { $p.name } +} +"#, + ); + + let canonical = output_success( + cli() + .arg("lint") + .arg("--query") + .arg(&query_path) + .arg("--schema") + .arg(&schema_path) + .arg("--json"), + ); + let deprecated_lint = output_success( + cli() + .arg("query") + .arg("lint") + .arg("--query") + .arg(&query_path) + .arg("--schema") + .arg(&schema_path) + .arg("--json"), + ); + let deprecated_check = output_success( + cli() + .arg("query") + .arg("check") + .arg("--query") + .arg(&query_path) + .arg("--schema") + .arg(&schema_path) + .arg("--json"), + ); + + assert_eq!(stdout_string(&canonical), stdout_string(&deprecated_lint)); + assert_eq!(stdout_string(&canonical), stdout_string(&deprecated_check)); + + // Canonical form must NOT emit the deprecation warning. + let canonical_stderr = String::from_utf8(canonical.stderr).unwrap(); + assert!( + !canonical_stderr.contains("deprecated"), + "`omnigraph lint` is canonical and must not warn; got stderr: {canonical_stderr}" + ); + + // Deprecated forms MUST emit the one-line warning, pointing at the + // new top-level `omnigraph lint`. + let lint_stderr = String::from_utf8(deprecated_lint.stderr).unwrap(); + assert!( + lint_stderr.contains("`omnigraph query lint` is deprecated") + && lint_stderr.contains("`omnigraph lint`"), + "expected deprecation warning pointing at `omnigraph lint`; got: {lint_stderr}" + ); + let check_stderr = String::from_utf8(deprecated_check.stderr).unwrap(); + assert!( + check_stderr.contains("`omnigraph query check` is deprecated") + && check_stderr.contains("`omnigraph lint`"), + "expected deprecation warning pointing at `omnigraph lint`; got: {check_stderr}" + ); +} + +/// Bare `omnigraph check` is NOT a clap `visible_alias` on `lint` (MR-981 §6: +/// visible aliases give agents two canonical names to emit interchangeably). +/// It's an argv-level shim: rewrites to `omnigraph lint`, prints a one-line +/// stderr deprecation warning, and produces identical stdout to the canonical +/// invocation. Cargo/Go users typing `check` keep working; help text shows +/// only `lint`. +#[test] +fn deprecated_check_top_level_rewrites_to_lint() { + let temp = tempdir().unwrap(); + let schema_path = temp.path().join("schema.pg"); + let query_path = temp.path().join("queries.gq"); + write_file( + &schema_path, + r#" +node Person { + name: String +} +"#, + ); + write_query_file( + &query_path, + r#" +query list_people() { + match { $p: Person } + return { $p.name } +} +"#, + ); + + let canonical = output_success( + cli() + .arg("lint") + .arg("--query") + .arg(&query_path) + .arg("--schema") + .arg(&schema_path) + .arg("--json"), + ); + let deprecated_check = output_success( + cli() + .arg("check") + .arg("--query") + .arg(&query_path) + .arg("--schema") + .arg(&schema_path) + .arg("--json"), + ); + + assert_eq!(stdout_string(&canonical), stdout_string(&deprecated_check)); + + let check_stderr = String::from_utf8(deprecated_check.stderr).unwrap(); + assert!( + check_stderr.contains("`omnigraph check` is deprecated") + && check_stderr.contains("`omnigraph lint`"), + "expected `omnigraph check` deprecation warning pointing at `omnigraph lint`; got: {check_stderr}" + ); + + // `check` must NOT appear in the canonical `omnigraph --help` output — + // agents copy the surface from help text and would otherwise emit both + // names interchangeably. + let help = cli().arg("--help").output().unwrap(); + let stdout = String::from_utf8(help.stdout).unwrap(); + let check_aliased = stdout + .lines() + .any(|line| line.trim_start().starts_with("lint") && line.contains("check")); + assert!( + !check_aliased, + "`check` must not be advertised as a visible alias of `lint`; help output: {stdout}" + ); +} + +/// `omnigraph read` and `omnigraph change` are kept as visible clap +/// aliases for the new canonical `query` / `mutate` subcommands, plus an +/// argv-level deprecation warning. The warning is emitted to stderr; the +/// command otherwise behaves identically to the canonical form. +#[test] +fn deprecated_read_and_change_subcommands_emit_warnings() { + // Both subcommands require `--query`/`--query-string`/`--alias`, so + // invoking them with no args will exit non-zero. That's fine -- + // we only care that the deprecation warning is printed before the + // argument-required error. + let output = cli().arg("read").output().unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("`omnigraph read` is deprecated") + && stderr.contains("`omnigraph query`"), + "expected `omnigraph read` deprecation warning; got: {stderr}" + ); + + let output = cli().arg("change").output().unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("`omnigraph change` is deprecated") + && stderr.contains("`omnigraph mutate`"), + "expected `omnigraph change` deprecation warning; got: {stderr}" + ); + + // Sanity check the inverse: the canonical names must NOT print the + // deprecation banner. + let output = cli().arg("query").arg("--help").output().unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + !stderr.contains("deprecated"), + "`omnigraph query` is canonical and must not warn; got: {stderr}" + ); + let output = cli().arg("mutate").arg("--help").output().unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + !stderr.contains("deprecated"), + "`omnigraph mutate` is canonical and must not warn; got: {stderr}" + ); +} + +#[test] +fn query_lint_can_use_local_graph_via_positional_uri() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let query_path = temp.path().join("queries.gq"); + init_graph(&graph); write_query_file( &query_path, r#" @@ -654,24 +850,24 @@ query list_people() { .arg("--query") .arg(&query_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["status"], "ok"); - assert_eq!(payload["schema_source"]["kind"], "repo"); + assert_eq!(payload["schema_source"]["kind"], "graph"); assert_eq!( payload["schema_source"]["uri"].as_str(), - Some(repo.to_string_lossy().as_ref()) + Some(graph.to_string_lossy().as_ref()) ); } #[test] -fn query_lint_can_resolve_repo_and_query_from_config() { +fn query_lint_can_resolve_graph_and_query_from_config() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let config_path = temp.path().join("omnigraph.yaml"); - init_repo(&repo); + init_graph(&graph); write_query_file( &temp.path().join("queries.gq"), r#" @@ -681,7 +877,7 @@ query list_people() { } "#, ); - write_config(&config_path, &local_yaml_config(&repo)); + write_config(&config_path, &local_yaml_config(&graph)); let output = output_success( cli() @@ -696,10 +892,10 @@ query list_people() { let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["status"], "ok"); - assert_eq!(payload["schema_source"]["kind"], "repo"); + assert_eq!(payload["schema_source"]["kind"], "graph"); assert_eq!( payload["schema_source"]["uri"].as_str(), - Some(repo.to_string_lossy().as_ref()) + Some(graph.to_string_lossy().as_ref()) ); } @@ -727,12 +923,12 @@ query list_people() { ); let stderr = String::from_utf8_lossy(&output.stderr); assert!( - stderr.contains("query lint is only supported against local repo URIs in this milestone") + stderr.contains("query lint is only supported against local graph URIs in this milestone") ); } #[test] -fn query_lint_requires_schema_or_resolvable_repo_target() { +fn query_lint_requires_schema_or_resolvable_graph_target() { let temp = tempdir().unwrap(); let query_path = temp.path().join("queries.gq"); write_query_file( @@ -754,7 +950,7 @@ query list_people() { ); let stderr = String::from_utf8_lossy(&output.stderr); assert!( - stderr.contains("query lint requires --schema or a resolvable repo target") + stderr.contains("query lint requires --schema or a resolvable graph target") ); } @@ -846,8 +1042,8 @@ query bad_update($slug: String) { #[test] fn load_json_outputs_summary_for_main_branch() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); let data = fixture("test.jsonl"); let output = output_success( @@ -856,7 +1052,7 @@ fn load_json_outputs_summary_for_main_branch() { .arg("--data") .arg(&data) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); @@ -871,16 +1067,16 @@ fn load_json_outputs_summary_for_main_branch() { #[test] fn load_into_feature_branch_with_merge_mode_succeeds() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("feature"), @@ -901,7 +1097,7 @@ fn load_into_feature_branch_with_merge_mode_succeeds() { .arg("feature") .arg("--mode") .arg("merge") - .arg(&repo), + .arg(&graph), ); let stdout = stdout_string(&output); @@ -913,15 +1109,15 @@ fn load_into_feature_branch_with_merge_mode_succeeds() { #[test] fn read_json_outputs_rows_for_named_query() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); let queries = fixture("test.gq"); let output = output_success( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(&queries) .arg("--name") @@ -941,16 +1137,16 @@ fn read_json_outputs_rows_for_named_query() { #[test] fn export_jsonl_outputs_source_rows_for_selected_branch_and_type() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("feature"), @@ -970,13 +1166,13 @@ fn export_jsonl_outputs_source_rows_for_selected_branch_and_type() { .arg("feature") .arg("--mode") .arg("append") - .arg(&repo), + .arg(&graph), ); let output = output_success( cli() .arg("export") - .arg(&repo) + .arg(&graph) .arg("--branch") .arg("feature") .arg("--type") @@ -1025,7 +1221,7 @@ fn policy_validate_fails_for_invalid_policy_file() { &config, r#" project: - name: policy-test-repo + name: policy-test-graph policy: file: ./policy.yaml "#, @@ -1117,11 +1313,11 @@ fn policy_explain_reports_decision_and_matched_rule() { #[test] fn read_can_resolve_uri_from_config() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let config = temp.path().join("omnigraph.yaml"); - init_repo(&repo); - load_fixture(&repo); - write_config(&config, &local_yaml_config(&repo)); + init_graph(&graph); + load_fixture(&graph); + write_config(&config, &local_yaml_config(&graph)); let output = output_success( cli() @@ -1143,11 +1339,11 @@ fn read_can_resolve_uri_from_config() { #[test] fn read_alias_from_yaml_config_runs_with_kv_output() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let config = temp.path().join("omnigraph.yaml"); let query = temp.path().join("aliases.gq"); - init_repo(&repo); - load_fixture(&repo); + init_graph(&graph); + load_fixture(&graph); write_query_file( &query, &std::fs::read_to_string(fixture("test.gq")).unwrap(), @@ -1156,7 +1352,7 @@ fn read_alias_from_yaml_config_runs_with_kv_output() { &config, &format!( "{}aliases:\n owner:\n command: read\n query: aliases.gq\n name: get_person\n args: [name]\n format: kv\n", - local_yaml_config(&repo) + local_yaml_config(&graph) ), ); @@ -1178,16 +1374,16 @@ fn read_alias_from_yaml_config_runs_with_kv_output() { #[test] fn read_alias_uses_alias_target_without_cli_default_and_accepts_url_like_arg() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let config = temp.path().join("omnigraph.yaml"); let query = temp.path().join("aliases.gq"); let data = temp.path().join("url-like.jsonl"); - init_repo(&repo); + init_graph(&graph); write_jsonl( &data, r#"{"type":"Person","data":{"name":"https://example.com","age":30}}"#, ); - output_success(cli().arg("load").arg("--data").arg(&data).arg(&repo)); + output_success(cli().arg("load").arg("--data").arg(&data).arg(&graph)); write_query_file( &query, &std::fs::read_to_string(fixture("test.gq")).unwrap(), @@ -1196,7 +1392,7 @@ fn read_alias_uses_alias_target_without_cli_default_and_accepts_url_like_arg() { &config, &format!( "graphs:\n local:\n uri: '{}'\nquery:\n roots:\n - .\npolicy: {{}}\naliases:\n owner:\n command: read\n query: aliases.gq\n name: get_person\n args: [name]\n graph: local\n format: kv\n", - repo.to_string_lossy() + graph.to_string_lossy() ), ); @@ -1218,11 +1414,11 @@ fn read_alias_uses_alias_target_without_cli_default_and_accepts_url_like_arg() { #[test] fn change_alias_from_yaml_config_persists_changes() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let config = temp.path().join("omnigraph.yaml"); let query = temp.path().join("mutations.gq"); - init_repo(&repo); - load_fixture(&repo); + init_graph(&graph); + load_fixture(&graph); write_query_file( &query, r#" @@ -1235,7 +1431,7 @@ query insert_person($name: String, $age: I32) { &config, &format!( "{}aliases:\n add_person:\n command: change\n query: mutations.gq\n name: insert_person\n args: [name, age]\n", - local_yaml_config(&repo) + local_yaml_config(&graph) ), ); @@ -1256,7 +1452,7 @@ query insert_person($name: String, $age: I32) { let verify = output_success( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -1272,14 +1468,14 @@ query insert_person($name: String, $age: I32) { #[test] fn read_csv_format_outputs_header_and_row_values() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); let output = output_success( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -1298,14 +1494,14 @@ fn read_csv_format_outputs_header_and_row_values() { #[test] fn read_jsonl_format_outputs_metadata_header_first() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); let output = output_success( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -1324,9 +1520,9 @@ fn read_jsonl_format_outputs_metadata_header_first() { #[test] fn change_json_outputs_affected_counts_and_persists() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); let mutation_file = temp.path().join("mutations.gq"); write_query_file( &mutation_file, @@ -1340,7 +1536,7 @@ query insert_person($name: String, $age: I32) { let output = output_success( cli() .arg("change") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(&mutation_file) .arg("--params") @@ -1356,7 +1552,7 @@ query insert_person($name: String, $age: I32) { let verify = output_success( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -1373,11 +1569,11 @@ query insert_person($name: String, $age: I32) { #[test] fn change_can_resolve_uri_and_branch_from_config() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let config = temp.path().join("omnigraph.yaml"); - init_repo(&repo); - load_fixture(&repo); - write_config(&config, &local_yaml_config(&repo)); + init_graph(&graph); + load_fixture(&graph); + write_config(&config, &local_yaml_config(&graph)); let mutation_file = temp.path().join("config-mutations.gq"); write_query_file( &mutation_file, @@ -1407,14 +1603,14 @@ query insert_person($name: String, $age: I32) { #[test] fn read_requires_name_for_multi_query_files() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); let output = output_failure( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(fixture("test.gq")), ); @@ -1422,18 +1618,114 @@ fn read_requires_name_for_multi_query_files() { assert!(stderr.contains("multiple queries")); } +#[test] +fn read_supports_inline_query_string() { + let temp = tempdir().unwrap(); + let repo = graph_path(temp.path()); + init_graph(&repo); + load_fixture(&repo); + + let output = output_success( + cli() + .arg("read") + .arg(&repo) + .arg("-e") + .arg("query find($name: String) { match { $p: Person { name: $name } } return { $p.name, $p.age } }") + .arg("--params") + .arg(r#"{"name":"Alice"}"#) + .arg("--json"), + ); + let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(payload["query_name"], "find"); + assert_eq!(payload["row_count"], 1); + assert_eq!(payload["rows"][0]["p.name"], "Alice"); +} + +#[test] +fn change_supports_inline_query_string() { + let temp = tempdir().unwrap(); + let repo = graph_path(temp.path()); + init_graph(&repo); + load_fixture(&repo); + + let output = output_success( + cli() + .arg("change") + .arg(&repo) + .arg("--query-string") + .arg("query add($name: String, $age: I32) { insert Person { name: $name, age: $age } }") + .arg("--params") + .arg(r#"{"name":"Inline","age":42}"#) + .arg("--json"), + ); + let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(payload["query_name"], "add"); + assert_eq!(payload["affected_nodes"], 1); + + let verify = output_success( + cli() + .arg("read") + .arg(&repo) + .arg("-e") + .arg("query find($name: String) { match { $p: Person { name: $name } } return { $p.name } }") + .arg("--params") + .arg(r#"{"name":"Inline"}"#) + .arg("--json"), + ); + let verify_payload: Value = serde_json::from_slice(&verify.stdout).unwrap(); + assert_eq!(verify_payload["row_count"], 1); +} + +#[test] +fn read_rejects_query_string_combined_with_query() { + let temp = tempdir().unwrap(); + let repo = graph_path(temp.path()); + init_graph(&repo); + load_fixture(&repo); + + let output = output_failure( + cli() + .arg("read") + .arg(&repo) + .arg("--query") + .arg(fixture("test.gq")) + .arg("-e") + .arg("query whatever() { match { $p: Person } return { $p.name } }"), + ); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("cannot be used") || stderr.contains("conflict"), + "expected clap conflict error, got: {stderr}" + ); +} + +#[test] +fn read_rejects_empty_query_string() { + let temp = tempdir().unwrap(); + let repo = graph_path(temp.path()); + init_graph(&repo); + load_fixture(&repo); + + let output = output_failure(cli().arg("read").arg(&repo).arg("-e").arg("")); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("must not be empty"), + "expected empty-string rejection, got: {stderr}" + ); +} + #[test] fn branch_create_json_outputs_source_and_name() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); let output = output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("feature") @@ -1443,21 +1735,21 @@ fn branch_create_json_outputs_source_and_name() { assert_eq!(payload["from"], "main"); assert_eq!(payload["name"], "feature"); - assert_eq!(payload["uri"], repo.to_string_lossy().as_ref()); + assert_eq!(payload["uri"], graph.to_string_lossy().as_ref()); } #[test] fn branch_list_outputs_sorted_branches() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("zeta"), @@ -1467,13 +1759,13 @@ fn branch_list_outputs_sorted_branches() { .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("alpha"), ); - let output = output_success(cli().arg("branch").arg("list").arg("--uri").arg(&repo)); + let output = output_success(cli().arg("branch").arg("list").arg("--uri").arg(&graph)); let stdout = stdout_string(&output); let lines = stdout .lines() @@ -1487,15 +1779,15 @@ fn branch_list_outputs_sorted_branches() { #[test] fn branch_delete_json_outputs_name_and_removes_branch() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("feature"), @@ -1506,15 +1798,15 @@ fn branch_delete_json_outputs_name_and_removes_branch() { .arg("branch") .arg("delete") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("feature") .arg("--json"), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["name"], "feature"); - assert_eq!(payload["uri"], repo.to_string_lossy().as_ref()); + assert_eq!(payload["uri"], graph.to_string_lossy().as_ref()); - let listed = output_success(cli().arg("branch").arg("list").arg("--uri").arg(&repo)); + let listed = output_success(cli().arg("branch").arg("list").arg("--uri").arg(&graph)); let stdout = stdout_string(&listed); let lines = stdout .lines() @@ -1527,15 +1819,15 @@ fn branch_delete_json_outputs_name_and_removes_branch() { #[test] fn branch_delete_rejects_main() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); let output = output_failure( cli() .arg("branch") .arg("delete") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("main"), ); let stderr = String::from_utf8(output.stderr).unwrap(); @@ -1545,16 +1837,16 @@ fn branch_delete_rejects_main() { #[test] fn branch_merge_defaults_target_to_main() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("feature"), @@ -1574,7 +1866,7 @@ fn branch_merge_defaults_target_to_main() { .arg("feature") .arg("--mode") .arg("append") - .arg(&repo), + .arg(&graph), ); let merge_output = output_success( @@ -1582,7 +1874,7 @@ fn branch_merge_defaults_target_to_main() { .arg("branch") .arg("merge") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("feature") .arg("--json"), ); @@ -1594,7 +1886,7 @@ fn branch_merge_defaults_target_to_main() { let snapshot_output = output_success( cli() .arg("snapshot") - .arg(&repo) + .arg(&graph) .arg("--branch") .arg("main") .arg("--json"), @@ -1614,16 +1906,16 @@ fn branch_merge_defaults_target_to_main() { #[test] fn branch_merge_supports_explicit_target() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("feature"), @@ -1633,7 +1925,7 @@ fn branch_merge_supports_explicit_target() { .arg("branch") .arg("create") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("--from") .arg("main") .arg("experiment"), @@ -1653,7 +1945,7 @@ fn branch_merge_supports_explicit_target() { .arg("feature") .arg("--mode") .arg("append") - .arg(&repo), + .arg(&graph), ); let merge_output = output_success( @@ -1661,7 +1953,7 @@ fn branch_merge_supports_explicit_target() { .arg("branch") .arg("merge") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("feature") .arg("--into") .arg("experiment") @@ -1675,17 +1967,17 @@ fn branch_merge_supports_explicit_target() { #[test] fn snapshot_json_returns_manifest_version_and_tables() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); - let output = output_success(cli().arg("snapshot").arg(&repo).arg("--json")); + let output = output_success(cli().arg("snapshot").arg(&graph).arg("--json")); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["branch"], "main"); assert_eq!( payload["manifest_version"].as_u64().unwrap(), - manifest_dataset_version(&repo) + manifest_dataset_version(&graph) ); assert!(payload["tables"].as_array().unwrap().len() >= 4); } @@ -1755,11 +2047,11 @@ fn read_embedded_rows(path: std::path::PathBuf) -> Vec { #[test] fn snapshot_can_resolve_uri_from_config() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let config = temp.path().join("omnigraph.yaml"); - init_repo(&repo); - load_fixture(&repo); - write_config(&config, &local_yaml_config(&repo)); + init_graph(&graph); + load_fixture(&graph); + write_config(&config, &local_yaml_config(&graph)); let output = output_success( cli() @@ -1775,11 +2067,11 @@ fn snapshot_can_resolve_uri_from_config() { #[test] fn snapshot_human_output_includes_branch_and_table_summaries() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); - let output = output_success(cli().arg("snapshot").arg(&repo)); + let output = output_success(cli().arg("snapshot").arg(&graph)); let stdout = stdout_string(&output); assert!(stdout.contains("branch: main")); @@ -1791,11 +2083,11 @@ fn snapshot_human_output_includes_branch_and_table_summaries() { #[test] fn commit_show_accepts_long_uri_flag() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); - let list = output_success(cli().arg("commit").arg("list").arg(&repo).arg("--json")); + let list = output_success(cli().arg("commit").arg("list").arg(&graph).arg("--json")); let list_payload: Value = serde_json::from_slice(&list.stdout).unwrap(); let commit_id = list_payload["commits"][0]["graph_commit_id"] .as_str() @@ -1807,7 +2099,7 @@ fn commit_show_accepts_long_uri_flag() { .arg("commit") .arg("show") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg(&commit_id) .arg("--json"), ); @@ -1818,11 +2110,11 @@ fn commit_show_accepts_long_uri_flag() { } #[test] -fn cli_fails_for_missing_repo() { +fn cli_fails_for_missing_graph() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); - let output = output_failure(cli().arg("snapshot").arg(&repo)); + let output = output_failure(cli().arg("snapshot").arg(&graph)); let stderr = String::from_utf8(output.stderr).unwrap(); assert!( stderr.contains("_schema.pg") @@ -1834,7 +2126,7 @@ fn cli_fails_for_missing_repo() { #[test] fn cli_fails_for_missing_schema_or_data_file() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let missing_schema = temp.path().join("missing.pg"); let missing_data = temp.path().join("missing.jsonl"); @@ -1843,7 +2135,7 @@ fn cli_fails_for_missing_schema_or_data_file() { .arg("init") .arg("--schema") .arg(&missing_schema) - .arg(&repo), + .arg(&graph), ); assert!( String::from_utf8(init_output.stderr) @@ -1851,13 +2143,13 @@ fn cli_fails_for_missing_schema_or_data_file() { .contains("No such file") ); - init_repo(&repo); + init_graph(&graph); let load_output = output_failure( cli() .arg("load") .arg("--data") .arg(&missing_data) - .arg(&repo), + .arg(&graph), ); assert!( String::from_utf8(load_output.stderr) @@ -1869,16 +2161,16 @@ fn cli_fails_for_missing_schema_or_data_file() { #[test] fn cli_fails_for_invalid_merge_requests() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); let missing_branch = output_failure( cli() .arg("branch") .arg("merge") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("missing"), ); let missing_branch_stderr = String::from_utf8(missing_branch.stderr).unwrap(); @@ -1893,7 +2185,7 @@ fn cli_fails_for_invalid_merge_requests() { .arg("branch") .arg("merge") .arg("--uri") - .arg(&repo) + .arg(&graph) .arg("main") .arg("--into") .arg("main"), @@ -1921,9 +2213,9 @@ fn cli_fails_for_invalid_merge_requests() { #[test] fn schema_apply_allow_data_loss_flag_promotes_drops_to_hard() { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("drop-age.pg"); - init_repo(&repo); + init_graph(&graph); // Drop the nullable `age` column. let next_schema = fs::read_to_string(fixture("test.pg")) @@ -1939,7 +2231,7 @@ fn schema_apply_allow_data_loss_flag_promotes_drops_to_hard() { .arg(&schema_path) .arg("--allow-data-loss") .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["applied"], true); @@ -1962,9 +2254,9 @@ fn schema_apply_without_allow_data_loss_keeps_soft_drops() { // drops stay Soft. Pins default semantics against accidental Hard // promotion if a future refactor changes the option threading. let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema_path = temp.path().join("drop-age-soft.pg"); - init_repo(&repo); + init_graph(&graph); let next_schema = fs::read_to_string(fixture("test.pg")) .unwrap() @@ -1978,7 +2270,7 @@ fn schema_apply_without_allow_data_loss_keeps_soft_drops() { .arg("--schema") .arg(&schema_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(payload["applied"], true); @@ -2004,8 +2296,8 @@ fn schema_plan_parity_cli_and_sdk() { // the HTTP soft/hard drop tests, which exercise apply with // identical fixtures. let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); + let graph = graph_path(temp.path()); + init_graph(&graph); let schema_path = temp.path().join("plan-parity.pg"); let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( " age: I32?\n}", @@ -2021,13 +2313,13 @@ fn schema_plan_parity_cli_and_sdk() { .arg("--schema") .arg(&schema_path) .arg("--json") - .arg(&repo), + .arg(&graph), ); let cli_payload: Value = serde_json::from_slice(&cli_output.stdout).unwrap(); - // SDK side: open repo, call plan_schema. + // SDK side: open graph, call plan_schema. let plan = tokio::runtime::Runtime::new().unwrap().block_on(async { - let db = Omnigraph::open(repo.to_string_lossy().as_ref()) + let db = Omnigraph::open(graph.to_string_lossy().as_ref()) .await .unwrap(); db.plan_schema(&next_schema).await.unwrap() @@ -2040,3 +2332,339 @@ fn schema_plan_parity_cli_and_sdk() { ); assert_eq!(cli_payload["supported"], plan.supported); } + +// ─── MR-668 PR 8 — omnigraph graphs subcommand ───────────────────────────── + +/// `omnigraph graphs --help` lists only the read-only `list` +/// subcommand. Runtime add (`create`) and remove (`delete`) are +/// deferred — operators add/remove graphs by editing `omnigraph.yaml` +/// and restarting. This test pins the deferral against accidental +/// re-introduction. +#[test] +fn graphs_subcommand_help_lists_list_only() { + let output = output_success(cli().arg("graphs").arg("--help")); + let stdout = stdout_string(&output); + assert!( + stdout.contains("list"), + "expected `list` subcommand in help output:\n{stdout}" + ); + let lowered = stdout.to_lowercase(); + assert!( + !lowered.contains("create a new graph"), + "graph create should not be in v0.6.0 help; got:\n{stdout}" + ); + assert!( + !lowered.contains("delete a graph"), + "graph delete should not be in v0.6.0 help; got:\n{stdout}" + ); +} + +/// `omnigraph graphs list` against a local URI errors with a clear +/// message — the CLI only operates against remote multi-graph servers. +#[test] +fn graphs_list_against_local_uri_errors_with_remote_only_message() { + let output = output_failure( + cli() + .arg("graphs") + .arg("list") + .arg("--uri") + .arg("/tmp/local"), + ); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert!( + stderr.contains("remote multi-graph server URL"), + "expected 'remote multi-graph server URL' rejection in stderr; got:\n{stderr}" + ); +} + +fn queries_test_config(graph_uri: &str, entry: &str, gq_file: &str) -> String { + format!( + "graphs:\n local:\n uri: '{}'\n queries:\n {entry}:\n file: ./{gq_file}\n\ + cli:\n graph: local\npolicy: {{}}\n", + graph_uri.replace('\'', "''") + ) +} + +#[test] +fn queries_validate_exits_zero_on_clean_registry() { + let graph = SystemGraph::loaded(); + graph.write_query( + "find_person.gq", + "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + ); + let config = graph.write_config( + "omnigraph.yaml", + &queries_test_config(&graph.path().to_string_lossy(), "find_person", "find_person.gq"), + ); + let output = output_success(cli().arg("queries").arg("validate").arg("--config").arg(&config)); + let stdout = stdout_string(&output); + assert!(stdout.contains("OK"), "stdout:\n{stdout}"); +} + +#[test] +fn queries_validate_exits_nonzero_on_type_broken_query() { + let graph = SystemGraph::loaded(); + // `Widget` is not in the fixture schema. + graph.write_query("ghost.gq", "query ghost() { match { $w: Widget } return { $w.name } }"); + let config = graph.write_config( + "omnigraph.yaml", + &queries_test_config(&graph.path().to_string_lossy(), "ghost", "ghost.gq"), + ); + let output = output_failure(cli().arg("queries").arg("validate").arg("--config").arg(&config)); + let stdout = stdout_string(&output); + assert!( + stdout.contains("ghost"), + "validation should name the broken query; stdout:\n{stdout}" + ); +} + +#[test] +fn queries_list_prints_registered_query() { + let graph = SystemGraph::loaded(); + graph.write_query( + "find_person.gq", + "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + ); + // Exposed with an explicit tool name so the list shows the MCP suffix. + let config = graph.write_config( + "omnigraph.yaml", + &format!( + concat!( + "graphs:\n", + " local:\n", + " uri: '{}'\n", + " queries:\n", + " find_person:\n", + " file: ./find_person.gq\n", + " mcp: {{ expose: true, tool_name: lookup_person }}\n", + "cli:\n", + " graph: local\n", + "policy: {{}}\n", + ), + graph.path().to_string_lossy().replace('\'', "''") + ), + ); + let output = output_success(cli().arg("queries").arg("list").arg("--config").arg(&config)); + let stdout = stdout_string(&output); + assert!(stdout.contains("find_person"), "stdout:\n{stdout}"); + assert!( + stdout.contains("$name: String"), + "list should show typed params; stdout:\n{stdout}" + ); + assert!( + stdout.contains("[mcp: lookup_person]"), + "list should show the MCP tool name for exposed queries; stdout:\n{stdout}" + ); +} + +#[test] +fn queries_list_requires_graph_selection_for_per_graph_only_registries() { + let graph = SystemGraph::loaded(); + graph.write_query( + "find_person.gq", + "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + ); + let config = graph.write_config( + "omnigraph.yaml", + &format!( + concat!( + "graphs:\n", + " local:\n", + " uri: '{}'\n", + " queries:\n", + " find_person:\n", + " file: ./find_person.gq\n", + "policy: {{}}\n", + ), + graph.path().to_string_lossy().replace('\'', "''") + ), + ); + + let output = output_failure(cli().arg("queries").arg("list").arg("--config").arg(&config)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("local") && stderr.contains("--target local"), + "error must name the graph and give a concrete selection hint; stderr:\n{stderr}" + ); +} + +#[test] +fn queries_list_without_graph_selection_lists_top_level_registry() { + let graph = SystemGraph::loaded(); + graph.write_query( + "top_find.gq", + "query top_find($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + ); + let config = graph.write_config( + "omnigraph.yaml", + concat!( + "queries:\n", + " top_find:\n", + " file: ./top_find.gq\n", + "policy: {}\n", + ), + ); + + let output = output_success(cli().arg("queries").arg("list").arg("--config").arg(&config)); + let stdout = stdout_string(&output); + assert!(stdout.contains("top_find"), "stdout:\n{stdout}"); +} + +#[test] +fn queries_list_unknown_target_errors() { + // `queries list` opens no graph URI, so unknown-graph validation can't ride + // along on URI resolution the way it does for every other command. An + // unknown `--target` must still error (naming the graph) instead of + // silently falling back to the top-level registry and showing the wrong + // (or empty) catalog. + let graph = SystemGraph::loaded(); + graph.write_query( + "find_person.gq", + "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + ); + let config = graph.write_config( + "omnigraph.yaml", + &queries_test_config(&graph.path().to_string_lossy(), "find_person", "find_person.gq"), + ); + let output = output_failure( + cli() + .arg("queries") + .arg("list") + .arg("--target") + .arg("nonexistent") + .arg("--config") + .arg(&config), + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("nonexistent"), + "error must name the unknown graph; stderr:\n{stderr}" + ); +} + +#[test] +fn queries_commands_reject_named_graph_with_populated_top_level_block() { + // A named graph (here via `cli.graph`) uses its own `graphs.` block, + // so a populated top-level `queries:` block would be silently ignored — a + // config the server REFUSES to boot. `queries validate`/`list` must reject + // it too (matching boot) instead of validating/listing the per-graph block + // and giving a false green. + let graph = SystemGraph::loaded(); + graph.write_query( + "find_person.gq", + "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + ); + let config = graph.write_config( + "omnigraph.yaml", + &format!( + concat!( + "graphs:\n", + " local:\n", + " uri: '{}'\n", + " queries:\n", + " find_person:\n", + " file: ./find_person.gq\n", + "cli:\n", + " graph: local\n", + "queries:\n", // populated top-level block: the coherence violation + " legacy:\n", + " file: ./legacy.gq\n", + "policy: {{}}\n", + ), + graph.path().to_string_lossy().replace('\'', "''") + ), + ); + // Both resolve `local` from cli.graph (no positional URI), so both must + // error and name the graph + the ignored block — like server boot does. + for sub in ["validate", "list"] { + let output = output_failure(cli().arg("queries").arg(sub).arg("--config").arg(&config)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("local") && stderr.contains("queries"), + "`queries {sub}` must reject a named graph with a populated top-level block; stderr:\n{stderr}" + ); + } +} + +#[test] +fn queries_validate_exits_nonzero_on_duplicate_tool_name() { + // Two exposed queries claiming one MCP tool name is a load-time + // collision — `queries validate` must fail (offline, before the engine + // opens) and name both queries plus the contested tool. + let graph = SystemGraph::loaded(); + graph.write_query("a.gq", "query a() { match { $p: Person } return { $p.name } }"); + graph.write_query("b.gq", "query b() { match { $p: Person } return { $p.name } }"); + let config = graph.write_config( + "omnigraph.yaml", + &format!( + concat!( + "graphs:\n", + " local:\n", + " uri: '{}'\n", + " queries:\n", + " a:\n", + " file: ./a.gq\n", + " mcp: {{ expose: true, tool_name: dup }}\n", + " b:\n", + " file: ./b.gq\n", + " mcp: {{ expose: true, tool_name: dup }}\n", + "cli:\n", + " graph: local\n", + "policy: {{}}\n", + ), + graph.path().to_string_lossy().replace('\'', "''") + ), + ); + let output = output_failure(cli().arg("queries").arg("validate").arg("--config").arg(&config)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("dup") && stderr.contains("'a'") && stderr.contains("'b'"), + "duplicate tool name should be reported naming both queries; stderr:\n{stderr}" + ); +} + +#[test] +fn queries_validate_positional_uri_ignores_default_graph() { + // A positional URI is anonymous → the schema AND the registry both come + // from top-level, even when `cli.graph` names a graph whose per-graph + // queries would fail. Pins that the URI and registry can't diverge. + let graph = SystemGraph::loaded(); + graph.write_query( + "clean.gq", + "query clean($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + ); + // `Widget` is not in the fixture schema — the default graph's per-graph + // query would break validate if it were (wrongly) selected. + graph.write_query("broken.gq", "query broken() { match { $w: Widget } return { $w.name } }"); + let config = graph.write_config( + "omnigraph.yaml", + concat!( + "cli:\n graph: prod\n", + "graphs:\n", + " prod:\n", + " uri: /nonexistent-prod.omni\n", + " queries:\n", + " broken:\n", + " file: ./broken.gq\n", + "queries:\n", + " clean:\n", + " file: ./clean.gq\n", + "policy: {}\n", + ), + ); + // Positional URI = the real loaded graph; selection is anonymous, so the + // CLEAN top-level registry validates (not prod's broken one). + let output = output_success( + cli() + .arg("queries") + .arg("validate") + .arg(graph.path()) + .arg("--config") + .arg(&config), + ); + let stdout = stdout_string(&output); + assert!( + stdout.contains("OK"), + "positional URI must validate the top-level registry, not the cli.graph default; stdout:\n{stdout}" + ); +} diff --git a/crates/omnigraph-cli/tests/support/mod.rs b/crates/omnigraph-cli/tests/support/mod.rs index 31092ea..b62d861 100644 --- a/crates/omnigraph-cli/tests/support/mod.rs +++ b/crates/omnigraph-cli/tests/support/mod.rs @@ -52,7 +52,7 @@ pub fn fixture(name: &str) -> PathBuf { .join(name) } -pub fn repo_path(root: &Path) -> PathBuf { +pub fn graph_path(root: &Path) -> PathBuf { root.join("demo.omni") } @@ -86,14 +86,14 @@ pub fn parse_stdout_json(output: &Output) -> Value { serde_json::from_slice(&output.stdout).unwrap() } -pub fn init_repo(repo: &Path) { +pub fn init_graph(graph: &Path) { let schema = fixture("test.pg"); - output_success(cli().arg("init").arg("--schema").arg(&schema).arg(repo)); + output_success(cli().arg("init").arg("--schema").arg(&schema).arg(graph)); } -pub fn load_fixture(repo: &Path) { +pub fn load_fixture(graph: &Path) { let data = fixture("test.jsonl"); - output_success(cli().arg("load").arg("--data").arg(&data).arg(repo)); + output_success(cli().arg("load").arg("--data").arg(&data).arg(graph)); } pub fn write_jsonl(path: &Path, rows: &str) { @@ -116,7 +116,7 @@ fn yaml_string(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } -pub fn local_yaml_config(repo: &Path) -> String { +pub fn local_yaml_config(graph: &Path) -> String { format!( "\ graphs: @@ -130,7 +130,7 @@ query: - . policy: {{}} ", - yaml_string(&repo.to_string_lossy()) + yaml_string(&graph.to_string_lossy()) ) } @@ -200,9 +200,9 @@ fn spawn_server_process(mut command: StdCommand) -> TestServer { panic!("server did not become healthy"); } -pub fn spawn_server(repo: &Path) -> TestServer { +pub fn spawn_server(graph: &Path) -> TestServer { let mut command = server_process(); - command.arg(repo); + command.arg(graph); spawn_server_process(command) } @@ -221,58 +221,57 @@ pub fn spawn_server_with_config_env(config: &Path, envs: &[(&str, &str)]) -> Tes spawn_server_process(command) } - -pub struct SystemRepo { +pub struct SystemGraph { _temp: TempDir, - repo: PathBuf, + graph: PathBuf, } -impl SystemRepo { +impl SystemGraph { pub fn initialized() -> Self { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - Self { _temp: temp, repo } + let graph = graph_path(temp.path()); + init_graph(&graph); + Self { _temp: temp, graph } } pub fn loaded() -> Self { let temp = tempdir().unwrap(); - let repo = repo_path(temp.path()); - init_repo(&repo); - load_fixture(&repo); - Self { _temp: temp, repo } + let graph = graph_path(temp.path()); + init_graph(&graph); + load_fixture(&graph); + Self { _temp: temp, graph } } pub fn path(&self) -> &Path { - &self.repo + &self.graph } pub fn write_query(&self, name: &str, source: &str) -> PathBuf { - let path = self.repo.parent().unwrap().join(name); + let path = self.graph.parent().unwrap().join(name); write_query_file(&path, source); path } pub fn write_jsonl(&self, name: &str, rows: &str) -> PathBuf { - let path = self.repo.parent().unwrap().join(name); + let path = self.graph.parent().unwrap().join(name); write_jsonl(&path, rows); path } pub fn write_config(&self, name: &str, source: &str) -> PathBuf { - let path = self.repo.parent().unwrap().join(name); + let path = self.graph.parent().unwrap().join(name); write_config(&path, source); path } pub fn write_file(&self, name: &str, source: &str) -> PathBuf { - let path = self.repo.parent().unwrap().join(name); + let path = self.graph.parent().unwrap().join(name); write_file(&path, source); path } pub fn spawn_server(&self) -> TestServer { - spawn_server(&self.repo) + spawn_server(&self.graph) } pub fn spawn_server_with_config(&self, config: &Path) -> TestServer { diff --git a/crates/omnigraph-cli/tests/system_local.rs b/crates/omnigraph-cli/tests/system_local.rs index 3d3e9bf..4fc3e9a 100644 --- a/crates/omnigraph-cli/tests/system_local.rs +++ b/crates/omnigraph-cli/tests/system_local.rs @@ -66,7 +66,7 @@ fn yaml_string(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } -fn local_policy_config(repo: &SystemRepo) -> String { +fn local_policy_config(graph: &SystemGraph) -> String { format!( "\ project: @@ -74,21 +74,43 @@ project: graphs: local: uri: {} + policy: + file: ./policy.yaml cli: graph: local branch: main query: roots: - . -policy: - file: ./policy.yaml ", - yaml_string(&repo.path().to_string_lossy()) + yaml_string(&graph.path().to_string_lossy()) ) } -fn insert_person_query(repo: &SystemRepo, name: &str) -> std::path::PathBuf { - repo.write_query( +fn local_policy_server_graph_config(graph: &SystemGraph) -> String { + format!( + "\ +project: + name: policy-e2e-local +graphs: + local: + uri: {} + policy: + file: ./policy.yaml +server: + graph: local +cli: + branch: main +query: + roots: + - . +", + yaml_string(&graph.path().to_string_lossy()) + ) +} + +fn insert_person_query(graph: &SystemGraph, name: &str) -> std::path::PathBuf { + graph.write_query( name, r#" query insert_person($name: String, $age: I32) { @@ -98,8 +120,8 @@ query insert_person($name: String, $age: I32) { ) } -fn add_friend_query(repo: &SystemRepo, name: &str) -> std::path::PathBuf { - repo.write_query( +fn add_friend_query(graph: &SystemGraph, name: &str) -> std::path::PathBuf { + graph.write_query( name, r#" query add_friend($from: String, $to: String) { @@ -109,13 +131,13 @@ query add_friend($from: String, $to: String) { ) } -fn snapshot_table_row_count(repo: &SystemRepo, table_key: &str) -> u64 { - snapshot_table_row_count_at(repo.path(), table_key) +fn snapshot_table_row_count(graph: &SystemGraph, table_key: &str) -> u64 { + snapshot_table_row_count_at(graph.path(), table_key) } -fn snapshot_table_row_count_at(repo: &std::path::Path, table_key: &str) -> u64 { +fn snapshot_table_row_count_at(graph: &std::path::Path, table_key: &str) -> u64 { let payload = parse_stdout_json(&output_success( - cli().arg("snapshot").arg(repo).arg("--json"), + cli().arg("snapshot").arg(graph).arg("--json"), )); payload["tables"] .as_array() @@ -178,7 +200,7 @@ fn format_vector(values: &[f32]) -> String { .join(", ") } -fn s3_test_repo_uri(suite: &str) -> Option { +fn s3_test_graph_uri(suite: &str) -> Option { let bucket = env::var("OMNIGRAPH_S3_TEST_BUCKET").ok()?; let prefix = env::var("OMNIGRAPH_S3_TEST_PREFIX") .ok() @@ -193,21 +215,21 @@ fn s3_test_repo_uri(suite: &str) -> Option { #[test] fn local_cli_end_to_end_init_load_read_change_read_flow() { - let repo = SystemRepo::initialized(); - let mutation_file = insert_person_query(&repo, "system-local-init-change.gq"); + let graph = SystemGraph::initialized(); + let mutation_file = insert_person_query(&graph, "system-local-init-change.gq"); output_success( cli() .arg("load") .arg("--data") .arg(fixture("test.jsonl")) - .arg(repo.path()), + .arg(graph.path()), ); let read_before = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -222,7 +244,7 @@ fn local_cli_end_to_end_init_load_read_change_read_flow() { let change_payload = parse_stdout_json(&output_success( cli() .arg("change") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(&mutation_file) .arg("--params") @@ -235,7 +257,7 @@ fn local_cli_end_to_end_init_load_read_change_read_flow() { let read_after = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -246,19 +268,50 @@ fn local_cli_end_to_end_init_load_read_change_read_flow() { )); assert_eq!(read_after["row_count"], 1); assert_eq!(read_after["rows"][0]["p.name"], "Eve"); + + // Inline-source variants of the same read/change flow (CLI `-e` / + // `--query-string`). Confirms that file-less invocations reach the + // engine identically, including param binding and `branch=main` defaults. + let inline_change = parse_stdout_json(&output_success( + cli() + .arg("change") + .arg(graph.path()) + .arg("-e") + .arg("query add($name: String, $age: I32) { insert Person { name: $name, age: $age } }") + .arg("--params") + .arg(r#"{"name":"Inline","age":42}"#) + .arg("--json"), + )); + assert_eq!(inline_change["branch"], "main"); + assert_eq!(inline_change["query_name"], "add"); + assert_eq!(inline_change["affected_nodes"], 1); + + let inline_read = parse_stdout_json(&output_success( + cli() + .arg("read") + .arg(graph.path()) + .arg("--query-string") + .arg("query find($name: String) { match { $p: Person { name: $name } } return { $p.name, $p.age } }") + .arg("--params") + .arg(r#"{"name":"Inline"}"#) + .arg("--json"), + )); + assert_eq!(inline_read["row_count"], 1); + assert_eq!(inline_read["rows"][0]["p.name"], "Inline"); + assert_eq!(inline_read["rows"][0]["p.age"], 42); } #[test] fn local_cli_end_to_end_branch_change_merge_flow() { - let repo = SystemRepo::loaded(); - let mutation_file = insert_person_query(&repo, "system-local-change.gq"); + let graph = SystemGraph::loaded(); + let mutation_file = insert_person_query(&graph, "system-local-change.gq"); output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(repo.path()) + .arg(graph.path()) .arg("--from") .arg("main") .arg("feature"), @@ -267,7 +320,7 @@ fn local_cli_end_to_end_branch_change_merge_flow() { let change_payload = parse_stdout_json(&output_success( cli() .arg("change") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(&mutation_file) .arg("--branch") @@ -282,7 +335,7 @@ fn local_cli_end_to_end_branch_change_merge_flow() { let feature_read = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -301,7 +354,7 @@ fn local_cli_end_to_end_branch_change_merge_flow() { .arg("branch") .arg("merge") .arg("--uri") - .arg(repo.path()) + .arg(graph.path()) .arg("feature") .arg("--json"), )); @@ -310,7 +363,7 @@ fn local_cli_end_to_end_branch_change_merge_flow() { let main_read = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -327,7 +380,7 @@ fn local_cli_end_to_end_branch_change_merge_flow() { cli() .arg("commit") .arg("list") - .arg(repo.path()) + .arg(graph.path()) .arg("--branch") .arg("main") .arg("--json"), @@ -337,8 +390,8 @@ fn local_cli_end_to_end_branch_change_merge_flow() { #[test] fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { - let repo = SystemRepo::loaded(); - let ingest_data = repo.write_jsonl( + let graph = SystemGraph::loaded(); + let ingest_data = graph.write_jsonl( "system-local-ingest.jsonl", r#"{"type":"Person","data":{"name":"Zoe","age":33}} {"type":"Person","data":{"name":"Bob","age":26}}"#, @@ -351,7 +404,7 @@ fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { .arg(&ingest_data) .arg("--branch") .arg("feature-ingest") - .arg(repo.path()) + .arg(graph.path()) .arg("--json"), )); assert_eq!(ingest_payload["branch"], "feature-ingest"); @@ -364,7 +417,7 @@ fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { let feature_snapshot = parse_stdout_json(&output_success( cli() .arg("snapshot") - .arg(repo.path()) + .arg(graph.path()) .arg("--branch") .arg("feature-ingest") .arg("--json"), @@ -374,7 +427,7 @@ fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { let zoe = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -391,7 +444,7 @@ fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { let bob = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -408,20 +461,20 @@ fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { #[test] fn local_cli_export_round_trips_full_branch_graph() { - let repo = SystemRepo::loaded(); + let graph = SystemGraph::loaded(); output_success( cli() .arg("branch") .arg("create") .arg("--uri") - .arg(repo.path()) + .arg(graph.path()) .arg("--from") .arg("main") .arg("feature"), ); - let feature_data = repo.write_jsonl( + let feature_data = graph.write_jsonl( "system-local-export-feature.jsonl", r#"{"type":"Person","data":{"name":"Eve","age":29}} {"edge":"Knows","from":"Alice","to":"Eve"}"#, @@ -435,53 +488,56 @@ fn local_cli_export_round_trips_full_branch_graph() { .arg("feature") .arg("--mode") .arg("append") - .arg(repo.path()), + .arg(graph.path()), ); let exported = stdout_string(&output_success( cli() .arg("export") - .arg(repo.path()) + .arg(graph.path()) .arg("--branch") .arg("feature") .arg("--jsonl"), )); - let export_path = repo.write_jsonl("system-local-exported.jsonl", &exported); - let imported_repo = repo.path().parent().unwrap().join("imported-export.omni"); + let export_path = graph.write_jsonl("system-local-exported.jsonl", &exported); + let imported_graph = graph.path().parent().unwrap().join("imported-export.omni"); output_success( cli() .arg("init") .arg("--schema") .arg(fixture("test.pg")) - .arg(&imported_repo), + .arg(&imported_graph), ); output_success( cli() .arg("load") .arg("--data") .arg(&export_path) - .arg(&imported_repo), + .arg(&imported_graph), ); assert_eq!( - snapshot_table_row_count_at(&imported_repo, "node:Person"), + snapshot_table_row_count_at(&imported_graph, "node:Person"), 5 ); assert_eq!( - snapshot_table_row_count_at(&imported_repo, "node:Company"), + snapshot_table_row_count_at(&imported_graph, "node:Company"), 2 ); - assert_eq!(snapshot_table_row_count_at(&imported_repo, "edge:Knows"), 4); assert_eq!( - snapshot_table_row_count_at(&imported_repo, "edge:WorksAt"), + snapshot_table_row_count_at(&imported_graph, "edge:Knows"), + 4 + ); + assert_eq!( + snapshot_table_row_count_at(&imported_graph, "edge:WorksAt"), 2 ); let eve = parse_stdout_json(&output_success( cli() .arg("read") - .arg(&imported_repo) + .arg(&imported_graph) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -496,7 +552,7 @@ fn local_cli_export_round_trips_full_branch_graph() { let friends = parse_stdout_json(&output_success( cli() .arg("read") - .arg(&imported_repo) + .arg(&imported_graph) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -510,7 +566,7 @@ fn local_cli_export_round_trips_full_branch_graph() { #[test] fn local_cli_s3_end_to_end_init_load_read_flow() { - let Some(repo_uri) = s3_test_repo_uri("cli-local") else { + let Some(graph_uri) = s3_test_graph_uri("cli-local") else { eprintln!("skipping s3 cli test: OMNIGRAPH_S3_TEST_BUCKET is not set"); return; }; @@ -535,7 +591,7 @@ query: - . policy: {{}} ", - repo_uri + graph_uri ), ); @@ -544,14 +600,14 @@ policy: {{}} .arg("init") .arg("--schema") .arg(fixture("test.pg")) - .arg(&repo_uri), + .arg(&graph_uri), ); output_success( cli() .arg("load") .arg("--data") .arg(fixture("test.jsonl")) - .arg(&repo_uri), + .arg(&graph_uri), ); let read = parse_stdout_json(&output_success( @@ -584,13 +640,13 @@ policy: {{}} #[test] fn local_cli_failed_load_keeps_target_state_unchanged() { - let repo = SystemRepo::loaded(); - let bad_data = repo.write_jsonl( + let graph = SystemGraph::loaded(); + let bad_data = graph.write_jsonl( "system-bad-load.jsonl", r#"{"edge":"Knows","from":"Alice","to":"Missing"}"#, ); - let person_rows_before = snapshot_table_row_count(&repo, "node:Person"); - let knows_rows_before = snapshot_table_row_count(&repo, "edge:Knows"); + let person_rows_before = snapshot_table_row_count(&graph, "node:Person"); + let knows_rows_before = snapshot_table_row_count(&graph, "edge:Knows"); let output = output_failure( cli() @@ -599,17 +655,17 @@ fn local_cli_failed_load_keeps_target_state_unchanged() { .arg(&bad_data) .arg("--mode") .arg("append") - .arg(repo.path()), + .arg(graph.path()), ); let stderr = String::from_utf8(output.stderr).unwrap(); assert!(stderr.contains("not found") || stderr.contains("Missing")); assert_eq!( - snapshot_table_row_count(&repo, "node:Person"), + snapshot_table_row_count(&graph, "node:Person"), person_rows_before ); assert_eq!( - snapshot_table_row_count(&repo, "edge:Knows"), + snapshot_table_row_count(&graph, "edge:Knows"), knows_rows_before ); // Failed loads leave no run record (the run lifecycle has been @@ -618,13 +674,13 @@ fn local_cli_failed_load_keeps_target_state_unchanged() { #[test] fn local_cli_failed_change_keeps_target_state_unchanged() { - let repo = SystemRepo::loaded(); - let mutation_file = add_friend_query(&repo, "system-invalid-change.gq"); + let graph = SystemGraph::loaded(); + let mutation_file = add_friend_query(&graph, "system-invalid-change.gq"); let output = output_failure( cli() .arg("change") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(&mutation_file) .arg("--params") @@ -636,7 +692,7 @@ fn local_cli_failed_change_keeps_target_state_unchanged() { let friends_payload = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -652,8 +708,8 @@ fn local_cli_failed_change_keeps_target_state_unchanged() { #[test] fn local_cli_resolves_relative_query_against_config_base_dir() { - let repo = SystemRepo::loaded(); - let root = repo.path().parent().unwrap(); + let graph = SystemGraph::loaded(); + let root = graph.path().parent().unwrap(); let config_dir = root.join("config"); let query_dir = config_dir.join("queries"); let ambient_dir = root.join("ambient"); @@ -676,7 +732,7 @@ query: - queries policy: {{}} ", - repo.path().display() + graph.path().display() ), ); write_query_file( @@ -730,7 +786,7 @@ query get_person($name: String) { #[test] fn local_cli_datetime_and_list_types_round_trip_through_load_read_and_change() { let temp = tempfile::tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema = temp.path().join("datatypes.pg"); let data = temp.path().join("datatypes.jsonl"); let queries = temp.path().join("datatypes.gq"); @@ -805,13 +861,13 @@ query get_task($slug: String) { "#, ); - output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&repo)); - output_success(cli().arg("load").arg("--data").arg(&data).arg(&repo)); + output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&graph)); + output_success(cli().arg("load").arg("--data").arg(&data).arg(&graph)); let filtered = parse_stdout_json(&output_success( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(&queries) .arg("--name") @@ -836,7 +892,7 @@ query get_task($slug: String) { let insert_payload = parse_stdout_json(&output_success( cli() .arg("change") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(&queries) .arg("--name") @@ -852,7 +908,7 @@ query get_task($slug: String) { let update_payload = parse_stdout_json(&output_success( cli() .arg("change") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(&queries) .arg("--name") @@ -866,7 +922,7 @@ query get_task($slug: String) { let gamma = parse_stdout_json(&output_success( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(&queries) .arg("--name") @@ -893,7 +949,7 @@ query get_task($slug: String) { #[ignore = "requires GEMINI_API_KEY and network access"] fn local_cli_real_gemini_string_nearest_query_returns_expected_match() { let temp = tempfile::tempdir().unwrap(); - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let schema = temp.path().join("gemini.pg"); let data = temp.path().join("gemini.jsonl"); let queries = temp.path().join("gemini.gq"); @@ -935,13 +991,13 @@ query vector_search($q: String) { "#, ); - output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&repo)); - output_success(cli().arg("load").arg("--data").arg(&data).arg(&repo)); + output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&graph)); + output_success(cli().arg("load").arg("--data").arg(&data).arg(&graph)); let result = parse_stdout_json(&output_success( cli() .arg("read") - .arg(&repo) + .arg(&graph) .arg("--query") .arg(&queries) .arg("--name") @@ -957,7 +1013,7 @@ query vector_search($q: String) { // The publisher CAS conflict shape is verified end-to-end at the engine // level in -// `crates/omnigraph/tests/runs.rs::concurrent_writers_one_succeeds_one_gets_expected_version_mismatch` +// `crates/omnigraph/tests/writes.rs::concurrent_writers_one_succeeds_one_gets_expected_version_mismatch` // and at the HTTP boundary in // `crates/omnigraph-server/tests/server.rs::change_conflict_returns_manifest_conflict_409`. // A CLI-level race would be timing-dependent; with direct-publish the @@ -966,49 +1022,55 @@ query vector_search($q: String) { #[test] fn local_cli_policy_tooling_is_end_to_end() { // Sanity check for the read-only policy CLI surfaces. These don't - // mutate the graph — they just parse and evaluate the policy file — - // so they don't depend on PR #4's engine-side enforcement. - let repo = SystemRepo::loaded(); - let config = repo.write_config("omnigraph-policy.yaml", &local_policy_config(&repo)); - repo.write_config("policy.yaml", POLICY_E2E_YAML); - repo.write_config("policy.tests.yaml", POLICY_E2E_TESTS_YAML); - - let validate = output_success( - cli() - .arg("policy") - .arg("validate") - .arg("--config") - .arg(&config), + // mutate the graph; they parse and evaluate the effective policy for + // named graph selections, including per-graph policy files. + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + let server_graph_config = graph.write_config( + "omnigraph-policy-server.yaml", + &local_policy_server_graph_config(&graph), ); - assert!(stdout_string(&validate).contains("policy valid:")); + graph.write_config("policy.yaml", POLICY_E2E_YAML); + graph.write_config("policy.tests.yaml", POLICY_E2E_TESTS_YAML); - let tests = output_success(cli().arg("policy").arg("test").arg("--config").arg(&config)); - assert!(stdout_string(&tests).contains("policy tests passed: 2 cases")); + for config in [&config, &server_graph_config] { + let validate = output_success( + cli() + .arg("policy") + .arg("validate") + .arg("--config") + .arg(config), + ); + assert!(stdout_string(&validate).contains("policy valid:")); - let explain = output_success( - cli() - .arg("policy") - .arg("explain") - .arg("--config") - .arg(&config) - .arg("--actor") - .arg("act-bruno") - .arg("--action") - .arg("change") - .arg("--branch") - .arg("main"), - ); - let explain_stdout = stdout_string(&explain); - assert!(explain_stdout.contains("decision: deny")); - assert!(explain_stdout.contains("branch: main")); + let tests = output_success(cli().arg("policy").arg("test").arg("--config").arg(config)); + assert!(stdout_string(&tests).contains("policy tests passed: 2 cases")); + + let explain = output_success( + cli() + .arg("policy") + .arg("explain") + .arg("--config") + .arg(config) + .arg("--actor") + .arg("act-bruno") + .arg("--action") + .arg("change") + .arg("--branch") + .arg("main"), + ); + let explain_stdout = stdout_string(&explain); + assert!(explain_stdout.contains("decision: deny")); + assert!(explain_stdout.contains("branch: main")); + } } #[test] fn local_cli_change_enforces_engine_layer_policy() { - // Asserts MR-722 PR #4: when `policy.file` is configured in - // `omnigraph.yaml`, the CLI loads PolicyEngine into Omnigraph and - // every direct-engine write hits `enforce(action, scope, actor)` — - // identical to what the HTTP server gets, regardless of transport. + // Asserts MR-722 PR #4: when the selected graph has a configured + // policy file, the CLI loads PolicyEngine into Omnigraph and every + // direct-engine write hits `enforce(action, scope, actor)` — identical + // to what the HTTP server gets, regardless of transport. // // Three cases, each discriminating: // @@ -1022,10 +1084,10 @@ fn local_cli_change_enforces_engine_layer_policy() { // 3. Policy installed, `--as act-ragnor`, change on main → // Cedar permits (admins-write rule). Write succeeds and the // inserted row is readable. - let repo = SystemRepo::loaded(); - let config = repo.write_config("omnigraph-policy.yaml", &local_policy_config(&repo)); - repo.write_config("policy.yaml", POLICY_E2E_YAML); - let mutation_file = insert_person_query(&repo, "system-local-policy-change.gq"); + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + graph.write_config("policy.yaml", POLICY_E2E_YAML); + let mutation_file = insert_person_query(&graph, "system-local-policy-change.gq"); // Case 1: policy configured, no actor threaded → footgun guard. let no_actor = output_failure( @@ -1088,7 +1150,7 @@ fn local_cli_change_enforces_engine_layer_policy() { let verify = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -1101,6 +1163,32 @@ fn local_cli_change_enforces_engine_layer_policy() { assert_eq!(verify["rows"][0]["p.name"], "RagnorOnMain"); } +#[test] +fn local_cli_positional_uri_does_not_inherit_default_graph_policy() { + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + graph.write_config("policy.yaml", POLICY_E2E_YAML); + let mutation_file = insert_person_query(&graph, "system-local-policy-positional.gq"); + + let allowed = parse_stdout_json(&output_success( + cli() + .arg("--as") + .arg("act-bruno") + .arg("change") + .arg("--config") + .arg(&config) + .arg("--uri") + .arg(graph.path()) + .arg("--query") + .arg(&mutation_file) + .arg("--params") + .arg(r#"{"name":"PositionalUriBruno","age":4}"#) + .arg("--json"), + )); + assert_eq!(allowed["affected_nodes"], 1); + assert_eq!(allowed["actor_id"], "act-bruno"); +} + // ─── MR-722 PR A: CLI×writer matrix ─────────────────────────────────────── // // The change writer is covered above by `local_cli_change_enforces_engine_layer_policy`. @@ -1114,10 +1202,10 @@ fn local_cli_change_enforces_engine_layer_policy() { #[test] fn local_cli_load_enforces_engine_layer_policy() { - let repo = SystemRepo::loaded(); - let config = repo.write_config("omnigraph-policy.yaml", &local_policy_config(&repo)); - repo.write_config("policy.yaml", POLICY_E2E_YAML); - let data = repo.write_jsonl( + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + graph.write_config("policy.yaml", POLICY_E2E_YAML); + let data = graph.write_jsonl( "system-local-policy-load.jsonl", r#"{"type":"Person","data":{"name":"LoadPolicy","age":11}}"#, ); @@ -1158,10 +1246,10 @@ fn local_cli_load_enforces_engine_layer_policy() { #[test] fn local_cli_ingest_enforces_engine_layer_policy() { - let repo = SystemRepo::loaded(); - let config = repo.write_config("omnigraph-policy.yaml", &local_policy_config(&repo)); - repo.write_config("policy.yaml", POLICY_E2E_YAML); - let data = repo.write_jsonl( + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + graph.write_config("policy.yaml", POLICY_E2E_YAML); + let data = graph.write_jsonl( "system-local-policy-ingest.jsonl", r#"{"type":"Person","data":{"name":"IngestPolicy","age":12}}"#, ); @@ -1211,16 +1299,19 @@ fn local_cli_ingest_enforces_engine_layer_policy() { #[test] fn local_cli_schema_apply_enforces_engine_layer_policy() { - let repo = SystemRepo::loaded(); - let config = repo.write_config("omnigraph-policy.yaml", &local_policy_config(&repo)); - repo.write_config("policy.yaml", POLICY_E2E_YAML); + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + graph.write_config("policy.yaml", POLICY_E2E_YAML); // Additive: add a nullable property; SDK-compatible with the fixture // schema. Uses the schema-apply scope (TargetBranch("main")). let new_schema = std::fs::read_to_string(fixture("test.pg")) .unwrap() - .replace(" age: I32?\n}", " age: I32?\n nickname: String?\n}"); - let schema_path = repo.path().join("policy-additive.pg"); + .replace( + " age: I32?\n}", + " age: I32?\n nickname: String?\n}", + ); + let schema_path = graph.path().join("policy-additive.pg"); std::fs::write(&schema_path, &new_schema).unwrap(); let denied = output_failure( @@ -1256,11 +1347,67 @@ fn local_cli_schema_apply_enforces_engine_layer_policy() { assert_eq!(allowed["applied"], true); } +#[test] +fn local_cli_schema_apply_rejects_stored_query_breakage_before_publish() { + let graph = SystemGraph::loaded(); + graph.write_query( + "stored-find-person.gq", + "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + ); + let config = graph.write_config( + "omnigraph-stored-query-schema.yaml", + &format!( + "\ +graphs: + local: + uri: {} + queries: + find_person: + file: ./stored-find-person.gq +cli: + graph: local + branch: main +query: + roots: + - . +policy: {{}} +", + yaml_string(&graph.path().to_string_lossy()) + ), + ); + let renamed_schema = std::fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("age: I32?", "years: I32? @rename_from(\"age\")"); + let schema_path = graph.write_file("stored-query-breaks.pg", &renamed_schema); + + let rejected = output_failure( + cli() + .arg("schema") + .arg("apply") + .arg("--config") + .arg(&config) + .arg("--schema") + .arg(&schema_path) + .arg("--json"), + ); + let stderr = String::from_utf8_lossy(&rejected.stderr); + assert!( + stderr.contains("find_person") && stderr.contains("schema check"), + "schema apply should reject the stored-query breakage before publish; stderr: {stderr}" + ); + + let schema = stdout_string(&output_success( + cli().arg("schema").arg("show").arg("--config").arg(&config), + )); + assert!(schema.contains("age: I32?")); + assert!(!schema.contains("years: I32?")); +} + #[test] fn local_cli_branch_create_enforces_engine_layer_policy() { - let repo = SystemRepo::loaded(); - let config = repo.write_config("omnigraph-policy.yaml", &local_policy_config(&repo)); - repo.write_config("policy.yaml", POLICY_E2E_YAML); + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + graph.write_config("policy.yaml", POLICY_E2E_YAML); let denied = output_failure( cli() @@ -1296,9 +1443,9 @@ fn local_cli_branch_create_enforces_engine_layer_policy() { #[test] fn local_cli_branch_delete_enforces_engine_layer_policy() { - let repo = SystemRepo::loaded(); - let config = repo.write_config("omnigraph-policy.yaml", &local_policy_config(&repo)); - repo.write_config("policy.yaml", POLICY_E2E_YAML); + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + graph.write_config("policy.yaml", POLICY_E2E_YAML); // Pre-create the branch as ragnor so there's something to delete. output_success( @@ -1344,9 +1491,9 @@ fn local_cli_branch_delete_enforces_engine_layer_policy() { #[test] fn local_cli_branch_merge_enforces_engine_layer_policy() { - let repo = SystemRepo::loaded(); - let config = repo.write_config("omnigraph-policy.yaml", &local_policy_config(&repo)); - repo.write_config("policy.yaml", POLICY_E2E_YAML); + let graph = SystemGraph::loaded(); + let config = graph.write_config("omnigraph-policy.yaml", &local_policy_config(&graph)); + graph.write_config("policy.yaml", POLICY_E2E_YAML); // Pre-create a feature branch as ragnor (admins-branch-ops covers it). output_success( @@ -1400,7 +1547,7 @@ fn local_cli_branch_merge_enforces_engine_layer_policy() { // pin the precedence rule that `main.rs::resolve_cli_actor` implements: // `--as` flag > `cli.actor` from `omnigraph.yaml` > None. -fn local_policy_config_with_actor(repo: &SystemRepo, actor: &str) -> String { +fn local_policy_config_with_actor(graph: &SystemGraph, actor: &str) -> String { // Mirrors `local_policy_config` but adds `cli.actor` so the // config-only precedence path is exercised. The `cli:` block // already has `graph` and `branch`; appending `actor` here. @@ -1411,6 +1558,8 @@ project: graphs: local: uri: {} + policy: + file: ./policy.yaml cli: graph: local branch: main @@ -1418,10 +1567,8 @@ cli: query: roots: - . -policy: - file: ./policy.yaml ", - yaml_string(&repo.path().to_string_lossy()), + yaml_string(&graph.path().to_string_lossy()), actor, ) } @@ -1431,13 +1578,13 @@ fn local_cli_actor_from_config_used_when_no_flag() { // cli.actor: act-ragnor in omnigraph.yaml, no --as flag → change // permitted via admins-write rule. Proves the config-only path // works; previously the only proof was structural. - let repo = SystemRepo::loaded(); - let config = repo.write_config( + let graph = SystemGraph::loaded(); + let config = graph.write_config( "omnigraph-policy.yaml", - &local_policy_config_with_actor(&repo, "act-ragnor"), + &local_policy_config_with_actor(&graph, "act-ragnor"), ); - repo.write_config("policy.yaml", POLICY_E2E_YAML); - let mutation_file = insert_person_query(&repo, "system-local-cli-actor.gq"); + graph.write_config("policy.yaml", POLICY_E2E_YAML); + let mutation_file = insert_person_query(&graph, "system-local-cli-actor.gq"); let allowed = parse_stdout_json(&output_success( cli() @@ -1459,13 +1606,13 @@ fn local_cli_actor_flag_overrides_config_actor() { // cli.actor: act-ragnor in config + --as act-bruno on CLI → change // denied. Flag wins per the precedence rule. Without this test, a // future change that reverses precedence would ride through silently. - let repo = SystemRepo::loaded(); - let config = repo.write_config( + let graph = SystemGraph::loaded(); + let config = graph.write_config( "omnigraph-policy.yaml", - &local_policy_config_with_actor(&repo, "act-ragnor"), + &local_policy_config_with_actor(&graph, "act-ragnor"), ); - repo.write_config("policy.yaml", POLICY_E2E_YAML); - let mutation_file = insert_person_query(&repo, "system-local-cli-actor-override.gq"); + graph.write_config("policy.yaml", POLICY_E2E_YAML); + let mutation_file = insert_person_query(&graph, "system-local-cli-actor-override.gq"); let denied = output_failure( cli() diff --git a/crates/omnigraph-cli/tests/system_remote.rs b/crates/omnigraph-cli/tests/system_remote.rs index 15f3a6f..45bf502 100644 --- a/crates/omnigraph-cli/tests/system_remote.rs +++ b/crates/omnigraph-cli/tests/system_remote.rs @@ -37,11 +37,22 @@ rules: target_branch_scope: protected "#; +const GRAPH_LIST_SERVER_POLICY_YAML: &str = r#" +version: 1 +groups: + admins: [act-admin] +rules: + - id: admins-can-list-graphs + allow: + actors: { group: admins } + actions: [graph_list] +"#; + fn yaml_string(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } -fn remote_policy_server_config(repo: &SystemRepo) -> String { +fn remote_policy_server_config(graph: &SystemGraph) -> String { format!( "\ project: @@ -49,12 +60,12 @@ project: graphs: local: uri: {} + policy: + file: ./policy.yaml server: graph: local -policy: - file: ./policy.yaml ", - yaml_string(&repo.path().to_string_lossy()) + yaml_string(&graph.path().to_string_lossy()) ) } @@ -81,10 +92,10 @@ auth: #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_server_and_cli_end_to_end_flow() { - let repo = SystemRepo::loaded(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let mutation_file = repo.write_query( + let graph = SystemGraph::loaded(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let mutation_file = graph.write_query( "system-remote-change.gq", r#" query insert_person($name: String, $age: I32) { @@ -105,7 +116,7 @@ query insert_person($name: String, $age: I32) { assert_eq!(health["status"], "ok"); let local_snapshot = parse_stdout_json(&output_success( - cli().arg("snapshot").arg(repo.path()).arg("--json"), + cli().arg("snapshot").arg(graph.path()).arg("--json"), )); let snapshot = parse_stdout_json(&output_success( cli() @@ -120,7 +131,7 @@ query insert_person($name: String, $age: I32) { let local_read = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -180,7 +191,7 @@ query insert_person($name: String, $age: I32) { let local_verify = parse_stdout_json(&output_success( cli() .arg("read") - .arg(repo.path()) + .arg(graph.path()) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -192,6 +203,67 @@ query insert_person($name: String, $age: I32) { assert_eq!(local_verify["row_count"], 1); assert_eq!(local_verify["rows"][0]["p.name"], "Mina"); + // CLI `-e` over the HTTP transport (--config points at remote server). + // Confirms inline source survives the remote-execution path identically + // to file-based queries, and exercises `POST /query` end-to-end via the + // change-then-read round trip we just established. + let inline_remote_read = parse_stdout_json(&output_success( + cli() + .arg("read") + .arg("--config") + .arg(&config) + .arg("-e") + .arg("query find($name: String) { match { $p: Person { name: $name } } return { $p.name, $p.age } }") + .arg("--params") + .arg(r#"{"name":"Mina"}"#) + .arg("--json"), + )); + assert_eq!(inline_remote_read["row_count"], 1); + assert_eq!(inline_remote_read["rows"][0]["p.name"], "Mina"); + + let inline_remote_change = parse_stdout_json(&output_success( + cli() + .arg("change") + .arg("--config") + .arg(&config) + .arg("--query-string") + .arg("query add($name: String, $age: I32) { insert Person { name: $name, age: $age } }") + .arg("--params") + .arg(r#"{"name":"Inline","age":42}"#) + .arg("--json"), + )); + assert_eq!(inline_remote_change["affected_nodes"], 1); + + // `POST /query` happy path directly: a hand-rolled HTTP body using the + // new clean field names. + let http_query = client + .post(format!("{}/query", server.base_url)) + .json(&json!({ + "branch": "main", + "query": "query find($name: String) { match { $p: Person { name: $name } } return { $p.name } }", + "params": { "name": "Inline" } + })) + .send() + .unwrap() + .error_for_status() + .unwrap() + .json::() + .unwrap(); + assert_eq!(http_query["row_count"], 1); + assert_eq!(http_query["rows"][0]["p.name"], "Inline"); + + // `POST /query` rejects mutations with 400. + let http_query_mutation = client + .post(format!("{}/query", server.base_url)) + .json(&json!({ + "branch": "main", + "query": "query bad($name: String, $age: I32) { insert Person { name: $name, age: $age } }", + "params": { "name": "Nope", "age": 1 } + })) + .send() + .unwrap(); + assert_eq!(http_query_mutation.status(), reqwest::StatusCode::BAD_REQUEST); + // `run publish` / `run list` removed. Direct-to-target writes // already landed via the change call above; the commit graph is now // the audit surface (verified separately by `commit list`). @@ -199,11 +271,11 @@ query insert_person($name: String, $age: I32) { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] -fn remote_schema_apply_via_cli_updates_repo() { - let repo = SystemRepo::initialized(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let next_schema = repo.write_file( +fn remote_schema_apply_via_cli_updates_graph() { + let graph = SystemGraph::initialized(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let next_schema = graph.write_file( "next.pg", &fs::read_to_string(fixture("test.pg")).unwrap().replace( " age: I32?\n}", @@ -225,7 +297,7 @@ fn remote_schema_apply_via_cli_updates_repo() { let db = tokio::runtime::Runtime::new() .unwrap() - .block_on(Omnigraph::open(repo.path().to_string_lossy().as_ref())) + .block_on(Omnigraph::open(graph.path().to_string_lossy().as_ref())) .unwrap(); assert!( db.catalog().node_types["Person"] @@ -237,10 +309,10 @@ fn remote_schema_apply_via_cli_updates_repo() { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_schema_apply_rejects_unsupported_plan() { - let repo = SystemRepo::initialized(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let breaking_schema = repo.write_file( + let graph = SystemGraph::initialized(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let breaking_schema = graph.write_file( "breaking.pg", &fs::read_to_string(fixture("test.pg")) .unwrap() @@ -263,7 +335,7 @@ fn remote_schema_apply_rejects_unsupported_plan() { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_schema_apply_rejects_when_non_main_branch_exists() { - let repo = SystemRepo::initialized(); + let graph = SystemGraph::initialized(); output_success( cli() .arg("branch") @@ -271,12 +343,12 @@ fn remote_schema_apply_rejects_when_non_main_branch_exists() { .arg("--from") .arg("main") .arg("--uri") - .arg(repo.path()) + .arg(graph.path()) .arg("feature"), ); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let next_schema = repo.write_file( + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let next_schema = graph.write_file( "next.pg", &fs::read_to_string(fixture("test.pg")).unwrap().replace( " age: I32?\n}", @@ -294,16 +366,16 @@ fn remote_schema_apply_rejects_when_non_main_branch_exists() { .arg(&next_schema), ); let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("schema apply requires a repo with only main")); + assert!(stderr.contains("schema apply requires a graph with only main")); } #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_read_preserves_projection_order_in_json_and_csv() { - let repo = SystemRepo::loaded(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let ordered_query = repo.write_query( + let graph = SystemGraph::loaded(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let ordered_query = graph.write_query( "ordered-remote.gq", r#" query ordered_person($name: String) { @@ -358,10 +430,10 @@ query ordered_person($name: String) { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_branch_create_list_merge_flow() { - let repo = SystemRepo::loaded(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let mutation_file = repo.write_query( + let graph = SystemGraph::loaded(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let mutation_file = graph.write_query( "system-remote-branch-change.gq", r#" query insert_person($name: String, $age: I32) { @@ -455,9 +527,9 @@ query insert_person($name: String, $age: I32) { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_branch_delete_removes_branch() { - let repo = SystemRepo::loaded(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let graph = SystemGraph::loaded(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); parse_stdout_json(&output_success( cli() @@ -496,10 +568,10 @@ fn remote_branch_delete_removes_branch() { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_export_round_trips_full_branch_graph() { - let repo = SystemRepo::loaded(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let mutation_file = repo.write_query( + let graph = SystemGraph::loaded(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let mutation_file = graph.write_query( "system-remote-export-change.gq", r#" query insert_person($name: String, $age: I32) { @@ -563,8 +635,8 @@ query add_friend($from: String, $to: String) { .arg("feature") .arg("--jsonl"), )); - let export_path = repo.write_jsonl("system-remote-exported.jsonl", &exported); - let imported_repo = repo + let export_path = graph.write_jsonl("system-remote-exported.jsonl", &exported); + let imported_graph = graph .path() .parent() .unwrap() @@ -575,18 +647,18 @@ query add_friend($from: String, $to: String) { .arg("init") .arg("--schema") .arg(fixture("test.pg")) - .arg(&imported_repo), + .arg(&imported_graph), ); output_success( cli() .arg("load") .arg("--data") .arg(&export_path) - .arg(&imported_repo), + .arg(&imported_graph), ); let snapshot = parse_stdout_json(&output_success( - cli().arg("snapshot").arg(&imported_repo).arg("--json"), + cli().arg("snapshot").arg(&imported_graph).arg("--json"), )); assert_eq!( snapshot["tables"] @@ -610,7 +682,7 @@ query add_friend($from: String, $to: String) { let eve = parse_stdout_json(&output_success( cli() .arg("read") - .arg(&imported_repo) + .arg(&imported_graph) .arg("--query") .arg(fixture("test.gq")) .arg("--name") @@ -626,10 +698,10 @@ query add_friend($from: String, $to: String) { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_ingest_creates_review_branch_and_keeps_it_readable() { - let repo = SystemRepo::loaded(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let ingest_data = repo.write_jsonl( + let graph = SystemGraph::loaded(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let ingest_data = graph.write_jsonl( "system-remote-ingest.jsonl", r#"{"type":"Person","data":{"name":"Zoe","age":33}} {"type":"Person","data":{"name":"Bob","age":26}}"#, @@ -686,9 +758,9 @@ fn remote_ingest_creates_review_branch_and_keeps_it_readable() { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_ingest_reuses_existing_branch_and_merges_updates() { - let repo = SystemRepo::loaded(); - let server = repo.spawn_server(); - let config = repo.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); + let graph = SystemGraph::loaded(); + let server = graph.spawn_server(); + let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); output_success( cli() @@ -701,7 +773,7 @@ fn remote_ingest_reuses_existing_branch_and_merges_updates() { .arg("feature-ingest"), ); - let ingest_data = repo.write_jsonl( + let ingest_data = graph.write_jsonl( "system-remote-ingest-merge.jsonl", r#"{"type":"Person","data":{"name":"Bob","age":26}} {"type":"Person","data":{"name":"Zoe","age":33}}"#, @@ -767,23 +839,23 @@ fn remote_ingest_reuses_existing_branch_and_merges_updates() { #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_policy_enforces_branch_first_cli_workflow() { - let repo = SystemRepo::loaded(); + let graph = SystemGraph::loaded(); let server_config = - repo.write_config("server-policy.yaml", &remote_policy_server_config(&repo)); - repo.write_config("policy.yaml", REMOTE_POLICY_E2E_YAML); - let server = repo.spawn_server_with_config_env( + graph.write_config("server-policy.yaml", &remote_policy_server_config(&graph)); + graph.write_config("policy.yaml", REMOTE_POLICY_E2E_YAML); + let server = graph.spawn_server_with_config_env( &server_config, &[( "OMNIGRAPH_SERVER_BEARER_TOKENS_JSON", r#"{"act-bruno":"team-token","act-ragnor":"admin-token"}"#, )], ); - let client_config = repo.write_config( + let client_config = graph.write_config( "omnigraph-policy.yaml", &remote_policy_client_config(&server.base_url), ); - repo.write_config(".env.omni", "POLICY_TEST_TOKEN=team-token\n"); - let mutation_file = repo.write_query( + graph.write_config(".env.omni", "POLICY_TEST_TOKEN=team-token\n"); + let mutation_file = graph.write_query( "system-remote-policy-change.gq", r#" query insert_person($name: String, $age: I32) { @@ -888,3 +960,112 @@ query insert_person($name: String, $age: I32) { assert_eq!(verify["row_count"], 1); assert_eq!(verify["rows"][0]["p.name"], "PolicyRemote"); } + +// ─── MR-668 PR 8 — omnigraph graphs list end-to-end ──────────────────────── + +/// Multi-graph server + CLI `omnigraph graphs list` end-to-end. +/// +/// Steps: +/// 1. Init a graph `alpha` on disk and write an `omnigraph.yaml` +/// whose `graphs:` map references it. +/// 2. Spawn the server with `--config `. +/// 3. `omnigraph graphs list` — expect to see `alpha`. +/// +/// Ignored by default — spawning servers needs loopback socket +/// permissions some sandboxes lack. +#[test] +#[ignore = "requires loopback socket permissions in sandboxed runners"] +fn graphs_list_against_multi_graph_server() { + let cfg_dir = tempfile::tempdir().unwrap(); + let schema_path = fixture("test.pg"); + + // Init `alpha` on disk. + let alpha_uri = cfg_dir.path().join("alpha.omni"); + tokio::runtime::Runtime::new().unwrap().block_on(async { + Omnigraph::init( + alpha_uri.to_str().unwrap(), + &fs::read_to_string(&schema_path).unwrap(), + ) + .await + .unwrap(); + }); + + fs::write( + cfg_dir.path().join("server-policy.yaml"), + GRAPH_LIST_SERVER_POLICY_YAML, + ) + .unwrap(); + + // Server config with `graphs:` map and no `server.graph` selector + // — multi mode (rule 4 of the inference matrix). `GET /graphs` is a + // server-scoped action, so the success path needs an explicit server + // policy and bearer token. + let server_config_path = cfg_dir.path().join("omnigraph.yaml"); + fs::write( + &server_config_path, + format!( + "\ +server: + policy: + file: ./server-policy.yaml +graphs: + alpha: + uri: {} +", + yaml_string(&alpha_uri.to_string_lossy()) + ), + ) + .unwrap(); + + let server = spawn_server_with_config_env( + &server_config_path, + &[( + "OMNIGRAPH_SERVER_BEARER_TOKENS_JSON", + r#"{"act-admin":"admin-token"}"#, + )], + ); + + // Client config — the CLI's `--target dev` resolves to `server.base_url`. + let client_config_path = cfg_dir.path().join("client.yaml"); + fs::write( + &client_config_path, + format!( + "\ +graphs: + dev: + uri: {} + bearer_token_env: GRAPH_LIST_TOKEN +cli: + graph: dev +auth: + env_file: ./.env.omni +", + yaml_string(&server.base_url) + ), + ) + .unwrap(); + fs::write( + cfg_dir.path().join(".env.omni"), + "GRAPH_LIST_TOKEN=admin-token\n", + ) + .unwrap(); + + // `graphs list` lists `alpha`. + let payload = parse_stdout_json(&output_success( + cli() + .arg("graphs") + .arg("list") + .arg("--config") + .arg(&client_config_path) + .arg("--json"), + )); + let ids: Vec<&str> = payload["graphs"] + .as_array() + .unwrap() + .iter() + .map(|g| g["graph_id"].as_str().unwrap()) + .collect(); + assert_eq!(ids, vec!["alpha"]); + + drop(server); +} diff --git a/crates/omnigraph-compiler/Cargo.toml b/crates/omnigraph-compiler/Cargo.toml index 7bb8df0..545db83 100644 --- a/crates/omnigraph-compiler/Cargo.toml +++ b/crates/omnigraph-compiler/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-compiler" -version = "0.4.2" +version = "0.6.1" edition = "2024" description = "Schema/query compiler for Omnigraph. Zero Lance dependency." license = "MIT" diff --git a/crates/omnigraph-compiler/src/catalog/schema_plan.rs b/crates/omnigraph-compiler/src/catalog/schema_plan.rs index a20820d..a9e26b2 100644 --- a/crates/omnigraph-compiler/src/catalog/schema_plan.rs +++ b/crates/omnigraph-compiler/src/catalog/schema_plan.rs @@ -150,9 +150,7 @@ impl SchemaMigrationStep { /// non-`UnsupportedChange` variant). pub fn diagnostic(&self) -> Option<&'static crate::lint::DiagnosticCode> { match self { - Self::UnsupportedChange { - code: Some(c), .. - } => crate::lint::lookup(c), + Self::UnsupportedChange { code: Some(c), .. } => crate::lint::lookup(c), _ => None, } } @@ -1037,10 +1035,7 @@ node Person { .unwrap(); let plan = plan_schema_migration(&accepted, &desired).unwrap(); - assert!( - plan.supported, - "drop-type plan must be supported: {plan:?}" - ); + assert!(plan.supported, "drop-type plan must be supported: {plan:?}"); assert!( plan.steps.iter().any(|step| matches!( step, @@ -1182,8 +1177,7 @@ node Person @description("new") { for step in steps { let json = serde_json::to_string(&step).expect("serialize"); - let round_trip: SchemaMigrationStep = - serde_json::from_str(&json).expect("deserialize"); + let round_trip: SchemaMigrationStep = serde_json::from_str(&json).expect("deserialize"); assert_eq!(step, round_trip, "round-trip mismatch on {json}"); } } diff --git a/crates/omnigraph-compiler/src/ir/lower.rs b/crates/omnigraph-compiler/src/ir/lower.rs index c130d18..6999d69 100644 --- a/crates/omnigraph-compiler/src/ir/lower.rs +++ b/crates/omnigraph-compiler/src/ir/lower.rs @@ -271,9 +271,7 @@ fn lower_clauses( .traversals .iter() .find(|rt| { - rt.src == traversal.src - && rt.dst == traversal.dst - && rt.edge_type == edge.name + rt.src == traversal.src && rt.dst == traversal.dst && rt.edge_type == edge.name }) .map(|rt| rt.direction) .unwrap_or(Direction::Out); diff --git a/crates/omnigraph-compiler/src/ir/lower_tests.rs b/crates/omnigraph-compiler/src/ir/lower_tests.rs index 50ce93a..7aa140e 100644 --- a/crates/omnigraph-compiler/src/ir/lower_tests.rs +++ b/crates/omnigraph-compiler/src/ir/lower_tests.rs @@ -205,12 +205,8 @@ insert Knows { from: $name, to: $friend } let ir = lower_mutation_query(&qf.queries[0]).unwrap(); assert_eq!(ir.ops.len(), 2); - assert!( - matches!(&ir.ops[0], MutationOpIR::Insert { type_name, .. } if type_name == "Person") - ); - assert!( - matches!(&ir.ops[1], MutationOpIR::Insert { type_name, .. } if type_name == "Knows") - ); + assert!(matches!(&ir.ops[0], MutationOpIR::Insert { type_name, .. } if type_name == "Person")); + assert!(matches!(&ir.ops[1], MutationOpIR::Insert { type_name, .. } if type_name == "Knows")); } /// Destination binding is deferred: NodeScan + Expand + Filter (no cross-join). diff --git a/crates/omnigraph-compiler/src/lib.rs b/crates/omnigraph-compiler/src/lib.rs index 7ebc09a..ba1aba2 100644 --- a/crates/omnigraph-compiler/src/lib.rs +++ b/crates/omnigraph-compiler/src/lib.rs @@ -18,9 +18,9 @@ pub use catalog::schema_ir::{ pub use catalog::schema_plan::{ DropMode, SchemaMigrationPlan, SchemaMigrationStep, SchemaTypeKind, plan_schema_migration, }; -pub use lint::{DiagnosticCode, Family, SafetyTier, Severity}; pub use ir::ParamMap; pub use ir::lower::{lower_mutation_query, lower_query}; +pub use lint::{DiagnosticCode, Family, SafetyTier, Severity}; pub use query::ast::Literal; pub use query::lint::{ QueryLintFinding, QueryLintOutput, QueryLintQueryKind, QueryLintQueryResult, diff --git a/crates/omnigraph-compiler/src/lint/codes.rs b/crates/omnigraph-compiler/src/lint/codes.rs index e53bf31..ba870cf 100644 --- a/crates/omnigraph-compiler/src/lint/codes.rs +++ b/crates/omnigraph-compiler/src/lint/codes.rs @@ -116,7 +116,13 @@ pub const ALL_CODES: &[DiagnosticCode] = &[ ]; /// Codes actually emitted by the planner in v0 (i.e. not reserved). -pub const EMITTED_IN_V0: &[&str] = &["OG-DS-102", "OG-DS-103", "OG-DS-104", "OG-MF-103", "OG-MF-106"]; +pub const EMITTED_IN_V0: &[&str] = &[ + "OG-DS-102", + "OG-DS-103", + "OG-DS-104", + "OG-MF-103", + "OG-MF-106", +]; /// Look up a code by its string identifier. pub fn lookup(code: &str) -> Option<&'static DiagnosticCode> { diff --git a/crates/omnigraph-compiler/src/lint/mod.rs b/crates/omnigraph-compiler/src/lint/mod.rs index 79e9986..5c6c47d 100644 --- a/crates/omnigraph-compiler/src/lint/mod.rs +++ b/crates/omnigraph-compiler/src/lint/mod.rs @@ -24,5 +24,5 @@ pub mod codes; pub mod diagnostic; -pub use codes::{lookup, DiagnosticCode, ALL_CODES}; +pub use codes::{ALL_CODES, DiagnosticCode, lookup}; pub use diagnostic::{Family, SafetyTier, Severity}; diff --git a/crates/omnigraph-compiler/src/query/lint.rs b/crates/omnigraph-compiler/src/query/lint.rs index 38ae6ee..5f56774 100644 --- a/crates/omnigraph-compiler/src/query/lint.rs +++ b/crates/omnigraph-compiler/src/query/lint.rs @@ -38,7 +38,7 @@ pub enum QueryLintQueryKind { #[serde(rename_all = "lowercase")] pub enum QueryLintSchemaSourceKind { File, - Repo, + Graph, } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] @@ -59,9 +59,9 @@ impl QueryLintSchemaSource { } } - pub fn repo(uri: impl Into) -> Self { + pub fn graph(uri: impl Into) -> Self { Self { - kind: QueryLintSchemaSourceKind::Repo, + kind: QueryLintSchemaSourceKind::Graph, path: None, uri: Some(uri.into()), } diff --git a/crates/omnigraph-compiler/src/query/parser.rs b/crates/omnigraph-compiler/src/query/parser.rs index 20fedb8..4ba8476 100644 --- a/crates/omnigraph-compiler/src/query/parser.rs +++ b/crates/omnigraph-compiler/src/query/parser.rs @@ -137,12 +137,11 @@ fn parse_query_decl(pair: pest::iterators::Pair) -> Result { Rule::mutation_body => { for mutation_pair in body.into_inner() { if let Rule::mutation_stmt = mutation_pair.as_rule() { - let stmt = - mutation_pair.into_inner().next().ok_or_else(|| { - NanoError::Parse( - "mutation statement cannot be empty".to_string(), - ) - })?; + let stmt = mutation_pair.into_inner().next().ok_or_else(|| { + NanoError::Parse( + "mutation statement cannot be empty".to_string(), + ) + })?; mutations.push(parse_mutation_stmt(stmt)?); } } diff --git a/crates/omnigraph-compiler/src/schema/parser_tests.rs b/crates/omnigraph-compiler/src/schema/parser_tests.rs index 9b96a4e..2302cfb 100644 --- a/crates/omnigraph-compiler/src/schema/parser_tests.rs +++ b/crates/omnigraph-compiler/src/schema/parser_tests.rs @@ -271,9 +271,9 @@ age: I32? match &schema.declarations[0] { SchemaDecl::Node(n) => { assert!( - n.constraints.iter().any( - |c| matches!(c, Constraint::Range { property, .. } if property == "age") - ) + n.constraints + .iter() + .any(|c| matches!(c, Constraint::Range { property, .. } if property == "age")) ); } _ => panic!("expected Node"), diff --git a/crates/omnigraph-policy/Cargo.toml b/crates/omnigraph-policy/Cargo.toml index 3e19ce8..3d14fc5 100644 --- a/crates/omnigraph-policy/Cargo.toml +++ b/crates/omnigraph-policy/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-policy" -version = "0.4.2" +version = "0.6.1" edition = "2024" description = "Policy / authorization layer for Omnigraph — Cedar-backed PolicyEngine, PolicyChecker trait, ResourceScope enum." license = "MIT" diff --git a/crates/omnigraph-policy/src/lib.rs b/crates/omnigraph-policy/src/lib.rs index 41ddf82..cb59796 100644 --- a/crates/omnigraph-policy/src/lib.rs +++ b/crates/omnigraph-policy/src/lib.rs @@ -39,6 +39,38 @@ pub enum PolicyAction { /// future shape. Avoid writing such rules until the first consumer /// endpoint ships to prevent confusion. Admin, + /// MR-668: management action that operates on the server's graph + /// registry, not on a single graph's contents. The Cedar `appliesTo` + /// declaration binds it to `resource: Server` instead of the + /// per-graph `resource: Graph`. Operators authorize a group with: + /// ```yaml + /// rules: + /// - id: admins-can-list-graphs + /// allow: + /// actors: { group: admins } + /// actions: [graph_list] + /// ``` + /// `branch_scope` and `target_branch_scope` are NOT supported for + /// this action — there's no branch context at the server level. + /// Runtime `graph_create` / `graph_delete` are intentionally omitted + /// from v0.6.0; operators add and remove graphs by editing + /// `omnigraph.yaml` and restarting. + GraphList, + /// Gates invoking a server-side stored query by name. Per-graph and + /// **graph-scoped** (no branch dimension, like `Admin`): the per-branch + /// access of the query body is enforced by the inner `Read`/`Change` + /// gate, so branch-scoping this outer gate would be redundant (and was + /// wrong for snapshot reads). A rule that sets `branch_scope` on + /// `invoke_query` is rejected by `validate()`. In this release it is + /// **coarse**: an `invoke_query` allow rule permits *any* stored query + /// on the graph (no per-query dimension yet); a future, additive + /// refinement adds an optional query-name scope. + /// + /// This gate sits at the HTTP boundary. The engine `_as` writers still + /// enforce `Read`/`Change` per the query body, so a stored *mutation* + /// is double-gated: `invoke_query` to reach the tool, plus `change` for + /// the write itself. + InvokeQuery, } impl PolicyAction { @@ -52,6 +84,8 @@ impl PolicyAction { Self::BranchDelete => "branch_delete", Self::BranchMerge => "branch_merge", Self::Admin => "admin", + Self::GraphList => "graph_list", + Self::InvokeQuery => "invoke_query", } } @@ -65,6 +99,57 @@ impl PolicyAction { Self::BranchCreate | Self::SchemaApply | Self::BranchDelete | Self::BranchMerge ) } + + /// Which Cedar resource entity governs this action. + /// Per-graph actions (Read, Change, …) apply to `Omnigraph::Graph::""`. + /// Server-scoped management actions (GraphList) apply to + /// `Omnigraph::Server::"root"`. `Admin` is reserved without a current + /// call site; classified as per-graph until MR-724 picks a shape. + pub fn resource_kind(self) -> PolicyResourceKind { + match self { + Self::GraphList => PolicyResourceKind::Server, + Self::Read + | Self::Export + | Self::Change + | Self::SchemaApply + | Self::BranchCreate + | Self::BranchDelete + | Self::BranchMerge + | Self::Admin + | Self::InvokeQuery => PolicyResourceKind::Graph, + } + } +} + +/// Which Cedar entity an action's policies apply to. Internal to +/// `omnigraph-policy` — drives the `compile_policy_source` template +/// and the request-time resource UID construction. +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub enum PolicyResourceKind { + /// `Omnigraph::Graph::""` — per-graph actions. + Graph, + /// `Omnigraph::Server::"root"` — management actions. + Server, +} + +/// Which kind of policy file the caller is loading. Drives the +/// load-time validation that catches a "wrong action in wrong file" +/// mistake — a graph policy with `graph_list` rules, or a server +/// policy with `read` rules, both compile silently as Cedar but +/// never match any actual request. Typing the loader makes the +/// mistake a load-time error. +/// +/// Pairs with [`PolicyAction::resource_kind`]: every action's resource +/// kind must match the engine kind it's loaded under. +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub enum PolicyEngineKind { + /// Engine is loaded for a single graph; only actions whose + /// `resource_kind()` is `PolicyResourceKind::Graph` are allowed. + Graph, + /// Engine is loaded for server-level management endpoints; only + /// actions whose `resource_kind()` is `PolicyResourceKind::Server` + /// are allowed. + Server, } impl fmt::Display for PolicyAction { @@ -86,6 +171,8 @@ impl FromStr for PolicyAction { "branch_delete" => Ok(Self::BranchDelete), "branch_merge" => Ok(Self::BranchMerge), "admin" => Ok(Self::Admin), + "graph_list" => Ok(Self::GraphList), + "invoke_query" => Ok(Self::InvokeQuery), other => bail!("unknown policy action '{other}'"), } } @@ -153,9 +240,16 @@ pub enum PolicyExpectation { Deny, } +/// What a caller wants to do, sans identity. Actor identity flows +/// through a separate `actor_id: &str` parameter on +/// [`PolicyEngine::authorize`] / [`PolicyChecker::check`] — encoding +/// the architectural invariant that actor identity is server-authoritative +/// and must not be supplied by the same code path that supplies the +/// requested action. In the HTTP layer, the bearer-token middleware +/// resolves the actor and passes it independently; clients cannot +/// smuggle identity inside this struct. #[derive(Debug, Clone)] pub struct PolicyRequest { - pub actor_id: String, pub action: PolicyAction, pub branch: Option, pub target_branch: Option, @@ -172,7 +266,7 @@ pub struct PolicyCompiler; #[derive(Clone)] pub struct PolicyEngine { - repo_id: String, + graph_id: String, protected_branches: BTreeSet, known_actors: BTreeSet, schema: Schema, @@ -262,6 +356,34 @@ impl PolicyConfig { } } } + // MR-668: server-scoped actions have no branch context and + // must not be mixed with per-graph actions in the same + // rule (each rule generates one Cedar `permit` referencing + // a specific resource kind). + let mut server_scoped = false; + let mut graph_scoped = false; + for action in &rule.allow.actions { + match action.resource_kind() { + PolicyResourceKind::Server => server_scoped = true, + PolicyResourceKind::Graph => graph_scoped = true, + } + } + if server_scoped && graph_scoped { + bail!( + "policy rule '{}' mixes the server-scoped action `graph_list` \ + with per-graph actions; split into separate rules", + rule.id + ); + } + if server_scoped + && (rule.allow.branch_scope.is_some() || rule.allow.target_branch_scope.is_some()) + { + bail!( + "policy rule '{}' uses branch_scope/target_branch_scope with a \ + server-scoped action; server-scoped actions have no branch context", + rule.id + ); + } } Ok(()) @@ -291,7 +413,7 @@ impl PolicyTestConfig { } impl PolicyCompiler { - pub fn compile(config: &PolicyConfig, repo_id: &str) -> Result { + pub fn compile(config: &PolicyConfig, graph_id: &str) -> Result { config.validate()?; let (schema, schema_warnings) = Schema::from_cedarschema_str(policy_schema_source())?; let schema_warnings = schema_warnings @@ -300,8 +422,8 @@ impl PolicyCompiler { if !schema_warnings.is_empty() { bail!("policy schema warnings:\n{}", schema_warnings.join("\n")); } - let entities = compile_entities(config, repo_id, &schema)?; - let (policies, policy_to_rule) = compile_policies(config, repo_id)?; + let entities = compile_entities(config, graph_id, &schema)?; + let (policies, policy_to_rule) = compile_policies(config, graph_id)?; let validator = Validator::new(schema.clone()); let validation = validator.validate(&policies, ValidationMode::Strict); let errors = validation @@ -318,7 +440,7 @@ impl PolicyCompiler { .flat_map(|members| members.iter().cloned()) .collect(); Ok(PolicyEngine { - repo_id: repo_id.to_string(), + graph_id: graph_id.to_string(), protected_branches: config.protected_branches.iter().cloned().collect(), known_actors, schema, @@ -330,26 +452,61 @@ impl PolicyCompiler { } impl PolicyEngine { - pub fn load(path: &Path, repo_id: &str) -> Result { + /// Load a per-graph policy file. Rejects rules whose actions are + /// server-scoped (e.g. `graph_list`) — those belong in a server + /// policy file, not a per-graph one. + /// + /// `graph_id` is the label of the graph this engine governs; + /// becomes the Cedar `Omnigraph::Graph::""` resource + /// for every per-graph action evaluated against this engine. + pub fn load_graph(path: &Path, graph_id: &str) -> Result { let config = PolicyConfig::load(path)?; - PolicyCompiler::compile(&config, repo_id) + validate_kind_alignment(&config, PolicyEngineKind::Graph)?; + PolicyCompiler::compile(&config, graph_id) } - pub fn authorize(&self, request: &PolicyRequest) -> Result { - if !self.known_actors.contains(request.actor_id.as_str()) { + /// Load a server-level policy file. Rejects rules whose actions + /// are per-graph (e.g. `read`, `change`) — those belong in a + /// per-graph policy file, not the server one. Takes no `graph_id`: + /// server-scoped actions resolve against the singleton + /// `Omnigraph::Server::"root"` entity, never a Graph. + pub fn load_server(path: &Path) -> Result { + let config = PolicyConfig::load(path)?; + validate_kind_alignment(&config, PolicyEngineKind::Server)?; + // The Graph entity created by the compiler is never referenced + // by a server-scoped rule, so the label below is purely a + // placeholder. Use the canonical SERVER_RESOURCE_ID so any + // future inspection of an unreachable Graph entity at least + // points at the right concept. + PolicyCompiler::compile(&config, SERVER_RESOURCE_ID) + } + + /// Evaluate a request. `actor_id` is supplied as a separate + /// argument (not inside `PolicyRequest`) so the type system enforces + /// the "server-authoritative actor identity" invariant — clients + /// supplying a `PolicyRequest` cannot smuggle identity through the + /// same struct that carries the requested action. + pub fn authorize(&self, actor_id: &str, request: &PolicyRequest) -> Result { + if !self.known_actors.contains(actor_id) { return Ok(self.deny( - request, None, format!( "policy denied action '{}' for unknown actor '{}'", - request.action, request.actor_id + request.action, actor_id ), )); } - let principal = entity_uid("Actor", &request.actor_id)?; + let principal = entity_uid("Actor", actor_id)?; let action = entity_uid("Action", request.action.as_str())?; - let resource = entity_uid("Repo", &self.repo_id)?; + // Pick the resource entity based on the action's `resource_kind`. + // Server-scoped actions (`graph_list`) bind to + // `Omnigraph::Server::"root"`; per-graph actions bind to + // `Omnigraph::Graph::""`. + let resource = match request.action.resource_kind() { + PolicyResourceKind::Server => entity_uid("Server", SERVER_RESOURCE_ID)?, + PolicyResourceKind::Graph => entity_uid("Graph", &self.graph_id)?, + }; let context_value = json!({ "has_branch": request.branch.is_some(), "branch": request.branch.clone().unwrap_or_default(), @@ -386,7 +543,7 @@ impl PolicyEngine { matched_rule_id: matched_rule_id.clone(), message: format!( "policy allowed action '{}' for actor '{}'", - request.action, request.actor_id + request.action, actor_id ), }, Decision::Deny => { @@ -403,30 +560,27 @@ impl PolicyEngine { .as_deref() .map(|branch| format!(" targeting branch '{}'", branch)) .unwrap_or_default(), - request.actor_id + actor_id ); - self.deny(request, matched_rule_id, message) + self.deny(matched_rule_id, message) } }) } - pub fn validate_request(&self, request: &PolicyRequest) -> Result<()> { - let _ = self.authorize(request)?; - Ok(()) - } - pub fn run_tests(&self, tests: &PolicyTestConfig) -> Result<()> { if tests.version != 1 { bail!("policy test version must be 1"); } let mut failures = Vec::new(); for case in &tests.cases { - let decision = self.authorize(&PolicyRequest { - actor_id: case.actor.clone(), - action: case.action, - branch: case.branch.clone(), - target_branch: case.target_branch.clone(), - })?; + let decision = self.authorize( + &case.actor, + &PolicyRequest { + action: case.action, + branch: case.branch.clone(), + target_branch: case.target_branch.clone(), + }, + )?; let expected_allowed = matches!(case.expect, PolicyExpectation::Allow); if decision.allowed != expected_allowed { failures.push(format!( @@ -448,12 +602,7 @@ impl PolicyEngine { self.known_actors.len() } - fn deny( - &self, - _request: &PolicyRequest, - matched_rule_id: Option, - message: String, - ) -> PolicyDecision { + fn deny(&self, matched_rule_id: Option, message: String) -> PolicyDecision { PolicyDecision { allowed: false, matched_rule_id, @@ -462,7 +611,39 @@ impl PolicyEngine { } } -fn compile_entities(config: &PolicyConfig, repo_id: &str, schema: &Schema) -> Result { +/// Reject any rule whose actions don't match the engine kind +/// being loaded. Closes the "wrong action in wrong file silently +/// no-ops" class — `graph_list` in a per-graph file or `read` in +/// a server file fails at load time instead of compiling cleanly +/// and never matching a request. +fn validate_kind_alignment(config: &PolicyConfig, kind: PolicyEngineKind) -> Result<()> { + let required = match kind { + PolicyEngineKind::Graph => PolicyResourceKind::Graph, + PolicyEngineKind::Server => PolicyResourceKind::Server, + }; + for rule in &config.rules { + for action in &rule.allow.actions { + if action.resource_kind() != required { + let (got, expected_file) = match action.resource_kind() { + PolicyResourceKind::Server => ("server-scoped", "server policy file"), + PolicyResourceKind::Graph => ("per-graph", "per-graph policy file"), + }; + bail!( + "policy rule '{}' uses {} action '{}' in a {:?} policy file; \ + move it to a {}", + rule.id, + got, + action, + kind, + expected_file + ); + } + } + } + Ok(()) +} + +fn compile_entities(config: &PolicyConfig, graph_id: &str, schema: &Schema) -> Result { let mut group_entities = Vec::new(); for group in config.groups.keys() { group_entities.push(Entity::new( @@ -495,8 +676,8 @@ fn compile_entities(config: &PolicyConfig, repo_id: &str, schema: &Schema) -> Re )?); } - let repo_entity = Entity::new( - entity_uid("Repo", repo_id)?, + let graph_entity = Entity::new( + entity_uid("Graph", graph_id)?, HashMap::new(), HashSet::::new(), )?; @@ -504,13 +685,33 @@ fn compile_entities(config: &PolicyConfig, repo_id: &str, schema: &Schema) -> Re let mut entities = Vec::new(); entities.extend(group_entities); entities.extend(actor_entities); - entities.push(repo_entity); + entities.push(graph_entity); + + // MR-668: include the `Omnigraph::Server::"root"` entity + // whenever any rule references a server-scoped action. Cedar's + // schema validator will otherwise reject the policy. Keeping this + // conditional (rather than always-on) avoids polluting test + // assertions for graph-only policies. + let any_server_scoped = config.rules.iter().any(|rule| { + rule.allow + .actions + .iter() + .any(|action| action.resource_kind() == PolicyResourceKind::Server) + }); + if any_server_scoped { + entities.push(Entity::new( + entity_uid("Server", SERVER_RESOURCE_ID)?, + HashMap::new(), + HashSet::::new(), + )?); + } + Ok(Entities::from_entities(entities, Some(schema))?) } fn compile_policies( config: &PolicyConfig, - repo_id: &str, + graph_id: &str, ) -> Result<(PolicySet, HashMap)> { let mut policies = Vec::new(); let mut policy_to_rule = HashMap::new(); @@ -518,7 +719,7 @@ fn compile_policies( for rule in &config.rules { for action in &rule.allow.actions { let policy_id = PolicyId::new(format!("{}:{}", rule.id, action.as_str())); - let source = compile_policy_source(rule, action, repo_id); + let source = compile_policy_source(rule, action, graph_id); let policy = Policy::parse(Some(policy_id.clone()), source.as_str())?; policy_to_rule.insert(policy_id.to_string(), rule.id.clone()); policies.push(policy); @@ -528,7 +729,7 @@ fn compile_policies( Ok((PolicySet::from_policies(policies)?, policy_to_rule)) } -fn compile_policy_source(rule: &PolicyRule, action: &PolicyAction, repo_id: &str) -> String { +fn compile_policy_source(rule: &PolicyRule, action: &PolicyAction, graph_id: &str) -> String { let mut conditions = Vec::new(); if let Some(scope) = rule.allow.branch_scope { conditions.push(branch_scope_condition(scope)); @@ -543,16 +744,29 @@ fn compile_policy_source(rule: &PolicyRule, action: &PolicyAction, repo_id: &str format!("\nwhen {{ {} }}", conditions.join(" && ")) }; + // MR-668: emit the resource literal that matches the action's + // `resource_kind`. Per-graph actions reference the engine's + // `Omnigraph::Graph::""` instance; server-scoped + // actions reference the singleton `Omnigraph::Server::"root"`. + let resource_literal = match action.resource_kind() { + PolicyResourceKind::Graph => { + format!("Omnigraph::Graph::{}", cedar_literal(graph_id)) + } + PolicyResourceKind::Server => { + format!("Omnigraph::Server::{}", cedar_literal(SERVER_RESOURCE_ID)) + } + }; + format!( r#"permit ( principal in Omnigraph::Group::{group}, action == Omnigraph::Action::{action}, - resource == Omnigraph::Repo::{repo} + resource == {resource_literal} ){when};"#, group = cedar_literal(&rule.allow.actors.group), action = cedar_literal(action.as_str()), - repo = cedar_literal(repo_id), when = when, + resource_literal = resource_literal, ) } @@ -581,6 +795,11 @@ fn target_branch_scope_condition(scope: PolicyBranchScope) -> String { } fn policy_schema_source() -> &'static str { + // MR-668: `entity Server;` plus the `graph_list` action that + // binds to it. Per-graph actions stay bound to `Graph`. + // The Cedar schema string lives here (not on a fixture file) so any + // omnigraph-policy build picks up the new vocabulary in lock-step + // with the Rust code. r#" namespace Omnigraph { type RequestContext = { @@ -594,20 +813,29 @@ namespace Omnigraph { entity Actor in [Group]; entity Group; - entity Repo; + entity Graph; + entity Server; - action "read" appliesTo { principal: Actor, resource: Repo, context: RequestContext }; - action "export" appliesTo { principal: Actor, resource: Repo, context: RequestContext }; - action "change" appliesTo { principal: Actor, resource: Repo, context: RequestContext }; - action "schema_apply" appliesTo { principal: Actor, resource: Repo, context: RequestContext }; - action "branch_create" appliesTo { principal: Actor, resource: Repo, context: RequestContext }; - action "branch_delete" appliesTo { principal: Actor, resource: Repo, context: RequestContext }; - action "branch_merge" appliesTo { principal: Actor, resource: Repo, context: RequestContext }; - action "admin" appliesTo { principal: Actor, resource: Repo, context: RequestContext }; + action "read" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + action "export" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + action "change" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + action "schema_apply" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + action "branch_create" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + action "branch_delete" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + action "branch_merge" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + action "admin" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + action "invoke_query" appliesTo { principal: Actor, resource: Graph, context: RequestContext }; + + action "graph_list" appliesTo { principal: Actor, resource: Server, context: RequestContext }; } "# } +/// Canonical id of the `Omnigraph::Server` Cedar entity. There's only one +/// (the running server); the id is fixed at `"root"` so Cedar rules can +/// reference it unambiguously: `resource == Omnigraph::Server::"root"`. +const SERVER_RESOURCE_ID: &str = "root"; + fn entity_uid(entity_type: &str, id: &str) -> Result { let typename = EntityTypeName::from_str(&format!("Omnigraph::{entity_type}"))?; let entity_id = EntityId::from_str(id).map_err(|err| eyre!(err.to_string()))?; @@ -619,10 +847,6 @@ fn cedar_literal(value: &str) -> String { } impl PolicyRequest { - pub fn actor_id(&self) -> &str { - &self.actor_id - } - pub fn action(&self) -> PolicyAction { self.action } @@ -761,13 +985,12 @@ impl PolicyChecker for PolicyEngine { ) -> Result<(), PolicyError> { let (branch, target_branch) = scope.to_branch_pair(); let request = PolicyRequest { - actor_id: actor.to_string(), action, branch: branch.map(|s| s.to_string()), target_branch: target_branch.map(|s| s.to_string()), }; let decision = self - .authorize(&request) + .authorize(actor, &request) .map_err(|e| PolicyError::Internal(e.to_string()))?; if decision.allowed { Ok(()) @@ -780,7 +1003,7 @@ impl PolicyChecker for PolicyEngine { #[cfg(test)] mod tests { use super::{ - PolicyAction, PolicyCompiler, PolicyConfig, PolicyExpectation, PolicyRequest, + PolicyAction, PolicyCompiler, PolicyConfig, PolicyEngine, PolicyExpectation, PolicyRequest, PolicyTestCase, PolicyTestConfig, }; @@ -881,35 +1104,41 @@ rules: ) .unwrap(); - let engine = PolicyCompiler::compile(&policy, "repo").unwrap(); + let engine = PolicyCompiler::compile(&policy, "graph").unwrap(); let allow = engine - .authorize(&PolicyRequest { - actor_id: "act-bruno".to_string(), - action: PolicyAction::Change, - branch: Some("feature".to_string()), - target_branch: None, - }) + .authorize( + "act-bruno", + &PolicyRequest { + action: PolicyAction::Change, + branch: Some("feature".to_string()), + target_branch: None, + }, + ) .unwrap(); assert!(allow.allowed); assert_eq!(allow.matched_rule_id.as_deref(), Some("team-write")); let deny = engine - .authorize(&PolicyRequest { - actor_id: "act-bruno".to_string(), - action: PolicyAction::BranchDelete, - branch: None, - target_branch: Some("main".to_string()), - }) + .authorize( + "act-bruno", + &PolicyRequest { + action: PolicyAction::BranchDelete, + branch: None, + target_branch: Some("main".to_string()), + }, + ) .unwrap(); assert!(!deny.allowed); let admin = engine - .authorize(&PolicyRequest { - actor_id: "act-andrew".to_string(), - action: PolicyAction::BranchDelete, - branch: None, - target_branch: Some("main".to_string()), - }) + .authorize( + "act-andrew", + &PolicyRequest { + action: PolicyAction::BranchDelete, + branch: None, + target_branch: Some("main".to_string()), + }, + ) .unwrap(); assert!(admin.allowed); assert_eq!(admin.matched_rule_id.as_deref(), Some("admins-promote")); @@ -932,7 +1161,7 @@ rules: "#, ) .unwrap(); - let engine = PolicyCompiler::compile(&policy, "repo").unwrap(); + let engine = PolicyCompiler::compile(&policy, "graph").unwrap(); let tests = PolicyTestConfig { version: 1, cases: vec![ @@ -976,25 +1205,381 @@ rules: ) .unwrap(); - let engine = PolicyCompiler::compile(&policy, "repo").unwrap(); + let engine = PolicyCompiler::compile(&policy, "graph").unwrap(); let allow = engine - .authorize(&PolicyRequest { - actor_id: "act-ragnor".to_string(), - action: PolicyAction::SchemaApply, - branch: None, - target_branch: Some("main".to_string()), - }) + .authorize( + "act-ragnor", + &PolicyRequest { + action: PolicyAction::SchemaApply, + branch: None, + target_branch: Some("main".to_string()), + }, + ) .unwrap(); assert!(allow.allowed); let deny = engine - .authorize(&PolicyRequest { - actor_id: "act-ragnor".to_string(), - action: PolicyAction::SchemaApply, - branch: None, - target_branch: Some("feature".to_string()), - }) + .authorize( + "act-ragnor", + &PolicyRequest { + action: PolicyAction::SchemaApply, + branch: None, + target_branch: Some("feature".to_string()), + }, + ) .unwrap(); assert!(!deny.allowed); } + + // ─── MR-668 — server-scoped action (graph_list) ─ + + #[test] + fn graph_list_action_authorizes_against_server_resource() { + let policy: PolicyConfig = serde_yaml::from_str( + r#" +version: 1 +groups: + admins: [act-andrew] + viewers: [act-bruno] +rules: + - id: admins-list-graphs + allow: + actors: { group: admins } + actions: [graph_list] +"#, + ) + .unwrap(); + + // The graph_label passed at compile time is irrelevant for + // server-scoped actions — they resolve against + // `Omnigraph::Server::"root"` regardless. We pass a sentinel + // so it's obvious the value isn't used. + let engine = PolicyCompiler::compile(&policy, "ignored").unwrap(); + + let allow = engine + .authorize( + "act-andrew", + &PolicyRequest { + action: PolicyAction::GraphList, + branch: None, + target_branch: None, + }, + ) + .unwrap(); + assert!(allow.allowed); + assert_eq!(allow.matched_rule_id.as_deref(), Some("admins-list-graphs")); + + // Different actor, same policy → deny. + let deny = engine + .authorize( + "act-bruno", + &PolicyRequest { + action: PolicyAction::GraphList, + branch: None, + target_branch: None, + }, + ) + .unwrap(); + assert!(!deny.allowed); + } + + #[test] + fn invoke_query_authorizes_per_graph() { + let policy: PolicyConfig = serde_yaml::from_str( + r#" +version: 1 +groups: + team: [act-alice] + others: [act-bruno] +rules: + - id: team-invoke-queries + allow: + actors: { group: team } + actions: [invoke_query] +"#, + ) + .unwrap(); + let engine = PolicyCompiler::compile(&policy, "graph").unwrap(); + + let allow = engine + .authorize( + "act-alice", + &PolicyRequest { + action: PolicyAction::InvokeQuery, + branch: None, + target_branch: None, + }, + ) + .unwrap(); + assert!(allow.allowed); + assert_eq!( + allow.matched_rule_id.as_deref(), + Some("team-invoke-queries") + ); + + // Actor outside the group → deny. + let deny = engine + .authorize( + "act-bruno", + &PolicyRequest { + action: PolicyAction::InvokeQuery, + branch: None, + target_branch: None, + }, + ) + .unwrap(); + assert!(!deny.allowed); + } + + #[test] + fn invoke_query_rejects_branch_scope() { + // invoke_query is graph-scoped (like admin) — per-branch access is + // enforced by the inner read/change gate — so a rule that puts a + // `branch_scope` qualifier on it is rejected at validate(). + let policy: PolicyConfig = serde_yaml::from_str( + r#" +version: 1 +groups: + team: [act-alice] +rules: + - id: team-invoke-any-branch + allow: + actors: { group: team } + actions: [invoke_query] + branch_scope: any +"#, + ) + .unwrap(); + let err = policy.validate().unwrap_err().to_string(); + assert!( + err.contains("branch_scope") && err.contains("invoke_query"), + "branch_scope on invoke_query must be rejected: {err}" + ); + } + + #[test] + fn server_scoped_rule_cannot_use_branch_scope() { + let policy: PolicyConfig = serde_yaml::from_str( + r#" +version: 1 +groups: + admins: [act-andrew] +rules: + - id: bad-branch-scope-on-graph-list + allow: + actors: { group: admins } + actions: [graph_list] + branch_scope: any +"#, + ) + .unwrap(); + let err = policy.validate().unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("branch_scope") || msg.contains("server-scoped"), + "expected branch_scope rejection for server-scoped action; got: {msg}" + ); + } + + #[test] + fn rule_mixing_server_and_per_graph_actions_is_rejected() { + // A single rule must reference exactly one resource kind. + // `graph_list` (Server) + `read` (Graph) in one allow block + // is invalid — operators must split the rule. + let policy: PolicyConfig = serde_yaml::from_str( + r#" +version: 1 +groups: + admins: [act-andrew] +rules: + - id: mixed-resource-kinds + allow: + actors: { group: admins } + actions: [graph_list, read] +"#, + ) + .unwrap(); + let err = policy.validate().unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("server-scoped") || msg.contains("split into separate rules"), + "expected mix-resource-kinds rejection; got: {msg}" + ); + } + + #[test] + fn per_graph_rules_continue_to_work_alongside_server_rules() { + // Decision 6 contract: existing operator policies (which only + // reference per-graph actions) keep compiling and authorizing + // as before, even when the compiled-in schema now declares + // `Server` + `graph_*` actions. This pins the "Cedar refactor + // is operator-invisible" promise. + let policy: PolicyConfig = serde_yaml::from_str( + r#" +version: 1 +groups: + team: [act-andrew] +protected_branches: [main] +rules: + - id: team-read + allow: + actors: { group: team } + actions: [read, export] + branch_scope: any +"#, + ) + .unwrap(); + let engine = PolicyCompiler::compile(&policy, "graph").unwrap(); + let allow = engine + .authorize( + "act-andrew", + &PolicyRequest { + action: PolicyAction::Read, + branch: Some("main".to_string()), + target_branch: None, + }, + ) + .unwrap(); + assert!(allow.allowed); + assert_eq!(allow.matched_rule_id.as_deref(), Some("team-read")); + } + + // ─── MR-668 follow-up — load_graph / load_server kind alignment ─ + + /// A per-graph policy file containing a `graph_list` rule fails + /// at load time. Pre-fix, the file compiled cleanly and the rule + /// silently never matched (per-graph engine never gets a + /// `graph_list` check). Closes the "wrong action, wrong file, + /// silent no-op" class. + #[test] + fn load_graph_rejects_server_scoped_action() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("bad-graph-policy.yaml"); + std::fs::write( + &path, + r#" +version: 1 +groups: + admins: [act-andrew] +rules: + - id: misplaced-graph-list + allow: + actors: { group: admins } + actions: [graph_list] +"#, + ) + .unwrap(); + let err = match PolicyEngine::load_graph(&path, "g1") { + Ok(_) => panic!("expected server-scoped action in per-graph file to be rejected"), + Err(e) => e, + }; + let msg = err.to_string(); + assert!( + msg.contains("server-scoped") && msg.contains("graph_list"), + "expected server-scoped-in-graph-file rejection, got: {msg}" + ); + } + + /// A server policy file containing a `read` rule fails at load + /// time. Pre-fix, the file compiled cleanly and the rule silently + /// never matched (server engine never gets a `read` check). + #[test] + fn load_server_rejects_per_graph_action() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("bad-server-policy.yaml"); + std::fs::write( + &path, + r#" +version: 1 +groups: + team: [act-andrew] +rules: + - id: misplaced-read + allow: + actors: { group: team } + actions: [read] + branch_scope: any +"#, + ) + .unwrap(); + let err = match PolicyEngine::load_server(&path) { + Ok(_) => panic!("expected per-graph action in server file to be rejected"), + Err(e) => e, + }; + let msg = err.to_string(); + assert!( + msg.contains("per-graph") && msg.contains("read"), + "expected per-graph-in-server-file rejection, got: {msg}" + ); + } + + /// Positive case: a properly-shaped per-graph policy loads via + /// `load_graph` and authorizes as expected. Verifies the + /// kind-alignment check is permissive when the file is correct. + #[test] + fn load_graph_accepts_per_graph_only_policy() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ok-graph-policy.yaml"); + std::fs::write( + &path, + r#" +version: 1 +groups: + team: [act-andrew] +rules: + - id: team-read + allow: + actors: { group: team } + actions: [read] + branch_scope: any +"#, + ) + .unwrap(); + let engine = PolicyEngine::load_graph(&path, "g1").unwrap(); + let decision = engine + .authorize( + "act-andrew", + &PolicyRequest { + action: PolicyAction::Read, + branch: Some("main".to_string()), + target_branch: None, + }, + ) + .unwrap(); + assert!(decision.allowed); + } + + /// Positive case: a properly-shaped server policy loads via + /// `load_server` and authorizes the `graph_list` action. + #[test] + fn load_server_accepts_server_only_policy() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ok-server-policy.yaml"); + std::fs::write( + &path, + r#" +version: 1 +groups: + admins: [act-andrew] +rules: + - id: admins-list-graphs + allow: + actors: { group: admins } + actions: [graph_list] +"#, + ) + .unwrap(); + let engine = PolicyEngine::load_server(&path).unwrap(); + let decision = engine + .authorize( + "act-andrew", + &PolicyRequest { + action: PolicyAction::GraphList, + branch: None, + target_branch: None, + }, + ) + .unwrap(); + assert!(decision.allowed); + } } diff --git a/crates/omnigraph-server/Cargo.toml b/crates/omnigraph-server/Cargo.toml index b12ddfe..5994aa1 100644 --- a/crates/omnigraph-server/Cargo.toml +++ b/crates/omnigraph-server/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-server" -version = "0.4.2" +version = "0.6.1" edition = "2024" description = "HTTP server for the Omnigraph graph database." license = "MIT" @@ -19,9 +19,9 @@ default = [] aws = ["dep:aws-config", "dep:aws-sdk-secretsmanager"] [dependencies] -omnigraph = { package = "omnigraph-engine", path = "../omnigraph", version = "0.4.2" } -omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.4.2" } -omnigraph-policy = { path = "../omnigraph-policy", version = "0.4.2" } +omnigraph = { package = "omnigraph-engine", path = "../omnigraph", version = "0.6.1" } +omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.1" } +omnigraph-policy = { path = "../omnigraph-policy", version = "0.6.1" } axum = { workspace = true } clap = { workspace = true } color-eyre = { workspace = true } @@ -37,7 +37,10 @@ futures = { workspace = true } sha2 = { workspace = true } subtle = { workspace = true } async-trait = { workspace = true } +arc-swap = { workspace = true } dashmap = "6" +regex = { workspace = true } +thiserror = { workspace = true } aws-config = { version = "1", optional = true, default-features = false, features = ["rustls", "rt-tokio", "credentials-process", "sso"] } aws-sdk-secretsmanager = { version = "1", optional = true, default-features = false, features = ["rustls", "rt-tokio"] } diff --git a/crates/omnigraph-server/examples/bench_actor_isolation.rs b/crates/omnigraph-server/examples/bench_actor_isolation.rs index 1eca032..5a708e0 100644 --- a/crates/omnigraph-server/examples/bench_actor_isolation.rs +++ b/crates/omnigraph-server/examples/bench_actor_isolation.rs @@ -199,8 +199,8 @@ async fn drive_light_actor( let mut other = 0usize; for op_idx in 0..ops { let request_body = ChangeRequest { - query_source: "query insert_person($name: String, $age: I32) {\n insert Person { name: $name, age: $age }\n}".to_string(), - query_name: Some("insert_person".to_string()), + query: "query insert_person($name: String, $age: I32) {\n insert Person { name: $name, age: $age }\n}".to_string(), + name: Some("insert_person".to_string()), params: Some(serde_json::json!({ "name": format!("light-{actor_idx}-{op_idx}"), "age": op_idx as i32, @@ -259,10 +259,10 @@ async fn main() { } let temp = tempfile::tempdir().expect("tempdir"); - let repo = temp.path().join("bench.omni"); - Omnigraph::init(repo.to_str().unwrap(), SCHEMA) + let graph = temp.path().join("bench.omni"); + Omnigraph::init(graph.to_str().unwrap(), SCHEMA) .await - .expect("init repo"); + .expect("init graph"); // Build bearer tokens: one for the heavy actor + one per light actor. let mut tokens: Vec<(String, String)> = @@ -270,21 +270,17 @@ async fn main() { for i in 0..args.light_actors { tokens.push((format!("act-light-{i}"), format!("light-token-{i}"))); } - let db = Omnigraph::open(repo.to_str().unwrap()) + let db = Omnigraph::open(graph.to_str().unwrap()) .await - .expect("open repo"); + .expect("open graph"); // Construct a custom WorkloadController with the requested caps and // pass it through `AppState::new_with_workload`. Avoids the // `unsafe { std::env::set_var(...) }` antipattern that violates // `setenv`'s thread-safety precondition once the multi-thread tokio // runtime is up. let workload = WorkloadController::new(args.inflight_cap, args.byte_cap); - let state = AppState::new_with_workload( - repo.to_string_lossy().to_string(), - db, - tokens, - workload, - ); + let state = + AppState::new_with_workload(graph.to_string_lossy().to_string(), db, tokens, workload); let app = build_app(state); eprintln!( diff --git a/crates/omnigraph-server/examples/bench_concurrent_http.rs b/crates/omnigraph-server/examples/bench_concurrent_http.rs index 11505e7..6a8411a 100644 --- a/crates/omnigraph-server/examples/bench_concurrent_http.rs +++ b/crates/omnigraph-server/examples/bench_concurrent_http.rs @@ -121,8 +121,8 @@ async fn drive_actor( for op_idx in 0..ops { let table_idx = pick_table(actor_idx, op_idx, mode, num_tables); let request_body = ChangeRequest { - query_source: build_query_source(table_idx), - query_name: Some("insert_item".to_string()), + query: build_query_source(table_idx), + name: Some("insert_item".to_string()), params: Some(serde_json::json!({ "name": format!("a{actor_idx}_o{op_idx}"), "value": op_idx as i32, @@ -152,7 +152,9 @@ async fn drive_actor( errors += 1; // Drain body for logging on the first few failures. if errors <= 3 { - let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap_or_default(); + let body = to_bytes(response.into_body(), 64 * 1024) + .await + .unwrap_or_default(); eprintln!( "actor {actor_idx} op {op_idx} status {status} body {}", String::from_utf8_lossy(&body) @@ -173,13 +175,13 @@ async fn main() { } let temp = tempfile::tempdir().expect("tempdir"); - let repo = temp.path().join("bench.omni"); + let graph = temp.path().join("bench.omni"); let schema = build_schema(args.tables); - Omnigraph::init(repo.to_str().unwrap(), &schema) + Omnigraph::init(graph.to_str().unwrap(), &schema) .await - .expect("init repo"); + .expect("init graph"); - let state = AppState::open(repo.to_string_lossy().to_string()) + let state = AppState::open(graph.to_string_lossy().to_string()) .await .expect("open AppState"); let app = build_app(state); diff --git a/crates/omnigraph-server/src/api.rs b/crates/omnigraph-server/src/api.rs index 1195f12..4a6024f 100644 --- a/crates/omnigraph-server/src/api.rs +++ b/crates/omnigraph-server/src/api.rs @@ -1,8 +1,11 @@ use omnigraph::db::{GraphCommit, MergeOutcome, ReadTarget, SchemaApplyResult, Snapshot}; use omnigraph::error::{MergeConflict, MergeConflictKind}; use omnigraph::loader::{IngestResult, LoadMode}; +use crate::queries::StoredQuery; use omnigraph_compiler::SchemaMigrationStep; +use omnigraph_compiler::query::ast::Param; use omnigraph_compiler::result::QueryResult; +use omnigraph_compiler::types::{PropType, ScalarType}; use serde::{Deserialize, Serialize}; use serde_json::Value; use utoipa::{IntoParams, ToSchema}; @@ -235,7 +238,9 @@ pub struct CommitListOutput { pub struct ReadRequest { /// GQ query source. May declare one or more named queries; pick one with /// `query_name` if there is more than one. - #[schema(example = "query get_person($name: String) {\n match {\n $p: Person { name: $name }\n }\n return { $p.name, $p.age }\n}")] + #[schema( + example = "query get_person($name: String) {\n match {\n $p: Person { name: $name }\n }\n return { $p.name, $p.age }\n}" + )] pub query_source: String, /// Name of the query to run when `query_source` declares multiple. Optional /// when only one query is declared. @@ -248,25 +253,219 @@ pub struct ReadRequest { pub snapshot: Option, } +/// Inline read-query request for `POST /query`. +/// +/// Friendlier-named alternative to [`ReadRequest`] for ad-hoc reads and +/// AI-agent integration. Mutations are rejected with 400 — use `POST +/// /mutate` (or its deprecated alias `POST /change`) for write queries. +/// Field names are deliberately short (`query`, `name`) to match the GQ +/// keyword and the CLI `-e` flag. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct QueryRequest { + /// GQ read-query source. May declare one or more named queries; pick one + /// with `name` when more than one is declared. Mutations + /// (`insert`/`update`/`delete`) get 400 — use `POST /mutate` (or its + /// deprecated alias `POST /change`) instead. + #[schema(example = "query get_person($name: String) {\n match {\n $p: Person { name: $name }\n }\n return { $p.name, $p.age }\n}")] + pub query: String, + /// Name of the query to run when `query` declares multiple. Optional when + /// only one query is declared. + pub name: Option, + /// JSON object whose keys match the query's declared parameters. + pub params: Option, + /// Branch to read from. Mutually exclusive with `snapshot`. Defaults to `main`. + pub branch: Option, + /// Snapshot id to read from. Mutually exclusive with `branch`. + pub snapshot: Option, +} + #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ChangeRequest { /// GQ mutation source containing `insert`, `update`, or `delete` statements. - /// May declare multiple named mutations; pick one with `query_name`. - #[schema(example = "query insert_person($name: String, $age: I32) {\n insert Person { name: $name, age: $age }\n}")] - pub query_source: String, - /// Name of the mutation to run when `query_source` declares multiple. - pub query_name: Option, + /// May declare multiple named mutations; pick one with `name`. + /// + /// Accepts the legacy field name `query_source` as a deserialization alias. + #[schema( + example = "query insert_person($name: String, $age: I32) {\n insert Person { name: $name, age: $age }\n}" + )] + #[serde(alias = "query_source")] + pub query: String, + /// Name of the mutation to run when `query` declares multiple. + /// + /// Accepts the legacy field name `query_name` as a deserialization alias. + #[serde(default, alias = "query_name")] + pub name: Option, /// JSON object whose keys match the mutation's declared parameters. + #[serde(default)] pub params: Option, /// Target branch. Defaults to `main`. + #[serde(default)] pub branch: Option, } +/// Body for `POST /queries/{name}` — invokes the server-side stored query +/// named in the path. The query source and name come from the registry, +/// never the body; only the runtime inputs are supplied here. +#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)] +pub struct InvokeStoredQueryRequest { + /// JSON object whose keys match the stored query's declared parameters. + #[serde(default)] + pub params: Option, + /// Branch to run against. Defaults to `main`; for a stored mutation the + /// write targets this branch. + #[serde(default)] + pub branch: Option, + /// Snapshot id to read from (read queries only — rejected for a stored + /// mutation). Mutually exclusive with `branch`. + #[serde(default)] + pub snapshot: Option, +} + +/// Response for `POST /queries/{name}`: the read envelope for a stored +/// read, or the mutation envelope for a stored mutation. Serialized +/// **untagged**, so the wire shape is exactly [`ReadOutput`] or +/// [`ChangeOutput`] — classification follows the stored query, not a +/// wrapper field. +#[derive(Debug, Serialize, ToSchema)] +#[serde(untagged)] +pub enum InvokeStoredQueryResponse { + Read(ReadOutput), + Change(ChangeOutput), +} + +/// The kind of a stored-query parameter, decomposed so a client (e.g. an +/// MCP server) can build a typed input schema with a closed `match` and +/// never re-parse omnigraph's type spelling. `bigint`/`date`/`datetime`/ +/// `blob` are carried as JSON strings on the wire: a 64-bit integer past +/// 2^53 loses precision as a JSON number, and Date/DateTime are ISO +/// strings, Blob a blob-URI string. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ParamKind { + String, + Bool, + Int, + #[serde(rename = "bigint")] + BigInt, + Float, + Date, + #[serde(rename = "datetime")] + DateTime, + Blob, + Vector, + List, +} + +/// One declared parameter of a stored query, projected for the catalog. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ParamDescriptor { + pub name: String, + pub kind: ParamKind, + /// Element kind when `kind == list` (always a scalar — the grammar + /// forbids lists of vectors or nested lists). + #[serde(skip_serializing_if = "Option::is_none")] + pub item_kind: Option, + /// Dimension when `kind == vector`. + #[serde(skip_serializing_if = "Option::is_none")] + pub vector_dim: Option, + /// `false` → the caller must supply it; `true` → optional. + pub nullable: bool, +} + +/// One entry in the stored-query catalog (`GET /queries`). +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct QueryCatalogEntry { + /// Registry key / invoke path segment (`POST /queries/{name}`). + pub name: String, + /// MCP tool id (the `tool_name` override, else `name`). + pub tool_name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub instruction: Option, + /// `true` for a stored mutation → an MCP read-only hint of `false`. + pub mutation: bool, + pub params: Vec, +} + +/// Response for `GET /queries`: the `mcp.expose` subset of a graph's +/// stored-query registry, each with typed parameters. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct QueriesCatalogOutput { + pub queries: Vec, +} + +/// Total map from a resolved scalar to its catalog kind. Exhaustive on +/// purpose: a new `ScalarType` is a compile error here until catalogued. +fn scalar_kind(scalar: ScalarType) -> ParamKind { + match scalar { + ScalarType::String => ParamKind::String, + ScalarType::Bool => ParamKind::Bool, + ScalarType::I32 | ScalarType::U32 => ParamKind::Int, + ScalarType::I64 | ScalarType::U64 => ParamKind::BigInt, + ScalarType::F32 | ScalarType::F64 => ParamKind::Float, + ScalarType::Date => ParamKind::Date, + ScalarType::DateTime => ParamKind::DateTime, + ScalarType::Blob => ParamKind::Blob, + ScalarType::Vector(_) => ParamKind::Vector, + } +} + +fn param_descriptor(param: &Param) -> ParamDescriptor { + match PropType::from_param_type_name(¶m.type_name, param.nullable) { + Some(pt) if pt.list => ParamDescriptor { + name: param.name.clone(), + kind: ParamKind::List, + item_kind: Some(scalar_kind(pt.scalar)), + vector_dim: None, + nullable: param.nullable, + }, + Some(pt) => { + let (kind, vector_dim) = match pt.scalar { + ScalarType::Vector(dim) => (ParamKind::Vector, Some(dim)), + other => (scalar_kind(other), None), + }; + ParamDescriptor { + name: param.name.clone(), + kind, + item_kind: None, + vector_dim, + nullable: param.nullable, + } + } + // Unreachable for a parsed query (every declared param type is + // grammatical); fall back to an opaque string so the field is still + // usable rather than dropped. + None => ParamDescriptor { + name: param.name.clone(), + kind: ParamKind::String, + item_kind: None, + vector_dim: None, + nullable: param.nullable, + }, + } +} + +/// Project a loaded stored query into its catalog entry (typed params, +/// MCP tool name, read/mutate flag, description/instruction). +pub fn query_catalog_entry(query: &StoredQuery) -> QueryCatalogEntry { + QueryCatalogEntry { + name: query.name.clone(), + tool_name: query.effective_tool_name().to_string(), + description: query.decl.description.clone(), + instruction: query.decl.instruction.clone(), + mutation: query.is_mutation(), + params: query.decl.params.iter().map(param_descriptor).collect(), + } +} + #[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)] pub struct SchemaApplyRequest { /// Project schema in `.pg` source form. The diff against the current /// schema produces the migration steps that will be applied. - #[schema(example = "node Person {\n name: String @key\n age: I32?\n}\n\nedge Knows: Person -> Person")] + #[schema( + example = "node Person {\n name: String @key\n age: I32?\n}\n\nedge Knows: Person -> Person" + )] pub schema_source: String, /// When true, promote every `DropMode::Soft` step in the plan to /// `DropMode::Hard`, making the prior column data unreachable @@ -303,7 +502,9 @@ pub struct IngestRequest { pub mode: Option, /// NDJSON payload: one record per line, each shaped /// `{"type": "", "data": {...}}`. - #[schema(example = "{\"type\": \"Person\", \"data\": {\"name\": \"Alice\", \"age\": 30}}\n{\"type\": \"Person\", \"data\": {\"name\": \"Bob\", \"age\": 25}}")] + #[schema( + example = "{\"type\": \"Person\", \"data\": {\"name\": \"Alice\", \"age\": 30}}\n{\"type\": \"Person\", \"data\": {\"name\": \"Bob\", \"age\": 25}}" + )] pub data: String, } @@ -344,6 +545,11 @@ pub enum ErrorCode { Forbidden, BadRequest, NotFound, + /// 405 Method Not Allowed — the route exists but the active server + /// mode doesn't serve this method (e.g. `GET /graphs` in single-graph + /// mode). Distinct from 404 so clients can tell "wrong context" from + /// "no such resource." + MethodNotAllowed, Conflict, /// 429 Too Many Requests — per-actor admission cap exceeded. /// Clients should respect the `Retry-After` header. @@ -467,3 +673,23 @@ pub fn read_target_output(target: &ReadTarget) -> ReadTargetOutput { }, } } + +// ─── MR-668 — management endpoint shapes ────────────────────────────────── + +/// One entry in the response from `GET /graphs`. Cluster operators +/// consume this list to discover which graphs the server is currently +/// serving. The shape is intentionally minimal — `graph_id` and `uri` +/// are the only fields a routing client needs. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct GraphInfo { + pub graph_id: String, + pub uri: String, +} + +/// Response from `GET /graphs`. Lists every graph registered with the +/// server in alphabetical order by `graph_id` (sorted server-side so +/// clients get deterministic output across requests). +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct GraphListResponse { + pub graphs: Vec, +} diff --git a/crates/omnigraph-server/src/auth.rs b/crates/omnigraph-server/src/auth.rs index 80b6ed5..4f05228 100644 --- a/crates/omnigraph-server/src/auth.rs +++ b/crates/omnigraph-server/src/auth.rs @@ -119,7 +119,10 @@ pub(crate) fn parse_json_secret_payload(payload: &str) -> Result) -> Result { - let config = - aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; + let config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; let client = aws_sdk_secretsmanager::Client::new(&config); Ok(Self { client, @@ -200,8 +202,8 @@ pub use aws::SecretsManagerTokenSource; #[cfg(test)] mod tests { use super::*; - use std::env; use serial_test::serial; + use std::env; fn clear_env() { unsafe { @@ -232,7 +234,10 @@ mod tests { unsafe { env::remove_var("OMNIGRAPH_SERVER_BEARER_TOKEN"); } - assert_eq!(tokens, vec![("default".to_string(), "some-token".to_string())]); + assert_eq!( + tokens, + vec![("default".to_string(), "some-token".to_string())] + ); } #[tokio::test] diff --git a/crates/omnigraph-server/src/config.rs b/crates/omnigraph-server/src/config.rs index 7145ff2..b308b72 100644 --- a/crates/omnigraph-server/src/config.rs +++ b/crates/omnigraph-server/src/config.rs @@ -6,8 +6,16 @@ use std::path::{Path, PathBuf}; use clap::ValueEnum; use color_eyre::eyre::{Result, bail}; use serde::{Deserialize, Serialize}; + pub const DEFAULT_CONFIG_FILE: &str = "omnigraph.yaml"; +pub fn graph_resource_id_for_selection( + selected_graph: Option<&str>, + normalized_uri: &str, +) -> String { + selected_graph.unwrap_or(normalized_uri).to_string() +} + #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct ProjectConfig { pub name: Option, @@ -17,6 +25,20 @@ pub struct ProjectConfig { pub struct TargetConfig { pub uri: String, pub bearer_token_env: Option, + /// Per-graph Cedar policy file (MR-668). In single-graph mode this + /// field is unused — the top-level `policy.file` applies. In + /// multi-graph mode, each `graphs..policy.file` governs that + /// graph's HTTP-layer Cedar enforcement. + #[serde(default)] + pub policy: PolicySettings, + /// Per-graph stored-query registry: an inline `name -> entry` + /// map. Mirrors the per-graph `policy` shape — each + /// `graphs..queries` declares that graph's stored queries. Absent + /// (or empty) = no stored queries for the graph. v1 is inline-only; + /// an external `queries.yaml` manifest indirection is a deferred + /// convenience. + #[serde(default)] + pub queries: BTreeMap, } #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Serialize, Deserialize, ValueEnum)] @@ -59,6 +81,12 @@ pub struct ServerDefaults { #[serde(rename = "graph")] pub graph: Option, pub bind: Option, + /// Server-level Cedar policy (MR-668). Governs management endpoints + /// — currently `GET /graphs`; future runtime add/remove endpoints + /// will plug in here too. In single-graph mode this is unused — the + /// top-level `policy.file` covers the single graph. + #[serde(default)] + pub policy: PolicySettings, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -77,10 +105,63 @@ pub struct PolicySettings { pub file: Option, } +/// One stored-query registry entry. The map **key** is the query's +/// identity — it must equal the `query ` symbol declared inside +/// the referenced `.gq` file (asserted when the registry loads). +/// Renaming the key (or the symbol) is a breaking change to callers, by +/// design. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct QueryEntry { + /// Path to the `.gq` file (relative to the config's `base_dir`). The + /// file may declare several queries; the registry selects the one + /// whose symbol matches the map key. + pub file: String, + #[serde(default)] + pub mcp: McpSettings, +} + +/// MCP exposure for a stored query. A *deployment* concern (the same +/// `.gq` may be exposed in one graph and hidden in another), so it lives +/// in YAML rather than in the `.gq` source. **Default `expose: true`** — +/// declaring a query in the manifest *is* the opt-in, so it appears in the +/// MCP tool catalog (`GET /queries`) by default; set `expose: false` to +/// keep a query HTTP/service-callable but hidden from the agent tool list. +/// `expose` governs catalog membership only — it is **not** an +/// authorization gate (invocation is gated by `invoke_query`), so a hidden +/// query is still invocable by name with the right permission. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct McpSettings { + #[serde(default = "mcp_expose_default")] + pub expose: bool, + pub tool_name: Option, +} + +fn mcp_expose_default() -> bool { + true +} + +impl Default for McpSettings { + fn default() -> Self { + Self { + expose: mcp_expose_default(), + tool_name: None, + } + } +} + #[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AliasCommand { + /// Read alias (canonical: `query`). The legacy spelling `read` is + /// kept as the variant name for back-compat with serialized configs + /// and external SDK callers; `query` is accepted on the wire via the + /// serde alias. + #[serde(alias = "query")] Read, + /// Mutation alias (canonical: `mutate`). The legacy spelling `change` + /// is kept as the variant name for back-compat; `mutate` is accepted + /// on the wire via the serde alias. + #[serde(alias = "mutate")] Change, } @@ -115,6 +196,12 @@ pub struct OmnigraphConfig { pub aliases: BTreeMap, #[serde(default)] pub policy: PolicySettings, + /// Top-level stored-query registry, used in single-graph + /// mode — mirrors how the top-level `policy` applies to the single + /// graph. In multi-graph mode this is unused; each graph's + /// `graphs..queries` applies instead. + #[serde(default)] + pub queries: BTreeMap, #[serde(skip)] base_dir: PathBuf, } @@ -130,6 +217,7 @@ impl Default for OmnigraphConfig { query: QueryDefaults::default(), aliases: BTreeMap::new(), policy: PolicySettings::default(), + queries: BTreeMap::new(), base_dir: PathBuf::new(), } } @@ -197,23 +285,164 @@ impl OmnigraphConfig { } pub fn resolve_auth_env_file(&self) -> Option { - let path = self.auth.env_file.as_deref()?; - let path = Path::new(path); - Some(if path.is_absolute() { - path.to_path_buf() - } else { - self.base_dir.join(path) - }) + self.auth + .env_file + .as_deref() + .map(|path| self.resolve_config_path(path)) } pub fn resolve_policy_file(&self) -> Option { - let path = self.policy.file.as_deref()?; - let path = Path::new(path); - Some(if path.is_absolute() { - path.to_path_buf() - } else { - self.base_dir.join(path) - }) + self.policy + .file + .as_deref() + .map(|path| self.resolve_config_path(path)) + } + + /// Resolve the per-graph policy file path for the named target, + /// relative to the config file's `base_dir`. Returns `None` if the + /// target is unknown or no per-graph `policy.file` is set. + pub fn resolve_target_policy_file(&self, target_name: &str) -> Option { + let target = self.graphs.get(target_name)?; + target + .policy + .file + .as_deref() + .map(|path| self.resolve_config_path(path)) + } + + /// The top-level stored-query registry entries (single-graph mode). + pub fn query_entries(&self) -> &BTreeMap { + &self.queries + } + + /// The per-graph stored-query registry entries for a named target + /// (multi-graph mode). Returns `None` if the target is unknown. + pub fn target_query_entries( + &self, + target_name: &str, + ) -> Option<&BTreeMap> { + self.graphs.get(target_name).map(|target| &target.queries) + } + + /// The stored-query registry entries that apply for a graph + /// selection — the single definition of "which `queries:` block + /// governs graph X", shared by server boot and the CLI so the two + /// can't drift. A named graph present in `graphs:` uses its + /// per-graph block; everything else (no selection, or a name that is + /// not a known graph, e.g. a bare URI) falls back to the top-level + /// block (single-graph mode). + pub fn query_entries_for(&self, graph: Option<&str>) -> &BTreeMap { + match graph { + Some(name) if self.graphs.contains_key(name) => &self.graphs[name].queries, + _ => &self.queries, + } + } + + /// The single CLI gate that turns a raw graph selection into a *validated* + /// one — the fallible counterpart to the infallible + /// [`OmnigraphConfig::query_entries_for`]. Both `queries` subcommands route + /// their selection through here so neither can skip a check the other (or + /// server boot) applies: + /// * a known name passes through, but only after the same coherence check + /// server boot enforces + /// ([`OmnigraphConfig::ensure_top_level_blocks_honored`]) — a named graph + /// with a populated top-level block is rejected; + /// * an unknown name errors with the **same** message + /// [`OmnigraphConfig::resolve_target_uri`] produces, so a command that + /// opens no URI rejects an unknown `--target` exactly like the + /// URI-resolving commands do; + /// * an anonymous selection (`None`, e.g. a bare URI) stays anonymous, + /// resolving to the top-level registry downstream (top-level honored). + pub fn resolve_graph_selection<'a>(&self, graph: Option<&'a str>) -> Result> { + match graph { + Some(name) if self.graphs.contains_key(name) => { + self.ensure_top_level_blocks_honored(Some(name))?; + Ok(Some(name)) + } + Some(name) => bail!("graph '{}' not found in {}", name, DEFAULT_CONFIG_FILE), + None => Ok(None), + } + } + + pub fn resolve_policy_tooling_graph_selection(&self) -> Result> { + self.resolve_graph_selection(self.cli_graph_name().or_else(|| self.server_graph_name())) + } + + /// The policy file that applies for a graph selection — the policy + /// sibling of [`OmnigraphConfig::query_entries_for`], so policy and + /// queries resolve by the same identity rule. A named graph in + /// `graphs:` uses its per-graph `policy.file` with **no** top-level + /// fallback (a named graph with no per-graph policy has no policy — + /// that keeps the boot-time coherence check meaningful); anything else + /// (no selection, or a bare URI) uses the top-level `policy.file`. + pub fn resolve_policy_file_for(&self, graph: Option<&str>) -> Option { + match graph { + Some(name) if self.graphs.contains_key(name) => self.resolve_target_policy_file(name), + _ => self.resolve_policy_file(), + } + } + + /// Names of any top-level config blocks (`policy.file`, `queries:`) + /// that are populated. Used by the boot-time coherence check: when a + /// **named** graph is served (single-mode by name, or multi-mode), + /// the top-level blocks are not honored, so a populated one is a + /// configuration error rather than a silent no-op. + pub fn populated_top_level_blocks(&self) -> Vec<&'static str> { + let mut blocks = Vec::new(); + if self.policy.file.is_some() { + blocks.push("policy.file"); + } + if !self.queries.is_empty() { + blocks.push("queries"); + } + blocks + } + + /// A named graph uses its own `graphs.` block, so a populated + /// top-level block would be silently ignored — a config error. The single + /// definition of that rule, shared by server boot and the CLI selection + /// gate ([`OmnigraphConfig::resolve_graph_selection`]) so the two can't + /// drift. An anonymous selection (`None`, e.g. a bare URI) legitimately + /// honors the top-level blocks, so it is never rejected here. + pub fn ensure_top_level_blocks_honored(&self, selected: Option<&str>) -> Result<()> { + if let Some(name) = selected { + let unhonored = self.populated_top_level_blocks(); + if !unhonored.is_empty() { + bail!( + "named graph '{name}' uses its own `graphs.{name}.…` block, but top-level {} \ + {} set and would be ignored. Move it to `graphs.{name}` (e.g. \ + `graphs.{name}.policy.file`, `graphs.{name}.queries`).", + unhonored.join(" and "), + if unhonored.len() == 1 { "is" } else { "are" }, + ); + } + } + Ok(()) + } + + /// Resolve a stored-query `.gq` file path (from a registry entry), + /// relative to the config's `base_dir`. Mirrors policy-file + /// resolution; the registry loader calls this to turn each entry's + /// `file:` value into an absolute path. + pub fn resolve_query_file(&self, value: &str) -> PathBuf { + self.resolve_config_path(value) + } + + /// Resolve the server-level policy file path (used by management + /// endpoints). Returns `None` if `server.policy.file` is not set. + pub fn resolve_server_policy_file(&self) -> Option { + self.server + .policy + .file + .as_deref() + .map(|path| self.resolve_config_path(path)) + } + + /// Resolve a raw config-supplied URI (which may be relative) to its + /// absolute form. URIs containing `://` are passed through as-is; + /// relative paths are joined with the config file's `base_dir`. + pub fn resolve_uri_value(&self, value: &str) -> String { + self.resolve_config_uri(value) } pub fn resolve_policy_tests_file(&self) -> Option { @@ -282,6 +511,15 @@ impl OmnigraphConfig { self.base_dir.join(path).to_string_lossy().to_string() } } + + fn resolve_config_path(&self, value: &str) -> PathBuf { + let path = Path::new(value); + if path.is_absolute() { + path.to_path_buf() + } else { + self.base_dir.join(path) + } + } } pub fn default_config_path() -> PathBuf { @@ -333,7 +571,9 @@ mod tests { use tempfile::tempdir; - use super::{ReadOutputFormat, TableCellLayout, load_config_in}; + use super::{ + ReadOutputFormat, TableCellLayout, graph_resource_id_for_selection, load_config_in, + }; #[test] fn load_config_reads_yaml_defaults_from_current_dir() { @@ -397,6 +637,114 @@ policy: {} assert!(config.graphs.is_empty()); } + #[test] + fn graph_resource_id_for_selection_uses_name_or_anonymous_uri() { + assert_eq!( + graph_resource_id_for_selection(Some("local"), "/tmp/graph.omni"), + "local" + ); + assert_eq!( + graph_resource_id_for_selection(None, "/tmp/graph.omni"), + "/tmp/graph.omni" + ); + } + + #[test] + fn resolve_graph_selection_validates_membership_and_coherence() { + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + "graphs:\n local:\n uri: ./demo.omni\n", + ) + .unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); + + // A known graph passes through unchanged. + assert_eq!(config.resolve_graph_selection(Some("local")).unwrap(), Some("local")); + // An anonymous selection stays anonymous (→ top-level registry downstream). + assert_eq!(config.resolve_graph_selection(None).unwrap(), None); + // An unknown name errors, naming the graph (matching resolve_target_uri). + let err = config.resolve_graph_selection(Some("ghost")).unwrap_err().to_string(); + assert!( + err.contains("ghost") && err.contains("not found"), + "unknown graph must error naming it: {err}" + ); + + // Coherence: a named graph plus a populated top-level block is the + // config server boot refuses, so the gate rejects it too (shared rule + // via ensure_top_level_blocks_honored). An anonymous selection still + // passes — top-level is honored when no graph is named. + let temp2 = tempdir().unwrap(); + fs::write( + temp2.path().join("omnigraph.yaml"), + "graphs:\n local:\n uri: ./demo.omni\npolicy:\n file: ./top.yaml\n", + ) + .unwrap(); + let incoherent = load_config_in(temp2.path(), None).unwrap(); + let err = incoherent + .resolve_graph_selection(Some("local")) + .unwrap_err() + .to_string(); + assert!( + err.contains("local") && err.contains("policy.file"), + "named graph + populated top-level block must be rejected, naming both: {err}" + ); + assert_eq!( + incoherent.resolve_graph_selection(None).unwrap(), + None, + "anonymous selection still honors top-level" + ); + } + + #[test] + fn policy_tooling_graph_selection_prefers_cli_then_server_and_validates() { + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + "graphs:\n local:\n uri: ./local.omni\n prod:\n uri: ./prod.omni\n\ + server:\n graph: local\ncli:\n graph: prod\n", + ) + .unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); + assert_eq!( + config.resolve_policy_tooling_graph_selection().unwrap(), + Some("prod") + ); + + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + "graphs:\n local:\n uri: ./local.omni\nserver:\n graph: local\n", + ) + .unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); + assert_eq!( + config.resolve_policy_tooling_graph_selection().unwrap(), + Some("local") + ); + + let temp = tempdir().unwrap(); + fs::write(temp.path().join("omnigraph.yaml"), "policy: {}\n").unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); + assert_eq!(config.resolve_policy_tooling_graph_selection().unwrap(), None); + + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + "graphs:\n local:\n uri: ./local.omni\nserver:\n graph: ghost\n", + ) + .unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); + let err = config + .resolve_policy_tooling_graph_selection() + .unwrap_err() + .to_string(); + assert!( + err.contains("ghost") && err.contains("not found"), + "unknown server.graph must use graph-selection validation: {err}" + ); + } + #[test] fn resolve_query_path_searches_config_roots() { let temp = tempdir().unwrap(); @@ -435,6 +783,118 @@ policy: {} assert_eq!(resolved, config_dir.join("local.gq")); } + #[test] + fn queries_block_round_trips_inline_and_per_graph() { + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + r#" +graphs: + prod: + uri: s3://bucket/prod + queries: + find_user: + file: ./queries/find_user.gq + mcp: + expose: true + tool_name: lookup_user + internal_audit: + file: ./queries/audit.gq +queries: + single_mode_q: + file: ./q.gq +"#, + ) + .unwrap(); + + let config = load_config_in(temp.path(), None).unwrap(); + + // Per-graph registry (multi-graph mode). + let prod = config.target_query_entries("prod").unwrap(); + assert_eq!(prod.len(), 2); + let find_user = &prod["find_user"]; + assert_eq!(find_user.file, "./queries/find_user.gq"); + assert!(find_user.mcp.expose); + assert_eq!(find_user.mcp.tool_name.as_deref(), Some("lookup_user")); + // Default exposure is true (the manifest entry is the opt-in); tool_name absent. + let audit = &prod["internal_audit"]; + assert!(audit.mcp.expose); + assert!(audit.mcp.tool_name.is_none()); + + // Top-level registry (single-graph mode). + assert_eq!(config.query_entries().len(), 1); + + // The shared selector resolves the same blocks the server boot + // and the CLI use: a known graph → its per-graph block; no + // selection or an unknown name → the top-level block (the latter + // pins the behavior of the CLI's now-deleted fallback arm). + assert_eq!(config.query_entries_for(Some("prod")).len(), 2); + assert_eq!(config.query_entries_for(None).len(), 1); + assert_eq!(config.query_entries_for(Some("nonexistent")).len(), 1); + + // Path resolution joins against base_dir, like policy files. + assert_eq!( + config.resolve_query_file(&find_user.file), + temp.path().join("./queries/find_user.gq") + ); + } + + #[test] + fn resolve_policy_file_for_follows_identity() { + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + "policy:\n file: ./top.yaml\ngraphs:\n prod:\n uri: s3://b/prod\n \ + policy:\n file: ./prod.yaml\n bare:\n uri: s3://b/bare\n", + ) + .unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); + + // Named graph with its own policy → per-graph (not top-level). + assert!( + config + .resolve_policy_file_for(Some("prod")) + .unwrap() + .ends_with("prod.yaml") + ); + // Named graph with NO per-graph policy → None (no top-level fallback; + // load-bearing for the boot coherence check). + assert!(config.resolve_policy_file_for(Some("bare")).is_none()); + // Anonymous (bare URI) or an unknown name → top-level. + assert!( + config + .resolve_policy_file_for(None) + .unwrap() + .ends_with("top.yaml") + ); + assert!( + config + .resolve_policy_file_for(Some("nope")) + .unwrap() + .ends_with("top.yaml") + ); + } + + #[test] + fn queries_block_absent_yields_empty_registry() { + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + "graphs:\n local:\n uri: ./demo.omni\n", + ) + .unwrap(); + + let config = load_config_in(temp.path(), None).unwrap(); + // Additive: no `queries:` anywhere → empty registries everywhere. + assert!(config.query_entries().is_empty()); + assert!( + config + .target_query_entries("local") + .unwrap() + .is_empty() + ); + } + #[test] fn policy_block_accepts_non_empty_mapping() { let temp = tempdir().unwrap(); diff --git a/crates/omnigraph-server/src/graph_id.rs b/crates/omnigraph-server/src/graph_id.rs new file mode 100644 index 0000000..ffccd2a --- /dev/null +++ b/crates/omnigraph-server/src/graph_id.rs @@ -0,0 +1,254 @@ +//! `GraphId` — registry-level identity for a graph in multi-graph mode (MR-668). +//! +//! Validation lives in `GraphId::try_from(String)`; nothing else can construct a +//! `GraphId`. The newtype prevents `graph_id` strings from escaping the storage +//! root via path traversal or colliding with engine-reserved filenames. +//! +//! Regex: `^[a-zA-Z0-9-]{1,64}$` +//! +//! The engine reserves every filename starting with `_` at the graph root +//! (`_schema.pg`, `_schema.ir.json`, `__schema_state.json`, `__manifest/`, +//! `__recovery/`, etc.). Disallowing leading underscores at the regex level +//! means a `graph_id` can never collide with engine-managed files. Path +//! traversal (`..`, `/`) is unrepresentable. +//! +//! `policies` is additionally reserved as a future-proofing measure for a +//! potential `/graphs/policies/...` cluster route. + +use std::fmt; +use std::sync::OnceLock; + +use color_eyre::eyre::{Result, bail}; +use regex::Regex; +use serde::{Deserialize, Serialize}; + +/// Maximum length of a `GraphId` value. +pub const GRAPH_ID_MAX_LEN: usize = 64; + +/// Validated registry-level identity for a graph. +/// +/// Constructed only via `GraphId::try_from(String)` or +/// `GraphId::try_from(&str)`. The inner `String` is private to enforce the +/// validation contract. +#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] +#[serde(transparent)] +pub struct GraphId(String); + +impl GraphId { + /// View the validated identifier as `&str`. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for GraphId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl AsRef for GraphId { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl TryFrom for GraphId { + type Error = color_eyre::eyre::Error; + + fn try_from(value: String) -> Result { + validate(value.as_str())?; + Ok(Self(value)) + } +} + +impl TryFrom<&str> for GraphId { + type Error = color_eyre::eyre::Error; + + fn try_from(value: &str) -> Result { + validate(value)?; + Ok(Self(value.to_string())) + } +} + +// Custom Deserialize that re-runs validation. Otherwise a serde-derived impl +// would accept any String, defeating the newtype's guarantee. +impl<'de> Deserialize<'de> for GraphId { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + Self::try_from(s).map_err(serde::de::Error::custom) + } +} + +fn validate(value: &str) -> Result<()> { + if value.is_empty() { + bail!("graph_id must not be empty"); + } + if value.len() > GRAPH_ID_MAX_LEN { + bail!( + "graph_id '{}' is {} chars; max {}", + value, + value.len(), + GRAPH_ID_MAX_LEN + ); + } + if !regex().is_match(value) { + bail!( + "graph_id '{}' must match ^[a-zA-Z0-9-]{{1,64}}$ — \ + no underscores (engine reserves them), no path separators, no unicode", + value + ); + } + if is_reserved(value) { + bail!( + "graph_id '{}' is reserved (would collide with engine-managed names or \ + future cluster routes)", + value + ); + } + Ok(()) +} + +fn regex() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| Regex::new(r"^[a-zA-Z0-9-]{1,64}$").expect("regex literal")) +} + +/// Reserved `graph_id` values that the regex alone wouldn't catch. +/// The leading-underscore rule already excludes every engine-managed +/// filename pattern (`_schema.pg`, `__manifest`, etc.); the regex +/// `^[a-zA-Z0-9-]{1,64}$` (see `regex()`) additionally rejects every +/// dot-containing name structurally — `openapi.json` and friends +/// never reach this check. +/// +/// This list only needs to cover route-prefix collisions and +/// top-level endpoint names whose spellings DO satisfy the regex +/// (no dots, no underscores). +fn is_reserved(value: &str) -> bool { + matches!(value, "policies" | "healthz" | "openapi" | "graphs") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_simple_alphanumeric_ids() { + for ok in ["alpha", "beta", "tenant-001", "A", "g", "X-9-z"] { + GraphId::try_from(ok).unwrap_or_else(|_| panic!("expected accept: {ok}")); + } + } + + #[test] + fn accepts_64_char_max() { + let max = "a".repeat(64); + GraphId::try_from(max.as_str()).unwrap(); + } + + #[test] + fn rejects_empty() { + assert!(GraphId::try_from("").is_err()); + } + + #[test] + fn rejects_over_64_chars() { + let too_long = "a".repeat(65); + assert!(GraphId::try_from(too_long.as_str()).is_err()); + } + + #[test] + fn rejects_leading_underscore() { + // Engine reserves every `_*` filename at the graph root. + assert!(GraphId::try_from("_internal").is_err()); + assert!(GraphId::try_from("__manifest").is_err()); + } + + #[test] + fn rejects_underscores_anywhere() { + // The regex doesn't allow `_` at all — keeps the disallow-leading-`_` + // rule cheap to enforce. If the rule changes later, we'd need to + // distinguish "starts with `_`" from "contains `_`". + assert!(GraphId::try_from("tenant_alpha").is_err()); + } + + #[test] + fn rejects_path_separators() { + for bad in ["alpha/beta", "../etc", "..", "alpha\\beta"] { + assert!(GraphId::try_from(bad).is_err(), "expected reject: {bad}"); + } + } + + #[test] + fn rejects_unicode() { + assert!(GraphId::try_from("αlpha").is_err()); + assert!(GraphId::try_from("graph-✨").is_err()); + } + + #[test] + fn rejects_whitespace() { + assert!(GraphId::try_from(" alpha").is_err()); + assert!(GraphId::try_from("alpha ").is_err()); + assert!(GraphId::try_from("alpha beta").is_err()); + assert!(GraphId::try_from("\talpha").is_err()); + } + + #[test] + fn rejects_dots() { + // Reserves the "extension"-shaped ids that look like filenames. + assert!(GraphId::try_from(".").is_err()); + assert!(GraphId::try_from("alpha.beta").is_err()); + assert!(GraphId::try_from("alpha.").is_err()); + } + + #[test] + fn rejects_reserved_route_names() { + // Names that satisfy the regex but are still reserved because + // they'd collide with top-level route prefixes / endpoint names. + // Dot-containing names (e.g. `openapi.json`) are rejected by the + // regex, not this list — `rejects_dots` above covers them. + for bad in ["policies", "healthz", "openapi", "graphs"] { + assert!( + GraphId::try_from(bad).is_err(), + "expected reject (reserved): {bad}" + ); + } + } + + #[test] + fn display_returns_inner_string() { + let id = GraphId::try_from("alpha").unwrap(); + assert_eq!(format!("{id}"), "alpha"); + assert_eq!(id.as_str(), "alpha"); + } + + #[test] + fn serialize_round_trips_via_json() { + let id = GraphId::try_from("tenant-007").unwrap(); + let json = serde_json::to_string(&id).unwrap(); + assert_eq!(json, "\"tenant-007\""); + let back: GraphId = serde_json::from_str(&json).unwrap(); + assert_eq!(back, id); + } + + #[test] + fn deserialize_runs_validation() { + // Hostile payload must not produce a GraphId. + let bad = serde_json::from_str::("\"_evil\""); + assert!(bad.is_err()); + let bad = serde_json::from_str::("\"../../etc\""); + assert!(bad.is_err()); + } + + #[test] + fn hash_equality_works_for_use_as_map_key() { + use std::collections::HashMap; + let a = GraphId::try_from("alpha").unwrap(); + let b = GraphId::try_from("alpha").unwrap(); + let mut m = HashMap::new(); + m.insert(a, 1u32); + assert_eq!(m.get(&b), Some(&1)); + } +} diff --git a/crates/omnigraph-server/src/identity.rs b/crates/omnigraph-server/src/identity.rs new file mode 100644 index 0000000..250640d --- /dev/null +++ b/crates/omnigraph-server/src/identity.rs @@ -0,0 +1,308 @@ +//! Identity types for the multi-graph server (MR-668) + forward-compatible +//! shapes for Cloud mode (RFC 0003) and OAuth provider (RFC 0004). +//! +//! Per decision 13 in the implementation plan: ship the type shapes that +//! Cloud mode will consume, without committing to any trait shape +//! (`TokenVerifier` stays draft in RFC 0001). Every Cluster-mode call site +//! constructs these types with their Cluster-mode-specific values: +//! +//! - `tenant_id: None` (Cloud will set `Some(...)` from the OAuth `org_id` claim) +//! - `scopes: vec![Scope::Full]` (Cloud will populate from the OAuth `scope` claim) +//! - `source: AuthSource::Static` (Cloud / OIDC will set `AuthSource::Oidc`) +//! +//! The enums use `#[non_exhaustive]` so RFC 0001 step 1 / RFC 0004 can +//! add variants without breaking exhaustive matches in callers. + +use std::fmt; +use std::sync::Arc; +use std::sync::OnceLock; + +use color_eyre::eyre::{Result, bail}; +use regex::Regex; +use serde::{Deserialize, Serialize}; + +use crate::graph_id::GraphId; + +/// Maximum length of a `TenantId` value. +pub const TENANT_ID_MAX_LEN: usize = 64; + +/// Cloud-mode tenant identifier. Validated with the same regex as +/// `GraphId` so the two interchange syntactically. +/// +/// `None` in Cluster mode; Cloud mode (RFC 0003) sets `Some(...)` from +/// the OAuth `org_id` claim. Constructed only via `try_from` so callers +/// cannot bypass validation. +#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)] +#[serde(transparent)] +pub struct TenantId(String); + +impl TenantId { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for TenantId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl AsRef for TenantId { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl TryFrom for TenantId { + type Error = color_eyre::eyre::Error; + + fn try_from(value: String) -> Result { + validate_tenant_id(value.as_str())?; + Ok(Self(value)) + } +} + +impl TryFrom<&str> for TenantId { + type Error = color_eyre::eyre::Error; + + fn try_from(value: &str) -> Result { + validate_tenant_id(value)?; + Ok(Self(value.to_string())) + } +} + +impl<'de> Deserialize<'de> for TenantId { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + Self::try_from(s).map_err(serde::de::Error::custom) + } +} + +fn validate_tenant_id(value: &str) -> Result<()> { + if value.is_empty() { + bail!("tenant_id must not be empty"); + } + if value.len() > TENANT_ID_MAX_LEN { + bail!( + "tenant_id '{}' is {} chars; max {}", + value, + value.len(), + TENANT_ID_MAX_LEN + ); + } + if !tenant_id_regex().is_match(value) { + bail!("tenant_id '{}' must match ^[a-zA-Z0-9-]{{1,64}}$", value); + } + Ok(()) +} + +fn tenant_id_regex() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| Regex::new(r"^[a-zA-Z0-9-]{1,64}$").expect("regex literal")) +} + +/// Registry HashMap key. Cluster mode populates `tenant_id: None`; +/// Cloud mode (RFC 0003) populates `tenant_id: Some(...)`. +/// +/// The `Option` field is the **single forward-compatibility seam** +/// between Cluster and Cloud modes. Every handler reaches the engine via +/// `state.registry.get(&key)` — the key shape stays stable, so handlers +/// don't get re-touched when Cloud mode lands. +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +pub struct GraphKey { + pub tenant_id: Option, + pub graph_id: GraphId, +} + +impl GraphKey { + /// Cluster-mode constructor (`tenant_id: None`). + pub fn cluster(graph_id: GraphId) -> Self { + Self { + tenant_id: None, + graph_id, + } + } + + /// Cloud-mode constructor — reserved for RFC 0003; included here so + /// the seam is visible even though no Cluster-mode code path calls it. + pub fn cloud(tenant_id: TenantId, graph_id: GraphId) -> Self { + Self { + tenant_id: Some(tenant_id), + graph_id, + } + } +} + +impl fmt::Display for GraphKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.tenant_id { + Some(t) => write!(f, "{}/{}", t, self.graph_id), + None => write!(f, "{}", self.graph_id), + } + } +} + +/// Authorization scope. Cluster mode: every authenticated actor gets +/// `Scope::Full`. Cloud mode (RFC 0004) adds OAuth-style scopes via the +/// dashboard-configured `graph:read`, `graph:write`, `graph:admin`, +/// `graph:*` set; those become additional variants here. +/// +/// `#[non_exhaustive]` so RFC 0004 can extend without breaking matches. +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] +#[non_exhaustive] +pub enum Scope { + /// Full access. The Cluster-mode default — every authenticated actor + /// has unrestricted access subject to Cedar policy. + Full, +} + +/// How the actor was authenticated. Cluster mode: every actor authenticates +/// via the existing SHA-256 hash compare against a static token set, so +/// `AuthSource::Static`. RFC 0001 step 1 adds `AuthSource::Oidc` when the +/// `OidcJwtVerifier` ships. +/// +/// `#[non_exhaustive]` so RFC 0001 can extend without breaking matches. +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] +#[non_exhaustive] +pub enum AuthSource { + /// Authenticated via the static bearer-token hash table. + Static, +} + +/// Server-resolved actor identity. Replaces the previous +/// `AuthenticatedActor(Arc)` from `lib.rs`. +/// +/// The fields are populated by `authenticate_bearer_token` after a successful +/// constant-time hash match. **Clients cannot set any of these fields directly** +/// — this is the MR-731 invariant. See `authorize_request` in `lib.rs` for the +/// chokepoint that overwrites any client-supplied actor identity. +/// +/// Cluster mode constructs this with `tenant_id: None`, `scopes: vec![Scope::Full]`, +/// `source: AuthSource::Static` via the convenience constructor below. +#[derive(Debug, Clone)] +pub struct ResolvedActor { + pub actor_id: Arc, + pub tenant_id: Option, + pub scopes: Vec, + pub source: AuthSource, +} + +impl ResolvedActor { + /// Cluster-mode constructor — Static auth, no tenant, Full scope. + /// Used by `authenticate_bearer_token` after a successful hash match. + pub fn cluster_static(actor_id: Arc) -> Self { + Self { + actor_id, + tenant_id: None, + scopes: vec![Scope::Full], + source: AuthSource::Static, + } + } + + /// View the actor identifier as `&str`. Stable across the Cluster/Cloud + /// boundary — Cedar always sees this value as the principal. + pub fn actor_id_str(&self) -> &str { + &self.actor_id + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tenant_id_accepts_simple_values() { + for ok in ["alpha", "tenant-001", "X", "01HZWA0KT0H0V0V0V0V0V0V0V0"] { + TenantId::try_from(ok).unwrap_or_else(|_| panic!("expected accept: {ok}")); + } + } + + #[test] + fn tenant_id_rejects_empty_and_over_max() { + assert!(TenantId::try_from("").is_err()); + let too_long = "a".repeat(65); + assert!(TenantId::try_from(too_long.as_str()).is_err()); + } + + #[test] + fn tenant_id_rejects_path_traversal() { + assert!(TenantId::try_from("../etc").is_err()); + assert!(TenantId::try_from("alpha/beta").is_err()); + } + + #[test] + fn tenant_id_deserialize_runs_validation() { + let bad: Result = serde_json::from_str("\"../evil\""); + assert!(bad.is_err()); + } + + #[test] + fn graph_key_cluster_constructor_sets_no_tenant() { + let id = GraphId::try_from("alpha").unwrap(); + let key = GraphKey::cluster(id.clone()); + assert!(key.tenant_id.is_none()); + assert_eq!(key.graph_id, id); + } + + #[test] + fn graph_key_cloud_constructor_sets_tenant() { + let tenant = TenantId::try_from("acme").unwrap(); + let id = GraphId::try_from("alpha").unwrap(); + let key = GraphKey::cloud(tenant.clone(), id.clone()); + assert_eq!(key.tenant_id.as_ref(), Some(&tenant)); + assert_eq!(key.graph_id, id); + } + + #[test] + fn graph_key_displays_with_or_without_tenant() { + let id = GraphId::try_from("alpha").unwrap(); + let cluster_key = GraphKey::cluster(id.clone()); + assert_eq!(format!("{cluster_key}"), "alpha"); + + let tenant = TenantId::try_from("acme").unwrap(); + let cloud_key = GraphKey::cloud(tenant, id); + assert_eq!(format!("{cloud_key}"), "acme/alpha"); + } + + #[test] + fn graph_key_is_hashable_for_map_use() { + use std::collections::HashMap; + let a = GraphKey::cluster(GraphId::try_from("alpha").unwrap()); + let b = GraphKey::cluster(GraphId::try_from("alpha").unwrap()); + let mut m: HashMap = HashMap::new(); + m.insert(a, 1); + assert_eq!(m.get(&b), Some(&1)); + } + + #[test] + fn graph_key_distinguishes_tenants() { + let id = GraphId::try_from("alpha").unwrap(); + let t1 = TenantId::try_from("acme").unwrap(); + let t2 = TenantId::try_from("globex").unwrap(); + let k1 = GraphKey::cloud(t1, id.clone()); + let k2 = GraphKey::cloud(t2, id); + assert_ne!(k1, k2); + } + + #[test] + fn resolved_actor_cluster_defaults() { + let actor = ResolvedActor::cluster_static(Arc::::from("act-alice")); + assert_eq!(actor.actor_id_str(), "act-alice"); + assert!(actor.tenant_id.is_none()); + assert_eq!(actor.scopes, vec![Scope::Full]); + assert_eq!(actor.source, AuthSource::Static); + } + + #[test] + fn scope_and_auth_source_are_non_exhaustive() { + // Regression: keep the `#[non_exhaustive]` annotation. If someone + // removes it, this test still passes (matches are still legal); it's + // the cross-crate compile that catches it. Document the contract here. + let _scope = Scope::Full; + let _src = AuthSource::Static; + } +} diff --git a/crates/omnigraph-server/src/lib.rs b/crates/omnigraph-server/src/lib.rs index 0ab2249..60ebef3 100644 --- a/crates/omnigraph-server/src/lib.rs +++ b/crates/omnigraph-server/src/lib.rs @@ -1,9 +1,19 @@ pub mod api; pub mod auth; pub mod config; +pub mod graph_id; +pub mod identity; pub mod policy; +pub mod queries; +pub mod registry; pub mod workload; +pub use graph_id::GraphId; +pub use identity::{AuthSource, GraphKey, ResolvedActor, Scope, TenantId}; +pub use registry::{GraphHandle, GraphRegistry, InsertError, RegistryLookup, RegistrySnapshot}; + +use crate::queries::{QueryRegistry, check, format_check_breakages}; + use std::collections::{HashMap, HashSet}; use std::fs; use std::io; @@ -14,15 +24,18 @@ use std::sync::Arc; use api::{ BranchCreateOutput, BranchCreateRequest, BranchDeleteOutput, BranchListOutput, BranchMergeOutput, BranchMergeRequest, ChangeOutput, ChangeRequest, CommitListOutput, - CommitListQuery, ErrorCode, ErrorOutput, ExportRequest, HealthOutput, IngestOutput, - IngestRequest, ReadOutput, ReadRequest, SchemaApplyOutput, SchemaApplyRequest, SchemaOutput, - SnapshotQuery, ingest_output, schema_apply_output, snapshot_payload, + CommitListQuery, ErrorCode, ErrorOutput, ExportRequest, GraphInfo, GraphListResponse, + HealthOutput, IngestOutput, IngestRequest, InvokeStoredQueryRequest, + InvokeStoredQueryResponse, QueriesCatalogOutput, QueryRequest, ReadOutput, ReadRequest, + SchemaApplyOutput, SchemaApplyRequest, SchemaOutput, SnapshotQuery, ingest_output, + schema_apply_output, snapshot_payload, }; +pub use auth::{AWS_SECRET_ENV, EnvOrFileTokenSource, TokenSource, resolve_token_source}; use axum::body::{Body, Bytes}; use axum::extract::DefaultBodyLimit; -use axum::extract::{Extension, Path, Query, Request, State}; +use axum::extract::{Extension, OriginalUri, Path, Query, Request, State}; use axum::http::StatusCode; -use axum::http::header::{AUTHORIZATION, CONTENT_TYPE}; +use axum::http::header::{AUTHORIZATION, CONTENT_TYPE, HeaderName, HeaderValue}; use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post}; @@ -31,19 +44,21 @@ use color_eyre::eyre::{Result, WrapErr, bail}; pub use config::{ AliasCommand, AliasConfig, CliDefaults, DEFAULT_CONFIG_FILE, OmnigraphConfig, PolicySettings, ProjectConfig, QueryDefaults, ReadOutputFormat, ServerDefaults, TableCellLayout, TargetConfig, - load_config, + graph_resource_id_for_selection, load_config, }; use futures::stream; use omnigraph::db::{Omnigraph, ReadTarget}; use omnigraph::error::{ManifestConflictDetails, ManifestErrorKind, OmniError}; +use omnigraph::storage::normalize_root_uri; +use omnigraph_compiler::catalog::Catalog; use omnigraph_compiler::json_params_to_param_map; use omnigraph_compiler::query::parser::parse_query; use omnigraph_compiler::{JsonParamMode, ParamMap}; -pub use auth::{AWS_SECRET_ENV, EnvOrFileTokenSource, TokenSource, resolve_token_source}; pub use policy::{ PolicyAction, PolicyCompiler, PolicyConfig, PolicyDecision, PolicyEngine, PolicyExpectation, - PolicyRequest, PolicyTestConfig, + PolicyRequest, PolicyResourceKind, PolicyTestConfig, }; +use serde::Deserialize; use serde_json::Value; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; @@ -53,6 +68,8 @@ use tower_http::trace::TraceLayer; use tracing::{error, info, warn}; use tracing_subscriber::EnvFilter; use utoipa::OpenApi; +use utoipa::openapi::path::{Parameter, ParameterIn}; +use utoipa::openapi::schema::{Object, Type}; use utoipa::openapi::security::{Http, HttpAuthScheme, SecurityScheme}; type BearerTokenHash = [u8; 32]; @@ -72,10 +89,17 @@ fn hash_bearer_token(token: &str) -> BearerTokenHash { ), paths( server_health, + server_graphs_list, server_snapshot, - server_read, + // deprecated; the #[deprecated] attribute on the handler + // surfaces as `deprecated: true` on the OpenAPI operation. + #[allow(deprecated)] server_read, + server_query, server_export, - server_change, + #[allow(deprecated)] server_change, + server_mutate, + server_list_queries, + server_invoke_query, server_schema_apply, server_schema_get, server_ingest, @@ -111,9 +135,13 @@ const SERVER_SOURCE_VERSION: Option<&str> = option_env!("OMNIGRAPH_SOURCE_VERSIO #[derive(Debug, Clone)] pub struct ServerConfig { - pub uri: String, + /// Server topology + the graphs to open at startup. Single-mode + /// invocations (`omnigraph-server ` or `--target `) + /// produce `ServerConfigMode::Single`; multi-mode invocations + /// (`--config omnigraph.yaml` with a non-empty `graphs:` map and + /// no single-mode selector) produce `ServerConfigMode::Multi`. + pub mode: ServerConfigMode, pub bind: String, - pub policy_file: Option, /// Operator opt-in for fully-unauthenticated dev mode (MR-723). /// When neither bearer tokens nor a policy file are configured, /// `serve()` refuses to start unless this is true (set via @@ -125,23 +153,112 @@ pub struct ServerConfig { pub allow_unauthenticated: bool, } -#[derive(Clone)] -pub struct AppState { - uri: String, - /// PR 2 (MR-686): the engine is now `Arc` — no global - /// write lock. Concurrent handlers call `&self` engine APIs - /// directly. Per-(table, branch) write queues inside the engine - /// serialize same-key writers; per-actor admission control on - /// `workload` isolates noisy actors. - engine: Arc, - /// Per-actor admission control. See `workload::WorkloadController`. - workload: Arc, - bearer_tokens: Arc<[(BearerTokenHash, Arc)]>, - policy_engine: Option>, +/// What `load_server_settings` produces after applying the four-rule +/// mode inference matrix (MR-668 decision 2). +#[derive(Debug, Clone)] +pub enum ServerConfigMode { + /// Legacy invocation — one graph at the given URI. Either: + /// * `omnigraph-server ` (CLI positional), or + /// * `omnigraph-server --target --config omnigraph.yaml`, or + /// * `omnigraph-server --config omnigraph.yaml` with `server.graph` + /// set to a named target. + Single { + uri: String, + /// Cedar graph resource id for the single graph. A named selection + /// uses the graph name; an anonymous URI uses the normalized URI to + /// preserve legacy single-graph policy identity. + graph_id: String, + /// Top-level `policy.file` (single-graph Cedar policy). + policy_file: Option, + /// Top-level stored-query registry, loaded and identity-checked + /// at settings-build time; type-checked against the schema when + /// the engine opens. + queries: QueryRegistry, + }, + /// Multi-graph invocation — `--config omnigraph.yaml` with a + /// non-empty `graphs:` map and no single-mode selector. + Multi { + /// Per-graph startup configs, sorted by graph id (BTreeMap + /// iteration order). The parallel-open loop iterates this. + graphs: Vec, + /// Path to the config file the server was started from. Kept on + /// the mode so future runtime mutation (deferred — see release + /// notes) can locate the source of truth without re-parsing CLI + /// args. + config_path: PathBuf, + /// `server.policy.file` (server-level Cedar policy for the + /// management endpoints). Wired into `GET /graphs` authorization. + server_policy_file: Option, + }, } +/// One graph's startup-time configuration: id, opened URI, optional +/// per-graph policy file path. Constructed by `load_server_settings` +/// in multi mode; consumed by `serve`'s parallel open loop. #[derive(Debug, Clone)] -struct AuthenticatedActor(Arc); +pub struct GraphStartupConfig { + pub graph_id: String, + pub uri: String, + pub policy_file: Option, + /// Per-graph stored-query registry, loaded and identity-checked at + /// settings-build time; type-checked against the schema when this + /// graph's engine opens. + pub queries: QueryRegistry, +} + +/// Runtime routing for the server. Single mode = legacy +/// `omnigraph-server ` invocation, one graph, flat HTTP routes. +/// Multi mode = `--config omnigraph.yaml` with a non-empty `graphs:` +/// map, N graphs, cluster routes (`/graphs/{graph_id}/...`). Mode is +/// determined at startup by `load_server_settings`. +/// +/// In single mode the handle lives here directly — there is no +/// registry, no sentinel key, no walk-and-assert. In multi mode the +/// registry carries N handles and the middleware dispatches on the +/// URL's `{graph_id}` segment. +/// +/// Both modes share the same handler bodies — the routing middleware +/// (`resolve_graph_handle`) injects `Arc` as a request +/// extension so handlers never see the routing discriminator. +#[derive(Clone)] +pub enum GraphRouting { + /// Single-graph deployment: one handle, flat routes (`/snapshot`, + /// `/read`, …). The `handle.uri` field carries the URI the engine + /// was opened from. Backward compatible with v0.6.0 deployments. + Single { handle: Arc }, + /// Multi-graph deployment: many handles, cluster routes + /// (`/graphs/{graph_id}/...`). `config_path` is the `omnigraph.yaml` + /// the server reads at startup; preserved here so future runtime + /// mutation (deferred) can find the source of truth without + /// re-parsing CLI args. The server treats the file as + /// operator-owned and never writes it. + Multi { + registry: Arc, + config_path: Option, + }, +} + +#[derive(Clone)] +pub struct AppState { + /// Runtime routing — the single source of truth for where each + /// request's graph lives. Single mode holds the handle directly; + /// multi mode holds the registry + config path. Both arms are + /// the same shape from a handler's perspective: middleware + /// extracts an `Arc` and injects it as a request + /// extension. + routing: GraphRouting, + /// Per-actor admission control. Process-wide (not per-graph) — + /// see MR-668 decision Q6. + workload: Arc, + bearer_tokens: Arc<[(BearerTokenHash, Arc)]>, + /// Server-level Cedar policy. Used by management endpoints (`POST + /// /graphs`, `GET /graphs`) which act on the registry resource, + /// not on a per-graph resource. Loaded from `server.policy.file` + /// in `omnigraph.yaml`. `None` outside multi mode and when no + /// server policy is configured. Per-graph policies live on each + /// `GraphHandle.policy`. + server_policy: Option>, +} struct ExportStreamWriter { sender: mpsc::UnboundedSender>, @@ -160,12 +277,6 @@ impl Write for ExportStreamWriter { } } -impl AuthenticatedActor { - fn as_str(&self) -> &str { - &self.0 - } -} - #[derive(Debug)] pub struct ApiError { status: StatusCode, @@ -176,8 +287,58 @@ pub struct ApiError { } impl AppState { + /// Canonical single-mode constructor. Every other `new_*` / `open_*` + /// helper is a thin convenience wrapper around this one. Builds the + /// engine + per-graph policy through `build_single_mode`, which + /// applies `Omnigraph::with_policy` so HTTP-layer and engine-layer + /// policy can never diverge — there is no "policy installed on HTTP + /// but not on engine" representable state (closes the prior + /// `with_policy_engine` footgun that reused the engine `Arc` + /// without re-applying `with_policy`). + pub fn new_single( + uri: String, + db: Omnigraph, + bearer_tokens: Vec<(String, String)>, + policy_engine: Option, + workload: workload::WorkloadController, + ) -> Self { + let bearer_tokens = hash_bearer_tokens(bearer_tokens); + let per_graph_policy = policy_engine.map(Arc::new); + Self::build_single_mode(uri, db, bearer_tokens, per_graph_policy, Arc::new(workload), None) + } + + /// Like `new_single`, but attaches a pre-validated stored-query + /// registry. Private — the production single-mode boot path + /// (`open_single_with_queries`) is the only caller; every public + /// `new_*` constructor builds with no stored queries. + fn new_single_with_queries( + uri: String, + db: Omnigraph, + bearer_tokens: Vec<(String, String)>, + policy_engine: Option, + workload: workload::WorkloadController, + queries: Option>, + ) -> Self { + let bearer_tokens = hash_bearer_tokens(bearer_tokens); + let per_graph_policy = policy_engine.map(Arc::new); + Self::build_single_mode( + uri, + db, + bearer_tokens, + per_graph_policy, + Arc::new(workload), + queries, + ) + } + pub fn new(uri: String, db: Omnigraph) -> Self { - Self::new_with_bearer_tokens(uri, db, Vec::new()) + Self::new_single( + uri, + db, + Vec::new(), + None, + workload::WorkloadController::from_env(), + ) } pub fn new_with_bearer_token(uri: String, db: Omnigraph, bearer_token: Option) -> Self { @@ -193,7 +354,13 @@ impl AppState { db: Omnigraph, bearer_tokens: Vec<(String, String)>, ) -> Self { - Self::new_with_bearer_tokens_and_policy(uri, db, bearer_tokens, None) + Self::new_single( + uri, + db, + bearer_tokens, + None, + workload::WorkloadController::from_env(), + ) } pub fn new_with_bearer_tokens_and_policy( @@ -202,68 +369,27 @@ impl AppState { bearer_tokens: Vec<(String, String)>, policy_engine: Option, ) -> Self { - let bearer_tokens: Vec<(BearerTokenHash, Arc)> = bearer_tokens - .into_iter() - .map(|(actor, token)| (hash_bearer_token(&token), Arc::::from(actor))) - .collect(); - let policy_engine: Option> = policy_engine.map(Arc::new); - // MR-722 chassis: inject the policy checker into the engine so - // `Omnigraph::apply_schema_as` (and PR #3's fan-out of the - // remaining writers) gates at engine-layer too. HTTP-layer - // `authorize_request` still fires first; the engine-layer gate - // is the redundant-but-correct backstop, plus the only path - // that protects SDK / embedded callers. PR #3 removes the HTTP - // redundancy once we're confident the engine gate covers it. - let db = if let Some(engine) = policy_engine.as_ref() { - // Unsizing coercion: Arc → Arc. - // Needs the explicit `as` cast — Rust 2024 doesn't infer it through - // `Arc::clone`. - let checker = Arc::clone(engine) as Arc; - db.with_policy(checker) - } else { - db - }; - Self { + Self::new_single( uri, - engine: Arc::new(db), - workload: Arc::new(workload::WorkloadController::from_env()), - bearer_tokens: Arc::from(bearer_tokens), + db, + bearer_tokens, policy_engine, - } + workload::WorkloadController::from_env(), + ) } /// Construct with a caller-provided [`workload::WorkloadController`]. /// Tests and benches use this to override per-actor caps without - /// mutating global env vars (which is unsafe in Rust 2024 once the - /// async runtime is up — `setenv` isn't thread-safe). + /// mutating global env vars (unsafe in Rust 2024 once the async + /// runtime is up — `setenv` isn't thread-safe). For tests that also + /// need a custom `PolicyEngine`, use [`new_single`] directly. pub fn new_with_workload( uri: String, db: Omnigraph, bearer_tokens: Vec<(String, String)>, workload: workload::WorkloadController, ) -> Self { - let bearer_tokens: Vec<(BearerTokenHash, Arc)> = bearer_tokens - .into_iter() - .map(|(actor, token)| (hash_bearer_token(&token), Arc::::from(actor))) - .collect(); - Self { - uri, - engine: Arc::new(db), - workload: Arc::new(workload), - bearer_tokens: Arc::from(bearer_tokens), - policy_engine: None, - } - } - - /// Install a `PolicyEngine` post-construction (MR-723). Used by - /// integration tests that need to thread custom workload limits - /// alongside a permit-all policy — the existing `new_with_*` and - /// `new_with_workload` constructors don't compose. Production - /// callers should use `open_with_bearer_tokens_and_policy` which - /// installs the policy on both the HTTP state and the engine. - pub fn with_policy_engine(mut self, engine: PolicyEngine) -> Self { - self.policy_engine = Some(Arc::new(engine)); - self + Self::new_single(uri, db, bearer_tokens, None, workload) } pub async fn open(uri: impl Into) -> Result { @@ -285,7 +411,7 @@ impl AppState { uri: impl Into, bearer_tokens: Vec<(String, String)>, ) -> Result { - let uri = uri.into(); + let uri = normalize_root_uri(&uri.into()).wrap_err("normalize graph URI")?; let db = Omnigraph::open(&uri).await?; Ok(Self::new_with_bearer_tokens(uri, db, bearer_tokens)) } @@ -295,32 +421,171 @@ impl AppState { bearer_tokens: Vec<(String, String)>, policy_file: Option<&PathBuf>, ) -> Result { - let uri = uri.into(); + Self::open_single_with_queries( + uri, + bearer_tokens, + policy_file, + QueryRegistry::default(), + ) + .await + } + + /// Single-mode boot with a stored-query registry: open the engine, + /// **type-check the registry against the live schema and refuse to + /// start on a breakage** (same posture as bad policy YAML), log + /// non-blocking warnings, then attach the registry to the handle. + /// With an empty registry the check is a no-op and no registry is + /// attached — that is the path `open_with_bearer_tokens_and_policy` + /// (no stored queries) takes. + pub async fn open_single_with_queries( + uri: impl Into, + bearer_tokens: Vec<(String, String)>, + policy_file: Option<&PathBuf>, + queries: QueryRegistry, + ) -> Result { + Self::open_single_with_queries_for_graph_id(uri, bearer_tokens, policy_file, queries, None) + .await + } + + async fn open_single_with_queries_for_graph_id( + uri: impl Into, + bearer_tokens: Vec<(String, String)>, + policy_file: Option<&PathBuf>, + queries: QueryRegistry, + graph_id: Option, + ) -> Result { + // The "policy requires tokens" invariant is enforced once by + // `classify_server_runtime_state` in `serve()`, before either + // single-mode or multi-mode construction is reached. By the + // time we get here, the (policy, no-tokens) combination has + // already been rejected — no second bail needed. + let uri = normalize_root_uri(&uri.into()).wrap_err("normalize graph URI")?; + let graph_id = graph_id.unwrap_or_else(|| uri.clone()); let db = Omnigraph::open(&uri).await?; + + // Validate the registry against the live schema and resolve it to + // an attachable handle (refuse boot on breakage). + let registry = validate_and_attach(queries, &db.catalog(), &graph_id)?; + let policy_engine = match policy_file { - Some(path) => Some(PolicyEngine::load(path, &uri)?), + Some(path) => Some(PolicyEngine::load_graph(path, &graph_id)?), None => None, }; - if policy_engine.is_some() && bearer_tokens.is_empty() { - bail!("policy requires at least one configured bearer token actor"); - } - Ok(Self::new_with_bearer_tokens_and_policy( + Ok(Self::new_single_with_queries( uri, db, bearer_tokens, policy_engine, + workload::WorkloadController::from_env(), + registry, )) } - pub fn uri(&self) -> &str { - &self.uri + /// Single-mode shared construction: wraps the bare engine + per-graph + /// policy in a `GraphHandle` carried directly by `GraphRouting::Single`. + /// Per-graph policy enforcement on the engine (MR-722) is re-applied + /// via `Omnigraph::with_policy` so HTTP and engine layers can never + /// diverge. + fn build_single_mode( + uri: String, + db: Omnigraph, + bearer_tokens: Arc<[(BearerTokenHash, Arc)]>, + policy_engine: Option>, + workload: Arc, + queries: Option>, + ) -> Self { + // Engine-layer policy gate (MR-722). With a per-graph policy + // installed, every `_as` writer on `Omnigraph` calls into the + // PolicyChecker. HTTP-layer `authorize_request` is the first + // gate; engine-layer is the redundant-but-correct backstop. + let db = if let Some(policy) = policy_engine.as_ref() { + let checker = Arc::clone(policy) as Arc; + db.with_policy(checker) + } else { + db + }; + // `GraphHandle.key` is required by the struct, but in single + // mode it is never a registry key (there's no registry) and + // never compared against user input (routes are flat, no + // `{graph_id}` parameter). The label appears only in tracing + // output from `resolve_graph_handle`. The literal below is a + // log label, not a routing key — when the future cluster + // catalog ships, single mode may carry the catalog-assigned + // id here instead. + let uri = normalize_root_uri(&uri).unwrap_or(uri); + let key = GraphKey::cluster( + GraphId::try_from("default").expect("'default' is a valid GraphId log label"), + ); + let handle = Arc::new(GraphHandle { + key, + uri, + engine: Arc::new(db), + policy: policy_engine, + queries, + }); + Self { + routing: GraphRouting::Single { handle }, + workload, + bearer_tokens, + server_policy: None, + } + } + + /// Multi-mode constructor — used by the startup loop. Operators + /// reach this by invoking `omnigraph-server --config omnigraph.yaml` + /// with a non-empty `graphs:` map. + /// + /// Caller supplies the already-opened `GraphHandle`s and (optionally) + /// the path to the source config file. `server_policy` is loaded + /// from `server.policy.file` if configured. + pub fn new_multi( + handles: Vec>, + bearer_tokens: Vec<(String, String)>, + server_policy: Option, + workload: workload::WorkloadController, + config_path: Option, + ) -> std::result::Result { + let bearer_tokens = hash_bearer_tokens(bearer_tokens); + let registry = Arc::new(GraphRegistry::from_handles(handles)?); + Ok(Self { + routing: GraphRouting::Multi { + registry, + config_path, + }, + workload: Arc::new(workload), + bearer_tokens, + server_policy: server_policy.map(Arc::new), + }) + } + + /// Runtime routing accessor. Handlers don't typically inspect this — + /// they extract `Arc` via the routing middleware — but + /// `build_app` matches on it to decide flat vs nested route + /// mounting, and a handful of management endpoints (`GET /graphs`, + /// the OpenAPI cluster rewrite) match on the discriminant. + pub fn routing(&self) -> &GraphRouting { + &self.routing } fn requires_bearer_auth(&self) -> bool { - !self.bearer_tokens.is_empty() || self.policy_engine.is_some() + if !self.bearer_tokens.is_empty() { + return true; + } + if self.server_policy.is_some() { + return true; + } + // Any per-graph policy also requires auth — otherwise the + // policy gate would receive unauthenticated requests. Reading + // from `routing` is O(1) in both arms: single mode is a direct + // `handle.policy.is_some()` check, multi mode reads the + // cached `any_per_graph_policy` flag on the registry snapshot. + match &self.routing { + GraphRouting::Single { handle } => handle.policy.is_some(), + GraphRouting::Multi { registry, .. } => registry.snapshot_ref().any_per_graph_policy, + } } - fn authenticate_bearer_token(&self, provided_token: &str) -> Option> { + fn authenticate_bearer_token(&self, provided_token: &str) -> Option { // Hash the incoming token and compare against every stored digest in // constant time. Iterate all entries unconditionally so total work — // and therefore response timing — doesn't depend on which slot matches. @@ -331,12 +596,16 @@ impl AppState { matched = Some(Arc::clone(actor)); } } - matched + matched.map(ResolvedActor::cluster_static) } +} - fn policy_engine(&self) -> Option<&PolicyEngine> { - self.policy_engine.as_deref() - } +fn hash_bearer_tokens(bearer_tokens: Vec<(String, String)>) -> Arc<[(BearerTokenHash, Arc)]> { + let tokens: Vec<(BearerTokenHash, Arc)> = bearer_tokens + .into_iter() + .map(|(actor, token)| (hash_bearer_token(&token), Arc::::from(actor))) + .collect(); + Arc::from(tokens) } impl ApiError { @@ -380,6 +649,20 @@ impl ApiError { } } + /// HTTP 405 Method Not Allowed. Used when the route is mounted but + /// the active server mode doesn't serve it (`GET /graphs` in + /// single-graph mode returns this instead of 404 so clients can + /// distinguish "wrong context" from "no such resource"). + pub fn method_not_allowed(message: impl Into) -> Self { + Self { + status: StatusCode::METHOD_NOT_ALLOWED, + code: ErrorCode::MethodNotAllowed, + message: message.into(), + merge_conflicts: Vec::new(), + manifest_conflict: None, + } + } + pub fn conflict(message: impl Into) -> Self { Self { status: StatusCode::CONFLICT, @@ -435,10 +718,7 @@ impl ApiError { } } - fn manifest_version_conflict( - message: String, - details: api::ManifestConflictOutput, - ) -> Self { + fn manifest_version_conflict(message: String, details: api::ManifestConflictOutput) -> Self { Self { status: StatusCode::CONFLICT, code: ErrorCode::Conflict, @@ -487,6 +767,12 @@ impl ApiError { // engine gate fires, the bearer is valid — any failure from // the engine is a policy outcome, not an auth one. OmniError::Policy(message) => Self::forbidden(message), + // `Omnigraph::init` against an existing graph URI in strict + // mode. Not currently HTTP-reachable (POST /graphs was + // pulled), but mapping is wired so the variant has a + // single canonical translation when a future runtime + // create endpoint lands. + err @ OmniError::AlreadyInitialized { .. } => Self::conflict(err.to_string()), } } } @@ -550,6 +836,58 @@ pub fn init_tracing() { let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init(); } +/// Log each non-blocking advisory from a registry check report. +fn log_registry_warnings(label: &str, report: &queries::CheckReport) { + for warning in &report.warnings { + warn!(graph = label, query = %warning.query, "stored query: {}", warning.message); + } +} + +fn validate_registry_against_catalog( + registry: &QueryRegistry, + catalog: &Catalog, + label: &str, +) -> omnigraph::error::Result<()> { + let report = check(registry, catalog); + if report.has_breakages() { + return Err(OmniError::manifest(format_check_breakages(label, &report))); + } + log_registry_warnings(label, &report); + Ok(()) +} + +/// Validate a loaded stored-query registry against the live schema and +/// resolve it to an attachable handle. Refuses boot on any breakage +/// (same posture as bad policy YAML), logs the non-blocking warnings, +/// and collapses an empty registry to `None` (nothing attached). This is +/// the single gate every open path funnels through, so no opener can +/// attach a registry that has not been schema-checked. `label` names the +/// graph in messages. +fn validate_and_attach( + queries: QueryRegistry, + catalog: &Catalog, + label: &str, +) -> Result>> { + validate_registry_against_catalog(&queries, catalog, label) + .map_err(|err| color_eyre::eyre::eyre!(err.to_string()))?; + Ok(if queries.is_empty() { + None + } else { + Some(Arc::new(queries)) + }) +} + +/// Format every load error (parse / identity failure) into a multi-line +/// boot-abort message. +fn format_registry_load_errors(label: &str, errors: &[queries::LoadError]) -> String { + let joined = errors + .iter() + .map(|e| e.to_string()) + .collect::>() + .join("\n "); + format!("graph '{label}': stored-query registry failed to load:\n {joined}") +} + pub fn load_server_settings( config_path: Option<&PathBuf>, cli_uri: Option, @@ -558,10 +896,7 @@ pub fn load_server_settings( cli_allow_unauthenticated: bool, ) -> Result { let config = load_config(config_path)?; - let uri = - config.resolve_target_uri(cli_uri, cli_target.as_deref(), config.server_graph_name())?; let bind = cli_bind.unwrap_or_else(|| config.server_bind().to_string()); - let policy_file = config.resolve_policy_file(); // Either `--unauthenticated` or `OMNIGRAPH_UNAUTHENTICATED=1` flips // this. Treat any non-empty, non-"0"/"false" string as truthy — // standard 12-factor "any value is true" reading of the env var. @@ -574,14 +909,131 @@ pub fn load_server_settings( .unwrap_or(false); let allow_unauthenticated = cli_allow_unauthenticated || env_unauth; + // MR-668 decision 2 — four-rule mode inference matrix. + // + // 1. CLI `` positional → Single (URI = the value) + // 2. CLI `--target ` → Single (URI = graphs..uri) + // 3. `server.graph` in config → Single (URI = graphs..uri) + // 4. `--config` + non-empty `graphs:` + no single-mode selector + // → Multi (every entry in `graphs:`) + // 5. otherwise → error with migration hint + // + // Rules 1-3 are mutually compatible (CLI URI wins over `--target` + // wins over `server.graph`), reusing the existing + // `resolve_target_uri` precedence. + let has_cli_uri = cli_uri.is_some(); + let has_cli_target = cli_target.is_some(); + let has_server_graph = config.server_graph_name().is_some(); + let has_graphs_map = !config.graphs.is_empty(); + let has_explicit_config = config_path.is_some(); + + let mode = if has_cli_uri || has_cli_target || has_server_graph { + // Rules 1, 2, or 3 → Single mode. + let raw_uri = config.resolve_target_uri( + cli_uri, + cli_target.as_deref(), + config.server_graph_name(), + )?; + let uri = normalize_root_uri(&raw_uri).wrap_err_with(|| { + format!("normalize single-graph URI '{raw_uri}' from server settings") + })?; + // Config follows graph IDENTITY, not mode: a bare URI is anonymous + // (top-level config); a graph chosen by name uses its per-graph + // `graphs..{policy,queries}`. `resolve_target_uri` already + // errored on an unknown name, so a `Some(name)` here is a known graph. + let selected: Option<&str> = if has_cli_uri { + None + } else { + cli_target.as_deref().or_else(|| config.server_graph_name()) + }; + // A named selection must not leave a populated top-level block + // silently unused — refuse boot and point at the per-graph block. The + // same rule the CLI selection gate enforces, shared via one helper so + // the boot check and `omnigraph queries validate`/`list` can't drift. + config.ensure_top_level_blocks_honored(selected)?; + // Load + identity-check now (no engine needed); the schema + // type-check happens when the engine opens. + let policy_file = config.resolve_policy_file_for(selected); + let queries = QueryRegistry::load(&config, config.query_entries_for(selected)) + .map_err(|errs| color_eyre::eyre::eyre!(format_registry_load_errors(&uri, &errs)))?; + let graph_id = graph_resource_id_for_selection(selected, &uri); + ServerConfigMode::Single { + uri, + graph_id, + policy_file, + queries, + } + } else if has_explicit_config && has_graphs_map { + // Multi mode: every graph uses its per-graph block; top-level + // policy/queries are never honored, so a populated one is an error. + let unhonored = config.populated_top_level_blocks(); + if !unhonored.is_empty() { + bail!( + "multi-graph mode: top-level {} {} not honored — each graph uses its own \ + `graphs..…` block. Move per-graph rules there (and any \ + `graph_list` policy to `server.policy.file`).", + unhonored.join(" and "), + if unhonored.len() == 1 { "is" } else { "are" }, + ); + } + // Rule 4 → Multi mode. Build a startup config per graph. + let mut graphs = Vec::with_capacity(config.graphs.len()); + for (name, target) in &config.graphs { + // Validate the graph id can construct a `GraphId` newtype. + // Doing this here (not at registry insert) so a malformed + // omnigraph.yaml fails at startup with a clear error. + GraphId::try_from(name.clone()).map_err(|err| { + color_eyre::eyre::eyre!("invalid graph id '{name}' in omnigraph.yaml: {err}") + })?; + let raw_uri = config.resolve_uri_value(&target.uri); + let uri = normalize_root_uri(&raw_uri).wrap_err_with(|| { + format!("normalize URI '{raw_uri}' for graph '{name}' in omnigraph.yaml") + })?; + // Per-graph `queries:`, selected through the shared + // `query_entries_for` so server and CLI resolve identically. + // Load + identity-check now; the schema type-check happens + // when this graph's engine opens. + let queries = QueryRegistry::load(&config, config.query_entries_for(Some(name.as_str()))) + .map_err(|errs| color_eyre::eyre::eyre!(format_registry_load_errors(name, &errs)))?; + graphs.push(GraphStartupConfig { + graph_id: name.clone(), + uri, + policy_file: config.resolve_target_policy_file(name), + queries, + }); + } + let config_path = config_path + .cloned() + .expect("has_explicit_config implies config_path is Some"); + let server_policy_file = config.resolve_server_policy_file(); + ServerConfigMode::Multi { + graphs, + config_path, + server_policy_file, + } + } else { + // Rule 5 → error with migration hint. + bail!( + "no graph to serve: pass a URI (`omnigraph-server `), select a target \ + (`--target --config omnigraph.yaml`), set `server.graph: ` in \ + omnigraph.yaml, or for multi-graph mode add a `graphs:` map to the config \ + file referenced by `--config`." + ); + }; + Ok(ServerConfig { - uri, + mode, bind, - policy_file, allow_unauthenticated, }) } +/// Whether the loaded config will run the server in multi-graph mode. +/// Useful for the test that constructs `ServerConfig` directly. +pub fn server_config_is_multi(config: &ServerConfig) -> bool { + matches!(config.mode, ServerConfigMode::Multi { .. }) +} + /// MR-723 server runtime state, classified from the three-state matrix /// of (bearer tokens configured) × (policy file configured) at startup. /// @@ -594,10 +1046,14 @@ pub fn load_server_settings( /// server requires a valid bearer token; once authenticated, every /// action except `Read` is denied with 403. Closes the "tokens but /// forgot the policy file" trap. -/// * **PolicyEnabled** — policy file configured. Cedar evaluates every -/// authenticated request. Tokens may also be configured (typical) or -/// not (unusual but valid — every request fails 401 without a -/// bearer, which is effectively "locked"). +/// * **PolicyEnabled** — policy file configured and at least one +/// bearer token configured. Cedar evaluates every authenticated +/// request. Policy without tokens is rejected at startup — +/// such a server would 401 every request, which is bug-shaped +/// rather than feature-shaped (operators wanting "deny all +/// unauthenticated traffic" should configure tokens plus a +/// deny-all policy to get meaningful 403s with policy-decision +/// logging instead). #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum ServerRuntimeState { Open, @@ -606,8 +1062,15 @@ pub enum ServerRuntimeState { } /// Compute the [`ServerRuntimeState`] from the configured inputs. -/// Pulled out as a pure function so the 3-state matrix is unit-testable +/// Pulled out as a pure function so the matrix is unit-testable /// without standing up the full server. +/// +/// The classifier is the **single source of truth** for "should we +/// start?" — both `serve()`'s single-mode and multi-mode branches +/// call this before constructing their `AppState`. Adding a startup +/// invariant here means both modes enforce it automatically; the +/// alternative (per-constructor `bail!`) drifts the moment a third +/// mode is added. pub fn classify_server_runtime_state( has_tokens: bool, has_policy: bool, @@ -622,16 +1085,45 @@ pub fn classify_server_runtime_state( ), (false, false, true) => Ok(ServerRuntimeState::Open), (true, false, _) => Ok(ServerRuntimeState::DefaultDeny), - (_, true, _) => Ok(ServerRuntimeState::PolicyEnabled), + (false, true, _) => bail!( + "policy file is configured but no bearer tokens — every request would 401 \ + because no token can ever match. Configure at least one bearer token (see \ + docs/user/server.md), or remove the policy file. To deny all unauthenticated \ + traffic deliberately, configure tokens plus a deny-all Cedar rule — that \ + produces meaningful 403s with policy-decision logging instead of silent 401s." + ), + (true, true, _) => Ok(ServerRuntimeState::PolicyEnabled), } } pub fn build_app(state: AppState) -> Router { - let protected = Router::new() + // The per-graph protected routes, identical in single + multi mode. + // Two middleware layers wrap them (outer first, inner last): + // 1. `require_bearer_auth` — extracts the bearer token and injects + // `ResolvedActor` (or rejects 401). + // 2. `resolve_graph_handle` — injects `Arc` based on + // the active mode (single: the only handle; multi: lookup by + // `{graph_id}` in the URI path). + let per_graph_protected = Router::new() .route("/snapshot", get(server_snapshot)) .route("/export", post(server_export)) - .route("/read", post(server_read)) - .route("/change", post(server_change)) + // /read and /change are kept indefinitely for back-compat; + // their handlers carry #[deprecated] so the OpenAPI operation is + // flagged and their responses include RFC 9745 Deprecation + + // RFC 8288 Link headers. Suppress the call-site warning for the + // route registration itself. + .route("/read", post({ + #[allow(deprecated)] + server_read + })) + .route("/query", post(server_query)) + .route("/change", post({ + #[allow(deprecated)] + server_change + })) + .route("/mutate", post(server_mutate)) + .route("/queries", get(server_list_queries)) + .route("/queries/{name}", post(server_invoke_query)) .route("/schema", get(server_schema_get)) .route("/schema/apply", post(server_schema_apply)) .route( @@ -646,11 +1138,42 @@ pub fn build_app(state: AppState) -> Router { .route("/branches/merge", post(server_branch_merge)) .route("/commits", get(server_commit_list)) .route("/commits/{commit_id}", get(server_commit_show)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + resolve_graph_handle, + )) .route_layer(middleware::from_fn_with_state( state.clone(), require_bearer_auth, )); + // Management endpoints (`GET /graphs`) live alongside the per-graph + // router. They go through bearer auth but NOT through + // `resolve_graph_handle` — they operate on the registry directly. + // The endpoint is mounted in both modes; in single mode the handler + // returns 405 so clients see "resource exists, wrong context" + // rather than 404 "no such resource." + // + // Runtime add/remove (`POST /graphs`, `DELETE /graphs/{id}`) is not + // exposed in v0.6.0 — operators add graphs by editing + // `omnigraph.yaml` and restarting. + let management = Router::new() + .route("/graphs", get(server_graphs_list)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_bearer_auth, + )); + + // Mount the protected routes differently per mode: + // * Single → flat routes (legacy: `/snapshot`, `/read`, etc.) + // * Multi → nested under `/graphs/{graph_id}/...` + let protected: Router = match state.routing() { + GraphRouting::Single { .. } => per_graph_protected.merge(management), + GraphRouting::Multi { .. } => Router::new() + .nest("/graphs/{graph_id}", per_graph_protected) + .merge(management), + }; + Router::new() .route("/healthz", get(server_health)) .route("/openapi.json", get(server_openapi)) @@ -664,9 +1187,22 @@ pub async fn serve(config: ServerConfig) -> Result<()> { let token_source = resolve_token_source().await?; info!(source = token_source.name(), "loaded bearer token source"); let tokens = token_source.load().await?; + + // For runtime-state classification, "any policy configured" means + // either the top-level/single-mode policy file OR a server-level + // policy OR any per-graph policy file. Mirrors the + // `requires_bearer_auth` semantics on AppState. + let has_policy_configured = match &config.mode { + ServerConfigMode::Single { policy_file, .. } => policy_file.is_some(), + ServerConfigMode::Multi { + graphs, + server_policy_file, + .. + } => server_policy_file.is_some() || graphs.iter().any(|g| g.policy_file.is_some()), + }; let runtime_state = classify_server_runtime_state( !tokens.is_empty(), - config.policy_file.is_some(), + has_policy_configured, config.allow_unauthenticated, )?; match runtime_state { @@ -682,20 +1218,137 @@ pub async fn serve(config: ServerConfig) -> Result<()> { ), ServerRuntimeState::PolicyEnabled => {} } - let state = AppState::open_with_bearer_tokens_and_policy( - config.uri.clone(), - tokens, - config.policy_file.as_ref(), - ) - .await?; - let listener = TcpListener::bind(&config.bind).await?; - info!(uri = %config.uri, bind = %config.bind, "serving omnigraph"); + + let bind = config.bind.clone(); + let state = match config.mode { + ServerConfigMode::Single { + uri, + graph_id, + policy_file, + queries, + } => { + let uri_for_log = uri.clone(); + info!( + uri = %uri_for_log, + graph_id = %graph_id, + bind = %bind, + mode = "single", + "serving omnigraph" + ); + AppState::open_single_with_queries_for_graph_id( + uri, + tokens, + policy_file.as_ref(), + queries, + Some(graph_id), + ) + .await? + } + ServerConfigMode::Multi { + graphs, + config_path, + server_policy_file, + } => { + info!( + bind = %bind, + mode = "multi", + graph_count = graphs.len(), + config = %config_path.display(), + "serving omnigraph" + ); + open_multi_graph_state(graphs, tokens, server_policy_file.as_ref(), config_path).await? + } + }; + + let listener = TcpListener::bind(&bind).await?; axum::serve(listener, build_app(state)) .with_graceful_shutdown(shutdown_signal()) .await?; Ok(()) } +/// Parallel open of every graph in the startup config, with bounded +/// concurrency (`buffer_unordered(4)`). Fail-fast — the first open error +/// aborts startup; other in-flight opens are dropped (their `Omnigraph` +/// instances close cleanly via Arc drop). +/// +/// The bound 4 is a rule-of-thumb for I/O-bound work. At N ≤ 10 this +/// trades startup latency for a small amount of concurrent S3 / Lance +/// open pressure. +async fn open_multi_graph_state( + graphs: Vec, + tokens: Vec<(String, String)>, + server_policy_file: Option<&PathBuf>, + config_path: PathBuf, +) -> Result { + use futures::{StreamExt, TryStreamExt}; + + if graphs.is_empty() { + bail!("multi-graph mode requires at least one graph in the `graphs:` map"); + } + + // Server-level policy (loaded once, applies to management endpoints). + // The placeholder graph_id `"server"` is the sentinel the Cedar + // resource-model refactor maps to the singleton + // `Omnigraph::Server::"root"` entity at evaluation time. + let server_policy = match server_policy_file { + Some(path) => Some(PolicyEngine::load_server(path)?), + None => None, + }; + + // `try_collect` propagates the first error eagerly, dropping every + // in-flight open. `buffer_unordered + collect::>` would drain + // the stream before checking errors — incorrect for the docstring's + // "fail-fast" claim and wasteful on S3-backed graphs. + let handles: Vec> = futures::stream::iter(graphs.into_iter()) + .map(|cfg| async move { open_single_graph(cfg).await }) + .buffer_unordered(4) + .try_collect() + .await?; + + let workload = workload::WorkloadController::from_env(); + let state = AppState::new_multi(handles, tokens, server_policy, workload, Some(config_path)) + .map_err(|err| color_eyre::eyre::eyre!("multi-graph registry: {err}"))?; + Ok(state) +} + +/// Open one graph and wrap it in a `GraphHandle`. Used at startup by +/// `open_multi_graph_state`. +async fn open_single_graph(cfg: GraphStartupConfig) -> Result> { + let graph_id = GraphId::try_from(cfg.graph_id.clone()) + .map_err(|err| color_eyre::eyre::eyre!("graph id '{}': {err}", cfg.graph_id))?; + let uri = normalize_root_uri(&cfg.uri) + .wrap_err_with(|| format!("normalize URI for graph '{}'", cfg.graph_id))?; + + let db = Omnigraph::open(&uri) + .await + .map_err(|err| color_eyre::eyre::eyre!("open graph '{}' at {}: {err}", graph_id, uri))?; + + // Validate this graph's stored queries against the live schema and + // resolve them to an attachable handle (refuse boot on breakage). + // Done before the policy match rebinds `db`; the catalog handle is an + // owned `Arc`, so no borrow of `db` survives into the match. + let queries = validate_and_attach(cfg.queries, &db.catalog(), graph_id.as_str())?; + + let (policy_arc, db) = match &cfg.policy_file { + Some(path) => { + let policy = PolicyEngine::load_graph(path, graph_id.as_str())?; + let policy_arc: Arc = Arc::new(policy); + let checker = Arc::clone(&policy_arc) as Arc; + (Some(policy_arc), db.with_policy(checker)) + } + None => (None, db), + }; + + Ok(Arc::new(GraphHandle { + key: GraphKey::cluster(graph_id), + uri, + engine: Arc::new(db), + policy: policy_arc, + queries, + })) +} + async fn shutdown_signal() { if let Err(err) = tokio::signal::ctrl_c().await { error!(error = %err, "failed to install ctrl-c handler"); @@ -726,14 +1379,176 @@ async fn server_health() -> Json { }) } +#[utoipa::path( + get, + path = "/graphs", + tag = "management", + operation_id = "listGraphs", + responses( + (status = 200, description = "List of registered graphs", body = GraphListResponse), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + (status = 405, description = "Method not allowed (single-graph mode)", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// List every graph currently registered with this server (MR-668). +/// +/// Multi-graph mode only. In single mode, the route returns 405 — there's +/// no registry to enumerate. Cedar-gated by the server-level policy via +/// the `graph_list` action against `Omnigraph::Server::"root"`. +/// +/// Order: alphabetical by `graph_id` (server-sorted so clients see +/// deterministic output across requests). +async fn server_graphs_list( + State(state): State, + actor: Option>, +) -> std::result::Result, ApiError> { + // 405 in single mode — there's no registry to enumerate, and the + // legacy URL surface didn't expose this endpoint. + let registry = match state.routing() { + GraphRouting::Single { .. } => { + return Err(ApiError::method_not_allowed( + "GET /graphs is only available in multi-graph mode", + )); + } + GraphRouting::Multi { registry, .. } => registry, + }; + + // Server-level Cedar gate. `state.server_policy` is loaded from + // `server.policy.file` in `omnigraph.yaml` at startup. When no + // server policy is configured, `authorize_request_server` falls + // through to the MR-723 default-deny semantics (every non-Read + // action denied for an authenticated actor). `GraphList` is not + // `Read`, so without a server policy the request gets 403 — which + // is the right default (don't leak the registry until the operator + // explicitly authorizes it). + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + state.server_policy.as_deref(), + PolicyRequest { + action: PolicyAction::GraphList, + branch: None, + target_branch: None, + }, + )?; + + let mut graphs: Vec = registry + .list() + .into_iter() + .map(|handle| GraphInfo { + graph_id: handle.key.graph_id.as_str().to_string(), + uri: handle.uri.clone(), + }) + .collect(); + graphs.sort_by(|a, b| a.graph_id.cmp(&b.graph_id)); + Ok(Json(GraphListResponse { graphs })) +} + async fn server_openapi(State(state): State) -> Json { let mut doc = ApiDoc::openapi(); if !state.requires_bearer_auth() { strip_security(&mut doc); } + // MR-668: in multi mode, the protected routes live under + // `/graphs/{graph_id}/...`. Rewrite the doc so the spec matches + // the routes the router actually serves. Public paths (`/healthz`) + // stay flat in both modes. + if matches!(state.routing(), GraphRouting::Multi { .. }) { + nest_paths_under_cluster_prefix(&mut doc); + } Json(doc) } +/// Path prefix used to namespace per-graph routes in multi mode. +/// Kept in sync with the `Router::nest(...)` invocation in `build_app`. +const CLUSTER_PATH_PREFIX: &str = "/graphs/{graph_id}"; + +/// Operation-id prefix applied to every cloned cluster operation. +/// Decision 7 in the implementation plan — keeps operation IDs unique +/// across the spec when both flat and nested variants ever appear in +/// the same generation pass. +const CLUSTER_OPERATION_ID_PREFIX: &str = "cluster_"; + +/// Paths that stay flat in every server mode (public or server-level, +/// no per-graph dependency). Update this list when adding new +/// always-flat endpoints. `/graphs` is the management enumeration — +/// it lives at the root in both single mode (405) and multi mode, and +/// must never be rewritten to `/graphs/{graph_id}/graphs`. +const ALWAYS_FLAT_PATHS: &[&str] = &["/healthz", "/graphs"]; + +/// In multi-mode `server_openapi`, every protected path-item is +/// reattached under the cluster prefix. Operation IDs gain the +/// `cluster_` prefix so SDK generators don't collide if/when both +/// surfaces are merged. Every rewritten operation also declares the +/// required `{graph_id}` path parameter so the served OpenAPI document +/// remains internally valid. +/// +/// Removing the flat protected paths matches the runtime router — +/// in multi mode, requests to `/snapshot` etc. return 404, so the +/// spec must agree. +fn nest_paths_under_cluster_prefix(doc: &mut utoipa::openapi::OpenApi) { + let original = std::mem::take(&mut doc.paths.paths); + let mut rewritten = std::collections::BTreeMap::new(); + for (path, mut item) in original { + if ALWAYS_FLAT_PATHS.contains(&path.as_str()) { + rewritten.insert(path, item); + continue; + } + rename_operation_ids(&mut item, CLUSTER_OPERATION_ID_PREFIX); + add_cluster_graph_id_parameter(&mut item); + let new_path = format!("{CLUSTER_PATH_PREFIX}{path}"); + rewritten.insert(new_path, item); + } + doc.paths.paths = rewritten; +} + +fn add_cluster_graph_id_parameter(item: &mut utoipa::openapi::PathItem) { + for op in path_item_operations_mut(item) { + let parameters = op.parameters.get_or_insert_with(Vec::new); + let has_graph_id = parameters + .iter() + .any(|param| param.name == "graph_id" && param.parameter_in == ParameterIn::Path); + if !has_graph_id { + parameters.insert(0, graph_id_path_parameter()); + } + } +} + +fn graph_id_path_parameter() -> Parameter { + let mut parameter = Parameter::new("graph_id"); + parameter.parameter_in = ParameterIn::Path; + parameter.description = Some("Graph id to route the request to.".to_string()); + parameter.schema = Some(Object::with_type(Type::String).into()); + parameter +} + +/// Prefix every operation_id in this PathItem with `prefix`. +fn rename_operation_ids(item: &mut utoipa::openapi::PathItem, prefix: &str) { + for op in path_item_operations_mut(item) { + if let Some(id) = op.operation_id.as_deref() { + op.operation_id = Some(format!("{prefix}{id}")); + } + } +} + +fn path_item_operations_mut( + item: &mut utoipa::openapi::PathItem, +) -> impl Iterator { + [ + item.get.as_mut(), + item.post.as_mut(), + item.put.as_mut(), + item.delete.as_mut(), + item.options.as_mut(), + item.head.as_mut(), + item.patch.as_mut(), + item.trace.as_mut(), + ] + .into_iter() + .flatten() +} + fn strip_security(doc: &mut utoipa::openapi::OpenApi) { if let Some(components) = doc.components.as_mut() { components.security_schemes.clear(); @@ -781,11 +1596,77 @@ async fn require_bearer_auth( let Some(actor) = state.authenticate_bearer_token(provided_token) else { return Err(ApiError::unauthorized("invalid bearer token")); }; - request.extensions_mut().insert(AuthenticatedActor(actor)); + request.extensions_mut().insert(actor); Ok(next.run(request).await) } +/// Routing middleware (MR-668). Resolves the active graph for the +/// request and injects `Arc` as an extension so handlers can +/// extract it via `Extension>`. +/// +/// **Single mode**: the routing field holds the single handle directly. +/// Routes are flat; every request resolves to that handle, regardless +/// of the URI path. No registry walk, no sentinel key, no +/// programmer-error guard. +/// +/// **Multi mode**: routes are nested under `/graphs/{graph_id}/...`. The +/// middleware extracts `{graph_id}` from the URI path and looks it up in +/// the registry. Returns 404 if the graph is not registered. +/// +/// The middleware fires AFTER `require_bearer_auth`, so the actor is +/// already in the request extensions (or auth was off entirely). +async fn resolve_graph_handle( + State(state): State, + mut request: Request, + next: Next, +) -> std::result::Result { + let handle = match &state.routing { + GraphRouting::Single { handle } => Arc::clone(handle), + GraphRouting::Multi { registry, .. } => { + // `Router::nest("/graphs/{graph_id}", inner)` rewrites + // `request.uri().path()` to the inner suffix (e.g. `/snapshot`). + // The pre-rewrite URI is preserved in the `OriginalUri` + // request extension by axum's router; we read from there to + // extract `{graph_id}`. Fall back to the current URI only if + // the extension is missing, which shouldn't happen for + // nested routes but is safe defensive code. + let original_path: String = request + .extensions() + .get::() + .map(|OriginalUri(uri)| uri.path().to_string()) + .unwrap_or_else(|| request.uri().path().to_string()); + let graph_id_str = original_path + .strip_prefix("/graphs/") + .and_then(|rest| rest.split('/').next()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + ApiError::bad_request( + "cluster route missing /graphs/{graph_id} prefix".to_string(), + ) + })?; + let graph_id = GraphId::try_from(graph_id_str.to_string()) + .map_err(|err| ApiError::bad_request(err.to_string()))?; + let key = GraphKey::cluster(graph_id.clone()); + match registry.get(&key) { + RegistryLookup::Ready(handle) => handle, + RegistryLookup::Gone => { + return Err(ApiError::not_found(format!("graph '{graph_id}' not found"))); + } + } + } + }; + + // Per-request observability. `Span::current().record` would silently + // no-op here because no upstream `#[tracing::instrument(...)]` macro + // declares a `graph_id` field; emit an explicit event instead so the + // routing decision actually lands in logs. + info!(graph_id = %handle.key.graph_id, "graph routed"); + + request.extensions_mut().insert(handle); + Ok(next.run(request).await) +} + fn log_policy_decision(actor_id: &str, request: &PolicyRequest, decision: &PolicyDecision) { info!( actor_id = actor_id, @@ -798,62 +1679,123 @@ fn log_policy_decision(actor_id: &str, request: &PolicyRequest, decision: &Polic ); } -fn authorize_request( - state: &AppState, - actor: Option<&AuthenticatedActor>, - mut request: PolicyRequest, -) -> std::result::Result<(), ApiError> { - let Some(engine) = state.policy_engine() else { - // MR-723 default-deny path. We're here when no PolicyEngine is - // installed. Two startup-validated shapes can reach this: +/// The allow/deny **decision** an authorization check produces, kept +/// separate from the operational failures (`Err`) that can occur while +/// computing it. [`authorize_request`] collapses `Denied` to a 403; a caller +/// that needs to remap a denial without also remapping operational failures +/// (the stored-query invoke handler hides a denial as a 404) matches on this +/// directly, so a real 401 (missing bearer) or 500 (policy-evaluation error) +/// keeps its true status instead of being masked as the denial's response. +enum Authz { + Allowed, + Denied(String), +} + +/// HTTP-layer Cedar policy gate, returning the allow/deny [`Authz`] decision +/// and reserving `Err` for operational failures (401 missing bearer, 500 +/// policy-evaluation error). Two sources of the policy engine: +/// * Per-graph handler — passes `handle.policy.as_deref()` so the +/// graph's Cedar rules govern read/change/branch_*/schema_apply. +/// * Management handler — passes `state.server_policy.as_deref()` so +/// server-level Cedar rules govern `graph_list` (the only shipped +/// server-scoped action; runtime `graph_create` / `graph_delete` +/// are deferred until a managed cluster catalog lands). +/// +/// The MR-731 invariant lives inside this function: actor identity is +/// supplied as a separate argument from the resolved bearer match. The +/// `PolicyRequest` struct itself does not carry identity (the field was +/// dropped from the type), so handlers cannot smuggle it through the +/// request. See `actor_id_resolves_from_bearer_token_ignoring_client_supplied_headers` +/// at `tests/server.rs`. +fn authorize( + actor: Option<&ResolvedActor>, + policy: Option<&PolicyEngine>, + request: PolicyRequest, +) -> std::result::Result { + let Some(engine) = policy else { + // No PolicyEngine installed. Three runtime states can reach this: // // * **Open mode** (`--unauthenticated`): no tokens, no policy. - // `require_bearer_auth` short-circuits before this is called, - // but defense in depth — if a future change makes the - // middleware call here for an unauthenticated request, we - // want every action to remain Ok rather than 403. The - // operator opted in. + // Per-graph operations are open by operator opt-in (they + // accepted "trust the network" for graph data). // * **DefaultDeny mode**: tokens configured but no policy. The - // request went through bearer auth, so `actor` is Some and - // identifies a known actor. Only `Read` is permitted; every - // other action returns 403. This closes the "configured auth - // but forgot the policy file" trap from MR-723. - if actor.is_some() && request.action != PolicyAction::Read { - return Err(ApiError::forbidden( - "server runs in default-deny mode (bearer tokens configured but no \ - policy file). Only `read` actions are permitted; configure \ - `policy.file` in omnigraph.yaml to enable other actions.", + // request went through bearer auth, so `actor` is Some. Only + // per-graph `Read` is permitted; other per-graph actions + // return 403. Closes the "configured auth but forgot the + // policy file" trap from MR-723. + // * Either of the above with a **server-scoped** action + // (`graph_list`, future `graph_create`/`graph_delete`). + // + // Server-scoped actions are always denied here, regardless of + // mode or actor presence. The management surface leaks server + // topology (graph IDs + URIs that may contain S3 bucket paths + // or internal hostnames) — operators who opted into Open mode + // accepted exposure of graph DATA, not exposure of server + // topology. Closing the management surface by default in every + // runtime state means the docstring contract on + // `server_graphs_list` ("don't leak the registry until the + // operator explicitly authorizes it") holds uniformly; the + // operator's only path to enabling it is configuring an + // explicit `server.policy.file` in omnigraph.yaml. + if request.action.resource_kind() == PolicyResourceKind::Server { + return Ok(Authz::Denied( + "server-scoped actions require an explicit `server.policy.file` \ + configured in omnigraph.yaml — the management surface is closed \ + by default in every runtime state, including --unauthenticated, \ + so that server topology is never exposed without operator opt-in." + .to_string(), )); } - return Ok(()); + if actor.is_some() && request.action != PolicyAction::Read { + return Ok(Authz::Denied( + "server runs in default-deny mode (bearer tokens configured but no \ + policy file). Only `read` actions are permitted; configure \ + `policy.file` in omnigraph.yaml to enable other actions." + .to_string(), + )); + } + return Ok(Authz::Allowed); }; let Some(actor) = actor else { return Err(ApiError::unauthorized("missing bearer token")); }; - // SECURITY INVARIANT (MR-731): actor identity comes from the matched - // bearer token, never from a client-supplied request header, query - // parameter, or body field. This line is the single chokepoint where - // the authoritative actor (resolved from the bearer match by - // `require_bearer_auth`) overwrites whatever the handler put in the - // PolicyRequest. Removing or weakening it lets clients spoof identity — - // exactly the Supabase RLS footgun ("trusting raw_user_meta_data is - // asking the attacker if they're an admin"). The principle is codified - // in `docs/dev/invariants.md` Hard Invariant 11 ("clients cannot set + // SECURITY INVARIANT (MR-731): actor identity is supplied to the + // policy engine here as a separate argument, sourced from the + // bearer-token match resolved by `require_bearer_auth`. The + // `PolicyRequest` struct itself no longer carries `actor_id` (it + // was dropped from the type), so handlers cannot smuggle identity + // through the request body and there is no overwrite step that + // could be skipped. The principle is codified in + // `docs/dev/invariants.md` Hard Invariant 11 ("clients cannot set // actor identity directly") and pinned by the regression test // `actor_id_resolves_from_bearer_token_ignoring_client_supplied_headers` // in `crates/omnigraph-server/tests/server.rs`. - // - // Side effect: also prevents an empty-string default at any handler - // call site from ever reaching the engine as a policy subject. - request.actor_id = actor.as_str().to_string(); + let actor_id = actor.actor_id.as_ref(); let decision = engine - .authorize(&request) + .authorize(actor_id, &request) .map_err(|err| ApiError::internal(format!("policy: {err}")))?; - log_policy_decision(actor.as_str(), &request, &decision); + log_policy_decision(actor_id, &request, &decision); if decision.allowed { - Ok(()) + Ok(Authz::Allowed) } else { - Err(ApiError::forbidden(decision.message)) + Ok(Authz::Denied(decision.message)) + } +} + +/// Thin wrapper over [`authorize`] for the handlers that treat any denial as a +/// 403: a denial becomes `ApiError::forbidden`, and operational failures +/// (401 missing bearer, 500 policy-evaluation error) propagate unchanged. The +/// stored-query invoke handler does **not** use this — it consumes the +/// [`Authz`] decision directly to hide a denial as a 404 while letting an +/// operational failure keep its true status. +fn authorize_request( + actor: Option<&ResolvedActor>, + policy: Option<&PolicyEngine>, + request: PolicyRequest, +) -> std::result::Result<(), ApiError> { + match authorize(actor, policy, request)? { + Authz::Allowed => Ok(()), + Authz::Denied(message) => Err(ApiError::forbidden(message)), } } @@ -876,26 +1818,22 @@ fn authorize_request( /// count) for every table on the branch. Defaults to `main` when `branch` is /// omitted. Read-only. async fn server_snapshot( - State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Query(query): Query, ) -> std::result::Result, ApiError> { let branch = query.branch.unwrap_or_else(|| "main".to_string()); authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor - .as_ref() - .map(|Extension(actor)| actor.as_str().to_string()) - .unwrap_or_default(), action: PolicyAction::Read, branch: Some(branch.clone()), target_branch: None, }, )?; let snapshot = { - let db = &state.engine; + let db = &handle.engine; db.snapshot_of(ReadTarget::branch(branch.as_str())) .await .map_err(ApiError::from_omni)? @@ -903,6 +1841,21 @@ async fn server_snapshot( Ok(Json(snapshot_payload(&branch, &snapshot))) } +/// Header values that flag a response as coming from a deprecated route +/// (RFC 9745 / RFC 8288) and point at the canonical successor. +fn deprecation_headers(successor_link: &'static str) -> [(HeaderName, HeaderValue); 2] { + [ + ( + HeaderName::from_static("deprecation"), + HeaderValue::from_static("true"), + ), + ( + HeaderName::from_static("link"), + HeaderValue::from_static(successor_link), + ), + ] +} + #[utoipa::path( post, path = "/read", @@ -910,73 +1863,84 @@ async fn server_snapshot( operation_id = "read", request_body = ReadRequest, responses( - (status = 200, description = "Query results", body = ReadOutput), + (status = 200, description = "Query results (response includes `Deprecation: true` + `Link: ; rel=\"successor-version\"`)", body = ReadOutput), (status = 400, description = "Bad request", body = ErrorOutput), (status = 401, description = "Unauthorized", body = ErrorOutput), (status = 403, description = "Forbidden", body = ErrorOutput), ), security(("bearer_token" = [])), )] -/// Execute a GQ read query. +#[deprecated(note = "use POST /query instead; /read is kept indefinitely for byte-stable back-compat")] +/// **Deprecated** — use [`POST /query`](#tag/queries/operation/query) instead. /// -/// Runs the query in `query_source` against either a branch or a frozen -/// snapshot (mutually exclusive). When `query_source` defines multiple named -/// queries, pick one with `query_name`. `params` is a JSON object whose keys -/// match the parameters declared by the query. Returns rows as a JSON array -/// plus a `columns` list. Read-only. +/// Execute a GQ read query. Behavior is unchanged from prior releases; the +/// route is kept indefinitely for byte-stable back-compat. New integrations +/// should target `POST /query`, which has clean field names (`query` / +/// `name`) and a 400-on-mutation guard. Responses from this route include +/// `Deprecation: true` and `Link: ; rel="successor-version"` +/// headers per RFC 9745 / RFC 8288 so SDKs and proxies can surface the +/// signal. async fn server_read( - State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Json(request): Json, -) -> std::result::Result, ApiError> { - if request.branch.is_some() && request.snapshot.is_some() { - return Err(ApiError::bad_request( - "read request may specify branch or snapshot, not both", - )); - } - - let target = read_target_from_request(request.branch, request.snapshot); - let policy_branch = match &target { - ReadTarget::Branch(branch) => Some(branch.clone()), - ReadTarget::Snapshot(_) if state.policy_engine().is_some() && actor.is_some() => { - let db = &state.engine; - db.resolved_branch_of(target.clone()) - .await - .map(|branch| branch.or_else(|| Some("main".to_string()))) - .map_err(ApiError::from_omni)? - } - ReadTarget::Snapshot(_) => None, - }; - authorize_request( - &state, +) -> std::result::Result<([(HeaderName, HeaderValue); 2], Json), ApiError> { + let (selected_name, target, result) = run_query( + handle, actor.as_ref().map(|Extension(actor)| actor), - PolicyRequest { - actor_id: actor - .as_ref() - .map(|Extension(actor)| actor.as_str().to_string()) - .unwrap_or_default(), - action: PolicyAction::Read, - branch: policy_branch, - target_branch: None, - }, - )?; - let (selected_name, query_params) = - select_named_query(&request.query_source, request.query_name.as_deref()) - .map_err(|err| ApiError::bad_request(err.to_string()))?; - let params = query_params_from_json(&query_params, request.params.as_ref()) - .map_err(|err| ApiError::bad_request(err.to_string()))?; + &request.query_source, + request.query_name.as_deref(), + request.params.as_ref(), + request.branch, + request.snapshot, + false, // /read predates the D2 rule; legacy callers may submit mutating queries here + ) + .await?; + Ok(( + deprecation_headers("; rel=\"successor-version\""), + Json(api::read_output(selected_name, &target, result)), + )) +} - let result = { - let db = &state.engine; - db.query( - target.clone(), - &request.query_source, - &selected_name, - ¶ms, - ) - .await - .map_err(ApiError::from_omni)? - }; +#[utoipa::path( + post, + path = "/query", + tag = "queries", + operation_id = "query", + request_body = QueryRequest, + responses( + (status = 200, description = "Query results", body = ReadOutput), + (status = 400, description = "Bad request - also returned when the query body contains mutations; use POST /mutate (or its deprecated alias POST /change) for write queries", body = ErrorOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Execute an inline read query (friendlier-named alternative to `POST /read`). +/// +/// Designed for ad-hoc exploration and AI-agent tool-use: short field +/// names (`query`, `name`) match the CLI `-e` flag and the GQ `query` +/// keyword. Mutations (`insert`/`update`/`delete`) are rejected with 400 +/// -- use `POST /mutate` (or its deprecated alias `POST /change`) for +/// write queries. Otherwise behaves identically to `POST /read`: same +/// target semantics (branch xor snapshot), same Cedar action (Read), +/// same response shape. +async fn server_query( + Extension(handle): Extension>, + actor: Option>, + Json(request): Json, +) -> std::result::Result, ApiError> { + let (selected_name, target, result) = run_query( + handle, + actor.as_ref().map(|Extension(actor)| actor), + &request.query, + request.name.as_deref(), + request.params.as_ref(), + request.branch, + request.snapshot, + true, // /query is read-only; reject mutations + ) + .await?; Ok(Json(api::read_output(selected_name, &target, result))) } @@ -1001,25 +1965,21 @@ async fn server_read( /// streams the entire branch. Suitable for large exports — the response is /// streamed, not buffered. Read-only. async fn server_export( - State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Json(request): Json, ) -> std::result::Result { let branch = request.branch.unwrap_or_else(|| "main".to_string()); authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor - .as_ref() - .map(|Extension(actor)| actor.as_str().to_string()) - .unwrap_or_default(), action: PolicyAction::Export, branch: Some(branch.clone()), target_branch: None, }, )?; - let engine = Arc::clone(&state.engine); + let engine = Arc::clone(&handle.engine); let type_names = request.type_names.clone(); let table_keys = request.table_keys.clone(); let (tx, rx) = mpsc::unbounded_channel::>(); @@ -1045,12 +2005,195 @@ async fn server_export( .into_response()) } +/// Shared implementation behind `POST /mutate` (canonical) and +/// `POST /change` (deprecated alias). Returns the bare `ChangeOutput`; +/// each route handler wraps it (the alias also attaches Deprecation +/// headers). +/// Shared backend for `/mutate` (canonical) and `/change` (deprecated alias). +/// +/// Decoupled from `ChangeRequest` so MR-969's `/queries/{name}` stored-query +/// handler can call this directly with registry-supplied fields without +/// rebuilding the request body. Today's HTTP handlers unpack the request and +/// call here; the registry would do the same. +async fn run_mutate( + state: AppState, + handle: Arc, + actor: Option<&ResolvedActor>, + query: &str, + name: Option<&str>, + params_json: Option<&Value>, + branch: String, +) -> std::result::Result { + let actor_arc = actor + .map(|a| Arc::clone(&a.actor_id)) + .unwrap_or_else(|| Arc::::from("anonymous")); + let actor_id = actor.map(|a| a.actor_id.as_ref()); + authorize_request( + actor, + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::Change, + branch: Some(branch.clone()), + target_branch: None, + }, + )?; + // Per-actor admission: bound concurrent in-flight mutations and + // estimated bytes per actor. Cedar runs FIRST so denied requests + // don't consume admission slots. Estimate uses the request body + // size as a coarse proxy; engine memory pressure can run higher. + let est_bytes = query.len() as u64 + + params_json + .map(|p| p.to_string().len() as u64) + .unwrap_or(0); + let _admission = state + .workload + .try_admit(&actor_arc, est_bytes) + .map_err(ApiError::from_workload_reject)?; + let (selected_name, query_params) = + select_named_query(query, name).map_err(|err| ApiError::bad_request(err.to_string()))?; + let params = query_params_from_json(&query_params, params_json) + .map_err(|err| ApiError::bad_request(err.to_string()))?; + + let result = { + let db = &handle.engine; + db.mutate_as(&branch, query, &selected_name, ¶ms, actor_id) + .await + .map_err(ApiError::from_omni)? + }; + Ok(ChangeOutput { + branch, + query_name: selected_name, + affected_nodes: result.affected_nodes, + affected_edges: result.affected_edges, + actor_id: actor_id.map(str::to_string), + }) +} + +/// Shared backend for `/query` (canonical) and `/read` (deprecated alias). +/// +/// Mirrors [`run_mutate`]'s decoupled shape so MR-969's stored-query handler +/// can call here with registry-supplied fields. Rejects inline source that +/// contains mutations (D2 rule); callers wanting writes go through +/// [`run_mutate`] instead. +/// +/// Intentionally does **not** take [`AppState`] (unlike [`run_mutate`]): +/// reads are not admission-gated today, so there is no `state.workload` +/// consumer. The signature grows the parameter when Phase 1 (MR-976) adds +/// the request envelope's `expect: { max_rows_scanned: N }` budget, or +/// MR-969 extends per-actor admission to stored-read invocations. +async fn run_query( + handle: Arc, + actor: Option<&ResolvedActor>, + query: &str, + name: Option<&str>, + params_json: Option<&Value>, + branch: Option, + snapshot: Option, + reject_mutations: bool, +) -> std::result::Result<(String, ReadTarget, omnigraph_compiler::result::QueryResult), ApiError> { + if branch.is_some() && snapshot.is_some() { + return Err(ApiError::bad_request( + "request may specify branch or snapshot, not both", + )); + } + + let target = read_target_from_request(branch, snapshot); + let policy_branch = match &target { + ReadTarget::Branch(branch) => Some(branch.clone()), + ReadTarget::Snapshot(_) if handle.policy.is_some() && actor.is_some() => { + let db = &handle.engine; + db.resolved_branch_of(target.clone()) + .await + .map(|branch| branch.or_else(|| Some("main".to_string()))) + .map_err(ApiError::from_omni)? + } + ReadTarget::Snapshot(_) => None, + }; + authorize_request( + actor, + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::Read, + branch: policy_branch, + target_branch: None, + }, + )?; + let query_decl = + select_named_query_decl(query, name).map_err(|err| ApiError::bad_request(err.to_string()))?; + if reject_mutations && !query_decl.mutations.is_empty() { + return Err(ApiError::bad_request(format!( + "query '{}' contains mutations (insert/update/delete); use POST /mutate for write queries", + query_decl.name + ))); + } + let selected_name = query_decl.name.clone(); + let params = query_params_from_json(&query_decl.params, params_json) + .map_err(|err| ApiError::bad_request(err.to_string()))?; + + let result = { + let db = &handle.engine; + db.query(target.clone(), query, &selected_name, ¶ms) + .await + .map_err(ApiError::from_omni)? + }; + Ok((selected_name, target, result)) +} + #[utoipa::path( post, path = "/change", tag = "mutations", operation_id = "change", request_body = ChangeRequest, + responses( + (status = 200, description = "Mutation results (response includes `Deprecation: true` + `Link: ; rel=\"successor-version\"`)", body = ChangeOutput), + (status = 400, description = "Bad request", body = ErrorOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + (status = 409, description = "Merge conflict", body = ErrorOutput), + (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +#[deprecated(note = "use POST /mutate instead; /change is kept indefinitely for back-compat")] +/// **Deprecated** — use [`POST /mutate`](#tag/mutations/operation/mutate) instead. +/// +/// Apply a GQ mutation to a branch. Behavior is unchanged; the route is +/// kept indefinitely for back-compat. New integrations should target +/// `POST /mutate`, which has identical semantics and a name that pairs +/// cleanly with `POST /query`. Responses from this route include +/// `Deprecation: true` and `Link: ; rel="successor-version"` +/// headers per RFC 9745 / RFC 8288 so SDKs and proxies can surface the +/// signal. +async fn server_change( + State(state): State, + Extension(handle): Extension>, + actor: Option>, + Json(request): Json, +) -> std::result::Result<([(HeaderName, HeaderValue); 2], Json), ApiError> { + let branch = request.branch.unwrap_or_else(|| "main".to_string()); + let output = run_mutate( + state, + handle, + actor.as_ref().map(|Extension(actor)| actor), + &request.query, + request.name.as_deref(), + request.params.as_ref(), + branch, + ) + .await?; + Ok(( + deprecation_headers("; rel=\"successor-version\""), + Json(output), + )) +} + +#[utoipa::path( + post, + path = "/mutate", + tag = "mutations", + operation_id = "mutate", + request_body = ChangeRequest, responses( (status = 200, description = "Mutation results", body = ChangeOutput), (status = 400, description = "Bad request", body = ErrorOutput), @@ -1061,72 +2204,222 @@ async fn server_export( ), security(("bearer_token" = [])), )] -/// Apply a GQ mutation to a branch. +/// Apply a GQ mutation to a branch (canonical mutation endpoint). /// /// Writes to the named `branch` (defaults to `main`). Mutations are atomic /// per call and produce a new commit. Returns counts of nodes and edges /// affected. **Destructive**: on success the branch is updated; rejected /// mutations may still acquire locks briefly. Returns 409 on merge conflict. -async fn server_change( +/// +/// Pairs with `POST /query` (read-only). The legacy `POST /change` route +/// has identical semantics and is kept as a deprecated alias. +async fn server_mutate( State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Json(request): Json, ) -> std::result::Result, ApiError> { let branch = request.branch.unwrap_or_else(|| "main".to_string()); - let actor_arc = actor - .as_ref() - .map(|Extension(actor)| Arc::clone(&actor.0)) - .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor.as_ref().map(|Extension(actor)| actor.as_str()); - authorize_request( - &state, - actor.as_ref().map(|Extension(actor)| actor), + Ok(Json( + run_mutate( + state, + handle, + actor.as_ref().map(|Extension(actor)| actor), + &request.query, + request.name.as_deref(), + request.params.as_ref(), + branch, + ) + .await?, + )) +} + +/// Path parameter for `POST /queries/{name}`. +#[derive(Deserialize)] +struct QueryNamePath { + name: String, +} + +fn parse_optional_invoke_body( + body: Bytes, +) -> std::result::Result { + if body.is_empty() { + return Ok(InvokeStoredQueryRequest::default()); + } + serde_json::from_slice::>(&body) + .map(|request| request.unwrap_or_default()) + .map_err(|err| { + ApiError::bad_request(format!("invalid stored-query invocation body: {err}")) + }) +} + +#[utoipa::path( + post, + path = "/queries/{name}", + tag = "queries", + operation_id = "invoke_query", + params(("name" = String, Path, description = "Stored query name (the registry key)")), + request_body = Option, + responses( + (status = 200, description = "Read envelope (ReadOutput) or mutation envelope (ChangeOutput), serialized untagged", body = InvokeStoredQueryResponse), + (status = 400, description = "Bad request (param type error; snapshot on a stored mutation)", body = ErrorOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden (the inner `change` gate for a stored mutation)", body = ErrorOutput), + (status = 404, description = "Unknown stored query, or `invoke_query` denied — indistinguishable to a caller without the grant", body = ErrorOutput), + (status = 409, description = "Merge conflict", body = ErrorOutput), + (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), + (status = 500, description = "Policy evaluation error (a denial is reported as 404, not 500)", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Invoke a curated, server-side stored query by name. +/// +/// The query source comes from the graph's `queries:` registry, not the +/// request body — callers send only runtime inputs (`params`, `branch`, +/// `snapshot`). Gated by the `invoke_query` Cedar action at the boundary; +/// a stored *mutation* additionally passes the engine's `change` gate +/// (double-gated). An actor **without** `invoke_query` cannot tell a denied +/// query from a missing one — both return the same 404, so the catalog +/// can't be probed without the grant. Once `invoke_query` is held, the +/// inner `read`/`change` gate may surface a 403 for an existing query the +/// actor can't run (the intended double-gate signal). +async fn server_invoke_query( + State(state): State, + Extension(handle): Extension>, + actor: Option>, + Path(QueryNamePath { name }): Path, + body: Bytes, +) -> std::result::Result, ApiError> { + let req = parse_optional_invoke_body(body)?; + // A caller without `invoke_query` can't tell a denial from a missing + // query: both 404 with this exact message, so the catalog can't be + // probed without the grant. (A caller that holds invoke_query may still + // see the inner gate's 403 for an existing query it can't run — intended.) + const NOT_FOUND: &str = "stored query not found"; + let actor_ref = actor.as_ref().map(|Extension(actor)| actor); + + // Boundary gate (authentication already ran in `require_bearer_auth`). + // A denial is hidden as 404 (deny == missing, so the catalog can't be + // probed without the grant), but operational failures (401 missing bearer, + // 500 policy-evaluation error) propagate with their true status via `?` + // rather than being masked as a missing query. + match authorize( + actor_ref, + handle.policy.as_deref(), PolicyRequest { - actor_id: actor_id.map(str::to_string).unwrap_or_default(), - action: PolicyAction::Change, - branch: Some(branch.clone()), + action: PolicyAction::InvokeQuery, + // Graph-scoped: no branch dimension. The per-branch/snapshot + // access is enforced by the inner read/change gate in the + // runner, so the outer gate must not resolve a branch (doing so + // was wrong for snapshot reads). + branch: None, + target_branch: None, + }, + )? { + Authz::Allowed => {} + Authz::Denied(_) => return Err(ApiError::not_found(NOT_FOUND)), + } + + // Resolve against the per-graph registry (same 404 on a miss). + let stored = handle + .queries + .as_ref() + .and_then(|registry| registry.lookup(&name)) + .ok_or_else(|| ApiError::not_found(NOT_FOUND))?; + + // Detach what we need before `handle` moves into the runner — the + // registry borrow lives inside `handle`. + let source = Arc::clone(&stored.source); + let query_name = stored.name.clone(); + let is_mutation = stored.is_mutation(); + + info!( + graph = %handle.uri, + actor = ?actor_ref.map(|a| a.actor_id.as_ref()), + query = %query_name, + kind = if is_mutation { "mutate" } else { "read" }, + "stored query invoked" + ); + + if is_mutation { + if req.snapshot.is_some() { + return Err(ApiError::bad_request( + "stored mutation cannot target a snapshot", + )); + } + let branch = req.branch.unwrap_or_else(|| "main".to_string()); + let output = run_mutate( + state, + handle, + actor_ref, + &source, + Some(&query_name), + req.params.as_ref(), + branch, + ) + .await?; + Ok(Json(InvokeStoredQueryResponse::Change(output))) + } else { + let (selected, target, result) = run_query( + handle, + actor_ref, + &source, + Some(&query_name), + req.params.as_ref(), + req.branch, + req.snapshot, + true, + ) + .await?; + Ok(Json(InvokeStoredQueryResponse::Read(api::read_output( + selected, &target, result, + )))) + } +} + +#[utoipa::path( + get, + path = "/queries", + tag = "queries", + operation_id = "list_queries", + responses( + (status = 200, description = "Stored-query catalog (the mcp.expose subset, with typed params)", body = QueriesCatalogOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// List the graph's exposed stored queries as a typed tool catalog. +/// +/// Returns the `mcp.expose == true` subset of the `queries:` registry, each +/// with its MCP tool name, read/mutate flag, description/instruction, and +/// typed parameters — enough for a client to register them as tools without +/// fetching `.gq` source. Read-gated; the catalog is graph-wide (branch +/// independent — `read` is authorized against `main`). **Not** Cedar-filtered +/// per query yet, so it can list a query whose `invoke_query` the caller +/// lacks (a known gap until per-query authorization lands). +async fn server_list_queries( + Extension(handle): Extension>, + actor: Option>, +) -> std::result::Result, ApiError> { + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::Read, + branch: Some("main".to_string()), target_branch: None, }, )?; - // Per-actor admission: bound concurrent in-flight mutations and - // estimated bytes per actor. Cedar runs FIRST so denied requests - // don't consume admission slots. Estimate uses the request body - // size as a coarse proxy; engine memory pressure can run higher. - let est_bytes = request.query_source.len() as u64 - + request - .params - .as_ref() - .map(|p| p.to_string().len() as u64) - .unwrap_or(0); - let _admission = state - .workload - .try_admit(&actor_arc, est_bytes) - .map_err(ApiError::from_workload_reject)?; - let (selected_name, query_params) = - select_named_query(&request.query_source, request.query_name.as_deref()) - .map_err(|err| ApiError::bad_request(err.to_string()))?; - let params = query_params_from_json(&query_params, request.params.as_ref()) - .map_err(|err| ApiError::bad_request(err.to_string()))?; - - let result = { - let db = &state.engine; - db.mutate_as( - &branch, - &request.query_source, - &selected_name, - ¶ms, - actor_id, - ) - .await - .map_err(ApiError::from_omni)? + let queries = match handle.queries.as_ref() { + Some(registry) => registry + .iter() + .filter(|q| q.expose) + .map(api::query_catalog_entry) + .collect(), + None => Vec::new(), }; - Ok(Json(ChangeOutput { - branch, - query_name: selected_name, - affected_nodes: result.affected_nodes, - affected_edges: result.affected_edges, - actor_id: actor_id.map(str::to_string), - })) + Ok(Json(QueriesCatalogOutput { queries })) } #[utoipa::path( @@ -1147,24 +2440,20 @@ async fn server_change( /// Useful for clients that want to introspect available types and tables /// before constructing GQ queries. Read-only. async fn server_schema_get( - State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, ) -> std::result::Result, ApiError> { authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor - .as_ref() - .map(|Extension(actor)| actor.as_str().to_string()) - .unwrap_or_default(), action: PolicyAction::Read, branch: None, target_branch: None, }, )?; let schema_source = { - let db = &state.engine; + let db = &handle.engine; db.schema_source().to_string() }; Ok(Json(SchemaOutput { schema_source })) @@ -1193,19 +2482,21 @@ async fn server_schema_get( /// false the diff was unsupported and no changes were made. async fn server_schema_apply( State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Json(request): Json, ) -> std::result::Result, ApiError> { let actor_arc = actor .as_ref() - .map(|Extension(actor)| Arc::clone(&actor.0)) + .map(|Extension(actor)| Arc::clone(&actor.actor_id)) .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor.as_ref().map(|Extension(actor)| actor.as_str()); + let actor_id = actor + .as_ref() + .map(|Extension(actor)| actor.actor_id.as_ref()); authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor_id.map(str::to_string).unwrap_or_default(), action: PolicyAction::SchemaApply, branch: None, target_branch: Some("main".to_string()), @@ -1217,24 +2508,32 @@ async fn server_schema_apply( .try_admit(&actor_arc, est_bytes) .map_err(ApiError::from_workload_reject)?; let result = { - let db = &state.engine; + let db = &handle.engine; + let registry = handle.queries.as_deref(); + let label = handle.key.graph_id.as_str().to_string(); // Engine-layer policy enforcement (MR-722): pass the resolved // actor through so apply_schema_as can call enforce() with the // authoritative identity. With a policy installed in AppState, // engine-side enforcement re-checks the same decision the // HTTP-layer authorize_request just made above. PR #3 collapses // the redundancy. - db.apply_schema_as( + db.apply_schema_as_with_catalog_check( &request.schema_source, omnigraph::db::SchemaApplyOptions { allow_data_loss: request.allow_data_loss, }, actor_id, + |catalog| { + if let Some(registry) = registry { + validate_registry_against_catalog(registry, catalog, &label)?; + } + Ok(()) + }, ) .await .map_err(ApiError::from_omni)? }; - Ok(Json(schema_apply_output(state.uri(), result))) + Ok(Json(schema_apply_output(handle.uri.as_str(), result))) } #[utoipa::path( @@ -1261,7 +2560,8 @@ async fn server_schema_apply( /// `overwrite` or when ingest produces conflicting writes. async fn server_ingest( State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Json(request): Json, ) -> std::result::Result, ApiError> { let branch = request.branch.unwrap_or_else(|| "main".to_string()); @@ -1269,12 +2569,14 @@ async fn server_ingest( let mode = request.mode.unwrap_or(omnigraph::loader::LoadMode::Merge); let actor_arc = actor .as_ref() - .map(|Extension(actor)| Arc::clone(&actor.0)) + .map(|Extension(actor)| Arc::clone(&actor.actor_id)) .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor.as_ref().map(|Extension(actor)| actor.as_str()); + let actor_id = actor + .as_ref() + .map(|Extension(actor)| actor.actor_id.as_ref()); let branch_exists = { - let db = &state.engine; + let db = &handle.engine; db.branch_list() .await .map_err(ApiError::from_omni)? @@ -1284,10 +2586,9 @@ async fn server_ingest( if !branch_exists { authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor_id.map(str::to_string).unwrap_or_default(), action: PolicyAction::BranchCreate, branch: Some(from.clone()), target_branch: Some(branch.clone()), @@ -1295,10 +2596,9 @@ async fn server_ingest( )?; } authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor_id.map(str::to_string).unwrap_or_default(), action: PolicyAction::Change, branch: Some(branch.clone()), target_branch: None, @@ -1311,14 +2611,14 @@ async fn server_ingest( .map_err(ApiError::from_workload_reject)?; let result = { - let db = &state.engine; + let db = &handle.engine; db.ingest_as(&branch, Some(&from), &request.data, mode, actor_id) .await .map_err(ApiError::from_omni)? }; Ok(Json(ingest_output( - state.uri(), + handle.uri.as_str(), &result, actor_id.map(str::to_string), ))) @@ -1340,24 +2640,20 @@ async fn server_ingest( /// /// Returns branch names sorted alphabetically. Read-only. async fn server_branch_list( - State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, ) -> std::result::Result, ApiError> { authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor - .as_ref() - .map(|Extension(actor)| actor.as_str().to_string()) - .unwrap_or_default(), action: PolicyAction::Read, branch: None, target_branch: None, }, )?; let mut branches = { - let db = &state.engine; + let db = &handle.engine; db.branch_list().await.map_err(ApiError::from_omni)? }; branches.sort(); @@ -1387,22 +2683,19 @@ async fn server_branch_list( /// already exists. async fn server_branch_create( State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Json(request): Json, ) -> std::result::Result, ApiError> { let from = request.from.unwrap_or_else(|| "main".to_string()); let actor_arc = actor .as_ref() - .map(|Extension(actor)| Arc::clone(&actor.0)) + .map(|Extension(actor)| Arc::clone(&actor.actor_id)) .unwrap_or_else(|| Arc::::from("anonymous")); authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor - .as_ref() - .map(|Extension(actor)| actor.as_str().to_string()) - .unwrap_or_default(), action: PolicyAction::BranchCreate, branch: Some(from.clone()), target_branch: Some(request.name.clone()), @@ -1416,23 +2709,37 @@ async fn server_branch_create( .try_admit(&actor_arc, 256) .map_err(ApiError::from_workload_reject)?; { - let db = &state.engine; + let db = &handle.engine; db.branch_create_from_as( ReadTarget::branch(&from), &request.name, - actor.as_ref().map(|Extension(a)| a.as_str()), + actor.as_ref().map(|Extension(a)| a.actor_id.as_ref()), ) .await .map_err(ApiError::from_omni)?; } Ok(Json(BranchCreateOutput { - uri: state.uri().to_string(), + uri: handle.uri.clone(), from, name: request.name, - actor_id: actor.map(|Extension(actor)| actor.as_str().to_string()), + actor_id: actor.map(|Extension(actor)| actor.actor_id.as_ref().to_string()), })) } +/// Path-param shape for [`server_branch_delete`]. Named-field +/// deserialization (rather than `Path` or `Path<(String,)>`) +/// keeps the extractor stable across single-mode flat routes and +/// multi-mode nested routes: the `{branch}` capture is picked by +/// name and any other captures in scope (e.g. `{graph_id}` in +/// multi-mode) are ignored without breaking deserialization. +/// +/// Closes the "handler path-extractor type is positional and breaks +/// when route nesting changes" class. +#[derive(Deserialize)] +struct BranchPath { + branch: String, +} + #[utoipa::path( delete, path = "/branches/{branch}", @@ -1457,19 +2764,21 @@ async fn server_branch_create( /// exist. async fn server_branch_delete( State(state): State, - actor: Option>, - Path(branch): Path, + Extension(handle): Extension>, + actor: Option>, + Path(BranchPath { branch }): Path, ) -> std::result::Result, ApiError> { let actor_arc = actor .as_ref() - .map(|Extension(actor)| Arc::clone(&actor.0)) + .map(|Extension(actor)| Arc::clone(&actor.actor_id)) .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor.as_ref().map(|Extension(actor)| actor.as_str()); + let actor_id = actor + .as_ref() + .map(|Extension(actor)| actor.actor_id.as_ref()); authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor_id.map(str::to_string).unwrap_or_default(), action: PolicyAction::BranchDelete, branch: None, target_branch: Some(branch.clone()), @@ -1481,13 +2790,13 @@ async fn server_branch_delete( .try_admit(&actor_arc, 256) .map_err(ApiError::from_workload_reject)?; { - let db = &state.engine; + let db = &handle.engine; db.branch_delete_as(&branch, actor_id) .await .map_err(ApiError::from_omni)?; } Ok(Json(BranchDeleteOutput { - uri: state.uri().to_string(), + uri: handle.uri.clone(), name: branch, actor_id: actor_id.map(str::to_string), })) @@ -1517,20 +2826,22 @@ async fn server_branch_delete( /// unchanged in that case. **Destructive** to `target` on success. async fn server_branch_merge( State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Json(request): Json, ) -> std::result::Result, ApiError> { let target = request.target.unwrap_or_else(|| "main".to_string()); let actor_arc = actor .as_ref() - .map(|Extension(actor)| Arc::clone(&actor.0)) + .map(|Extension(actor)| Arc::clone(&actor.actor_id)) .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor.as_ref().map(|Extension(actor)| actor.as_str()); + let actor_id = actor + .as_ref() + .map(|Extension(actor)| actor.actor_id.as_ref()); authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor_id.map(str::to_string).unwrap_or_default(), action: PolicyAction::BranchMerge, branch: Some(request.source.clone()), target_branch: Some(target.clone()), @@ -1544,7 +2855,7 @@ async fn server_branch_merge( .try_admit(&actor_arc, 256) .map_err(ApiError::from_workload_reject)?; let outcome = { - let db = &state.engine; + let db = &handle.engine; db.branch_merge_as(&request.source, &target, actor_id) .await .map_err(ApiError::from_omni)? @@ -1575,25 +2886,21 @@ async fn server_branch_merge( /// Filter by `branch` to get the commits on a single branch (most recent /// first); omit to list across all branches. Read-only. async fn server_commit_list( - State(state): State, - actor: Option>, + Extension(handle): Extension>, + actor: Option>, Query(query): Query, ) -> std::result::Result, ApiError> { authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor - .as_ref() - .map(|Extension(actor)| actor.as_str().to_string()) - .unwrap_or_default(), action: PolicyAction::Read, branch: query.branch.clone(), target_branch: None, }, )?; let commits = { - let db = &state.engine; + let db = &handle.engine; db.list_commits(query.branch.as_deref()) .await .map_err(ApiError::from_omni)? @@ -1603,6 +2910,13 @@ async fn server_commit_list( })) } +/// Path-param shape for [`server_commit_show`]. See [`BranchPath`] +/// for the design rationale — same pattern, different field name. +#[derive(Deserialize)] +struct CommitPath { + commit_id: String, +} + #[utoipa::path( get, path = "/commits/{commit_id}", @@ -1619,30 +2933,27 @@ async fn server_commit_list( ), security(("bearer_token" = [])), )] + /// Get a single commit. /// /// Returns the commit's manifest version, parent commit(s), and creation /// metadata. Read-only. async fn server_commit_show( - State(state): State, - actor: Option>, - Path(commit_id): Path, + Extension(handle): Extension>, + actor: Option>, + Path(CommitPath { commit_id }): Path, ) -> std::result::Result, ApiError> { authorize_request( - &state, actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), PolicyRequest { - actor_id: actor - .as_ref() - .map(|Extension(actor)| actor.as_str().to_string()) - .unwrap_or_default(), action: PolicyAction::Read, branch: None, target_branch: None, }, )?; let commit = { - let db = &state.engine; + let db = &handle.engine; db.get_commit(&commit_id) .await .map_err(ApiError::from_omni)? @@ -1658,10 +2969,10 @@ fn read_target_from_request(branch: Option, snapshot: Option) -> } } -fn select_named_query( +fn select_named_query_decl( query_source: &str, requested_name: Option<&str>, -) -> Result<(String, Vec)> { +) -> Result { let parsed = parse_query(query_source)?; let query = if let Some(name) = requested_name { parsed @@ -1674,7 +2985,14 @@ fn select_named_query( } else { bail!("query file contains multiple queries; pass --name"); }; + Ok(query) +} +fn select_named_query( + query_source: &str, + requested_name: Option<&str>, +) -> Result<(String, Vec)> { + let query = select_named_query_decl(query_source, requested_name)?; Ok((query.name, query.params)) } @@ -1760,21 +3078,142 @@ fn server_bearer_tokens_from_env() -> Result> { #[cfg(test)] mod tests { use super::{ - ServerConfig, ServerRuntimeState, classify_server_runtime_state, hash_bearer_token, - load_server_settings, normalize_bearer_token, parse_bearer_tokens_json, serve, - server_bearer_tokens_from_env, + GraphStartupConfig, ServerConfig, ServerConfigMode, ServerRuntimeState, + classify_server_runtime_state, hash_bearer_token, load_server_settings, + normalize_bearer_token, parse_bearer_tokens_json, serve, server_bearer_tokens_from_env, }; use serial_test::serial; use std::env; use std::fs; use tempfile::tempdir; + /// `authorize` returns the allow/deny **decision** (`Authz`) and reserves + /// `Err` for operational failures, so the invoke handler can hide a denial + /// as 404 without also masking a 401/500. Pins each outcome. + #[test] + fn authorize_splits_decision_from_operational_error() { + use super::{Authz, PolicyAction, PolicyCompiler, PolicyConfig, PolicyRequest, ResolvedActor, authorize}; + use std::sync::Arc; + + fn req(action: PolicyAction) -> PolicyRequest { + PolicyRequest { action, branch: None, target_branch: None } + } + let actor = ResolvedActor::cluster_static(Arc::from("act-alice")); + + // --- No policy engine installed (open / default-deny modes) --- + // A server-scoped action is denied in every no-policy state. + assert!(matches!( + authorize(Some(&actor), None, req(PolicyAction::GraphList)).unwrap(), + Authz::Denied(_) + )); + // Authenticated actor + a non-read per-graph action → default-deny. + assert!(matches!( + authorize(Some(&actor), None, req(PolicyAction::Change)).unwrap(), + Authz::Denied(_) + )); + // `read` is the one per-graph action permitted without a policy. + assert!(matches!( + authorize(Some(&actor), None, req(PolicyAction::Read)).unwrap(), + Authz::Allowed + )); + // Open mode (no actor, no policy) → allowed. + assert!(matches!( + authorize(None, None, req(PolicyAction::Read)).unwrap(), + Authz::Allowed + )); + + // --- Policy engine installed --- + let policy: PolicyConfig = serde_yaml::from_str( + "version: 1\n\ + groups:\n team: [act-alice]\n\ + rules:\n - id: team-read\n allow:\n actors: { group: team }\n actions: [read]\n branch_scope: any\n", + ) + .unwrap(); + let engine = PolicyCompiler::compile(&policy, "graph").unwrap(); + + // A matched allow rule → Allowed. + assert!(matches!( + authorize( + Some(&actor), + Some(&engine), + PolicyRequest { action: PolicyAction::Read, branch: Some("main".to_string()), target_branch: None }, + ) + .unwrap(), + Authz::Allowed + )); + // Known actor, no matching allow rule → Denied, carrying the decision message. + match authorize( + Some(&actor), + Some(&engine), + PolicyRequest { action: PolicyAction::Change, branch: Some("main".to_string()), target_branch: None }, + ) + .unwrap() + { + Authz::Denied(message) => assert!(!message.is_empty(), "a deny carries its decision message"), + Authz::Allowed => panic!("change must be denied: only read is allowed"), + } + // Policy installed but no actor → operational failure (`Err`), NOT a + // decision. This is the split that keeps a 401/500 from being masked + // as the denial's response in the invoke handler. + assert!( + authorize(None, Some(&engine), req(PolicyAction::Read)).is_err(), + "a missing actor with a policy installed is an operational error, not a deny" + ); + } + #[test] fn hash_bearer_token_produces_32_byte_output() { let hash = hash_bearer_token("any-token"); assert_eq!(hash.len(), 32); } + /// The single gate both open paths funnel through: it refuses a + /// schema breakage (naming the graph label + query), attaches a clean + /// registry, and collapses an empty one to `None`. Pure over its args + /// (no engine), so it covers the multi-graph path's logic too — the + /// only per-path difference is the `label`, asserted here. + #[test] + fn validate_and_attach_gates_on_schema_and_collapses_empty() { + use crate::queries::{QueryRegistry, RegistrySpec}; + use omnigraph_compiler::catalog::build_catalog; + use omnigraph_compiler::schema::parser::parse_schema; + + let schema = parse_schema("node User {\nname: String\n}\n").unwrap(); + let catalog = build_catalog(&schema).unwrap(); + let spec = |name: &str, source: &str| RegistrySpec { + name: name.to_string(), + source: source.to_string(), + expose: false, + tool_name: None, + }; + + // Empty registry → nothing attached, no error. + let empty = + super::validate_and_attach(QueryRegistry::default(), &catalog, "g").unwrap(); + assert!(empty.is_none()); + + // A query that type-checks → attached. + let ok = QueryRegistry::from_specs(vec![spec( + "find_user", + "query find_user() { match { $u: User } return { $u.name } }", + )]) + .unwrap(); + assert!(super::validate_and_attach(ok, &catalog, "g").unwrap().is_some()); + + // A query referencing a type the schema lacks → boot refusal that + // names both the graph label and the offending query. + let broken = QueryRegistry::from_specs(vec![spec( + "ghost", + "query ghost() { match { $w: Widget } return { $w.name } }", + )]) + .unwrap(); + let err = super::validate_and_attach(broken, &catalog, "graph-x").unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("graph-x"), "labels the graph: {msg}"); + assert!(msg.contains("ghost"), "names the query: {msg}"); + assert!(msg.contains("schema check"), "mentions the schema check: {msg}"); + } + #[test] fn hash_bearer_token_is_deterministic() { assert_eq!( @@ -1817,7 +3256,13 @@ server: .unwrap(); let settings = load_server_settings(Some(&config), None, None, None, false).unwrap(); - assert_eq!(settings.uri, "/tmp/demo.omni"); + match &settings.mode { + ServerConfigMode::Single { uri, graph_id, .. } => { + assert_eq!(uri, "/tmp/demo.omni"); + assert_eq!(graph_id, "local"); + } + ServerConfigMode::Multi { .. } => panic!("expected Single mode, got Multi"), + } assert_eq!(settings.bind, "0.0.0.0:9090"); } @@ -1846,7 +3291,13 @@ server: false, ) .unwrap(); - assert_eq!(settings.uri, "/tmp/override.omni"); + match &settings.mode { + ServerConfigMode::Single { uri, graph_id, .. } => { + assert_eq!(uri, "/tmp/override.omni"); + assert_eq!(graph_id, "/tmp/override.omni"); + } + ServerConfigMode::Multi { .. } => panic!("expected Single mode, got Multi"), + } assert_eq!(settings.bind, "0.0.0.0:9999"); } @@ -1872,13 +3323,22 @@ server: let settings = load_server_settings(Some(&config), None, Some("dev".to_string()), None, false) .unwrap(); - assert_eq!(settings.uri, "http://127.0.0.1:8080"); + match &settings.mode { + ServerConfigMode::Single { uri, graph_id, .. } => { + assert_eq!(uri, "http://127.0.0.1:8080"); + assert_eq!(graph_id, "dev"); + } + ServerConfigMode::Multi { .. } => panic!("expected Single mode, got Multi"), + } } #[test] fn server_settings_require_uri_from_cli_or_config() { let error = load_server_settings(None, None, None, None, false).unwrap_err(); - assert!(error.to_string().contains("URI must be provided")); + assert!( + error.to_string().contains("no graph to serve"), + "expected mode-inference error, got: {error}", + ); } #[test] @@ -1913,6 +3373,58 @@ server: ); } + #[tokio::test] + #[serial] + async fn serve_refuses_to_start_with_policy_but_no_tokens_multi_mode() { + // Bug 2 from the bot-review pass: multi-mode startup was missing + // the "policy requires tokens" check that single-mode enforces. + // After centralizing the check in `classify_server_runtime_state`, + // both modes get the same enforcement. This test guards the + // multi-mode propagation path. + // + // Sibling test below pins single mode. Together they pin that + // the classifier is called from both branches of `serve()`. + let _guard = EnvGuard::set(&[ + ("OMNIGRAPH_SERVER_BEARER_TOKEN", None), + ("OMNIGRAPH_SERVER_BEARER_TOKENS_FILE", None), + ("OMNIGRAPH_SERVER_BEARER_TOKENS_JSON", None), + ("OMNIGRAPH_SERVER_BEARER_TOKENS_AWS_SECRET", None), + ("OMNIGRAPH_UNAUTHENTICATED", None), + ]); + let temp = tempdir().unwrap(); + // The classifier reads `has_policy_configured` from the config + // shape (does the Option contain a path?), not from file + // existence, so we can hand it a path without writing a real + // policy file — the bail fires before policy load. + let policy_path = temp.path().join("server-policy.yaml"); + let config = ServerConfig { + mode: ServerConfigMode::Multi { + graphs: vec![GraphStartupConfig { + graph_id: "alpha".to_string(), + uri: temp + .path() + .join("alpha.omni") + .to_string_lossy() + .into_owned(), + policy_file: None, + queries: crate::queries::QueryRegistry::default(), + }], + config_path: temp.path().join("omnigraph.yaml"), + server_policy_file: Some(policy_path), + }, + bind: "127.0.0.1:0".to_string(), + allow_unauthenticated: false, + }; + let result = serve(config).await; + let err = result + .expect_err("serve should refuse to start in multi mode with policy but no tokens"); + let msg = format!("{:?}", err); + assert!( + msg.contains("policy file is configured but no bearer tokens"), + "expected policy-without-tokens rejection in multi mode, got: {msg}", + ); + } + #[tokio::test] #[serial] async fn serve_refuses_to_start_in_state_1_without_unauthenticated() { @@ -1934,20 +3446,25 @@ server: ("OMNIGRAPH_UNAUTHENTICATED", None), ]); let temp = tempdir().unwrap(); - // Repo path doesn't need to exist — classifier fires before + // Graph path doesn't need to exist — classifier fires before // `AppState::open_with_bearer_tokens_and_policy`. let config = ServerConfig { - uri: temp - .path() - .join("repo.omni") - .to_string_lossy() - .into_owned(), + mode: ServerConfigMode::Single { + uri: temp + .path() + .join("graph.omni") + .to_string_lossy() + .into_owned(), + graph_id: "default".to_string(), + policy_file: None, + queries: crate::queries::QueryRegistry::default(), + }, bind: "127.0.0.1:0".to_string(), - policy_file: None, allow_unauthenticated: false, }; let result = serve(config).await; - let err = result.expect_err("serve should refuse to start in State 1 without --unauthenticated"); + let err = + result.expect_err("serve should refuse to start in State 1 without --unauthenticated"); let msg = format!("{:?}", err); assert!( msg.contains("no bearer tokens") || msg.contains("policy file"), @@ -2025,25 +3542,43 @@ server: } #[test] - fn classify_policy_enabled_always_wins() { - // State 3: any setup with a policy file → PolicyEnabled. The - // flag doesn't matter and tokens-or-not doesn't matter (no - // tokens + policy is unusual but valid — every request fails - // 401 without a bearer, which is effectively "locked"). + fn classify_policy_enabled_requires_tokens() { + // State 3: tokens + policy → PolicyEnabled, regardless of the + // `allow_unauthenticated` flag (Cedar evaluates the bearer, + // the flag is moot once tokens exist). assert_eq!( classify_server_runtime_state(true, true, false).unwrap(), ServerRuntimeState::PolicyEnabled ); - assert_eq!( - classify_server_runtime_state(false, true, false).unwrap(), - ServerRuntimeState::PolicyEnabled - ); assert_eq!( classify_server_runtime_state(true, true, true).unwrap(), ServerRuntimeState::PolicyEnabled ); } + #[test] + fn classify_policy_without_tokens_is_rejected() { + // Closes the "policy installed but no tokens → silent 401 on + // every request" footgun. The same shape that single-mode + // `open_with_bearer_tokens_and_policy` used to bail on + // privately is now rejected by the classifier so both single + // and multi mode get the same enforcement from one source of + // truth. + for allow_unauthenticated in [false, true] { + let err = + classify_server_runtime_state(false, true, allow_unauthenticated).unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("policy file is configured but no bearer tokens"), + "expected policy-without-tokens rejection message; got: {msg}" + ); + assert!( + msg.contains("every request would 401"), + "rejection message must name the failure mode; got: {msg}" + ); + } + } + #[test] fn normalize_bearer_token_trims_and_filters_blank_values() { assert_eq!(normalize_bearer_token(None), None); diff --git a/crates/omnigraph-server/src/main.rs b/crates/omnigraph-server/src/main.rs index 54af1ed..4e1c256 100644 --- a/crates/omnigraph-server/src/main.rs +++ b/crates/omnigraph-server/src/main.rs @@ -8,7 +8,7 @@ use omnigraph_server::{ServerConfig, init_tracing, load_server_settings, serve}; #[command(name = "omnigraph-server")] #[command(about = "HTTP server for the Omnigraph graph database")] struct Cli { - /// Repo URI + /// Graph URI uri: Option, #[arg(long)] target: Option, diff --git a/crates/omnigraph-server/src/queries.rs b/crates/omnigraph-server/src/queries.rs new file mode 100644 index 0000000..bf131c8 --- /dev/null +++ b/crates/omnigraph-server/src/queries.rs @@ -0,0 +1,688 @@ +//! Stored-query registry. +//! +//! A server-side registry of named, parameter-typed `.gq` queries that +//! operators declare in `omnigraph.yaml` (per-graph, or top-level in +//! single mode) and the server loads at startup. Each entry is parsed +//! and its identity asserted here (`load`); type-checking against the +//! live schema happens separately (a `check` pass) so the loader stays +//! callable without an open engine (the CLI's offline `queries check`). +//! +//! Identity is the query **name**: the manifest key must equal the +//! `query ` symbol declared in the referenced `.gq` file. The two +//! are asserted equal at load — one name, two places that must agree. +//! Renaming either is a breaking change to callers, by design. + +use std::collections::BTreeMap; +use std::fs; +use std::sync::Arc; + +use omnigraph_compiler::catalog::Catalog; +use omnigraph_compiler::query::ast::QueryDecl; +use omnigraph_compiler::query::parser::parse_query; +use omnigraph_compiler::query::typecheck::typecheck_query_decl; +use omnigraph_compiler::types::{PropType, ScalarType}; + +use crate::config::{OmnigraphConfig, QueryEntry}; + +/// One loaded stored query. `source` is the full `.gq` file text — the +/// invocation handler hands it to `run_query` / `run_mutate` verbatim, +/// which reuse the same parse/IR/exec path as the inline routes (no +/// parallel implementation). +#[derive(Debug, Clone)] +pub struct StoredQuery { + /// Identity: manifest key == `query ` symbol. + pub name: String, + /// Full `.gq` source text the query was selected from. + pub source: Arc, + /// Parsed declaration (params, mutations, description, …). + pub decl: QueryDecl, + /// Whether this query is listed in the MCP tool catalog (`GET /queries`). + /// Default `true` (the manifest entry is the opt-in); `expose: false` + /// keeps it HTTP/service-callable but hidden from the agent tool list. + /// Catalog membership only — not an authorization gate. + pub expose: bool, + /// Optional MCP tool-name override; defaults to `name`. + pub tool_name: Option, +} + +impl StoredQuery { + /// `true` if the selected declaration contains insert/update/delete + /// statements — drives read-vs-mutate routing at invocation time. + pub fn is_mutation(&self) -> bool { + !self.decl.mutations.is_empty() + } + + /// The MCP tool name this query is catalogued under: the explicit + /// `tool_name` override, else the query `name`. The catalog key — + /// enforced unique across exposed queries at load. Server-side + /// consumers (the uniqueness check, the future catalog projection) read + /// this; the CLI `queries list` resolves the same rule on its own DTO. + pub fn effective_tool_name(&self) -> &str { + self.tool_name.as_deref().unwrap_or(&self.name) + } +} + +/// A loaded, identity-checked stored-query registry for one graph. +#[derive(Debug, Clone, Default)] +pub struct QueryRegistry { + by_name: BTreeMap, +} + +/// In-memory registry entry before file I/O. Used by [`QueryRegistry::load`] +/// (after reading each `.gq` from disk) and directly by tests. +#[derive(Debug, Clone)] +pub struct RegistrySpec { + pub name: String, + pub source: String, + pub expose: bool, + pub tool_name: Option, +} + +/// A single registry load failure. Collected (not fail-fast) so a bad +/// `omnigraph.yaml` surfaces every broken entry at once, matching the +/// bad-policy-YAML posture. +#[derive(Debug, Clone)] +pub struct LoadError { + /// The offending query name, when the failure is entry-scoped. + pub query: Option, + pub message: String, +} + +impl std::fmt::Display for LoadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.query { + Some(name) => write!(f, "stored query '{name}': {}", self.message), + None => write!(f, "stored query registry: {}", self.message), + } + } +} + +impl QueryRegistry { + /// Build a registry from in-memory specs: parse each source, select + /// the declaration whose symbol equals the manifest key, and assert + /// they agree. Collects every failure. No schema type-checking here + /// — that is [`check`]. + pub fn from_specs(specs: Vec) -> Result> { + let mut by_name = BTreeMap::new(); + let mut errors = Vec::new(); + + for spec in specs { + match parse_query(&spec.source) { + Ok(file) => { + match file.queries.into_iter().find(|q| q.name == spec.name) { + Some(decl) => { + by_name.insert( + spec.name.clone(), + StoredQuery { + name: spec.name, + source: Arc::from(spec.source), + decl, + expose: spec.expose, + tool_name: spec.tool_name, + }, + ); + } + None => errors.push(LoadError { + query: Some(spec.name.clone()), + message: format!( + "no `query {}` declaration found in its `.gq` file \ + (the registry key must match the query symbol)", + spec.name + ), + }), + } + } + Err(err) => errors.push(LoadError { + query: Some(spec.name), + message: format!("parse error: {err}"), + }), + } + } + + // Exposed queries are catalogued under their effective tool name; + // two claiming one name is an MCP-namespace collision. Refuse it at + // load (collected, not fail-fast), naming the loser and the winner. + // Iterating the `BTreeMap` makes the winner deterministic (the + // lexicographically-first query name; config is a map, so YAML + // declaration order isn't preserved anyway) and the error order + // stable. Scoped to a block so these borrows of `by_name` end + // before it is moved into `Self`. + { + let mut claimed: BTreeMap<&str, &str> = BTreeMap::new(); + for query in by_name.values().filter(|q| q.expose) { + let tool = query.effective_tool_name(); + if let Some(winner) = claimed.insert(tool, &query.name) { + errors.push(LoadError { + query: Some(query.name.clone()), + message: format!( + "MCP tool name '{tool}' already claimed by exposed query '{winner}'" + ), + }); + } + } + } + + if errors.is_empty() { + Ok(Self { by_name }) + } else { + Err(errors) + } + } + + /// Read each registry entry's `.gq` file from disk and build the + /// registry. `entries` is either the top-level `queries` map (single + /// mode) or a graph's `queries` map (multi mode); `config` resolves + /// each entry's relative `file:` path against `base_dir`. + pub fn load( + config: &OmnigraphConfig, + entries: &BTreeMap, + ) -> Result> { + let mut specs = Vec::with_capacity(entries.len()); + let mut errors = Vec::new(); + for (name, entry) in entries { + let path = config.resolve_query_file(&entry.file); + match fs::read_to_string(&path) { + Ok(source) => specs.push(RegistrySpec { + name: name.clone(), + source, + expose: entry.mcp.expose, + tool_name: entry.mcp.tool_name.clone(), + }), + Err(err) => errors.push(LoadError { + query: Some(name.clone()), + message: format!("cannot read '{}': {err}", path.display()), + }), + } + } + + // Parse/identity/uniqueness-check the readable specs even when some + // files failed to read, so every broken entry (I/O, parse, identity, + // tool-name collision) surfaces in one pass rather than one per + // restart. I/O errors come first (in `entries` key order), then the + // spec errors. A non-empty `errors` always fails the load. + match Self::from_specs(specs) { + Ok(registry) if errors.is_empty() => Ok(registry), + Ok(_) => Err(errors), + Err(spec_errors) => { + errors.extend(spec_errors); + Err(errors) + } + } + } + + pub fn lookup(&self, name: &str) -> Option<&StoredQuery> { + self.by_name.get(name) + } + + pub fn iter(&self) -> impl Iterator { + self.by_name.values() + } + + pub fn is_empty(&self) -> bool { + self.by_name.is_empty() + } + + pub fn len(&self) -> usize { + self.by_name.len() + } +} + +/// A stored query that fails to type-check against the live schema — +/// e.g. it references a node/edge type or property that was renamed or +/// removed by a migration. Breakages **block server boot** (same posture +/// as bad policy YAML), surfacing schema drift at the deploy boundary +/// rather than silently at invocation time. +#[derive(Debug, Clone)] +pub struct Breakage { + pub query: String, + pub message: String, +} + +/// A non-blocking advisory found during validation. Logged at boot; +/// never blocks startup. Currently: an MCP-exposed query that declares a +/// parameter an agent cannot realistically supply. +#[derive(Debug, Clone)] +pub struct Warning { + pub query: String, + pub message: String, +} + +/// Outcome of validating a registry against a schema. Breakages are +/// fatal (boot refuses); warnings are advisory. +#[derive(Debug, Clone, Default)] +pub struct CheckReport { + pub breakages: Vec, + pub warnings: Vec, +} + +impl CheckReport { + pub fn has_breakages(&self) -> bool { + !self.breakages.is_empty() + } + + pub fn is_clean(&self) -> bool { + self.breakages.is_empty() && self.warnings.is_empty() + } +} + +/// Validate a loaded registry against the live schema. +/// +/// Pure over `(registry, catalog)` — takes an already-parsed registry and +/// a catalog, so it is callable both at server boot (with the engine's +/// `catalog()`) and offline from the CLI (`omnigraph queries check`), +/// without coupling to server config or an open engine connection. +/// +/// Every query is type-checked via the same `typecheck_query_decl` the +/// engine runs for inline queries — no parallel implementation. Failures +/// are **collected, not fail-fast**, so an operator sees every broken +/// query in one pass. +/// +/// Advisory lint (warn, never block): an `mcp.expose: true` query that +/// declares a `Vector(N)` parameter. An LLM cannot supply a raw embedding +/// vector; such a query should take a `String` parameter and let the +/// engine embed it server-side at query time. Service-to-service callers +/// may legitimately pass vectors, so this warns rather than rejects. +pub fn check(registry: &QueryRegistry, catalog: &Catalog) -> CheckReport { + let mut report = CheckReport::default(); + for query in registry.iter() { + if let Err(err) = typecheck_query_decl(catalog, &query.decl) { + report.breakages.push(Breakage { + query: query.name.clone(), + message: err.to_string(), + }); + } + if query.expose { + for param in &query.decl.params { + // Resolve to the structured type via the compiler's own + // resolver rather than string-matching `Vector(` — one + // canonical definition of "is a vector", so this lint can't + // drift from how the parser/type system spells the type. + let is_vector = PropType::from_param_type_name(¶m.type_name, param.nullable) + .is_some_and(|pt| matches!(pt.scalar, ScalarType::Vector(_))); + if is_vector { + report.warnings.push(Warning { + query: query.name.clone(), + message: format!( + "MCP-exposed query declares a `{}` parameter `${}` that agents \ + cannot supply; use a `String` parameter for server-side embedding", + param.type_name, param.name + ), + }); + } + } + } + } + report +} + +/// Format every breakage in a registry check report into a multi-line +/// operator-facing message, naming each offending query. +pub fn format_check_breakages(label: &str, report: &CheckReport) -> String { + let joined = report + .breakages + .iter() + .map(|b| format!("query '{}': {}", b.query, b.message)) + .collect::>() + .join("\n "); + format!( + "graph '{label}': {} stored quer{} failed the schema check:\n {joined}", + report.breakages.len(), + if report.breakages.len() == 1 { + "y" + } else { + "ies" + } + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec(name: &str, source: &str, expose: bool) -> RegistrySpec { + RegistrySpec { + name: name.to_string(), + source: source.to_string(), + expose, + tool_name: None, + } + } + + fn spec_tool(name: &str, source: &str, expose: bool, tool_name: &str) -> RegistrySpec { + RegistrySpec { + name: name.to_string(), + source: source.to_string(), + expose, + tool_name: Some(tool_name.to_string()), + } + } + + #[test] + fn key_equal_symbol_loads() { + let reg = QueryRegistry::from_specs(vec![spec( + "find_user", + "query find_user($id: String) { match { $u: User } return { $u.name } }", + true, + )]) + .unwrap(); + let q = reg.lookup("find_user").unwrap(); + assert_eq!(q.name, "find_user"); + assert!(q.expose); + assert_eq!(q.decl.params.len(), 1); + assert!(!q.is_mutation()); + // No override → the effective tool name is the query name. + assert_eq!(q.effective_tool_name(), "find_user"); + + // An explicit override is what the catalog keys on. + let with_tool = QueryRegistry::from_specs(vec![spec_tool( + "find_user", + "query find_user($id: String) { match { $u: User } return { $u.name } }", + true, + "lookup_user", + )]) + .unwrap(); + assert_eq!( + with_tool.lookup("find_user").unwrap().effective_tool_name(), + "lookup_user" + ); + } + + #[test] + fn key_mismatch_is_an_identity_error() { + let errors = QueryRegistry::from_specs(vec![spec( + "find_user", + // symbol is `lookup`, key is `find_user` — must be rejected. + "query lookup($id: String) { match { $u: User } return { $u.name } }", + false, + )]) + .unwrap_err(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].query.as_deref(), Some("find_user")); + assert!(errors[0].message.contains("must match the query symbol")); + } + + #[test] + fn multi_query_file_selects_the_matching_symbol() { + let source = "query a($x: I64) { match { $u: User } return { $u.name } }\n\ + query b($y: String) { match { $u: User } return { $u.name } }"; + let reg = QueryRegistry::from_specs(vec![spec("b", source, false)]).unwrap(); + let q = reg.lookup("b").unwrap(); + assert_eq!(q.name, "b"); + assert_eq!(q.decl.params[0].name, "y"); + assert!(reg.lookup("a").is_none(), "only the selected symbol is registered"); + } + + #[test] + fn duplicate_exposed_tool_name_is_a_load_error() { + // Two MCP-exposed queries claiming one tool name is an ambiguity in + // the catalog key space — refused at load, naming both queries and + // the contested tool. + let errors = QueryRegistry::from_specs(vec![ + spec_tool("a", "query a() { match { $u: User } return { $u.name } }", true, "dup"), + spec_tool("b", "query b() { match { $u: User } return { $u.name } }", true, "dup"), + ]) + .unwrap_err(); + assert_eq!(errors.len(), 1); + let msg = errors[0].to_string(); + assert!(msg.contains("'dup'"), "names the contested tool: {msg}"); + assert!(msg.contains("'a'"), "names the winning query: {msg}"); + assert!(msg.contains("'b'"), "names the losing query: {msg}"); + } + + #[test] + fn duplicate_tool_name_among_unexposed_is_allowed() { + // Unexposed queries have no MCP tool, so a shared effective tool + // name is inert — must not error (pins the exposed-only scope). + let reg = QueryRegistry::from_specs(vec![ + spec_tool("a", "query a() { match { $u: User } return { $u.name } }", false, "dup"), + spec_tool("b", "query b() { match { $u: User } return { $u.name } }", false, "dup"), + ]) + .unwrap(); + assert_eq!(reg.len(), 2); + } + + #[test] + fn parse_error_surfaces_per_entry() { + let errors = + QueryRegistry::from_specs(vec![spec("broken", "query broken( {{ not valid", false)]) + .unwrap_err(); + assert_eq!(errors[0].query.as_deref(), Some("broken")); + assert!(errors[0].message.contains("parse error")); + } + + #[test] + fn errors_collect_rather_than_fail_fast() { + let errors = QueryRegistry::from_specs(vec![ + spec("good", "query good() { match { $u: User } return { $u.name } }", false), + spec("mismatch", "query other() { match { $u: User } return { $u.name } }", false), + spec("broken", "query broken(", false), + ]) + .unwrap_err(); + // `good` loads cleanly; only the mismatch and the parse error are + // reported, and both surface in one pass (not fail-fast). + assert_eq!(errors.len(), 2); + } + + #[test] + fn mutation_body_classifies_as_mutation() { + let reg = QueryRegistry::from_specs(vec![spec( + "add_user", + "query add_user($name: String) { insert User { name: $name } }", + false, + )]) + .unwrap(); + assert!(reg.lookup("add_user").unwrap().is_mutation()); + } + + // --- check(registry, catalog) --- + + use omnigraph_compiler::catalog::build_catalog; + use omnigraph_compiler::schema::parser::parse_schema; + + fn test_catalog() -> Catalog { + let schema = parse_schema( + r#" +node User { +name: String +age: I32? +embedding: Vector(4) +} +"#, + ) + .unwrap(); + build_catalog(&schema).unwrap() + } + + #[test] + fn check_passes_for_valid_query() { + let reg = QueryRegistry::from_specs(vec![spec( + "find_user", + "query find_user($name: String) { match { $u: User { name: $name } } return { $u.age } }", + false, + )]) + .unwrap(); + let report = check(®, &test_catalog()); + assert!(report.is_clean(), "unexpected: {:?}", report); + } + + #[test] + fn check_reports_unknown_type_as_breakage() { + let reg = QueryRegistry::from_specs(vec![spec( + "ghost", + // `Widget` is not in the schema. + "query ghost() { match { $w: Widget } return { $w.name } }", + false, + )]) + .unwrap(); + let report = check(®, &test_catalog()); + assert!(report.has_breakages()); + assert_eq!(report.breakages[0].query, "ghost"); + } + + #[test] + fn check_reports_unknown_property_as_breakage() { + let reg = QueryRegistry::from_specs(vec![spec( + "bad_prop", + // `User` exists but has no `nickname`. + "query bad_prop() { match { $u: User } return { $u.nickname } }", + false, + )]) + .unwrap(); + let report = check(®, &test_catalog()); + assert!(report.has_breakages()); + assert_eq!(report.breakages[0].query, "bad_prop"); + } + + #[test] + fn check_collects_every_breakage_not_fail_fast() { + let reg = QueryRegistry::from_specs(vec![ + spec("a", "query a() { match { $w: Widget } return { $w.x } }", false), + spec("b", "query b() { match { $g: Gadget } return { $g.y } }", false), + spec( + "ok", + "query ok() { match { $u: User } return { $u.name } }", + false, + ), + ]) + .unwrap(); + let report = check(®, &test_catalog()); + assert_eq!(report.breakages.len(), 2, "both bad queries reported: {:?}", report); + } + + #[test] + fn vector_param_on_exposed_query_warns() { + let reg = QueryRegistry::from_specs(vec![spec( + "vec_search", + "query vec_search($q: Vector(4)) { match { $u: User } return { $u.name } \ + order { nearest($u.embedding, $q) } limit 3 }", + true, // mcp.expose + )]) + .unwrap(); + let report = check(®, &test_catalog()); + assert!(!report.has_breakages(), "valid query: {:?}", report); + assert_eq!(report.warnings.len(), 1); + assert_eq!(report.warnings[0].query, "vec_search"); + } + + #[test] + fn vector_param_on_unexposed_query_is_silent() { + let reg = QueryRegistry::from_specs(vec![spec( + "vec_search", + "query vec_search($q: Vector(4)) { match { $u: User } return { $u.name } \ + order { nearest($u.embedding, $q) } limit 3 }", + false, // not exposed — vector param is fine for service-to-service callers + )]) + .unwrap(); + let report = check(®, &test_catalog()); + assert!(report.is_clean(), "unexpected: {:?}", report); + } + + #[test] + fn non_vector_param_on_exposed_query_does_not_warn() { + // The recommended `String` alternative on an exposed query does not + // resolve to a Vector, so the embedding advisory stays silent. Guards + // the structured type check against a false positive (and pins that + // only `Vector(_)` triggers the warning). + let reg = QueryRegistry::from_specs(vec![spec( + "search", + "query search($name: String) { match { $u: User { name: $name } } return { $u.name } }", + true, + )]) + .unwrap(); + let report = check(®, &test_catalog()); + assert!(report.is_clean(), "no breakage or warning expected: {:?}", report); + } + + // --- catalog projection (api::query_catalog_entry) --- + + #[test] + fn catalog_entry_projects_every_param_kind() { + use crate::api::{self, ParamKind}; + let reg = QueryRegistry::from_specs(vec![spec_tool( + "all_types", + "query all_types($s: String, $i: I32, $big: I64, $u: U64, $f: F64, $b: Bool, \ + $d: Date, $dt: DateTime, $blob: Blob, $opt: String?, $list: [I32], $vec: Vector(4)) \ + { match { $x: User } return { $x.name } }", + true, + "all", + )]) + .unwrap(); + let entry = api::query_catalog_entry(reg.lookup("all_types").unwrap()); + assert_eq!(entry.name, "all_types"); + assert_eq!(entry.tool_name, "all"); + assert!(!entry.mutation); + + let by: std::collections::HashMap<_, _> = + entry.params.iter().map(|p| (p.name.as_str(), p)).collect(); + assert_eq!(by["s"].kind, ParamKind::String); + assert_eq!(by["i"].kind, ParamKind::Int); + assert_eq!(by["big"].kind, ParamKind::BigInt, "I64 → bigint (string on the wire)"); + assert_eq!(by["u"].kind, ParamKind::BigInt, "U64 → bigint"); + assert_eq!(by["f"].kind, ParamKind::Float); + assert_eq!(by["b"].kind, ParamKind::Bool); + assert_eq!(by["d"].kind, ParamKind::Date); + assert_eq!(by["dt"].kind, ParamKind::DateTime); + assert_eq!(by["blob"].kind, ParamKind::Blob); + assert!(!by["s"].nullable); + assert!(by["opt"].nullable, "String? → nullable"); + assert_eq!(by["list"].kind, ParamKind::List); + assert_eq!(by["list"].item_kind, Some(ParamKind::Int), "[I32] → list of int"); + assert_eq!(by["vec"].kind, ParamKind::Vector); + assert_eq!(by["vec"].vector_dim, Some(4)); + } + + #[test] + fn catalog_entry_flags_mutation_and_empty_params() { + use crate::api; + let reg = QueryRegistry::from_specs(vec![spec( + "add_user", + "query add_user($name: String) { insert User { name: $name } }", + true, + )]) + .unwrap(); + let entry = api::query_catalog_entry(reg.lookup("add_user").unwrap()); + assert!(entry.mutation, "insert body → mutation flag"); + + let reg2 = QueryRegistry::from_specs(vec![spec( + "no_params", + "query no_params() { match { $u: User } return { $u.name } }", + true, + )]) + .unwrap(); + let entry2 = api::query_catalog_entry(reg2.lookup("no_params").unwrap()); + assert!(entry2.params.is_empty(), "no declared params → empty list"); + } + + // --- load() error collection (file I/O + parse in one pass) --- + + #[test] + fn load_collects_io_and_parse_errors_in_one_pass() { + use crate::config::load_config; + let temp = tempfile::tempdir().unwrap(); + std::fs::write( + temp.path().join("good.gq"), + "query good() { match { $u: User } return { $u.name } }", + ) + .unwrap(); + std::fs::write(temp.path().join("broken.gq"), "query broken( {{ not valid").unwrap(); + // `missing.gq` is deliberately not written (an I/O failure). + std::fs::write( + temp.path().join("omnigraph.yaml"), + "queries:\n good:\n file: ./good.gq\n \ + missing:\n file: ./missing.gq\n broken:\n file: ./broken.gq\n", + ) + .unwrap(); + let config = load_config(Some(&temp.path().join("omnigraph.yaml"))).unwrap(); + + let errors = QueryRegistry::load(&config, config.query_entries()).unwrap_err(); + let joined = errors.iter().map(|e| e.to_string()).collect::>().join("\n"); + // Both the missing file AND the parse error surface in one pass — + // the I/O failure must not mask the parse failure. + assert!(joined.contains("missing"), "I/O error must surface: {joined}"); + assert!( + joined.contains("broken") && joined.contains("parse error"), + "the parse error in a readable file must surface in the same pass: {joined}" + ); + assert!(!joined.contains("'good'"), "the valid entry is not an error: {joined}"); + } +} diff --git a/crates/omnigraph-server/src/registry.rs b/crates/omnigraph-server/src/registry.rs new file mode 100644 index 0000000..54115e4 --- /dev/null +++ b/crates/omnigraph-server/src/registry.rs @@ -0,0 +1,570 @@ +//! `GraphRegistry` — the multi-graph routing substrate (MR-668). +//! +//! Holds the open `Arc` for every graph the server is currently +//! serving. Lock-free reads via `ArcSwap`; mutations +//! serialize through `mutate: Mutex<()>` for read-modify-write atomicity. +//! +//! **Deletion is deferred** in v0.6.0 (MR-668 scope cut). The registry has +//! no `tombstones` field, no `RegistryLookup::Tombstoned` variant, no +//! `tombstone()` / `clear_tombstone()` methods. When `DELETE /graphs/{id}` +//! lands in a follow-up release, those return without breaking caller +//! signatures (`Gone` is the closest semantic — the graph is no longer +//! in the registry). +//! +//! Engine instance survival across registry mutations: +//! a request that grabbed `Arc` before a registry swap keeps +//! the engine alive via its own `Arc` clone (see `server_export` at +//! `lib.rs:1019-1033` for the spawn-and-clone pattern). The engine drops +//! when the last `Arc` clone drops, regardless of the +//! registry's current state. + +use std::collections::HashMap; +use std::sync::Arc; + +use arc_swap::ArcSwap; +use omnigraph::db::Omnigraph; +use omnigraph::storage::normalize_root_uri; +#[cfg(test)] +use tokio::sync::Mutex; + +use crate::identity::GraphKey; +use crate::policy::PolicyEngine; +use crate::queries::QueryRegistry; + +/// Open handle for a single graph in the registry. Cheap to clone (`Arc`-wrapped +/// engine + policy). Cluster-mode handlers extract this via +/// `Extension>` injected by the routing middleware. +pub struct GraphHandle { + /// Registry key. In Cluster mode `key.tenant_id` is always `None`. + pub key: GraphKey, + /// The URI the engine was opened from (`s3://...` or local path). + /// Stable for the engine's lifetime; surfaced in responses like + /// `BranchCreateOutput.uri`. + pub uri: String, + /// Engine. Reads/writes go directly through `&self` methods on + /// `Omnigraph` (no `RwLock` — MR-686 preserved). + pub engine: Arc, + /// Per-graph Cedar policy. `None` means "no policy gate on engine-layer + /// `_as` writers"; the HTTP-layer `require_bearer_auth` middleware still + /// runs regardless. + pub policy: Option>, + /// Per-graph stored-query registry, loaded and validated at + /// startup. `None` means the operator declared no stored queries for + /// this graph — `POST /queries/{name}` then 404s. Mirrors the + /// optional `policy` shape. + pub queries: Option>, +} + +/// Immutable snapshot of the registry's current state. Replaced atomically +/// via `ArcSwap`; readers see a consistent view of all graphs without locking. +/// +/// Derived state (`any_per_graph_policy`) is computed at snapshot +/// construction so request-time middleware doesn't have to walk the +/// graph map every call. Construct only via [`RegistrySnapshot::new`] +/// (or `Default`) so the field stays in sync with `graphs`. +pub struct RegistrySnapshot { + pub graphs: HashMap>, + /// `true` iff any registered graph has a per-graph policy installed. + /// Used by `AppState::requires_bearer_auth` to decide whether the + /// auth middleware should challenge a request — a per-graph policy + /// implies bearer auth is required even when no server-level tokens + /// or policy are configured. + pub any_per_graph_policy: bool, +} + +impl RegistrySnapshot { + /// Build a snapshot from a graph map, deriving cached fields. + /// The only construction path — direct struct-literal use elsewhere + /// would let derived state drift from `graphs`. + pub fn new(graphs: HashMap>) -> Self { + let any_per_graph_policy = graphs.values().any(|h| h.policy.is_some()); + Self { + graphs, + any_per_graph_policy, + } + } +} + +impl Default for RegistrySnapshot { + fn default() -> Self { + Self::new(HashMap::new()) + } +} + +/// Result of a registry lookup. Two-valued — `Tombstoned` deferred with DELETE. +pub enum RegistryLookup { + /// Graph is open and ready to serve. + Ready(Arc), + /// Graph is not in the registry (never existed, or was unregistered in a + /// future release). Handlers respond with 404. + Gone, +} + +/// Why an `insert` was rejected. +#[derive(Debug, thiserror::Error)] +pub enum InsertError { + /// Another handle already exists for this `GraphKey`. Maps to HTTP 409. + #[error("graph '{0}' is already registered")] + DuplicateKey(GraphKey), + /// Another handle is open against this URI. Two graphs sharing a URI + /// would commit through the same Lance manifest and corrupt each other. + /// Maps to HTTP 409. + #[error("URI '{0}' is already registered as another graph")] + DuplicateUri(String), + /// A handle carried an invalid graph URI. Maps to startup failure. + #[error("URI '{uri}' is invalid: {message}")] + InvalidUri { uri: String, message: String }, +} + +pub struct GraphRegistry { + snapshot: ArcSwap, + /// Serializes runtime mutations through [`GraphRegistry::insert`]. + /// Gated with `insert` because they share a single contract — if + /// the consumer goes away, so does the lock. Re-introducing one + /// requires re-introducing the other. + #[cfg(test)] + mutate: Mutex<()>, +} + +impl GraphRegistry { + /// Empty registry. Used as a placeholder before startup populates it. + pub fn new() -> Self { + Self { + snapshot: ArcSwap::from_pointee(RegistrySnapshot::default()), + #[cfg(test)] + mutate: Mutex::new(()), + } + } + + /// Build a registry from a startup-time list of open handles. + /// Rejects duplicate `GraphKey`s and duplicate URIs. + pub fn from_handles(handles: Vec>) -> Result { + let mut graphs: HashMap> = HashMap::with_capacity(handles.len()); + let mut seen_uris: HashMap = HashMap::with_capacity(handles.len()); + for handle in handles { + let (canonical_uri, handle) = canonicalize_handle_uri(handle)?; + if graphs.contains_key(&handle.key) { + return Err(InsertError::DuplicateKey(handle.key.clone())); + } + if seen_uris.contains_key(&canonical_uri) { + return Err(InsertError::DuplicateUri(handle.uri.clone())); + } + seen_uris.insert(canonical_uri, handle.key.clone()); + graphs.insert(handle.key.clone(), handle); + } + Ok(Self { + snapshot: ArcSwap::from_pointee(RegistrySnapshot::new(graphs)), + #[cfg(test)] + mutate: Mutex::new(()), + }) + } + + /// Lock-free snapshot read. Callers that need derived state cached + /// on the snapshot (e.g. `any_per_graph_policy`) go through here; + /// callers that only need values of `graphs` should use [`list`] + /// or [`get`]. + pub fn snapshot_ref(&self) -> arc_swap::Guard> { + self.snapshot.load() + } + + /// Lock-free read. Returns `Ready` if the graph is in the current snapshot, + /// `Gone` otherwise. + pub fn get(&self, key: &GraphKey) -> RegistryLookup { + let snapshot = self.snapshot.load(); + match snapshot.graphs.get(key) { + Some(handle) => RegistryLookup::Ready(Arc::clone(handle)), + None => RegistryLookup::Gone, + } + } + + /// Snapshot the full set of currently-registered handles. Ordering + /// matches the underlying `HashMap` iteration (intentionally + /// non-deterministic — callers that need a stable order sort by + /// `handle.key.graph_id`). + pub fn list(&self) -> Vec> { + let snapshot = self.snapshot.load(); + snapshot.graphs.values().cloned().collect() + } + + /// Number of registered graphs (excluding any future tombstones). + pub fn len(&self) -> usize { + self.snapshot.load().graphs.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Add a new handle. Async because the mutex is `tokio::sync::Mutex` + /// (a future managed-catalog flow may hold it across `.await` points + /// during atomic registry mutations). Rejects duplicate `GraphKey` + /// and duplicate `uri`. + /// + /// **Test-only surface.** No production code reaches this — startup + /// uses `from_handles`, and runtime add/remove is deferred. The + /// race-contract tests below pin the mutex linearization point so + /// that when a real consumer ships (managed cluster catalog), the + /// concurrency contract is already proven. Ungate by removing + /// `#[cfg(test)]` once that consumer is in scope. + /// + /// Race semantics (pinned by `concurrent_insert_same_key_exactly_one_succeeds`): + /// under N concurrent calls with the same key, exactly one returns + /// `Ok(())` and the rest return `Err(InsertError::DuplicateKey(_))`. + #[cfg(test)] + pub async fn insert(&self, handle: Arc) -> Result<(), InsertError> { + let _guard = self.mutate.lock().await; + let current = self.snapshot.load(); + let (canonical_uri, handle) = canonicalize_handle_uri(handle)?; + if current.graphs.contains_key(&handle.key) { + return Err(InsertError::DuplicateKey(handle.key.clone())); + } + for existing in current.graphs.values() { + let existing_uri = + normalize_root_uri(&existing.uri).map_err(|err| InsertError::InvalidUri { + uri: existing.uri.clone(), + message: err.to_string(), + })?; + if existing_uri == canonical_uri { + return Err(InsertError::DuplicateUri(handle.uri.clone())); + } + } + let mut new_graphs = current.graphs.clone(); + new_graphs.insert(handle.key.clone(), handle); + self.snapshot + .store(Arc::new(RegistrySnapshot::new(new_graphs))); + Ok(()) + } +} + +fn canonicalize_handle_uri( + handle: Arc, +) -> Result<(String, Arc), InsertError> { + let canonical_uri = normalize_root_uri(&handle.uri).map_err(|err| InsertError::InvalidUri { + uri: handle.uri.clone(), + message: err.to_string(), + })?; + if canonical_uri == handle.uri { + return Ok((canonical_uri, handle)); + } + let canonical_handle = Arc::new(GraphHandle { + key: handle.key.clone(), + uri: canonical_uri.clone(), + engine: Arc::clone(&handle.engine), + policy: handle.policy.clone(), + queries: handle.queries.clone(), + }); + Ok((canonical_uri, canonical_handle)) +} + +impl Default for GraphRegistry { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use std::path::Path; + + use tempfile::TempDir; + + use super::*; + use crate::graph_id::GraphId; + + const TEST_SCHEMA: &str = "node Person { name: String @key }\n"; + + async fn build_handle(graph_id: &str, dir: &Path) -> Arc { + let graph_uri = dir.join(graph_id).to_str().unwrap().to_string(); + let engine = Omnigraph::init(&graph_uri, TEST_SCHEMA) + .await + .expect("init engine for registry test"); + Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from(graph_id).unwrap()), + uri: graph_uri, + engine: Arc::new(engine), + policy: None, + queries: None, + }) + } + + #[tokio::test] + async fn new_registry_is_empty() { + let registry = GraphRegistry::new(); + assert!(registry.is_empty()); + assert_eq!(registry.len(), 0); + assert!(registry.list().is_empty()); + } + + #[tokio::test] + async fn insert_then_get_returns_ready() { + let dir = TempDir::new().unwrap(); + let registry = GraphRegistry::new(); + let handle = build_handle("alpha", dir.path()).await; + registry.insert(Arc::clone(&handle)).await.unwrap(); + + match registry.get(&handle.key) { + RegistryLookup::Ready(found) => { + assert!(Arc::ptr_eq(&found, &handle)); + } + RegistryLookup::Gone => panic!("expected Ready, got Gone"), + } + } + + #[tokio::test] + async fn get_nonexistent_returns_gone() { + let registry = GraphRegistry::new(); + let key = GraphKey::cluster(GraphId::try_from("ghost").unwrap()); + match registry.get(&key) { + RegistryLookup::Gone => {} + RegistryLookup::Ready(_) => panic!("expected Gone"), + } + } + + #[tokio::test] + async fn insert_duplicate_key_returns_error() { + let dir = TempDir::new().unwrap(); + let registry = GraphRegistry::new(); + let h1 = build_handle("alpha", dir.path()).await; + // Same key, different URI sub-path (build_handle uses graph_id as subdir). + let dir2 = TempDir::new().unwrap(); + let h2 = build_handle("alpha", dir2.path()).await; + registry.insert(h1).await.unwrap(); + + match registry.insert(h2).await { + Err(InsertError::DuplicateKey(_)) => {} + other => panic!("expected DuplicateKey, got {other:?}"), + } + } + + #[tokio::test] + async fn insert_duplicate_uri_returns_error() { + let dir = TempDir::new().unwrap(); + // Two handles with the same URI but different keys. + let shared_uri = dir.path().join("shared").to_str().unwrap().to_string(); + let engine = Omnigraph::init(&shared_uri, TEST_SCHEMA).await.unwrap(); + let engine = Arc::new(engine); + let h1 = Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from("alpha").unwrap()), + uri: shared_uri.clone(), + engine: Arc::clone(&engine), + policy: None, + queries: None, + }); + let h2 = Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from("beta").unwrap()), + uri: shared_uri, + engine, + policy: None, + queries: None, + }); + + let registry = GraphRegistry::new(); + registry.insert(h1).await.unwrap(); + match registry.insert(h2).await { + Err(InsertError::DuplicateUri(_)) => {} + other => panic!("expected DuplicateUri, got {other:?}"), + } + } + + #[tokio::test] + async fn list_returns_all_inserted_handles() { + let dir = TempDir::new().unwrap(); + let registry = GraphRegistry::new(); + for name in ["alpha", "beta", "gamma"] { + let h = build_handle(name, dir.path()).await; + registry.insert(h).await.unwrap(); + } + assert_eq!(registry.len(), 3); + let mut ids: Vec<_> = registry + .list() + .into_iter() + .map(|h| h.key.graph_id.as_str().to_string()) + .collect(); + ids.sort(); + assert_eq!(ids, vec!["alpha", "beta", "gamma"]); + } + + #[tokio::test] + async fn from_handles_bulk_init_succeeds() { + let dir = TempDir::new().unwrap(); + let handles = vec![ + build_handle("alpha", dir.path()).await, + build_handle("beta", dir.path()).await, + ]; + let registry = GraphRegistry::from_handles(handles).unwrap(); + assert_eq!(registry.len(), 2); + } + + #[tokio::test] + async fn from_handles_rejects_duplicate_keys() { + let dir1 = TempDir::new().unwrap(); + let dir2 = TempDir::new().unwrap(); + let h1 = build_handle("alpha", dir1.path()).await; + let h2 = build_handle("alpha", dir2.path()).await; + let err = match GraphRegistry::from_handles(vec![h1, h2]) { + Ok(_) => panic!("expected DuplicateKey, got Ok"), + Err(err) => err, + }; + assert!( + matches!(err, InsertError::DuplicateKey(_)), + "expected DuplicateKey, got {err}", + ); + } + + #[tokio::test] + async fn from_handles_rejects_duplicate_uris() { + let dir = TempDir::new().unwrap(); + let shared_uri = dir.path().join("shared").to_str().unwrap().to_string(); + let engine = Arc::new(Omnigraph::init(&shared_uri, TEST_SCHEMA).await.unwrap()); + let h1 = Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from("alpha").unwrap()), + uri: shared_uri.clone(), + engine: Arc::clone(&engine), + policy: None, + queries: None, + }); + let h2 = Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from("beta").unwrap()), + uri: shared_uri, + engine, + policy: None, + queries: None, + }); + let err = match GraphRegistry::from_handles(vec![h1, h2]) { + Ok(_) => panic!("expected DuplicateUri, got Ok"), + Err(err) => err, + }; + assert!( + matches!(err, InsertError::DuplicateUri(_)), + "expected DuplicateUri, got {err}", + ); + } + + /// Race test modeled on `actor_admission_race_does_not_exceed_cap` + /// at `tests/server.rs:3596+`. Spawn N concurrent inserts with the + /// same `GraphKey` (each constructing its own `GraphHandle` against + /// its own tempdir). Exactly one must succeed; the others must + /// return `DuplicateKey`. No `unwrap` panic: the `Mutex<()>` + + /// in-mutex re-check is the linearization point. + #[tokio::test(flavor = "multi_thread")] + async fn concurrent_insert_same_key_exactly_one_succeeds() { + const N: usize = 8; + + let registry = Arc::new(GraphRegistry::new()); + // Pre-create N handles (each in its own tempdir; same key). + let mut handles = Vec::with_capacity(N); + let mut dirs = Vec::with_capacity(N); + for _ in 0..N { + let d = TempDir::new().unwrap(); + handles.push(build_handle("contested", d.path()).await); + dirs.push(d); + } + + let barrier = Arc::new(tokio::sync::Barrier::new(N)); + let mut tasks = Vec::with_capacity(N); + for handle in handles { + let registry = Arc::clone(®istry); + let barrier = Arc::clone(&barrier); + tasks.push(tokio::spawn(async move { + barrier.wait().await; + registry.insert(handle).await + })); + } + + let mut ok_count = 0usize; + let mut dup_count = 0usize; + for t in tasks { + match t.await.unwrap() { + Ok(()) => ok_count += 1, + Err(InsertError::DuplicateKey(_)) => dup_count += 1, + Err(other) => panic!("unexpected error: {other:?}"), + } + } + assert_eq!(ok_count, 1, "exactly one insert must succeed"); + assert_eq!(dup_count, N - 1, "the rest must return DuplicateKey"); + assert_eq!(registry.len(), 1); + + // Drop the dirs at the end (preserves engines until tasks finish). + drop(dirs); + } + + /// Concurrent inserts with **distinct** keys all succeed. + /// Linearizability over the mutex still serializes them. + #[tokio::test(flavor = "multi_thread")] + async fn concurrent_insert_distinct_keys_all_succeed() { + const N: usize = 8; + + let registry = Arc::new(GraphRegistry::new()); + // Pre-create N handles with distinct ids, each in its own tempdir. + let mut handles = Vec::with_capacity(N); + let mut dirs = Vec::with_capacity(N); + for i in 0..N { + let d = TempDir::new().unwrap(); + handles.push(build_handle(&format!("graph-{i}"), d.path()).await); + dirs.push(d); + } + + let barrier = Arc::new(tokio::sync::Barrier::new(N)); + let mut tasks = Vec::with_capacity(N); + for handle in handles { + let registry = Arc::clone(®istry); + let barrier = Arc::clone(&barrier); + tasks.push(tokio::spawn(async move { + barrier.wait().await; + registry.insert(handle).await + })); + } + for t in tasks { + t.await.unwrap().unwrap(); + } + assert_eq!(registry.len(), N); + drop(dirs); + } + + /// Concurrent reads during a write must always see a consistent + /// snapshot (no torn state). With `ArcSwap`, the read either sees + /// the old snapshot or the new one — never both, never neither. + #[tokio::test(flavor = "multi_thread")] + async fn concurrent_reads_during_inserts_see_consistent_snapshots() { + let dir = TempDir::new().unwrap(); + let registry = Arc::new(GraphRegistry::new()); + + // Spawn a writer that inserts graph-0..graph-9 sequentially. + const N_WRITES: usize = 10; + let writer_registry = Arc::clone(®istry); + let writer_dir = dir.path().to_path_buf(); + let writer = tokio::spawn(async move { + for i in 0..N_WRITES { + let h = build_handle(&format!("graph-{i}"), &writer_dir).await; + writer_registry.insert(h).await.unwrap(); + } + }); + + // Reader loop: repeatedly snapshot the registry until the writer + // finishes. Every snapshot's len must be in [0, N_WRITES], and + // for every key g in the snapshot, get(g) must return Ready. + let reader_registry = Arc::clone(®istry); + let reader = tokio::spawn(async move { + for _ in 0..200 { + let snap = reader_registry.list(); + assert!(snap.len() <= N_WRITES); + for handle in &snap { + match reader_registry.get(&handle.key) { + RegistryLookup::Ready(found) => { + assert!(Arc::ptr_eq(&found, handle)); + } + RegistryLookup::Gone => panic!( + "snapshot listed key {} but get() returned Gone", + handle.key.graph_id + ), + } + } + tokio::task::yield_now().await; + } + }); + + writer.await.unwrap(); + reader.await.unwrap(); + assert_eq!(registry.len(), N_WRITES); + } +} diff --git a/crates/omnigraph-server/src/workload.rs b/crates/omnigraph-server/src/workload.rs index efc7068..4e84532 100644 --- a/crates/omnigraph-server/src/workload.rs +++ b/crates/omnigraph-server/src/workload.rs @@ -270,12 +270,13 @@ mod tests { let err = controller .try_admit(&actor, 100) .expect_err("third should reject on count"); - assert!(matches!(err, RejectReason::InFlightCountExceeded { cap: 2 })); + assert!(matches!( + err, + RejectReason::InFlightCountExceeded { cap: 2 } + )); drop(g1); // After drop, a new admit succeeds again. - let _g3 = controller - .try_admit(&actor, 100) - .expect("admit after drop"); + let _g3 = controller.try_admit(&actor, 100).expect("admit after drop"); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -356,7 +357,9 @@ mod tests { let bob: Arc = "bob".into(); let _ga = controller.try_admit(&alice, 100).expect("alice ok"); // Alice over count cap, Bob unaffected. - let err = controller.try_admit(&alice, 100).expect_err("alice rejected"); + let err = controller + .try_admit(&alice, 100) + .expect_err("alice rejected"); assert!(matches!(err, RejectReason::InFlightCountExceeded { .. })); let _gb = controller.try_admit(&bob, 100).expect("bob ok"); } diff --git a/crates/omnigraph-server/tests/openapi.rs b/crates/omnigraph-server/tests/openapi.rs index 86a124d..3d13e74 100644 --- a/crates/omnigraph-server/tests/openapi.rs +++ b/crates/omnigraph-server/tests/openapi.rs @@ -19,42 +19,42 @@ fn fixture(name: &str) -> PathBuf { .join(name) } -fn repo_path(root: &Path) -> PathBuf { +fn graph_path(root: &Path) -> PathBuf { root.join("openapi_test.omni") } -async fn init_loaded_repo() -> tempfile::TempDir { +async fn init_loaded_graph() -> tempfile::TempDir { let temp = tempfile::tempdir().unwrap(); - let repo = repo_path(temp.path()); - fs::create_dir_all(&repo).unwrap(); + let graph = graph_path(temp.path()); + fs::create_dir_all(&graph).unwrap(); let schema = fs::read_to_string(fixture("test.pg")).unwrap(); let data = fs::read_to_string(fixture("test.jsonl")).unwrap(); - Omnigraph::init(repo.to_str().unwrap(), &schema) + Omnigraph::init(graph.to_str().unwrap(), &schema) .await .unwrap(); - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); load_jsonl(&mut db, &data, LoadMode::Overwrite) .await .unwrap(); temp } -async fn app_for_loaded_repo() -> (tempfile::TempDir, Router) { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let state = AppState::open(repo.to_string_lossy().to_string()) +async fn app_for_loaded_graph() -> (tempfile::TempDir, Router) { + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let state = AppState::open(graph.to_string_lossy().to_string()) .await .unwrap(); let app = build_app(state); (temp, app) } -async fn app_for_loaded_repo_with_auth(token: &str) -> (tempfile::TempDir, Router) { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); +async fn app_for_loaded_graph_with_auth(token: &str) -> (tempfile::TempDir, Router) { + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); let state = AppState::new_with_bearer_token( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), db, Some(token.to_string()), ); @@ -84,7 +84,7 @@ fn openapi_json() -> Value { #[tokio::test] async fn openapi_endpoint_returns_200_with_valid_json() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let request = Request::builder() .method(Method::GET) .uri("/openapi.json") @@ -97,7 +97,7 @@ async fn openapi_endpoint_returns_200_with_valid_json() { #[tokio::test] async fn openapi_endpoint_returns_openapi_31_version() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let request = Request::builder() .method(Method::GET) .uri("/openapi.json") @@ -113,11 +113,11 @@ async fn openapi_endpoint_returns_openapi_31_version() { #[tokio::test] async fn openapi_endpoint_does_not_require_auth() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); let state = AppState::new_with_bearer_token( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), db, Some("secret-token".to_string()), ); @@ -129,7 +129,11 @@ async fn openapi_endpoint_does_not_require_auth() { .body(Body::empty()) .unwrap(); let (status, _) = json_response(&app, request).await; - assert_eq!(status, StatusCode::OK, "/openapi.json should not require auth"); + assert_eq!( + status, + StatusCode::OK, + "/openapi.json should not require auth" + ); } // --------------------------------------------------------------------------- @@ -157,10 +161,15 @@ fn openapi_info_contains_version() { const EXPECTED_PATHS: &[&str] = &[ "/healthz", + "/graphs", "/snapshot", "/read", + "/query", "/export", "/change", + "/mutate", + "/queries", + "/queries/{name}", "/schema", "/schema/apply", "/ingest", @@ -227,6 +236,64 @@ fn openapi_change_is_post() { assert!(doc["paths"]["/change"]["post"].is_object()); } +#[test] +fn openapi_mutate_is_post() { + let doc = openapi_json(); + assert!(doc["paths"]["/mutate"]["post"].is_object()); +} + +// Deprecation flagging — `/read` and `/change` are kept indefinitely for +// back-compat but are flagged so OpenAPI codegens (typescript-fetch, +// openapi-generator, oapi-codegen, etc.) emit @deprecated on the generated +// SDK methods. The canonical successors `/query` and `/mutate` are not +// flagged. See `deprecation_headers` in `omnigraph-server/src/lib.rs` for +// the matching runtime signal (RFC 9745 + RFC 8288 headers). +#[test] +fn openapi_read_is_deprecated() { + let doc = openapi_json(); + assert_eq!( + doc["paths"]["/read"]["post"]["deprecated"], + serde_json::Value::Bool(true), + "/read must be flagged deprecated in OpenAPI; use /query instead" + ); +} + +#[test] +fn openapi_change_is_deprecated() { + let doc = openapi_json(); + assert_eq!( + doc["paths"]["/change"]["post"]["deprecated"], + serde_json::Value::Bool(true), + "/change must be flagged deprecated in OpenAPI; use /mutate instead" + ); +} + +#[test] +fn openapi_query_is_not_deprecated() { + let doc = openapi_json(); + let deprecated = doc["paths"]["/query"]["post"] + .get("deprecated") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + assert!( + !deprecated, + "/query is the canonical read endpoint and must not be deprecated" + ); +} + +#[test] +fn openapi_mutate_is_not_deprecated() { + let doc = openapi_json(); + let deprecated = doc["paths"]["/mutate"]["post"] + .get("deprecated") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + assert!( + !deprecated, + "/mutate is the canonical mutation endpoint and must not be deprecated" + ); +} + #[test] fn openapi_ingest_is_post() { let doc = openapi_json(); @@ -278,6 +345,7 @@ const EXPECTED_SCHEMAS: &[&str] = &[ "BranchMergeRequest", "ChangeOutput", "ChangeRequest", + "QueryRequest", "CommitListOutput", "CommitOutput", "ErrorCode", @@ -368,13 +436,65 @@ fn read_output_schema_has_expected_fields() { #[test] fn change_request_schema_has_expected_fields() { + // Canonical field names on the wire are now `query` and `name`. The + // schema descriptions document `query_source` and `query_name` as + // legacy deserialization aliases for backward compatibility. let doc = openapi_json(); let schema = &doc["components"]["schemas"]["ChangeRequest"]; let props = schema["properties"].as_object().unwrap(); - assert!(props.contains_key("query_source")); - assert!(props.contains_key("query_name")); + assert!(props.contains_key("query")); + assert!(props.contains_key("name")); assert!(props.contains_key("params")); assert!(props.contains_key("branch")); + let query_desc = schema["properties"]["query"]["description"] + .as_str() + .unwrap_or_default(); + assert!( + query_desc.contains("query_source"), + "expected `query` description to mention the legacy `query_source` alias, got: {query_desc}" + ); +} + +#[test] +fn query_request_schema_has_expected_fields() { + let doc = openapi_json(); + let schema = &doc["components"]["schemas"]["QueryRequest"]; + let props = schema["properties"].as_object().unwrap(); + assert!(props.contains_key("query")); + assert!(props.contains_key("name")); + assert!(props.contains_key("params")); + assert!(props.contains_key("branch")); + assert!(props.contains_key("snapshot")); +} + +#[test] +fn query_request_query_is_required() { + let doc = openapi_json(); + let schema = &doc["components"]["schemas"]["QueryRequest"]; + let required: Vec<&str> = schema["required"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap()) + .collect(); + assert!(required.contains(&"query")); +} + +#[test] +fn openapi_query_is_post() { + let doc = openapi_json(); + assert!(doc["paths"]["/query"]["post"].is_object()); +} + +#[test] +fn query_endpoint_documents_mutation_400() { + let doc = openapi_json(); + let four_hundred = &doc["paths"]["/query"]["post"]["responses"]["400"]; + let description = four_hundred["description"].as_str().unwrap_or_default(); + assert!( + description.contains("mutations") || description.contains("POST /mutate"), + "expected /query 400 response to mention mutation rejection, got: {description}" + ); } #[test] @@ -583,6 +703,8 @@ fn protected_endpoints_reference_bearer_token_security() { ("/read", "post"), ("/change", "post"), ("/schema/apply", "post"), + ("/queries", "get"), + ("/queries/{name}", "post"), ("/ingest", "post"), ("/export", "post"), ("/snapshot", "get"), @@ -626,10 +748,13 @@ fn branch_delete_has_branch_path_parameter() { let params = doc["paths"]["/branches/{branch}"]["delete"]["parameters"] .as_array() .unwrap(); - let has_branch = params.iter().any(|p| { - p["name"].as_str() == Some("branch") && p["in"].as_str() == Some("path") - }); - assert!(has_branch, "DELETE /branches/{{branch}} must have 'branch' path parameter"); + let has_branch = params + .iter() + .any(|p| p["name"].as_str() == Some("branch") && p["in"].as_str() == Some("path")); + assert!( + has_branch, + "DELETE /branches/{{branch}} must have 'branch' path parameter" + ); } #[test] @@ -638,10 +763,13 @@ fn commit_show_has_commit_id_path_parameter() { let params = doc["paths"]["/commits/{commit_id}"]["get"]["parameters"] .as_array() .unwrap(); - let has_commit_id = params.iter().any(|p| { - p["name"].as_str() == Some("commit_id") && p["in"].as_str() == Some("path") - }); - assert!(has_commit_id, "GET /commits/{{commit_id}} must have 'commit_id' path parameter"); + let has_commit_id = params + .iter() + .any(|p| p["name"].as_str() == Some("commit_id") && p["in"].as_str() == Some("path")); + assert!( + has_commit_id, + "GET /commits/{{commit_id}} must have 'commit_id' path parameter" + ); } #[test] @@ -650,10 +778,13 @@ fn snapshot_has_branch_query_parameter() { let params = doc["paths"]["/snapshot"]["get"]["parameters"] .as_array() .unwrap(); - let has_branch = params.iter().any(|p| { - p["name"].as_str() == Some("branch") && p["in"].as_str() == Some("query") - }); - assert!(has_branch, "GET /snapshot must have 'branch' query parameter"); + let has_branch = params + .iter() + .any(|p| p["name"].as_str() == Some("branch") && p["in"].as_str() == Some("query")); + assert!( + has_branch, + "GET /snapshot must have 'branch' query parameter" + ); } #[test] @@ -662,10 +793,13 @@ fn commits_has_branch_query_parameter() { let params = doc["paths"]["/commits"]["get"]["parameters"] .as_array() .unwrap(); - let has_branch = params.iter().any(|p| { - p["name"].as_str() == Some("branch") && p["in"].as_str() == Some("query") - }); - assert!(has_branch, "GET /commits must have 'branch' query parameter"); + let has_branch = params + .iter() + .any(|p| p["name"].as_str() == Some("branch") && p["in"].as_str() == Some("query")); + assert!( + has_branch, + "GET /commits must have 'branch' query parameter" + ); } // --------------------------------------------------------------------------- @@ -741,8 +875,7 @@ fn error_responses_reference_error_output_schema() { ]; for (path, method, status) in paths_with_errors { - let content = - &doc["paths"][path][method]["responses"][status]["content"]; + let content = &doc["paths"][path][method]["responses"][status]["content"]; let schema = &content["application/json"]["schema"]; let ref_path = schema["$ref"].as_str().unwrap(); assert!( @@ -784,6 +917,34 @@ fn post_endpoints_have_request_body() { } } +#[test] +fn invoke_stored_query_request_body_is_optional() { + let doc = openapi_json(); + let request_body = &doc["paths"]["/queries/{name}"]["post"]["requestBody"]; + assert!( + request_body.is_object(), + "POST /queries/{{name}} should document its optional request body" + ); + assert_eq!( + request_body["required"].as_bool().unwrap_or(false), + false, + "stored-query invocation body should be optional" + ); + let schema = &request_body["content"]["application/json"]["schema"]; + let ref_path = schema["$ref"] + .as_str() + .or_else(|| { + schema["oneOf"] + .as_array() + .and_then(|schemas| schemas.iter().find_map(|schema| schema["$ref"].as_str())) + }) + .unwrap(); + assert!( + ref_path.contains("InvokeStoredQueryRequest"), + "POST /queries/{{name}} requestBody should reference InvokeStoredQueryRequest, got {ref_path}" + ); +} + // --------------------------------------------------------------------------- // Serialization round-trip test // --------------------------------------------------------------------------- @@ -804,7 +965,7 @@ fn openapi_spec_round_trips_through_json() { #[tokio::test] async fn open_mode_spec_has_no_security_schemes() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let request = Request::builder() .method(Method::GET) .uri("/openapi.json") @@ -820,7 +981,7 @@ async fn open_mode_spec_has_no_security_schemes() { #[tokio::test] async fn open_mode_spec_has_no_operation_security() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let request = Request::builder() .method(Method::GET) .uri("/openapi.json") @@ -841,7 +1002,7 @@ async fn open_mode_spec_has_no_operation_security() { #[tokio::test] async fn auth_mode_spec_includes_bearer_token_security_scheme() { - let (_temp, app) = app_for_loaded_repo_with_auth("secret").await; + let (_temp, app) = app_for_loaded_graph_with_auth("secret").await; let request = Request::builder() .method(Method::GET) .uri("/openapi.json") @@ -855,7 +1016,7 @@ async fn auth_mode_spec_includes_bearer_token_security_scheme() { #[tokio::test] async fn auth_mode_spec_has_security_on_protected_operations() { - let (_temp, app) = app_for_loaded_repo_with_auth("secret").await; + let (_temp, app) = app_for_loaded_graph_with_auth("secret").await; let request = Request::builder() .method(Method::GET) .uri("/openapi.json") @@ -886,7 +1047,7 @@ async fn auth_mode_spec_has_security_on_protected_operations() { #[tokio::test] async fn auth_mode_spec_matches_static_generation() { - let (_temp, app) = app_for_loaded_repo_with_auth("secret").await; + let (_temp, app) = app_for_loaded_graph_with_auth("secret").await; let request = Request::builder() .method(Method::GET) .uri("/openapi.json") @@ -902,7 +1063,7 @@ async fn auth_mode_spec_matches_static_generation() { #[tokio::test] async fn auth_mode_healthz_still_has_no_security() { - let (_temp, app) = app_for_loaded_repo_with_auth("secret").await; + let (_temp, app) = app_for_loaded_graph_with_auth("secret").await; let request = Request::builder() .method(Method::GET) .uri("/openapi.json") @@ -918,8 +1079,7 @@ async fn auth_mode_healthz_still_has_no_security() { #[test] fn openapi_spec_is_up_to_date() { - let spec_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../openapi.json"); + let spec_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../openapi.json"); let generated = serde_json::to_string_pretty(&openapi_doc()).unwrap() + "\n"; @@ -943,3 +1103,290 @@ fn openapi_spec_is_up_to_date() { "openapi.json is out of date. Run: OMNIGRAPH_UPDATE_OPENAPI=1 cargo test -p omnigraph-server --test openapi openapi_spec_is_up_to_date" ); } + +// --------------------------------------------------------------------------- +// MR-668 — multi-mode OpenAPI cluster filter +// --------------------------------------------------------------------------- +// +// In multi-graph mode, `/openapi.json` reports cluster routes +// (`/graphs/{graph_id}/...`) instead of the legacy flat routes. The +// only flat path that survives is `/healthz`. Operation IDs gain a +// `cluster_` prefix so SDK generators have stable, unique ids. +// +// These tests exercise the request-time `server_openapi` handler via +// `oneshot`, not the static `ApiDoc::openapi()` — the rewrite happens +// only on the served document. + +const EXPECTED_CLUSTER_PATHS: &[&str] = &[ + "/graphs/{graph_id}/snapshot", + "/graphs/{graph_id}/read", + "/graphs/{graph_id}/export", + "/graphs/{graph_id}/change", + "/graphs/{graph_id}/schema", + "/graphs/{graph_id}/schema/apply", + "/graphs/{graph_id}/ingest", + "/graphs/{graph_id}/branches", + "/graphs/{graph_id}/branches/{branch}", + "/graphs/{graph_id}/branches/merge", + "/graphs/{graph_id}/commits", + "/graphs/{graph_id}/commits/{commit_id}", +]; + +async fn app_for_multi_mode(graph_ids: &[&str]) -> (Vec, Router) { + use std::sync::Arc; + + use omnigraph_server::{GraphHandle, GraphId, GraphKey}; + + let mut dirs = Vec::with_capacity(graph_ids.len()); + let mut handles = Vec::with_capacity(graph_ids.len()); + for id in graph_ids { + let dir = tempfile::tempdir().unwrap(); + let graph_uri = dir.path().join(id).to_str().unwrap().to_string(); + let schema = fs::read_to_string(fixture("test.pg")).unwrap(); + let engine = Omnigraph::init(&graph_uri, &schema).await.unwrap(); + handles.push(Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from(*id).unwrap()), + uri: graph_uri, + engine: Arc::new(engine), + policy: None, + queries: None, + })); + dirs.push(dir); + } + let workload = omnigraph_server::workload::WorkloadController::from_env(); + let state = AppState::new_multi(handles, Vec::new(), None, workload, None).unwrap(); + let app = build_app(state); + (dirs, app) +} + +#[tokio::test] +async fn multi_mode_openapi_lists_cluster_paths() { + let (_dirs, app) = app_for_multi_mode(&["alpha"]).await; + let request = Request::builder() + .method(Method::GET) + .uri("/openapi.json") + .body(Body::empty()) + .unwrap(); + let (status, json) = json_response(&app, request).await; + assert_eq!(status, StatusCode::OK); + let paths = json["paths"].as_object().expect("paths must be an object"); + let path_keys: HashSet<&str> = paths.keys().map(|k| k.as_str()).collect(); + for expected in EXPECTED_CLUSTER_PATHS { + assert!( + path_keys.contains(expected), + "missing cluster path in multi-mode spec: {expected}. \ + Found: {path_keys:?}" + ); + } +} + +#[tokio::test] +async fn multi_mode_openapi_drops_flat_protected_paths() { + let (_dirs, app) = app_for_multi_mode(&["alpha"]).await; + let request = Request::builder() + .method(Method::GET) + .uri("/openapi.json") + .body(Body::empty()) + .unwrap(); + let (_, json) = json_response(&app, request).await; + let paths = json["paths"].as_object().unwrap(); + // None of the legacy flat protected paths should appear in multi mode. + let flat_protected = [ + "/snapshot", + "/read", + "/export", + "/change", + "/schema", + "/schema/apply", + "/ingest", + "/branches", + "/branches/{branch}", + "/branches/merge", + "/commits", + "/commits/{commit_id}", + ]; + for flat in flat_protected { + assert!( + !paths.contains_key(flat), + "flat path {flat} must not appear in multi-mode spec; \ + cluster routes are the only protected surface" + ); + } +} + +#[tokio::test] +async fn multi_mode_openapi_keeps_management_paths_flat() { + let (_dirs, app) = app_for_multi_mode(&["alpha"]).await; + let request = Request::builder() + .method(Method::GET) + .uri("/openapi.json") + .body(Body::empty()) + .unwrap(); + let (_, json) = json_response(&app, request).await; + let paths = json["paths"].as_object().unwrap(); + for flat in ["/healthz", "/graphs"] { + assert!( + paths.contains_key(flat), + "{flat} must remain flat in multi mode" + ); + let nested = format!("/graphs/{{graph_id}}{flat}"); + assert!( + !paths.contains_key(&nested), + "{flat} must NOT be cluster-prefixed to {nested}" + ); + } +} + +#[tokio::test] +async fn multi_mode_openapi_prefixes_operation_ids_with_cluster() { + let (_dirs, app) = app_for_multi_mode(&["alpha"]).await; + let request = Request::builder() + .method(Method::GET) + .uri("/openapi.json") + .body(Body::empty()) + .unwrap(); + let (_, json) = json_response(&app, request).await; + // Every cluster path operation must have a `cluster_` operation_id. + // Flat-mounted paths (healthz, management /graphs) keep their + // original operation_ids — they're not per-graph. + let paths = json["paths"].as_object().unwrap(); + let mut checked = 0; + for (path, item) in paths { + if path == "/healthz" || path == "/graphs" { + continue; + } + for method in ["get", "post", "put", "delete", "patch"] { + if let Some(op) = item.get(method).filter(|v| v.is_object()) { + if let Some(id) = op["operationId"].as_str() { + assert!( + id.starts_with("cluster_"), + "operation_id at {path}.{method} must start with `cluster_`, got `{id}`" + ); + checked += 1; + } + } + } + } + assert!( + checked >= EXPECTED_CLUSTER_PATHS.len(), + "expected at least {} cluster operation_ids; checked {checked}", + EXPECTED_CLUSTER_PATHS.len() + ); +} + +#[tokio::test] +async fn multi_mode_openapi_declares_graph_id_path_parameter() { + let (_dirs, app) = app_for_multi_mode(&["alpha"]).await; + let request = Request::builder() + .method(Method::GET) + .uri("/openapi.json") + .body(Body::empty()) + .unwrap(); + let (_, json) = json_response(&app, request).await; + let paths = json["paths"].as_object().unwrap(); + + for expected_path in EXPECTED_CLUSTER_PATHS { + let item = paths + .get(*expected_path) + .unwrap_or_else(|| panic!("missing cluster path {expected_path}")); + for method in ["get", "post", "put", "delete", "patch"] { + let Some(operation) = item.get(method).filter(|value| value.is_object()) else { + continue; + }; + let parameters = operation["parameters"] + .as_array() + .unwrap_or_else(|| panic!("{expected_path}.{method} missing parameters")); + let graph_id = parameters + .iter() + .find(|param| param["name"] == "graph_id" && param["in"] == "path") + .unwrap_or_else(|| { + panic!("{expected_path}.{method} missing graph_id path parameter") + }); + assert_eq!( + graph_id["required"].as_bool(), + Some(true), + "{expected_path}.{method} graph_id parameter must be required" + ); + assert_eq!( + graph_id["schema"]["type"].as_str(), + Some("string"), + "{expected_path}.{method} graph_id parameter must be string typed" + ); + } + } + + for flat in ["/healthz", "/graphs"] { + let item = paths.get(flat).unwrap(); + for method in ["get", "post", "put", "delete", "patch"] { + if let Some(operation) = item.get(method).filter(|value| value.is_object()) { + let has_graph_id = operation["parameters"] + .as_array() + .map(|params| { + params + .iter() + .any(|param| param["name"] == "graph_id" && param["in"] == "path") + }) + .unwrap_or(false); + assert!( + !has_graph_id, + "{flat}.{method} must not declare graph_id; it remains flat" + ); + } + } + } +} + +#[tokio::test] +async fn multi_mode_operation_ids_are_unique() { + // Sanity check: the cluster_ prefix prevents collision with flat ids + // (which don't appear in multi mode, but the contract is "unique + // across the spec"). Verify every operation_id in the multi-mode + // spec is unique. + let (_dirs, app) = app_for_multi_mode(&["alpha"]).await; + let request = Request::builder() + .method(Method::GET) + .uri("/openapi.json") + .body(Body::empty()) + .unwrap(); + let (_, json) = json_response(&app, request).await; + let paths = json["paths"].as_object().unwrap(); + let mut seen_ids: HashSet = HashSet::new(); + for (_, item) in paths { + for method in ["get", "post", "put", "delete", "patch"] { + if let Some(op) = item.get(method).filter(|v| v.is_object()) { + if let Some(id) = op["operationId"].as_str() { + assert!( + seen_ids.insert(id.to_string()), + "duplicate operation_id `{id}` in multi-mode spec" + ); + } + } + } + } +} + +#[tokio::test] +async fn single_mode_openapi_unchanged_by_cluster_filter() { + // Regression: single mode still emits the legacy flat surface. + let (_temp, app) = app_for_loaded_graph().await; + let request = Request::builder() + .method(Method::GET) + .uri("/openapi.json") + .body(Body::empty()) + .unwrap(); + let (_, json) = json_response(&app, request).await; + let paths = json["paths"].as_object().unwrap(); + let path_keys: HashSet<&str> = paths.keys().map(|k| k.as_str()).collect(); + for expected in EXPECTED_PATHS { + assert!( + path_keys.contains(expected), + "single mode must still emit flat path: {expected}" + ); + } + for cluster in EXPECTED_CLUSTER_PATHS { + assert!( + !path_keys.contains(cluster), + "single mode must NOT emit cluster path: {cluster}" + ); + } +} diff --git a/crates/omnigraph-server/tests/server.rs b/crates/omnigraph-server/tests/server.rs index bd77337..4a49a14 100644 --- a/crates/omnigraph-server/tests/server.rs +++ b/crates/omnigraph-server/tests/server.rs @@ -8,14 +8,15 @@ use axum::body::{Body, to_bytes}; use axum::http::header::AUTHORIZATION; use axum::http::{Method, Request, StatusCode}; use lance::index::DatasetIndexExt; -use omnigraph::db::{Omnigraph, ReadTarget, SchemaApplyOptions}; +use omnigraph::db::{Omnigraph, ReadTarget}; use omnigraph::error::OmniError; use omnigraph::loader::{LoadMode, load_jsonl}; use omnigraph_policy::{PolicyChecker, PolicyEngine}; use omnigraph_server::api::{ BranchCreateRequest, BranchMergeRequest, ChangeRequest, ErrorOutput, ExportRequest, - IngestRequest, ReadRequest, SchemaApplyRequest, SchemaOutput, + IngestRequest, QueryRequest, ReadRequest, SchemaApplyRequest, SchemaOutput, }; +use omnigraph_server::queries::{QueryRegistry, RegistrySpec}; use omnigraph_server::{AppState, build_app}; use serde_json::{Value, json}; use serial_test::serial; @@ -105,50 +106,513 @@ fn fixture(name: &str) -> PathBuf { .join(name) } -async fn init_loaded_repo() -> tempfile::TempDir { - init_repo_with_schema_and_data( +async fn init_loaded_graph() -> tempfile::TempDir { + init_graph_with_schema_and_data( &fs::read_to_string(fixture("test.pg")).unwrap(), &fs::read_to_string(fixture("test.jsonl")).unwrap(), ) .await } -async fn init_repo_with_schema_and_data(schema: &str, data: &str) -> tempfile::TempDir { +async fn init_graph_with_schema_and_data(schema: &str, data: &str) -> tempfile::TempDir { let temp = tempfile::tempdir().unwrap(); - let repo = repo_path(temp.path()); - fs::create_dir_all(&repo).unwrap(); - Omnigraph::init(repo.to_str().unwrap(), schema) + let graph = graph_path(temp.path()); + fs::create_dir_all(&graph).unwrap(); + Omnigraph::init(graph.to_str().unwrap(), schema) .await .unwrap(); - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); load_jsonl(&mut db, data, LoadMode::Overwrite) .await .unwrap(); temp } -async fn init_repo_with_schema(schema: &str) -> tempfile::TempDir { +async fn init_graph_with_schema(schema: &str) -> tempfile::TempDir { let temp = tempfile::tempdir().unwrap(); - let repo = repo_path(temp.path()); - fs::create_dir_all(&repo).unwrap(); - Omnigraph::init(repo.to_str().unwrap(), schema) + let graph = graph_path(temp.path()); + fs::create_dir_all(&graph).unwrap(); + Omnigraph::init(graph.to_str().unwrap(), schema) .await .unwrap(); temp } -fn repo_path(root: &Path) -> PathBuf { +fn graph_path(root: &Path) -> PathBuf { root.join("server.omni") } +fn stored_query_registry(specs: &[(&str, &str, bool)]) -> QueryRegistry { + QueryRegistry::from_specs( + specs + .iter() + .map(|(name, source, expose)| RegistrySpec { + name: name.to_string(), + source: source.to_string(), + expose: *expose, + tool_name: None, + }) + .collect(), + ) + .expect("specs parse and key==symbol") +} + +#[tokio::test] +async fn server_boots_with_a_valid_stored_query_registry() { + // A stored query that type-checks against the fixture schema + // (`Person { name, age }`) must let the server boot. + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let registry = stored_query_registry(&[( + "find_person", + "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }", + false, + )]); + let state = AppState::open_single_with_queries( + graph.to_string_lossy().to_string(), + vec![], + None, + registry, + ) + .await; + assert!(state.is_ok(), "valid registry should boot: {:?}", state.err()); +} + +#[tokio::test] +async fn server_refuses_boot_on_type_broken_stored_query() { + // A stored query referencing a type not in the schema (`Widget`) + // must abort boot, naming the offending query. + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let registry = stored_query_registry(&[( + "ghost", + "query ghost() { match { $w: Widget } return { $w.name } }", + false, + )]); + let result = AppState::open_single_with_queries( + graph.to_string_lossy().to_string(), + vec![], + None, + registry, + ) + .await; + // `AppState` is not `Debug`, so match rather than `expect_err`. + let err = match result { + Ok(_) => panic!("type-broken stored query must refuse boot"), + Err(err) => err, + }; + let msg = err.to_string(); + assert!(msg.contains("ghost"), "error should name the broken query: {msg}"); + assert!( + msg.contains("schema check"), + "error should mention the schema check: {msg}" + ); +} + +/// Build a single-mode app with a stored-query registry plus a bearer→actor +/// pairing and a policy, so invoke tests exercise the `invoke_query` +/// boundary gate and the inner read/change gates together. +async fn app_with_stored_queries( + specs: &[(&str, &str, bool)], + tokens: &[(&str, &str)], + policy: &str, +) -> (tempfile::TempDir, Router) { + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let policy_path = temp.path().join("policy.yaml"); + fs::write(&policy_path, policy).unwrap(); + let registry = stored_query_registry(specs); + let state = AppState::open_single_with_queries( + graph.to_string_lossy().to_string(), + tokens + .iter() + .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) + .collect(), + Some(&policy_path), + registry, + ) + .await + .unwrap(); + (temp, build_app(state)) +} + +/// - `act-invoke`: invoke_query + read (stored reads, not mutations) +/// - `act-full`: invoke_query + read + change (stored mutations) +/// - `act-noinvoke`: read only, no invoke_query (boundary-denied) +/// - `act-invokeonly`: invoke_query only, no read (clears the boundary, inner read denies) +const INVOKE_POLICY_YAML: &str = r#" +version: 1 +groups: + invokers: ["act-invoke"] + full: ["act-full"] + readers: ["act-noinvoke"] + invoke_only: ["act-invokeonly"] +protected_branches: [main] +rules: + # invoke_query is graph-scoped — its own rules, no branch_scope. + - id: invokers-can-invoke + allow: + actors: { group: invokers } + actions: [invoke_query] + - id: full-can-invoke + allow: + actors: { group: full } + actions: [invoke_query] + - id: invoke-only-can-invoke + allow: + actors: { group: invoke_only } + actions: [invoke_query] + # read / change are branch-scoped. + - id: invokers-can-read + allow: + actors: { group: invokers } + actions: [read] + branch_scope: any + - id: full-can-read-change + allow: + actors: { group: full } + actions: [read, change] + branch_scope: any + - id: readers-can-read + allow: + actors: { group: readers } + actions: [read] + branch_scope: any +"#; + +const STORED_QUERY_SCHEMA_APPLY_POLICY_YAML: &str = r#" +version: 1 +groups: + admins: [act-ragnor] +protected_branches: [main] +rules: + - id: admins-can-invoke + allow: + actors: { group: admins } + actions: [invoke_query] + - id: admins-can-read + allow: + actors: { group: admins } + actions: [read] + branch_scope: any + - id: admins-can-schema-apply + allow: + actors: { group: admins } + actions: [schema_apply] + target_branch_scope: protected +"#; + +const FIND_PERSON_GQ: &str = + "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }"; + +fn invoke_request(name: &str, token: &str, body: Value) -> Request { + Request::builder() + .uri(format!("/queries/{name}")) + .method(Method::POST) + .header("content-type", "application/json") + .header("authorization", format!("Bearer {token}")) + .body(Body::from(serde_json::to_vec(&body).unwrap())) + .unwrap() +} + +fn invoke_request_bytes( + name: &str, + token: &str, + body: impl Into, + content_type: Option<&str>, +) -> Request { + let mut builder = Request::builder() + .uri(format!("/queries/{name}")) + .method(Method::POST) + .header("authorization", format!("Bearer {token}")); + if let Some(content_type) = content_type { + builder = builder.header("content-type", content_type); + } + builder.body(body.into()).unwrap() +} + +#[tokio::test(flavor = "multi_thread")] +async fn invoke_stored_read_returns_rows() { + let (_temp, app) = app_with_stored_queries( + &[("find_person", FIND_PERSON_GQ, false)], + &[("act-invoke", "t-invoke")], + INVOKE_POLICY_YAML, + ) + .await; + let (status, body) = json_response( + &app, + invoke_request("find_person", "t-invoke", json!({ "params": { "name": "Alice" } })), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {body}"); + assert_eq!(body["query_name"], "find_person"); + assert_eq!(body["row_count"], 1, "Alice is in the fixture; body: {body}"); + assert!(body["rows"].is_array(), "read envelope shape; body: {body}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn invoke_stored_read_accepts_absent_or_empty_body() { + let no_param_query = "query list_people() { match { $p: Person } return { $p.name } }"; + let (_temp, app) = app_with_stored_queries( + &[("list_people", no_param_query, false)], + &[("act-invoke", "t-invoke")], + INVOKE_POLICY_YAML, + ) + .await; + + let (status, body) = json_response( + &app, + invoke_request_bytes("list_people", "t-invoke", Body::empty(), None), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {body}"); + assert_eq!(body["query_name"], "list_people"); + + let (status, body) = json_response( + &app, + invoke_request_bytes( + "list_people", + "t-invoke", + Body::empty(), + Some("application/json"), + ), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {body}"); + + let (status, body) = json_response( + &app, + invoke_request_bytes( + "list_people", + "t-invoke", + Body::from("{}"), + Some("application/json"), + ), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {body}"); + + let (status, body) = json_response( + &app, + invoke_request_bytes( + "list_people", + "t-invoke", + Body::from("{"), + Some("application/json"), + ), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "body: {body}"); + assert!( + body["error"] + .as_str() + .unwrap_or_default() + .contains("invalid stored-query invocation body"), + "malformed JSON should be rejected as bad request; body: {body}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn invoke_stored_mutation_double_gates_on_change() { + let specs: &[(&str, &str, bool)] = &[( + "add_person", + "query add_person($name: String) { insert Person { name: $name } }", + false, + )]; + let (_temp, app) = app_with_stored_queries( + specs, + &[("act-invoke", "t-invoke"), ("act-full", "t-full")], + INVOKE_POLICY_YAML, + ) + .await; + + // Has invoke_query but NOT change → the inner change gate denies (403). + let (status, body) = json_response( + &app, + invoke_request("add_person", "t-invoke", json!({ "params": { "name": "Eve" } })), + ) + .await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "invoke_query without change must 403; body: {body}" + ); + + // Has invoke_query + change → applied. + let (status, body) = json_response( + &app, + invoke_request("add_person", "t-full", json!({ "params": { "name": "Eve" } })), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {body}"); + assert_eq!(body["affected_nodes"], 1, "body: {body}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn invoke_stored_query_bad_param_is_400() { + let (_temp, app) = app_with_stored_queries( + &[("find_person", FIND_PERSON_GQ, false)], + &[("act-invoke", "t-invoke")], + INVOKE_POLICY_YAML, + ) + .await; + // `name` is declared String; pass a number. + let (status, body) = json_response( + &app, + invoke_request("find_person", "t-invoke", json!({ "params": { "name": 123 } })), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "body: {body}"); + assert!( + body["error"].as_str().unwrap_or_default().contains("name"), + "400 should name the offending param; body: {body}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn invoke_unknown_query_and_denied_actor_return_identical_404() { + let (_temp, app) = app_with_stored_queries( + &[("find_person", FIND_PERSON_GQ, false)], + &[("act-invoke", "t-invoke"), ("act-noinvoke", "t-noinvoke")], + INVOKE_POLICY_YAML, + ) + .await; + + // Authorized actor, unknown query name → 404. + let (unknown_status, unknown_body) = + json_response(&app, invoke_request("does_not_exist", "t-invoke", json!({}))).await; + // Denied actor (no invoke_query), real query name → 404. + let (denied_status, denied_body) = json_response( + &app, + invoke_request("find_person", "t-noinvoke", json!({ "params": { "name": "Alice" } })), + ) + .await; + + assert_eq!(unknown_status, StatusCode::NOT_FOUND); + assert_eq!(denied_status, StatusCode::NOT_FOUND); + assert_eq!( + unknown_body, denied_body, + "deny must be byte-identical to a missing query (no catalog probing)" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn invoke_query_holder_without_read_sees_403_not_404() { + // The 404-hiding is for callers WITHOUT invoke_query. An actor that + // HOLDS invoke_query but lacks `read` clears the boundary gate, then the + // inner read gate denies → 403 for an EXISTING read query, vs 404 for an + // unknown one. Existence is visible to grant-holders by design (the + // documented double-gate); this pins that actual contract. + let (_temp, app) = app_with_stored_queries( + &[("find_person", FIND_PERSON_GQ, false)], + &[("act-invokeonly", "t-invokeonly")], + INVOKE_POLICY_YAML, + ) + .await; + let (exists_status, _) = json_response( + &app, + invoke_request("find_person", "t-invokeonly", json!({ "params": { "name": "Alice" } })), + ) + .await; + let (absent_status, _) = + json_response(&app, invoke_request("does_not_exist", "t-invokeonly", json!({}))).await; + assert_eq!( + exists_status, + StatusCode::FORBIDDEN, + "an existing read query the holder can't read → inner-gate 403" + ); + assert_eq!(absent_status, StatusCode::NOT_FOUND, "unknown query still 404s"); +} + +fn get_request(uri: &str, token: &str) -> Request { + Request::builder() + .uri(uri) + .method(Method::GET) + .header("authorization", format!("Bearer {token}")) + .body(Body::empty()) + .unwrap() +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_queries_returns_only_exposed_with_typed_params() { + let (_temp, app) = app_with_stored_queries( + &[ + ("find_person", FIND_PERSON_GQ, true), + ( + "add_person", + "query add_person($name: String) { insert Person { name: $name } }", + true, + ), + ("hidden", "query hidden() { match { $p: Person } return { $p.name } }", false), + ], + &[("act-invoke", "t-invoke")], + INVOKE_POLICY_YAML, + ) + .await; + let (status, body) = json_response(&app, get_request("/queries", "t-invoke")).await; + assert_eq!(status, StatusCode::OK, "body: {body}"); + + let entries = body["queries"].as_array().unwrap(); + let names: Vec<&str> = entries.iter().map(|q| q["name"].as_str().unwrap()).collect(); + assert!( + names.contains(&"find_person") && names.contains(&"add_person"), + "exposed queries listed: {names:?}" + ); + assert!(!names.contains(&"hidden"), "non-exposed query hidden from the catalog: {names:?}"); + + let fp = entries.iter().find(|q| q["name"] == "find_person").unwrap(); + assert_eq!(fp["mutation"], false); + assert_eq!(fp["tool_name"], "find_person"); + assert_eq!(fp["params"][0]["name"], "name"); + assert_eq!(fp["params"][0]["kind"], "string"); + let ap = entries.iter().find(|q| q["name"] == "add_person").unwrap(); + assert_eq!(ap["mutation"], true, "stored insert → mutation"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_queries_is_read_gated_so_a_non_invoker_can_list() { + // The catalog is read-gated (not invoke_query-gated), so a reader who + // lacks invoke_query still enumerates the exposed queries — the + // documented probe-oracle gap until per-query Cedar filtering lands. + let (_temp, app) = app_with_stored_queries( + &[("find_person", FIND_PERSON_GQ, true)], + &[("act-noinvoke", "t-noinvoke")], + INVOKE_POLICY_YAML, + ) + .await; + let (status, body) = json_response(&app, get_request("/queries", "t-noinvoke")).await; + assert_eq!(status, StatusCode::OK, "read-gated catalog; body: {body}"); + let names: Vec<&str> = body["queries"] + .as_array() + .unwrap() + .iter() + .map(|q| q["name"].as_str().unwrap()) + .collect(); + assert!( + names.contains(&"find_person"), + "a reader lists the catalog despite lacking invoke_query: {names:?}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_queries_is_empty_when_no_registry() { + let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; + let (status, body) = json_response(&app, get_request("/queries", "demo-token")).await; + assert_eq!(status, StatusCode::OK, "body: {body}"); + assert!( + body["queries"].as_array().unwrap().is_empty(), + "no stored-query registry → empty catalog" + ); +} + fn drifted_test_schema() -> String { fs::read_to_string(fixture("test.pg")) .unwrap() .replace("age: I32?", "age: I64?") } -async fn manifest_dataset_version(repo: &Path) -> u64 { - Omnigraph::open(repo.to_string_lossy().as_ref()) +async fn manifest_dataset_version(graph: &Path) -> u64 { + Omnigraph::open(graph.to_string_lossy().as_ref()) .await .unwrap() .snapshot_of(ReadTarget::branch("main")) @@ -157,7 +621,7 @@ async fn manifest_dataset_version(repo: &Path) -> u64 { .version() } -fn s3_test_repo_uri(suite: &str) -> Option { +fn s3_test_graph_uri(suite: &str) -> Option { let bucket = env::var("OMNIGRAPH_S3_TEST_BUCKET").ok()?; let prefix = env::var("OMNIGRAPH_S3_TEST_PREFIX") .ok() @@ -170,10 +634,10 @@ fn s3_test_repo_uri(suite: &str) -> Option { Some(format!("s3://{}/{}/{}/{}", bucket, prefix, suite, unique)) } -async fn app_for_loaded_repo() -> (tempfile::TempDir, Router) { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let state = AppState::open(repo.to_string_lossy().to_string()) +async fn app_for_loaded_graph() -> (tempfile::TempDir, Router) { + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let state = AppState::open(graph.to_string_lossy().to_string()) .await .unwrap(); (temp, build_app(state)) @@ -186,7 +650,7 @@ async fn app_for_loaded_repo() -> (tempfile::TempDir, Router) { /// so test cases retain their pre-MR-723 semantics ("auth required, /// every action permitted") without conflicting with the new state /// matrix. Tests that specifically need the State-2 deny path use -/// `app_for_repo_with_auth_tokens_only` instead. +/// `app_for_graph_with_auth_tokens_only` instead. fn permit_all_policy_yaml(actors: &[&str]) -> String { let members = actors .iter() @@ -214,15 +678,15 @@ rules: ) } -async fn app_for_loaded_repo_with_auth(token: &str) -> (tempfile::TempDir, Router) { +async fn app_for_loaded_graph_with_auth(token: &str) -> (tempfile::TempDir, Router) { // `AppState::new_with_bearer_token(token)` maps the token to actor "default"; // permit-all policy needs to include that actor. - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, permit_all_policy_yaml(&["default"])).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![("default".to_string(), token.to_string())], Some(&policy_path), ) @@ -231,16 +695,16 @@ async fn app_for_loaded_repo_with_auth(token: &str) -> (tempfile::TempDir, Route (temp, build_app(state)) } -async fn app_for_loaded_repo_with_auth_tokens( +async fn app_for_loaded_graph_with_auth_tokens( tokens: &[(&str, &str)], ) -> (tempfile::TempDir, Router) { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); let policy_path = temp.path().join("policy.yaml"); let actors: Vec<&str> = tokens.iter().map(|(actor, _)| *actor).collect(); fs::write(&policy_path, permit_all_policy_yaml(&actors)).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), tokens .iter() .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) @@ -252,16 +716,16 @@ async fn app_for_loaded_repo_with_auth_tokens( (temp, build_app(state)) } -async fn app_for_loaded_repo_with_auth_tokens_and_policy( +async fn app_for_loaded_graph_with_auth_tokens_and_policy( tokens: &[(&str, &str)], policy: &str, ) -> (tempfile::TempDir, Router) { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, policy).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), tokens .iter() .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) @@ -273,17 +737,17 @@ async fn app_for_loaded_repo_with_auth_tokens_and_policy( (temp, build_app(state)) } -async fn app_for_repo_with_auth_tokens_and_policy( +async fn app_for_graph_with_auth_tokens_and_policy( schema: &str, tokens: &[(&str, &str)], policy: &str, ) -> (tempfile::TempDir, Router) { - let temp = init_repo_with_schema(schema).await; - let repo = repo_path(temp.path()); + let temp = init_graph_with_schema(schema).await; + let graph = graph_path(temp.path()); let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, policy).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), tokens .iter() .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) @@ -299,14 +763,14 @@ async fn app_for_repo_with_auth_tokens_and_policy( /// Exercises ServerRuntimeState::DefaultDeny — authenticated requests /// for Read succeed, every other action is rejected with 403 from /// `authorize_request`'s state-2 branch. -async fn app_for_repo_with_auth_tokens_only( +async fn app_for_graph_with_auth_tokens_only( schema: &str, tokens: &[(&str, &str)], ) -> (tempfile::TempDir, Router) { - let temp = init_repo_with_schema(schema).await; - let repo = repo_path(temp.path()); + let temp = init_graph_with_schema(schema).await; + let graph = graph_path(temp.path()); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), tokens .iter() .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) @@ -388,8 +852,8 @@ async fn json_response(app: &Router, request: Request) -> (StatusCode, Val } #[tokio::test] -async fn schema_apply_route_updates_repo_for_authorized_admin() { - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( +async fn schema_apply_route_updates_graph_for_authorized_admin() { + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, @@ -414,8 +878,8 @@ async fn schema_apply_route_updates_repo_for_authorized_admin() { assert_eq!(status, StatusCode::OK); assert_eq!(payload["applied"], true); - let repo = repo_path(temp.path()); - let reopened = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let graph = graph_path(temp.path()); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); assert!( reopened.catalog().node_types["Person"] .properties @@ -423,9 +887,86 @@ async fn schema_apply_route_updates_repo_for_authorized_admin() { ); } +#[tokio::test(flavor = "multi_thread")] +async fn schema_apply_route_rejects_stored_query_breakage_before_publish() { + let (temp, app) = app_with_stored_queries( + &[("find_person", FIND_PERSON_GQ, true)], + &[("act-ragnor", "admin-token")], + STORED_QUERY_SCHEMA_APPLY_POLICY_YAML, + ) + .await; + + let request = Request::builder() + .method(Method::POST) + .uri("/schema/apply") + .header("content-type", "application/json") + .header("authorization", "Bearer admin-token") + .body(Body::from( + serde_json::to_vec(&SchemaApplyRequest { + schema_source: renamed_age_schema(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "body: {payload}"); + let message = payload["error"].as_str().unwrap_or_default(); + assert!( + message.contains("find_person") && message.contains("schema check"), + "registry breakage should name the stored query; body: {payload}" + ); + + let reopened = Omnigraph::open(graph_path(temp.path()).to_str().unwrap()) + .await + .unwrap(); + let person = &reopened.catalog().node_types["Person"]; + assert!(person.properties.contains_key("age")); + assert!(!person.properties.contains_key("years")); + + let (invoke_status, invoke_body) = json_response( + &app, + invoke_request( + "find_person", + "admin-token", + json!({ "params": { "name": "Alice" } }), + ), + ) + .await; + assert_eq!(invoke_status, StatusCode::OK, "body: {invoke_body}"); + assert_eq!(invoke_body["row_count"], 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_apply_route_noop_keeps_valid_stored_query_registry() { + let (_temp, app) = app_with_stored_queries( + &[("find_person", FIND_PERSON_GQ, true)], + &[("act-ragnor", "admin-token")], + STORED_QUERY_SCHEMA_APPLY_POLICY_YAML, + ) + .await; + + let request = Request::builder() + .method(Method::POST) + .uri("/schema/apply") + .header("content-type", "application/json") + .header("authorization", "Bearer admin-token") + .body(Body::from( + serde_json::to_vec(&SchemaApplyRequest { + schema_source: fs::read_to_string(fixture("test.pg")).unwrap(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + assert_eq!(status, StatusCode::OK, "body: {payload}"); + assert_eq!(payload["applied"], false); +} + #[tokio::test] async fn schema_apply_route_requires_schema_apply_policy_permission() { - let (_temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (_temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], POLICY_YAML, @@ -456,7 +997,7 @@ async fn schema_apply_route_requires_schema_apply_policy_permission() { #[tokio::test] async fn schema_apply_route_requires_bearer_token_when_policy_enabled() { - let (_temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (_temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, @@ -486,7 +1027,7 @@ async fn schema_apply_route_requires_bearer_token_when_policy_enabled() { #[tokio::test] async fn schema_apply_route_can_rename_type() { - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, @@ -510,8 +1051,8 @@ async fn schema_apply_route_can_rename_type() { assert_eq!(status, StatusCode::OK); assert_eq!(payload["applied"], true); - let repo = repo_path(temp.path()); - let reopened = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let graph = graph_path(temp.path()); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); let snapshot = reopened .snapshot_of(ReadTarget::branch("main")) .await @@ -522,7 +1063,7 @@ async fn schema_apply_route_can_rename_type() { #[tokio::test] async fn schema_apply_route_can_rename_property() { - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, @@ -546,8 +1087,8 @@ async fn schema_apply_route_can_rename_property() { assert_eq!(status, StatusCode::OK); assert_eq!(payload["applied"], true); - let repo = repo_path(temp.path()); - let reopened = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let graph = graph_path(temp.path()); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); let person = &reopened.catalog().node_types["Person"]; assert!(person.properties.contains_key("years")); assert!(!person.properties.contains_key("age")); @@ -555,15 +1096,15 @@ async fn schema_apply_route_can_rename_property() { #[tokio::test] async fn schema_apply_route_can_add_index() { - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, ) .await; - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let before_index_count = { - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); let snapshot = db.snapshot_of(ReadTarget::branch("main")).await.unwrap(); let dataset = snapshot.open("node:Person").await.unwrap(); dataset.load_indices().await.unwrap().len() @@ -586,7 +1127,7 @@ async fn schema_apply_route_can_add_index() { assert_eq!(status, StatusCode::OK); assert_eq!(payload["applied"], true); - let reopened = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); let snapshot = reopened .snapshot_of(ReadTarget::branch("main")) .await @@ -598,7 +1139,7 @@ async fn schema_apply_route_can_add_index() { #[tokio::test] async fn schema_apply_route_rejects_unsupported_plan() { - let (_temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (_temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, @@ -629,16 +1170,16 @@ async fn schema_apply_route_rejects_unsupported_plan() { #[tokio::test] async fn schema_apply_route_rejects_when_non_main_branch_exists() { - let temp = init_repo_with_schema(&fs::read_to_string(fixture("test.pg")).unwrap()).await; - let repo = repo_path(temp.path()); - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let temp = init_graph_with_schema(&fs::read_to_string(fixture("test.pg")).unwrap()).await; + let graph = graph_path(temp.path()); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.branch_create("feature").await.unwrap(); drop(db); let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, SCHEMA_APPLY_POLICY_YAML).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![("act-ragnor".to_string(), "admin-token".to_string())], Some(&policy_path), ) @@ -754,7 +1295,7 @@ fn mock_embedding(input: &str, dim: usize) -> Vec { #[tokio::test(flavor = "multi_thread")] async fn healthz_succeeds_after_startup() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let (status, body) = json_response( &app, Request::builder() @@ -776,9 +1317,9 @@ async fn healthz_succeeds_after_startup() { #[tokio::test(flavor = "multi_thread")] async fn schema_drift_returns_conflict_for_snapshot_read_and_change() { - let (temp, app) = app_for_loaded_repo().await; - let repo = repo_path(temp.path()); - fs::write(repo.join("_schema.pg"), drifted_test_schema()).unwrap(); + let (temp, app) = app_for_loaded_graph().await; + let graph = graph_path(temp.path()); + fs::write(graph.join("_schema.pg"), drifted_test_schema()).unwrap(); let (snapshot_status, snapshot_body) = json_response( &app, @@ -831,8 +1372,8 @@ async fn schema_drift_returns_conflict_for_snapshot_read_and_change() { ); let change = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "Mina", "age": 28 })), branch: Some("main".to_string()), }; @@ -861,7 +1402,7 @@ async fn schema_drift_returns_conflict_for_snapshot_read_and_change() { #[tokio::test(flavor = "multi_thread")] async fn protected_routes_require_bearer_token() { - let (_temp, app) = app_for_loaded_repo_with_auth("demo-token").await; + let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; let (status, body) = json_response( &app, Request::builder() @@ -882,7 +1423,7 @@ async fn protected_routes_require_bearer_token() { #[tokio::test(flavor = "multi_thread")] async fn protected_routes_accept_valid_bearer_token_while_healthz_stays_open() { - let (_temp, app) = app_for_loaded_repo_with_auth("demo-token").await; + let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; let health = app .clone() @@ -915,9 +1456,9 @@ async fn protected_routes_accept_valid_bearer_token_while_healthz_stays_open() { #[tokio::test(flavor = "multi_thread")] async fn export_route_returns_jsonl_for_branch_snapshot() { let token = "demo-token"; - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.branch_create_from(ReadTarget::branch("main"), "feature") .await .unwrap(); @@ -942,7 +1483,7 @@ async fn export_route_returns_jsonl_for_branch_snapshot() { let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, permit_all_policy_yaml(&["default"])).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![("default".to_string(), token.to_string())], Some(&policy_path), ) @@ -983,9 +1524,11 @@ async fn export_route_returns_jsonl_for_branch_snapshot() { #[tokio::test(flavor = "multi_thread")] async fn protected_routes_accept_any_configured_team_bearer_token() { - let (_temp, app) = - app_for_loaded_repo_with_auth_tokens(&[("team-01", "token-one"), ("team-02", "token-two")]) - .await; + let (_temp, app) = app_for_loaded_graph_with_auth_tokens(&[ + ("team-01", "token-one"), + ("team-02", "token-two"), + ]) + .await; let (status, body) = json_response( &app, @@ -1009,8 +1552,8 @@ async fn protected_routes_accept_any_configured_team_bearer_token() { /// the policy outcome. #[tokio::test(flavor = "multi_thread")] async fn bearer_token_resolves_to_correct_actor_for_policy_decisions() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); let policy_path = temp.path().join("policy.yaml"); fs::write( &policy_path, @@ -1030,7 +1573,7 @@ rules: ) .unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![ ("act-a".to_string(), "token-a".to_string()), ("act-b".to_string(), "token-b".to_string()), @@ -1110,8 +1653,8 @@ rules: /// → actor identity contract. #[tokio::test(flavor = "multi_thread")] async fn actor_id_resolves_from_bearer_token_ignoring_client_supplied_headers() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); let policy_path = temp.path().join("policy.yaml"); // Same readers/writers split as // `bearer_token_resolves_to_correct_actor_for_policy_decisions` — @@ -1135,7 +1678,7 @@ rules: ) .unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![ ("act-a".to_string(), "token-a".to_string()), ("act-b".to_string(), "token-b".to_string()), @@ -1215,7 +1758,7 @@ rules: #[tokio::test(flavor = "multi_thread")] async fn policy_allows_read_but_distinguishes_401_from_403() { - let (_temp, app) = app_for_loaded_repo_with_auth_tokens_and_policy( + let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( &[("act-bruno", "team-token"), ("act-ragnor", "admin-token")], POLICY_YAML, ) @@ -1291,16 +1834,16 @@ async fn policy_allows_read_but_distinguishes_401_from_403() { #[tokio::test(flavor = "multi_thread")] async fn policy_uses_resolved_branch_for_snapshot_reads() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); let snapshot_id = { - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.resolve_snapshot("main").await.unwrap().to_string() }; let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, POLICY_PROTECTED_READ_YAML).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![("act-bruno".to_string(), "team-token".to_string())], Some(&policy_path), ) @@ -1338,9 +1881,9 @@ async fn policy_uses_resolved_branch_for_snapshot_reads() { #[tokio::test(flavor = "multi_thread")] async fn snapshot_route_returns_manifest_dataset_version() { - let (temp, app) = app_for_loaded_repo().await; - let repo = repo_path(temp.path()); - let expected_manifest_version = manifest_dataset_version(&repo).await; + let (temp, app) = app_for_loaded_graph().await; + let graph = graph_path(temp.path()); + let expected_manifest_version = manifest_dataset_version(&graph).await; let (snapshot_status, snapshot_body) = json_response( &app, @@ -1363,7 +1906,7 @@ async fn snapshot_route_returns_manifest_dataset_version() { #[tokio::test(flavor = "multi_thread")] async fn schema_route_returns_current_source() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let (status, body) = json_response( &app, Request::builder() @@ -1381,7 +1924,7 @@ async fn schema_route_returns_current_source() { #[tokio::test(flavor = "multi_thread")] async fn schema_route_requires_bearer_token_when_auth_configured() { - let (_temp, app) = app_for_loaded_repo_with_auth("demo-token").await; + let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; let (missing_status, missing_body) = json_response( &app, @@ -1416,13 +1959,13 @@ async fn schema_route_requires_bearer_token_when_auth_configured() { #[tokio::test(flavor = "multi_thread")] async fn schema_route_denied_when_actor_lacks_read_permission() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); let policy_path = temp.path().join("policy.yaml"); // Policy grants branch_create only — no read action for act-bruno. fs::write(&policy_path, INGEST_CREATE_ONLY_POLICY_YAML).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![("act-bruno".to_string(), "team-token".to_string())], Some(&policy_path), ) @@ -1450,9 +1993,9 @@ async fn schema_route_denied_when_actor_lacks_read_permission() { #[tokio::test(flavor = "multi_thread")] async fn policy_blocks_change_on_protected_main_but_allows_unprotected_branch() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.branch_create_from(ReadTarget::branch("main"), "feature") .await .unwrap(); @@ -1461,7 +2004,7 @@ async fn policy_blocks_change_on_protected_main_but_allows_unprotected_branch() let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, POLICY_YAML).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![("act-bruno".to_string(), "team-token".to_string())], Some(&policy_path), ) @@ -1470,8 +2013,8 @@ async fn policy_blocks_change_on_protected_main_but_allows_unprotected_branch() let app = build_app(state); let main_change = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "Mina", "age": 28 })), branch: Some("main".to_string()), }; @@ -1494,8 +2037,8 @@ async fn policy_blocks_change_on_protected_main_but_allows_unprotected_branch() ); let feature_change = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "Mina", "age": 28 })), branch: Some("feature".to_string()), }; @@ -1517,9 +2060,9 @@ async fn policy_blocks_change_on_protected_main_but_allows_unprotected_branch() #[tokio::test(flavor = "multi_thread")] async fn policy_blocks_non_admin_merge_to_main_and_allows_admin() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.branch_create_from(ReadTarget::branch("main"), "feature") .await .unwrap(); @@ -1535,7 +2078,7 @@ async fn policy_blocks_non_admin_merge_to_main_and_allows_admin() { let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, POLICY_YAML).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![ ("act-bruno".to_string(), "team-token".to_string()), ("act-ragnor".to_string(), "admin-token".to_string()), @@ -1587,11 +2130,11 @@ async fn policy_blocks_non_admin_merge_to_main_and_allows_admin() { async fn authenticated_change_stamps_actor_on_commits() { // With the Run state machine removed, actor_id is recorded // directly on the commit graph (no intermediate run record). - let (_temp, app) = app_for_loaded_repo_with_auth_tokens(&[("act-andrew", "token-one")]).await; + let (_temp, app) = app_for_loaded_graph_with_auth_tokens(&[("act-andrew", "token-one")]).await; let change = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "Mina", "age": 28 })), branch: Some("main".to_string()), }; @@ -1630,8 +2173,8 @@ async fn authenticated_change_stamps_actor_on_commits() { #[tokio::test(flavor = "multi_thread")] async fn ingest_creates_branch_returns_metadata_and_stamps_actor() { - let (temp, app) = app_for_loaded_repo_with_auth_tokens(&[("act-andrew", "token-one")]).await; - let repo = repo_path(temp.path()); + let (temp, app) = app_for_loaded_graph_with_auth_tokens(&[("act-andrew", "token-one")]).await; + let graph = graph_path(temp.path()); let ingest = IngestRequest { branch: Some("feature-ingest".to_string()), from: Some("main".to_string()), @@ -1661,7 +2204,7 @@ async fn ingest_creates_branch_returns_metadata_and_stamps_actor() { assert_eq!(body["tables"][0]["table_key"], "node:Person"); assert_eq!(body["tables"][0]["rows_loaded"], 2); - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); let snapshot = db .snapshot_of(ReadTarget::branch("feature-ingest")) .await @@ -1680,10 +2223,10 @@ async fn ingest_creates_branch_returns_metadata_and_stamps_actor() { #[tokio::test(flavor = "multi_thread")] async fn ingest_existing_branch_skips_branch_create_policy_check() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); { - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.branch_create_from(ReadTarget::branch("main"), "feature") .await .unwrap(); @@ -1691,7 +2234,7 @@ async fn ingest_existing_branch_skips_branch_create_policy_check() { let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, POLICY_YAML).unwrap(); let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![("act-bruno".to_string(), "team-token".to_string())], Some(&policy_path), ) @@ -1724,7 +2267,7 @@ async fn ingest_existing_branch_skips_branch_create_policy_check() { #[tokio::test(flavor = "multi_thread")] async fn ingest_denies_missing_branch_without_branch_create_permission() { - let (_temp, app) = app_for_loaded_repo_with_auth_tokens_and_policy( + let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( &[("act-bruno", "team-token")], POLICY_YAML, ) @@ -1757,7 +2300,7 @@ async fn ingest_denies_missing_branch_without_branch_create_permission() { #[tokio::test(flavor = "multi_thread")] async fn ingest_denies_when_actor_lacks_change_permission() { - let (_temp, app) = app_for_loaded_repo_with_auth_tokens_and_policy( + let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( &[("act-bruno", "team-token")], INGEST_CREATE_ONLY_POLICY_YAML, ) @@ -1790,7 +2333,7 @@ async fn ingest_denies_when_actor_lacks_change_permission() { #[tokio::test(flavor = "multi_thread")] async fn ingest_rejects_payloads_over_32_mib() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let oversize = IngestRequest { branch: Some("feature".to_string()), from: Some("main".to_string()), @@ -1815,7 +2358,7 @@ async fn ingest_rejects_payloads_over_32_mib() { #[tokio::test(flavor = "multi_thread")] async fn authenticated_branch_merge_stamps_merge_actor_on_head_commit() { - let (_temp, app) = app_for_loaded_repo_with_auth_tokens(&[ + let (_temp, app) = app_for_loaded_graph_with_auth_tokens(&[ ("act-andrew", "token-one"), ("act-ragnor", "token-two"), ]) @@ -1839,8 +2382,8 @@ async fn authenticated_branch_merge_stamps_merge_actor_on_head_commit() { assert_eq!(create_status, StatusCode::OK); let change = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "Zoe", "age": 33 })), branch: Some("feature".to_string()), }; @@ -1896,9 +2439,9 @@ async fn authenticated_branch_merge_stamps_merge_actor_on_head_commit() { #[tokio::test(flavor = "multi_thread")] async fn branch_merge_conflict_response_includes_structured_conflicts() { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.branch_create_from(ReadTarget::branch("main"), "feature") .await .unwrap(); @@ -1934,7 +2477,7 @@ async fn branch_merge_conflict_response_includes_structured_conflicts() { .unwrap(); drop(db); - let state = AppState::open(repo.to_string_lossy().to_string()) + let state = AppState::open(graph.to_string_lossy().to_string()) .await .unwrap(); let app = build_app(state); @@ -1966,11 +2509,11 @@ async fn branch_merge_conflict_response_includes_structured_conflicts() { #[tokio::test(flavor = "multi_thread")] async fn repeated_read_after_change_sees_updated_state_from_same_app() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let change = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "Mina", "age": 28 })), branch: Some("main".to_string()), }; @@ -2009,9 +2552,268 @@ async fn repeated_read_after_change_sees_updated_state_from_same_app() { assert_eq!(read_body["rows"][0]["p.name"], "Mina"); } +#[tokio::test(flavor = "multi_thread")] +async fn query_endpoint_runs_inline_read() { + let (_temp, app) = app_for_loaded_graph().await; + + let query = QueryRequest { + query: fs::read_to_string(fixture("test.gq")).unwrap(), + name: Some("get_person".to_string()), + params: Some(json!({ "name": "Alice" })), + branch: Some("main".to_string()), + snapshot: None, + }; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/query") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&query).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["query_name"], "get_person"); + assert_eq!(body["row_count"], 1); + assert_eq!(body["rows"][0]["p.name"], "Alice"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn query_endpoint_rejects_mutation_with_400() { + let (_temp, app) = app_for_loaded_graph().await; + + let query = QueryRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "Should", "age": 1 })), + branch: Some("main".to_string()), + snapshot: None, + }; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/query") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&query).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let err = body["error"].as_str().unwrap_or_default(); + assert!( + err.contains("contains mutations") && err.contains("POST /mutate"), + "expected mutation-rejection message pointing at canonical /mutate, got: {err}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn mutate_endpoint_runs_inline_mutation() { + // Canonical mutation endpoint. Pairs with `/query` on the read side. + // Same wire shape as `/change`, no deprecation signal. + let (_temp, app) = app_for_loaded_graph().await; + + let request = json!({ + "query": MUTATION_QUERIES, + "name": "insert_person", + "params": { "name": "Mutie", "age": 30 }, + "branch": "main", + }); + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/mutate") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&request).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + // Canonical route is NOT deprecated; no Deprecation header expected. + assert!( + response.headers().get("deprecation").is_none(), + "POST /mutate must not advertise itself as deprecated" + ); + let body_bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body: Value = serde_json::from_slice(&body_bytes).unwrap(); + assert_eq!(body["affected_nodes"], 1); + assert_eq!(body["query_name"], "insert_person"); + assert_eq!(body["branch"], "main"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn change_endpoint_emits_deprecation_headers() { + // `/change` is kept indefinitely for back-compat but flagged at runtime + // per RFC 9745 (`Deprecation: true`) + RFC 8288 (`Link: ; + // rel="successor-version"`). The OpenAPI side is covered by + // `openapi_change_is_deprecated` in tests/openapi.rs. + let (_temp, app) = app_for_loaded_graph().await; + + let request = json!({ + "query": MUTATION_QUERIES, + "name": "insert_person", + "params": { "name": "Legacyer", "age": 33 }, + "branch": "main", + }); + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&request).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response + .headers() + .get("deprecation") + .and_then(|v| v.to_str().ok()), + Some("true"), + "POST /change must advertise `Deprecation: true` (RFC 9745)" + ); + assert_eq!( + response.headers().get("link").and_then(|v| v.to_str().ok()), + Some("; rel=\"successor-version\""), + "POST /change must point at /mutate via `Link` rel=successor-version (RFC 8288)" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn read_endpoint_emits_deprecation_headers() { + // `/read` is kept indefinitely for byte-stable back-compat but flagged + // at runtime per RFC 9745 + RFC 8288. Successor is `/query`. + let (_temp, app) = app_for_loaded_graph().await; + + let request = ReadRequest { + query_source: fs::read_to_string(fixture("test.gq")).unwrap(), + query_name: Some("get_person".to_string()), + params: Some(json!({ "name": "Alice" })), + branch: Some("main".to_string()), + snapshot: None, + }; + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/read") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&request).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response + .headers() + .get("deprecation") + .and_then(|v| v.to_str().ok()), + Some("true"), + "POST /read must advertise `Deprecation: true` (RFC 9745)" + ); + assert_eq!( + response.headers().get("link").and_then(|v| v.to_str().ok()), + Some("; rel=\"successor-version\""), + "POST /read must point at /query via `Link` rel=successor-version (RFC 8288)" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn query_endpoint_does_not_emit_deprecation_headers() { + // Sanity check the inverse: the canonical `/query` endpoint must not + // carry deprecation signaling, so SDK codegens don't propagate a + // bogus `@deprecated` marker. + let (_temp, app) = app_for_loaded_graph().await; + + let request = QueryRequest { + query: fs::read_to_string(fixture("test.gq")).unwrap(), + name: Some("get_person".to_string()), + params: Some(json!({ "name": "Alice" })), + branch: Some("main".to_string()), + snapshot: None, + }; + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/query") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&request).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + assert!( + response.headers().get("deprecation").is_none(), + "POST /query is canonical and must not advertise itself as deprecated" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn change_endpoint_accepts_legacy_field_names() { + // The canonical wire field names on /change are `query` and `name`, but + // serde aliases keep the legacy `query_source`/`query_name` payload + // shape working for clients that haven't migrated yet. Pin both shapes. + let (_temp, app) = app_for_loaded_graph().await; + + let legacy_body = json!({ + "query_source": MUTATION_QUERIES, + "query_name": "insert_person", + "params": { "name": "Legacy", "age": 21 }, + "branch": "main", + }); + let (status, body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&legacy_body).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["affected_nodes"], 1); + + let canonical_body = json!({ + "query": MUTATION_QUERIES, + "name": "insert_person", + "params": { "name": "Canonical", "age": 22 }, + "branch": "main", + }); + let (status, body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&canonical_body).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["affected_nodes"], 1); +} + #[tokio::test(flavor = "multi_thread")] async fn remote_branch_list_create_merge_flow_works() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let (list_status, list_body) = json_response( &app, @@ -2056,8 +2858,8 @@ async fn remote_branch_list_create_merge_flow_works() { assert_eq!(list_body["branches"], json!(["feature", "main"])); let change = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "Zoe", "age": 33 })), branch: Some("feature".to_string()), }; @@ -2138,7 +2940,7 @@ async fn remote_branch_list_create_merge_flow_works() { #[tokio::test(flavor = "multi_thread")] async fn remote_branch_delete_flow_works() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let create = BranchCreateRequest { from: Some("main".to_string()), @@ -2183,14 +2985,14 @@ async fn remote_branch_delete_flow_works() { #[tokio::test(flavor = "multi_thread")] async fn branch_delete_denies_without_policy_permission() { - let (temp, app) = app_for_loaded_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( &[("act-andrew", "token-admin"), ("act-bruno", "token-team")], POLICY_YAML, ) .await; - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.branch_create_from(ReadTarget::branch("main"), "feature") .await .unwrap(); @@ -2216,8 +3018,8 @@ async fn branch_delete_denies_without_policy_permission() { } #[tokio::test(flavor = "multi_thread")] -async fn server_opens_s3_repo_directly_and_serves_snapshot_and_read() { - let Some(uri) = s3_test_repo_uri("server") else { +async fn server_opens_s3_graph_directly_and_serves_snapshot_and_read() { + let Some(uri) = s3_test_graph_uri("server") else { eprintln!("skipping s3 server test: OMNIGRAPH_S3_TEST_BUCKET is not set"); return; }; @@ -2315,9 +3117,9 @@ query vector_search_string($q: String) { ("OMNIGRAPH_EMBEDDINGS_MOCK", Some("1")), ("GEMINI_API_KEY", None), ]); - let temp = init_repo_with_schema_and_data(EMBED_SCHEMA, &data).await; - let repo = repo_path(temp.path()); - let state = AppState::open(repo.to_string_lossy().to_string()) + let temp = init_graph_with_schema_and_data(EMBED_SCHEMA, &data).await; + let graph = graph_path(temp.path()); + let state = AppState::open(graph.to_string_lossy().to_string()) .await .unwrap(); let app = build_app(state); @@ -2351,20 +3153,20 @@ async fn change_conflict_returns_manifest_conflict_409() { // a structured `manifest_conflict` body — `table_key`, `expected`, // and `actual` — so clients can detect-and-retry without parsing // the message. - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); // Build the server first so its handle pins the pre-mutation manifest // version. Then advance the manifest from outside the server. The // server's next /change call will capture stale `expected_versions` // (from its still-pinned snapshot) and the publisher's CAS rejects. - let state = AppState::open(repo.to_string_lossy().to_string()) + let state = AppState::open(graph.to_string_lossy().to_string()) .await .unwrap(); let app = build_app(state); { - let mut db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.mutate( "main", MUTATION_QUERIES, @@ -2390,8 +3192,8 @@ async fn change_conflict_returns_manifest_conflict_409() { .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("set_age".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("set_age".to_string()), params: Some(json!({ "name": "Alice", "age": 33 })), branch: Some("main".to_string()), }) @@ -2434,9 +3236,9 @@ async fn change_concurrent_inserts_same_key_serialize_without_409() { // node type and asserts: every request returns 200 (no 409), // and the final row count equals the seed count + N (every // staged batch actually committed). - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let state = AppState::open(repo.to_string_lossy().to_string()) + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let state = AppState::open(graph.to_string_lossy().to_string()) .await .unwrap(); let app = build_app(state); @@ -2450,8 +3252,8 @@ async fn change_concurrent_inserts_same_key_serialize_without_409() { let app = app.clone(); handles.push(tokio::spawn(async move { let body = serde_json::to_vec(&ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": format!("racer-{i}"), "age": i as i32 })), branch: Some("main".to_string()), }) @@ -2547,9 +3349,9 @@ async fn change_concurrent_updates_same_key_serialize_via_publisher_cas() { // Lance error variant. The drift check fires at the right architectural // layer (engine boundary, under the queue) and respects the existing // `MutationOpKind` policy. - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let state = AppState::open(repo.to_string_lossy().to_string()) + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let state = AppState::open(graph.to_string_lossy().to_string()) .await .unwrap(); let app = build_app(state); @@ -2563,8 +3365,8 @@ async fn change_concurrent_updates_same_key_serialize_via_publisher_cas() { let target_age = 100 + i as i32; handles.push(tokio::spawn(async move { let body = serde_json::to_vec(&ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("set_age".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("set_age".to_string()), params: Some(json!({ "name": "Alice", "age": target_age })), branch: Some("main".to_string()), }) @@ -2588,10 +3390,7 @@ async fn change_concurrent_updates_same_key_serialize_via_publisher_cas() { } let statuses: Vec = results.iter().map(|(s, _)| *s).collect(); - let ok_count = statuses - .iter() - .filter(|s| **s == StatusCode::OK) - .count(); + let ok_count = statuses.iter().filter(|s| **s == StatusCode::OK).count(); let conflict_count = statuses .iter() .filter(|s| **s == StatusCode::CONFLICT) @@ -2621,7 +3420,8 @@ async fn change_concurrent_updates_same_key_serialize_via_publisher_cas() { statuses ); assert_eq!( - ok_count, 1, + ok_count, + 1, "expected exactly one update to commit and N-1 to receive 409 manifest_conflict \ (op-kind-aware drift check rejects stale-V0 staged datasets at commit_all entry). \ Got {} OK + {} 409 + {} other. \ @@ -2678,8 +3478,8 @@ mod matrix { impl Harness { pub async fn new() -> Self { - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); // Build the WorkloadController explicitly with defaults rather // than letting `AppState::open` call // `WorkloadController::from_env()`. The admission-gate test @@ -2692,20 +3492,16 @@ mod matrix { // 429 instead of the expected 200. Constructing the // controller here with explicit defaults makes cells // independent of any env mutation other tests perform. - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); - let workload = - omnigraph_server::workload::WorkloadController::with_defaults(); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + let workload = omnigraph_server::workload::WorkloadController::with_defaults(); let state = AppState::new_with_workload( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), db, Vec::new(), workload, ); let app = build_app(state); - Self { - _temp: temp, - app, - } + Self { _temp: temp, app } } pub async fn create_branch(&self, from: &str, name: &str) { @@ -2738,8 +3534,8 @@ mod matrix { pub async fn insert_person(&self, branch: &str, name: &str, age: i32) { let body = serde_json::to_vec(&ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": name, "age": age })), branch: Some(branch.to_string()), }) @@ -2798,12 +3594,7 @@ mod matrix { ) .await .unwrap(); - assert_eq!( - r.status(), - StatusCode::OK, - "snapshot {} failed", - branch - ); + assert_eq!(r.status(), StatusCode::OK, "snapshot {} failed", branch); let body = to_bytes(r.into_body(), usize::MAX).await.unwrap(); let v: Value = serde_json::from_slice(&body).unwrap(); v["tables"] @@ -2822,10 +3613,7 @@ mod matrix { /// just count. pub async fn person_exists(&self, branch: &str, name: &str) -> bool { let body = serde_json::to_vec(&ReadRequest { - query_source: include_str!( - "../../omnigraph/tests/fixtures/test.gq" - ) - .to_string(), + query_source: include_str!("../../omnigraph/tests/fixtures/test.gq").to_string(), query_name: Some("get_person".to_string()), params: Some(json!({ "name": name })), branch: Some(branch.to_string()), @@ -2893,8 +3681,8 @@ mod matrix { /// /change either deadlocks or returns a non-200. pub async fn assert_post_op_sentinel(&self, cell: &str, sentinel: &str) { let body = serde_json::to_vec(&ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": sentinel, "age": 99 })), branch: Some("main".to_string()), }) @@ -2944,12 +3732,12 @@ mod matrix { .unwrap(); let response = app .oneshot( - Request::builder() - .uri("/branches/merge") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), + Request::builder() + .uri("/branches/merge") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), ) .await .unwrap(); @@ -2972,20 +3760,20 @@ mod matrix { tokio::spawn(async move { barrier.wait().await; let body = serde_json::to_vec(&ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": name, "age": age })), branch: Some(branch), }) .unwrap(); let response = app .oneshot( - Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), ) .await .unwrap(); @@ -3013,12 +3801,12 @@ mod matrix { .unwrap(); let response = app .oneshot( - Request::builder() - .uri("/branches") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), + Request::builder() + .uri("/branches") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), ) .await .unwrap(); @@ -3040,11 +3828,11 @@ mod matrix { barrier.wait().await; let response = app .oneshot( - Request::builder() - .uri(format!("/branches/{}", name)) - .method(Method::DELETE) - .body(Body::empty()) - .unwrap(), + Request::builder() + .uri(format!("/branches/{}", name)) + .method(Method::DELETE) + .body(Body::empty()) + .unwrap(), ) .await .unwrap(); @@ -3078,14 +3866,8 @@ async fn concurrent_branch_ops_morphological_matrix() { let (sa, sb) = h .run_pair( - matrix::op_merge( - "feature-a-cella".to_string(), - "target-a-cella".to_string(), - ), - matrix::op_merge( - "feature-b-cella".to_string(), - "target-b-cella".to_string(), - ), + matrix::op_merge("feature-a-cella".to_string(), "target-a-cella".to_string()), + matrix::op_merge("feature-b-cella".to_string(), "target-b-cella".to_string()), ) .await; assert_eq!(sa.status, StatusCode::OK, "[{}] merge a", cell); @@ -3128,20 +3910,15 @@ async fn concurrent_branch_ops_morphological_matrix() { let cell = "c:merge×merge:same-source-distinct-targets"; let h = matrix::Harness::new().await; h.create_branch("main", "src-shared-cellc").await; - h.insert_person("src-shared-cellc", "Sharon-cellc", 50).await; + h.insert_person("src-shared-cellc", "Sharon-cellc", 50) + .await; h.create_branch("main", "tgt-1-cellc").await; h.create_branch("main", "tgt-2-cellc").await; let (sa, sb) = h .run_pair( - matrix::op_merge( - "src-shared-cellc".to_string(), - "tgt-1-cellc".to_string(), - ), - matrix::op_merge( - "src-shared-cellc".to_string(), - "tgt-2-cellc".to_string(), - ), + matrix::op_merge("src-shared-cellc".to_string(), "tgt-1-cellc".to_string()), + matrix::op_merge("src-shared-cellc".to_string(), "tgt-2-cellc".to_string()), ) .await; assert_eq!(sa.status, StatusCode::OK, "[{}] merge into tgt-1", cell); @@ -3183,7 +3960,11 @@ async fn concurrent_branch_ops_morphological_matrix() { let conflict = error .manifest_conflict .expect("merge 409 must include manifest_conflict"); - assert_eq!(conflict.table_key, "node:Person", "[{}] conflict table", cell); + assert_eq!( + conflict.table_key, "node:Person", + "[{}] conflict table", + cell + ); h.assert_persons("main", cell, &["FrankD-celld"], &["EveD-celld"]) .await; } @@ -3236,22 +4017,18 @@ async fn concurrent_branch_ops_morphological_matrix() { let (sa, sb) = h .run_pair( - matrix::op_branch_create( - "alpha-cellf".to_string(), - "gamma-cellf".to_string(), - ), - matrix::op_branch_create( - "beta-cellf".to_string(), - "delta-cellf".to_string(), - ), + matrix::op_branch_create("alpha-cellf".to_string(), "gamma-cellf".to_string()), + matrix::op_branch_create("beta-cellf".to_string(), "delta-cellf".to_string()), ) .await; assert_eq!(sa.status, StatusCode::OK, "[{}] gamma create", cell); assert_eq!(sb.status, StatusCode::OK, "[{}] delta create", cell); // gamma forks off alpha → must contain Eve. - h.assert_persons("gamma-cellf", cell, &["Eve-cellf"], &[]).await; + h.assert_persons("gamma-cellf", cell, &["Eve-cellf"], &[]) + .await; // delta forks off beta → must NOT contain Eve. - h.assert_persons("delta-cellf", cell, &[], &["Eve-cellf"]).await; + h.assert_persons("delta-cellf", cell, &[], &["Eve-cellf"]) + .await; h.assert_post_op_sentinel(cell, "sentinel-cellf").await; } @@ -3272,7 +4049,8 @@ async fn concurrent_branch_ops_morphological_matrix() { assert_eq!(sa.status, StatusCode::OK, "[{}] create newborn", cell); assert_eq!(sb.status, StatusCode::OK, "[{}] delete doomed", cell); // newborn-cellg exists with main's content. - h.assert_persons("newborn-cellg", cell, &["Alice"], &[]).await; + h.assert_persons("newborn-cellg", cell, &["Alice"], &[]) + .await; h.assert_post_op_sentinel(cell, "sentinel-cellg").await; } @@ -3402,14 +4180,18 @@ async fn concurrent_branch_ops_morphological_matrix() { let conflict = error .manifest_conflict .expect("merge 409 must include manifest_conflict"); - assert_eq!(conflict.table_key, "node:Person", "[{}] conflict table", cell); + assert_eq!( + conflict.table_key, "node:Person", + "[{}] conflict table", + cell + ); h.assert_persons("main", cell, &["Steve-cellk"], &["Rita-cellk"]) .await; } - // Reopen via a fresh AppState on the same repo. - let repo_uri = format!("{}/server.omni", h._temp.path().display()); - let reopened = AppState::open(repo_uri.clone()).await.unwrap(); + // Reopen via a fresh AppState on the same graph. + let graph_uri = format!("{}/server.omni", h._temp.path().display()); + let reopened = AppState::open(graph_uri.clone()).await.unwrap(); let app2 = build_app(reopened); // Sanity: the same identity check via the new app must see // Rita and Steve. @@ -3472,9 +4254,9 @@ query insert_c($name: String) { const SEED_COMPANIES: u64 = 2; const PER_TYPE: usize = 4; - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let state = AppState::open(repo.to_string_lossy().to_string()) + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let state = AppState::open(graph.to_string_lossy().to_string()) .await .unwrap(); let app = build_app(state); @@ -3484,8 +4266,8 @@ query insert_c($name: String) { let app_p = app.clone(); handles.push(tokio::spawn(async move { let body = serde_json::to_vec(&ChangeRequest { - query_source: PERSON_QUERY.to_string(), - query_name: Some("insert_p".to_string()), + query: PERSON_QUERY.to_string(), + name: Some("insert_p".to_string()), params: Some(json!({ "name": format!("p-{i}"), "age": i as i32 })), branch: Some("main".to_string()), }) @@ -3501,8 +4283,8 @@ query insert_c($name: String) { let app_c = app.clone(); handles.push(tokio::spawn(async move { let body = serde_json::to_vec(&ChangeRequest { - query_source: COMPANY_QUERY.to_string(), - query_name: Some("insert_c".to_string()), + query: COMPANY_QUERY.to_string(), + name: Some("insert_c".to_string()), params: Some(json!({ "name": format!("c-{i}") })), branch: Some("main".to_string()), }) @@ -3547,7 +4329,11 @@ query insert_c($name: String) { let lookup_count = |table_key: &str| -> u64 { body["tables"] .as_array() - .and_then(|tables| tables.iter().find(|t| t["table_key"].as_str() == Some(table_key))) + .and_then(|tables| { + tables + .iter() + .find(|t| t["table_key"].as_str() == Some(table_key)) + }) .and_then(|t| t["row_count"].as_u64()) .unwrap_or_else(|| panic!("snapshot missing {}", table_key)) }; @@ -3592,9 +4378,9 @@ async fn ingest_per_actor_admission_cap_returns_429() { // `AppState::new_with_workload` constructor closes that bug class — // this test no longer mutates global state and no longer needs // `#[serial]`. - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); let workload = omnigraph_server::workload::WorkloadController::new( 1, // per-actor in-flight cap (the fixture under test) 1_000_000_000, // per-actor byte budget — large so it never bottlenecks @@ -3605,18 +4391,16 @@ async fn ingest_per_actor_admission_cap_returns_429() { // enough to clear the State 3 path so the test reaches workload. let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, permit_all_policy_yaml(&["act-flooder"])).unwrap(); - let policy_engine = omnigraph_server::PolicyEngine::load( - &policy_path, - repo.to_string_lossy().as_ref(), - ) - .unwrap(); - let state = AppState::new_with_workload( - repo.to_string_lossy().to_string(), + let policy_engine = + omnigraph_server::PolicyEngine::load_graph(&policy_path, graph.to_string_lossy().as_ref()) + .unwrap(); + let state = AppState::new_single( + graph.to_string_lossy().to_string(), db, vec![("act-flooder".to_string(), "flooder-token".to_string())], + Some(policy_engine), workload, - ) - .with_policy_engine(policy_engine); + ); let app = build_app(state); let _temp = temp; @@ -3709,9 +4493,82 @@ async fn ingest_per_actor_admission_cap_returns_429() { } } +/// Regression for B2 (MR-668): when an `AppState` is built with a +/// per-graph policy and a custom workload, the engine inside the +/// routing's `GraphHandle` MUST have the same policy applied via +/// `Omnigraph::with_policy`. Pre-fix, `new_with_workload(...).with_policy_engine(p)` +/// installed the policy only on the HTTP-layer `handle.policy`; the +/// underlying `Arc` was reused without `with_policy`, so any +/// caller reaching through `state.routing()` could bypass Cedar. +/// +/// This test reaches the engine the same way an embedded SDK consumer +/// or future routing code path would, and asserts the policy still +/// fires. The deny path is "act-blocked has a valid bearer but isn't in +/// the policy's allowed group" — i.e., authenticated-but-unauthorised. +#[tokio::test(flavor = "multi_thread")] +async fn engine_layer_policy_fires_via_direct_arc_omnigraph_from_new_single() { + use omnigraph_server::GraphRouting; + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + + // Permit `act-allowed` for change actions; `act-blocked` is not in + // any allowed group — every change request from them must deny. + let policy_path = temp.path().join("policy.yaml"); + fs::write(&policy_path, permit_all_policy_yaml(&["act-allowed"])).unwrap(); + let policy_engine = + omnigraph_server::PolicyEngine::load_graph(&policy_path, graph.to_string_lossy().as_ref()) + .unwrap(); + + let workload = omnigraph_server::workload::WorkloadController::new(100, 1_000_000_000); + let state = AppState::new_single( + graph.to_string_lossy().to_string(), + db, + vec![("act-blocked".to_string(), "block-token".to_string())], + Some(policy_engine), + workload, + ); + + // Reach into the routing and pull the engine the same way an + // embedded consumer holding `Arc` would. If `new_single` + // failed to apply `with_policy` to the engine, this `mutate_as` + // would succeed — the HTTP-layer is bypassed entirely. + let handle = match state.routing() { + GraphRouting::Single { handle } => Arc::clone(handle), + GraphRouting::Multi { .. } => panic!("expected single-mode routing"), + }; + let engine = Arc::clone(&handle.engine); + + let mut params: omnigraph_compiler::ParamMap = Default::default(); + params.insert( + "name".to_string(), + omnigraph_compiler::Literal::String("EngineLayerBlocked".to_string()), + ); + params.insert("age".to_string(), omnigraph_compiler::Literal::Integer(30)); + let result = engine + .mutate_as( + "main", + MUTATION_QUERIES, + "insert_person", + ¶ms, + Some("act-blocked"), + ) + .await; + match result { + Err(OmniError::Policy(_)) => { /* expected — engine-layer gate fired */ } + Ok(_) => panic!( + "engine-layer policy did NOT fire — act-blocked successfully ran mutate_as via \ + the engine pulled from the registry handle. AppState::new_single failed to apply \ + with_policy to the underlying Omnigraph engine. This is the B2 footgun the \ + with_policy_engine deletion was supposed to close." + ), + Err(other) => panic!("expected OmniError::Policy, got: {other:?}"), + } +} + #[tokio::test(flavor = "multi_thread")] async fn oversized_request_body_returns_payload_too_large() { - let (_temp, app) = app_for_loaded_repo().await; + let (_temp, app) = app_for_loaded_graph().await; let oversized = "x".repeat(1_100_000); let response = app .clone() @@ -3739,7 +4596,7 @@ async fn oversized_request_body_returns_payload_too_large() { #[tokio::test(flavor = "multi_thread")] async fn default_deny_mode_allows_read_for_authenticated_actor() { - let (_temp, app) = app_for_repo_with_auth_tokens_only( + let (_temp, app) = app_for_graph_with_auth_tokens_only( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-andrew", "demo-token")], ) @@ -3760,15 +4617,15 @@ async fn default_deny_mode_allows_read_for_authenticated_actor() { #[tokio::test(flavor = "multi_thread")] async fn default_deny_mode_rejects_change_with_forbidden() { - let (_temp, app) = app_for_repo_with_auth_tokens_only( + let (_temp, app) = app_for_graph_with_auth_tokens_only( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-andrew", "demo-token")], ) .await; let change = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "DefaultDeny", "age": 1 })), branch: Some("main".to_string()), }; @@ -3794,7 +4651,7 @@ async fn default_deny_mode_rejects_change_with_forbidden() { #[tokio::test(flavor = "multi_thread")] async fn default_deny_mode_rejects_schema_apply_with_forbidden() { - let (_temp, app) = app_for_repo_with_auth_tokens_only( + let (_temp, app) = app_for_graph_with_auth_tokens_only( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-andrew", "demo-token")], ) @@ -3802,7 +4659,7 @@ async fn default_deny_mode_rejects_schema_apply_with_forbidden() { let req = SchemaApplyRequest { schema_source: additive_schema_with_nickname(), - ..Default::default() + ..Default::default() }; let (status, body) = json_response( &app, @@ -3862,13 +4719,13 @@ enum ParityDecision { Deny, } -async fn build_parity_repo() -> (tempfile::TempDir, PathBuf, PathBuf) { - // Build a repo with `main` loaded and a `feature` branch ready for - // merge. Returns the repo path and a written policy.yaml path. - let temp = init_loaded_repo().await; - let repo = repo_path(temp.path()); +async fn build_parity_graph() -> (tempfile::TempDir, PathBuf, PathBuf) { + // Build a graph with `main` loaded and a `feature` branch ready for + // merge. Returns the graph path and a written policy.yaml path. + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); { - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.branch_create_from(ReadTarget::branch("main"), "feature") .await .unwrap(); @@ -3883,12 +4740,12 @@ async fn build_parity_repo() -> (tempfile::TempDir, PathBuf, PathBuf) { } let policy_path = temp.path().join("policy.yaml"); fs::write(&policy_path, PARITY_POLICY_YAML).unwrap(); - (temp, repo, policy_path) + (temp, graph, policy_path) } -async fn sdk_change_decision(repo: &Path, policy_path: &Path, actor: &str) -> ParityDecision { - let policy = PolicyEngine::load(policy_path, repo.to_string_lossy().as_ref()).unwrap(); - let db = Omnigraph::open(repo.to_str().unwrap()) +async fn sdk_change_decision(graph: &Path, policy_path: &Path, actor: &str) -> ParityDecision { + let policy = PolicyEngine::load_graph(policy_path, graph.to_string_lossy().as_ref()).unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()) .await .unwrap() .with_policy(Arc::new(policy) as Arc); @@ -3901,7 +4758,13 @@ async fn sdk_change_decision(repo: &Path, policy_path: &Path, actor: &str) -> Pa ); params.insert("age".to_string(), omnigraph_compiler::Literal::Integer(30)); let result = db - .mutate_as("main", MUTATION_QUERIES, "insert_person", ¶ms, Some(actor)) + .mutate_as( + "main", + MUTATION_QUERIES, + "insert_person", + ¶ms, + Some(actor), + ) .await; match result { Ok(_) => ParityDecision::Allow, @@ -3911,13 +4774,13 @@ async fn sdk_change_decision(repo: &Path, policy_path: &Path, actor: &str) -> Pa } async fn http_change_decision( - repo: &Path, + graph: &Path, policy_path: &PathBuf, actor: &str, token: &str, ) -> ParityDecision { let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![(actor.to_string(), token.to_string())], Some(policy_path), ) @@ -3925,8 +4788,8 @@ async fn http_change_decision( .unwrap(); let app = build_app(state); let req = ChangeRequest { - query_source: MUTATION_QUERIES.to_string(), - query_name: Some("insert_person".to_string()), + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), params: Some(json!({ "name": "ParityCharlie", "age": 30 })), branch: Some("main".to_string()), }; @@ -3948,9 +4811,9 @@ async fn http_change_decision( } } -async fn sdk_merge_decision(repo: &Path, policy_path: &Path, actor: &str) -> ParityDecision { - let policy = PolicyEngine::load(policy_path, repo.to_string_lossy().as_ref()).unwrap(); - let db = Omnigraph::open(repo.to_str().unwrap()) +async fn sdk_merge_decision(graph: &Path, policy_path: &Path, actor: &str) -> ParityDecision { + let policy = PolicyEngine::load_graph(policy_path, graph.to_string_lossy().as_ref()).unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()) .await .unwrap() .with_policy(Arc::new(policy) as Arc); @@ -3963,13 +4826,13 @@ async fn sdk_merge_decision(repo: &Path, policy_path: &Path, actor: &str) -> Par } async fn http_merge_decision( - repo: &Path, + graph: &Path, policy_path: &PathBuf, actor: &str, token: &str, ) -> ParityDecision { let state = AppState::open_with_bearer_tokens_and_policy( - repo.to_string_lossy().to_string(), + graph.to_string_lossy().to_string(), vec![(actor.to_string(), token.to_string())], Some(policy_path), ) @@ -4001,12 +4864,12 @@ async fn http_merge_decision( #[tokio::test(flavor = "multi_thread")] async fn policy_decision_parity_change_admin_on_main_allowed() { // (act-ragnor, change, main) — admins-change-anywhere rule applies. - // Both SDK and HTTP must allow. Each path uses its own fresh repo + // Both SDK and HTTP must allow. Each path uses its own fresh graph // because allow→side-effects. - let (_t1, repo1, policy1) = build_parity_repo().await; - let sdk = sdk_change_decision(&repo1, &policy1, "act-ragnor").await; - let (_t2, repo2, policy2) = build_parity_repo().await; - let http = http_change_decision(&repo2, &policy2, "act-ragnor", "ragnor-token").await; + let (_t1, graph1, policy1) = build_parity_graph().await; + let sdk = sdk_change_decision(&graph1, &policy1, "act-ragnor").await; + let (_t2, graph2, policy2) = build_parity_graph().await; + let http = http_change_decision(&graph2, &policy2, "act-ragnor", "ragnor-token").await; assert!( matches!(sdk, ParityDecision::Allow) && matches!(http, ParityDecision::Allow), "SDK={sdk:?} HTTP={http:?} — should both Allow", @@ -4016,11 +4879,11 @@ async fn policy_decision_parity_change_admin_on_main_allowed() { #[tokio::test(flavor = "multi_thread")] async fn policy_decision_parity_change_team_on_main_denied() { // (act-bruno, change, main) — no rule grants bruno change on - // protected. Both SDK and HTTP must deny. Same repo is reusable + // protected. Both SDK and HTTP must deny. Same graph is reusable // because deny→no side-effects. - let (_temp, repo, policy) = build_parity_repo().await; - let sdk = sdk_change_decision(&repo, &policy, "act-bruno").await; - let http = http_change_decision(&repo, &policy, "act-bruno", "bruno-token").await; + let (_temp, graph, policy) = build_parity_graph().await; + let sdk = sdk_change_decision(&graph, &policy, "act-bruno").await; + let http = http_change_decision(&graph, &policy, "act-bruno", "bruno-token").await; assert!( matches!(sdk, ParityDecision::Deny) && matches!(http, ParityDecision::Deny), "SDK={sdk:?} HTTP={http:?} — should both Deny", @@ -4030,12 +4893,12 @@ async fn policy_decision_parity_change_team_on_main_denied() { #[tokio::test(flavor = "multi_thread")] async fn policy_decision_parity_branch_merge_admin_allowed() { // (act-ragnor, branch_merge, feature→main) — admins-merge-to-protected - // rule applies. Both Allow. Each path uses its own fresh repo — + // rule applies. Both Allow. Each path uses its own fresh graph — // a successful merge consumes the feature branch's commit on main. - let (_t1, repo1, policy1) = build_parity_repo().await; - let sdk = sdk_merge_decision(&repo1, &policy1, "act-ragnor").await; - let (_t2, repo2, policy2) = build_parity_repo().await; - let http = http_merge_decision(&repo2, &policy2, "act-ragnor", "ragnor-token").await; + let (_t1, graph1, policy1) = build_parity_graph().await; + let sdk = sdk_merge_decision(&graph1, &policy1, "act-ragnor").await; + let (_t2, graph2, policy2) = build_parity_graph().await; + let http = http_merge_decision(&graph2, &policy2, "act-ragnor", "ragnor-token").await; assert!( matches!(sdk, ParityDecision::Allow) && matches!(http, ParityDecision::Allow), "SDK={sdk:?} HTTP={http:?} — should both Allow", @@ -4046,9 +4909,9 @@ async fn policy_decision_parity_branch_merge_admin_allowed() { async fn policy_decision_parity_branch_merge_team_denied() { // (act-bruno, branch_merge, feature→main) — no rule grants bruno // branch_merge. Both Deny. - let (_temp, repo, policy) = build_parity_repo().await; - let sdk = sdk_merge_decision(&repo, &policy, "act-bruno").await; - let http = http_merge_decision(&repo, &policy, "act-bruno", "bruno-token").await; + let (_temp, graph, policy) = build_parity_graph().await; + let sdk = sdk_merge_decision(&graph, &policy, "act-bruno").await; + let http = http_merge_decision(&graph, &policy, "act-bruno", "bruno-token").await; assert!( matches!(sdk, ParityDecision::Deny) && matches!(http, ParityDecision::Deny), "SDK={sdk:?} HTTP={http:?} — should both Deny", @@ -4065,16 +4928,16 @@ async fn policy_decision_parity_branch_merge_team_denied() { #[tokio::test(flavor = "multi_thread")] async fn schema_apply_route_soft_drops_property_via_http() { - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, ) .await; // Load a row that has the column we're about to drop. - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); { - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.load( "main", r#"{"type":"Person","data":{"name":"PreDrop","age":42}}"#, @@ -4083,7 +4946,7 @@ async fn schema_apply_route_soft_drops_property_via_http() { .await .unwrap(); } - let pre_version = manifest_dataset_version(&repo).await; + let pre_version = manifest_dataset_version(&graph).await; let (status, payload) = json_response( &app, @@ -4106,7 +4969,7 @@ async fn schema_apply_route_soft_drops_property_via_http() { assert_eq!(payload["applied"], true); // Catalog reflects the drop: `age` is gone from the live schema. - let reopened = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); assert!( !reopened.catalog().node_types["Person"] .properties @@ -4134,13 +4997,13 @@ async fn schema_apply_route_soft_drops_property_via_http() { #[tokio::test(flavor = "multi_thread")] async fn schema_apply_route_soft_drops_node_type_via_http() { - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, ) .await; - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let (status, payload) = json_response( &app, @@ -4162,7 +5025,7 @@ async fn schema_apply_route_soft_drops_node_type_via_http() { assert_eq!(status, StatusCode::OK); assert_eq!(payload["applied"], true); - let reopened = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); assert!( !reopened.catalog().node_types.contains_key("Company"), "catalog should not contain `Company` after drop" @@ -4175,15 +5038,15 @@ async fn schema_apply_route_soft_drops_node_type_via_http() { #[tokio::test(flavor = "multi_thread")] async fn schema_apply_route_hard_drops_property_with_allow_data_loss() { - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, ) .await; - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); { - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.load( "main", r#"{"type":"Person","data":{"name":"PreDropHard","age":50}}"#, @@ -4215,7 +5078,7 @@ async fn schema_apply_route_hard_drops_property_with_allow_data_loss() { assert_eq!(payload["applied"], true); // Catalog reflects the drop. - let reopened = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); assert!( !reopened.catalog().node_types["Person"] .properties @@ -4229,7 +5092,10 @@ async fn schema_apply_route_hard_drops_property_with_allow_data_loss() { .find(|s| s["kind"] == "drop_property") .expect("plan should include drop_property step"); let mode = &drop_step["mode"]; - assert_eq!(mode, "hard", "expected hard mode under allow_data_loss=true"); + assert_eq!( + mode, "hard", + "expected hard mode under allow_data_loss=true" + ); } #[tokio::test(flavor = "multi_thread")] @@ -4238,13 +5104,13 @@ async fn schema_apply_route_keeps_drops_soft_without_flag() { // allow_data_loss flag → drops stay Soft (prior column data // remains time-travel-reachable). Pins the default semantics // against accidental Hard promotion. - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, ) .await; - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); let (status, payload) = json_response( &app, @@ -4273,7 +5139,7 @@ async fn schema_apply_route_keeps_drops_soft_without_flag() { .expect("plan should include drop_property step"); let mode = &drop_step["mode"]; assert_eq!(mode, "soft", "expected soft mode without allow_data_loss"); - let _ = repo; + let _ = graph; } #[tokio::test(flavor = "multi_thread")] @@ -4282,17 +5148,17 @@ async fn schema_apply_route_additive_property_preserves_existing_rows() { // AddProperty wasn't pinned with a row-count check anywhere. // Load N rows, apply schema adding nullable property, verify // every row is still readable and the new column is null. - let (temp, app) = app_for_repo_with_auth_tokens_and_policy( + let (temp, app) = app_for_graph_with_auth_tokens_and_policy( &fs::read_to_string(fixture("test.pg")).unwrap(), &[("act-ragnor", "admin-token")], SCHEMA_APPLY_POLICY_YAML, ) .await; - let repo = repo_path(temp.path()); + let graph = graph_path(temp.path()); // Standard fixture data: 4 Persons + 1 Company. Load it. let pre_count = { - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); db.load( "main", &fs::read_to_string(fixture("test.jsonl")).unwrap(), @@ -4329,8 +5195,9 @@ async fn schema_apply_route_additive_property_preserves_existing_rows() { assert_eq!(payload["applied"], true); // Row count preserved. - let db = Omnigraph::open(repo.to_str().unwrap()).await.unwrap(); - let snap = db.snapshot_of(omnigraph::db::ReadTarget::branch("main")) + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + let snap = db + .snapshot_of(omnigraph::db::ReadTarget::branch("main")) .await .unwrap(); let post_count = snap.entry("node:Person").expect("Person").row_count; @@ -4339,3 +5206,1004 @@ async fn schema_apply_route_additive_property_preserves_existing_rows() { "AddProperty should preserve row count", ); } + +// ─── MR-668: multi-graph startup ────────────────────────────────────────── + +mod multi_graph_startup { + use super::*; + use omnigraph::storage::normalize_root_uri; + use omnigraph_server::{ + GraphHandle, GraphId, GraphKey, GraphRegistry, InsertError, ServerConfig, ServerConfigMode, + load_server_settings, + }; + use std::sync::Arc; + + async fn build_multi_mode_app(graph_ids: &[&str]) -> (Vec, Router) { + let mut dirs = Vec::with_capacity(graph_ids.len()); + let mut handles = Vec::with_capacity(graph_ids.len()); + for id in graph_ids { + let dir = tempfile::tempdir().unwrap(); + let graph_uri = dir.path().join(id).to_str().unwrap().to_string(); + let schema = fs::read_to_string(fixture("test.pg")).unwrap(); + let engine = Omnigraph::init(&graph_uri, &schema).await.unwrap(); + handles.push(Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from(*id).unwrap()), + uri: graph_uri, + engine: Arc::new(engine), + policy: None, + queries: None, + })); + dirs.push(dir); + } + let workload = omnigraph_server::workload::WorkloadController::from_env(); + let state = AppState::new_multi(handles, Vec::new(), None, workload, None).unwrap(); + let app = build_app(state); + (dirs, app) + } + + /// Cluster route `/graphs/{graph_id}/snapshot` resolves to the right + /// engine. Two graphs side by side; assert each responds to its own + /// id and does NOT respond to the other's URL. + #[tokio::test(flavor = "multi_thread")] + async fn cluster_routes_dispatch_per_graph_handle() { + let (_dirs, app) = build_multi_mode_app(&["alpha", "beta"]).await; + for id in ["alpha", "beta"] { + let resp = app + .clone() + .oneshot( + Request::builder() + .method(Method::GET) + .uri(format!("/graphs/{id}/snapshot?branch=main")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + resp.status(), + StatusCode::OK, + "graph '{id}' must respond OK on its cluster snapshot route" + ); + } + } + + /// Unknown graph id under the cluster prefix yields 404 (not 500, + /// not 410 — `Gone` is reserved for the future DELETE flow). + #[tokio::test(flavor = "multi_thread")] + async fn cluster_route_for_unknown_graph_returns_404() { + let (_dirs, app) = build_multi_mode_app(&["alpha"]).await; + let resp = app + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/graphs/nonexistent/snapshot?branch=main") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::NOT_FOUND); + } + + /// Coverage net for cluster-route regressions across every + /// protected handler — not just the few that have inner path + /// params. Bug-1 surfaced because only `/snapshot` was being + /// exercised in cluster mode, leaving the other six protected + /// routes implicitly untested. This sweep hits each one and + /// asserts the response shows the handler was reached: no 404 + /// (router didn't match), no 500 with "Wrong number of path + /// arguments" (path extractor broke), no 500 with "missing + /// extension" (routing middleware didn't inject the handle). + /// + /// Status codes are negative assertions because each handler's + /// happy-path inputs differ — what matters is "the request + /// reached the handler," not "the handler returned 200." The + /// individual handlers' logic is already tested in single mode. + #[tokio::test(flavor = "multi_thread")] + async fn all_protected_cluster_routes_resolve_to_their_handler() { + let (_dirs, app) = build_multi_mode_app(&["alpha"]).await; + + // (method, path, body) — one minimal request per protected + // cluster route. Bodies are valid enough that the router and + // extractors succeed; whether the engine ultimately returns + // 200 or 4xx is per-handler and not what this test pins. + let cases: &[(Method, &str, Option<&str>)] = &[ + (Method::GET, "/graphs/alpha/snapshot?branch=main", None), + (Method::GET, "/graphs/alpha/schema", None), + (Method::GET, "/graphs/alpha/branches", None), + (Method::GET, "/graphs/alpha/commits", None), + ( + Method::POST, + "/graphs/alpha/read", + Some(r#"{"query_source":"query q() { return {} }"}"#), + ), + ( + Method::POST, + "/graphs/alpha/change", + Some(r#"{"query_source":"query q() { return {} }"}"#), + ), + ( + Method::POST, + "/graphs/alpha/export", + Some(r#"{"branch":"main"}"#), + ), + ( + Method::POST, + "/graphs/alpha/schema/apply", + Some(r#"{"schema_source":"","allow_data_loss":false}"#), + ), + (Method::POST, "/graphs/alpha/ingest", Some(r#"{"data":""}"#)), + ( + Method::POST, + "/graphs/alpha/branches/merge", + Some(r#"{"source":"main","target":"main"}"#), + ), + ]; + + for (method, path, body) in cases { + let req_body = body + .map(|s| Body::from(s.to_string())) + .unwrap_or_else(Body::empty); + let req = Request::builder() + .method(method.clone()) + .uri(*path) + .header("content-type", "application/json") + .body(req_body) + .unwrap(); + let resp = app.clone().oneshot(req).await.unwrap(); + let status = resp.status(); + let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap(); + let body_str = String::from_utf8_lossy(&bytes); + + assert_ne!( + status, + StatusCode::NOT_FOUND, + "{} {} — router didn't match (cluster-route mounting regression). Body: {}", + method, + path, + body_str, + ); + assert!( + !(status == StatusCode::INTERNAL_SERVER_ERROR + && body_str.contains("Wrong number of path arguments")), + "{} {} — path extractor broke (Bug-1 class regression). Body: {}", + method, + path, + body_str, + ); + assert!( + !(status == StatusCode::INTERNAL_SERVER_ERROR + && body_str.to_lowercase().contains("missing extension")), + "{} {} — routing middleware didn't inject GraphHandle. Body: {}", + method, + path, + body_str, + ); + } + } + + /// Regression for the bot-surfaced path-extractor bug: cluster + /// routes whose inner path also captures a parameter + /// (`/graphs/{graph_id}/branches/{branch}`, + /// `/graphs/{graph_id}/commits/{commit_id}`) must extract the + /// inner param cleanly. Axum 0.8 propagates the outer `{graph_id}` + /// capture into nested handlers, so a `Path` extractor + /// would see two values and fail with "Wrong number of path + /// arguments. Expected 1 but got 2." Today both DELETE branch and + /// GET commit-by-id break in multi-mode because their handlers + /// use bare `Path` — this test pins the fix. + /// + /// The broader `all_protected_cluster_routes_resolve_to_their_handler` + /// test sweeps the full route surface; this one stays narrowly + /// targeted at the inner-path-param shape because that's the + /// specific regression class. + #[tokio::test(flavor = "multi_thread")] + async fn cluster_routes_with_inner_path_params_deserialize_correctly() { + let (_dirs, app) = build_multi_mode_app(&["alpha"]).await; + + // Create a branch we can then delete — DELETE /graphs/alpha/branches/feature + let create_resp = app + .clone() + .oneshot( + Request::builder() + .method(Method::POST) + .uri("/graphs/alpha/branches") + .header("content-type", "application/json") + .body(Body::from(r#"{"name":"feature"}"#)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + create_resp.status(), + StatusCode::OK, + "branch create on the cluster route must succeed before delete can be tested" + ); + + // DELETE /graphs/{graph_id}/branches/{branch} — exercises a handler + // whose only Path extractor (`branch`) is inside a nested route + // that also captures `graph_id`. The handler must pick `branch` + // by name, not by position. + let delete_resp = app + .clone() + .oneshot( + Request::builder() + .method(Method::DELETE) + .uri("/graphs/alpha/branches/feature") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let delete_status = delete_resp.status(); + let delete_body = to_bytes(delete_resp.into_body(), usize::MAX).await.unwrap(); + assert_eq!( + delete_status, + StatusCode::OK, + "DELETE /graphs/{{id}}/branches/{{branch}} must extract `branch` cleanly. \ + Body: {}", + String::from_utf8_lossy(&delete_body), + ); + + // GET /graphs/{graph_id}/commits/{commit_id} — same shape: the + // handler's only Path extractor is the inner `commit_id`, which + // must deserialize by name even though `graph_id` is also in scope. + // We don't know a real commit_id, but the failure mode under test + // is path extraction, not commit lookup — a 404 from the engine + // is fine; a 500 with "Wrong number of path arguments" is the bug. + let commit_resp = app + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/graphs/alpha/commits/0000000000000000") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let commit_status = commit_resp.status(); + let commit_body = to_bytes(commit_resp.into_body(), usize::MAX).await.unwrap(); + let body_str = String::from_utf8_lossy(&commit_body); + assert!( + commit_status != StatusCode::INTERNAL_SERVER_ERROR + || !body_str.contains("Wrong number of path arguments"), + "GET /graphs/{{id}}/commits/{{commit_id}} must extract `commit_id` cleanly. \ + Got: {} | {}", + commit_status, + body_str, + ); + } + + /// Flat routes 404 in multi mode — the router only mounts under + /// `/graphs/{graph_id}/...` so `/snapshot` doesn't resolve. + #[tokio::test(flavor = "multi_thread")] + async fn flat_routes_404_in_multi_mode() { + let (_dirs, app) = build_multi_mode_app(&["alpha"]).await; + let resp = app + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/snapshot?branch=main") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::NOT_FOUND); + } + + /// `GraphId` validation runs at startup — a reserved name in + /// `omnigraph.yaml` produces a clear error rather than getting + /// rejected per-request. + #[test] + fn load_server_settings_rejects_reserved_graph_id() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +graphs: + policies: + uri: /tmp/g1.omni +"#, + ) + .unwrap(); + let err = load_server_settings(Some(&config_path), None, None, None, false).unwrap_err(); + assert!( + err.to_string().contains("invalid graph id 'policies'"), + "expected reserved-name rejection, got: {err}" + ); + } + + #[tokio::test(flavor = "multi_thread")] + async fn registry_rejects_duplicate_normalized_graph_uris() { + let dir = tempfile::tempdir().unwrap(); + let graph_uri = dir.path().join("same").to_str().unwrap().to_string(); + let schema = fs::read_to_string(fixture("test.pg")).unwrap(); + let engine = Arc::new(Omnigraph::init(&graph_uri, &schema).await.unwrap()); + + let alpha = Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from("alpha").unwrap()), + uri: graph_uri.clone(), + engine: Arc::clone(&engine), + policy: None, + queries: None, + }); + let beta = Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from("beta").unwrap()), + uri: format!("file://{graph_uri}/"), + engine, + policy: None, + queries: None, + }); + + match GraphRegistry::from_handles(vec![alpha, beta]) { + Err(InsertError::DuplicateUri(uri)) => { + assert!( + normalize_root_uri(&uri).is_ok(), + "duplicate URI should still be parseable, got {uri}" + ); + } + Err(err) => panic!("expected DuplicateUri for normalized aliases, got {err:?}"), + Ok(_) => panic!("expected DuplicateUri for normalized aliases, got Ok"), + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn registry_stores_canonical_graph_uri() { + let dir = tempfile::tempdir().unwrap(); + let graph_uri = dir.path().join("canonical").to_str().unwrap().to_string(); + let schema = fs::read_to_string(fixture("test.pg")).unwrap(); + let engine = Omnigraph::init(&graph_uri, &schema).await.unwrap(); + let handle = Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from("alpha").unwrap()), + uri: format!("file://{graph_uri}/"), + engine: Arc::new(engine), + policy: None, + queries: None, + }); + + let registry = GraphRegistry::from_handles(vec![handle]).unwrap(); + let listed = registry.list(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].uri, graph_uri); + } + + // ── Four-rule mode inference matrix ─────────────────────────────── + + /// Rule 1: CLI positional URI → Single. + #[test] + fn mode_inference_cli_uri_is_single() { + let settings = load_server_settings( + None, + Some("/tmp/cli.omni".to_string()), + None, + None, + true, // allow unauth so we get past the runtime-state check + ) + .unwrap(); + match settings.mode { + ServerConfigMode::Single { uri, .. } => assert_eq!(uri, "/tmp/cli.omni"), + ServerConfigMode::Multi { .. } => panic!("expected Single (rule 1), got Multi"), + } + } + + /// Rule 2: --target picks one graph from `graphs:` map → Single. + #[test] + fn mode_inference_cli_target_is_single() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +graphs: + alpha: + uri: /tmp/alpha.omni + beta: + uri: /tmp/beta.omni +"#, + ) + .unwrap(); + let settings = + load_server_settings(Some(&config_path), None, Some("alpha".into()), None, true) + .unwrap(); + match settings.mode { + ServerConfigMode::Single { uri, .. } => assert_eq!(uri, "/tmp/alpha.omni"), + ServerConfigMode::Multi { .. } => panic!("expected Single (rule 2), got Multi"), + } + } + + /// Rule 3: `server.graph` set → Single (target picked from config). + #[test] + fn mode_inference_server_graph_is_single() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +graphs: + alpha: + uri: /tmp/alpha.omni + beta: + uri: /tmp/beta.omni +server: + graph: beta +"#, + ) + .unwrap(); + let settings = load_server_settings(Some(&config_path), None, None, None, true).unwrap(); + match settings.mode { + ServerConfigMode::Single { uri, .. } => assert_eq!(uri, "/tmp/beta.omni"), + ServerConfigMode::Multi { .. } => panic!("expected Single (rule 3), got Multi"), + } + } + + /// Rule 4: `--config` + non-empty `graphs:` + no single-mode selector → Multi. + #[test] + fn mode_inference_config_plus_graphs_is_multi() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +graphs: + alpha: + uri: /tmp/alpha.omni + beta: + uri: /tmp/beta.omni +"#, + ) + .unwrap(); + let settings = load_server_settings(Some(&config_path), None, None, None, true).unwrap(); + match settings.mode { + ServerConfigMode::Multi { graphs, .. } => { + let ids: Vec<&str> = graphs.iter().map(|g| g.graph_id.as_str()).collect(); + // BTreeMap iteration order is alphabetical. + assert_eq!(ids, vec!["alpha", "beta"]); + } + ServerConfigMode::Single { .. } => panic!("expected Multi (rule 4), got Single"), + } + } + + #[test] + fn mode_inference_multi_rejects_top_level_policy_file() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +policy: + file: ./policy.yaml +graphs: + alpha: + uri: /tmp/alpha.omni +"#, + ) + .unwrap(); + let err = load_server_settings(Some(&config_path), None, None, None, true).unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("top-level") && msg.contains("policy.file") && msg.contains("not honored"), + "expected top-level-not-honored guidance, got: {msg}" + ); + assert!( + msg.contains("graphs."), + "expected per-graph migration guidance, got: {msg}" + ); + assert!( + msg.contains("server.policy.file"), + "expected server policy migration guidance, got: {msg}" + ); + } + + #[test] + fn mode_inference_multi_rejects_top_level_queries() { + // Symmetric to the policy guard: a top-level `queries:` block in + // multi-graph mode is not honored (each graph uses its own), so it + // is a loud error rather than a silent no-op. + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + "queries:\n q:\n file: ./q.gq\ngraphs:\n alpha:\n uri: /tmp/alpha.omni\n", + ) + .unwrap(); + let err = load_server_settings(Some(&config_path), None, None, None, true).unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("queries") && msg.contains("not honored"), + "top-level queries must be rejected in multi-graph mode: {msg}" + ); + } + + #[test] + fn single_mode_named_graph_rejects_top_level_blocks() { + // Serving a graph by name (`--target`/`server.graph`) uses its + // per-graph block; a populated top-level block would be silently + // shadowed, so boot refuses and names the per-graph location. + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + "policy:\n file: ./top.yaml\ngraphs:\n prod:\n uri: /tmp/prod.omni\n", + ) + .unwrap(); + let err = + load_server_settings(Some(&config_path), None, Some("prod".to_string()), None, true) + .unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("prod") && msg.contains("policy.file") && msg.contains("graphs.prod"), + "named single-mode + top-level policy must refuse, naming the graph: {msg}" + ); + } + + #[test] + fn single_mode_named_graph_uses_per_graph_policy_and_queries() { + // The identity rule: `--target prod` attaches `graphs.prod`'s own + // policy + queries, not the top-level ones (which are absent here). + let temp = tempfile::tempdir().unwrap(); + fs::write( + temp.path().join("prod.gq"), + "query pq() { match { $u: User } return { $u.name } }", + ) + .unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + "graphs:\n prod:\n uri: /tmp/prod.omni\n policy:\n file: ./prod-policy.yaml\n \ + queries:\n pq:\n file: ./prod.gq\n", + ) + .unwrap(); + let settings = + load_server_settings(Some(&config_path), None, Some("prod".to_string()), None, true) + .unwrap(); + match settings.mode { + ServerConfigMode::Single { + graph_id, + policy_file, + queries, + .. + } => { + assert_eq!(graph_id, "prod", "named single-mode keeps graph identity"); + assert!( + policy_file + .as_ref() + .is_some_and(|p| p.ends_with("prod-policy.yaml")), + "per-graph policy attached: {policy_file:?}" + ); + assert!(queries.lookup("pq").is_some(), "per-graph query attached"); + } + other => panic!("expected Single mode, got {other:?}"), + } + } + + #[test] + fn mode_inference_normalizes_multi_graph_uris() { + let temp = tempfile::tempdir().unwrap(); + let graph = temp.path().join("alpha.omni"); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + format!( + r#" +graphs: + alpha: + uri: file://{}/ +"#, + graph.display() + ), + ) + .unwrap(); + let settings = load_server_settings(Some(&config_path), None, None, None, true).unwrap(); + match settings.mode { + ServerConfigMode::Multi { graphs, .. } => { + assert_eq!(graphs[0].uri, graph.to_string_lossy()); + } + ServerConfigMode::Single { .. } => panic!("expected Multi"), + } + } + + /// Rule 5: nothing → error with migration hint. + #[test] + fn mode_inference_no_inputs_errors_with_migration_hint() { + let err = load_server_settings(None, None, None, None, true).unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("no graph to serve"), + "expected migration-hint error, got: {msg}" + ); + } + + /// Rule 4 sub-case: `--config` with empty `graphs:` map and no + /// single-mode selector → rule 5 fires (no graph to serve). + #[test] + fn mode_inference_empty_graphs_map_errors() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write(&config_path, "server:\n bind: 127.0.0.1:8080\n").unwrap(); + let err = load_server_settings(Some(&config_path), None, None, None, true).unwrap_err(); + assert!(err.to_string().contains("no graph to serve")); + } + + /// `--config` + `` together: URI wins → Single (the CLI URI + /// takes precedence over the config's graphs map). + #[test] + fn mode_inference_cli_uri_overrides_graphs_map() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +graphs: + alpha: + uri: /tmp/alpha.omni +"#, + ) + .unwrap(); + let settings = load_server_settings( + Some(&config_path), + Some("/tmp/cli-override.omni".to_string()), + None, + None, + true, + ) + .unwrap(); + match settings.mode { + ServerConfigMode::Single { uri, .. } => { + assert_eq!( + uri, "/tmp/cli-override.omni", + "CLI URI must win over graphs: map" + ); + } + ServerConfigMode::Multi { .. } => { + panic!("expected Single (CLI URI wins), got Multi") + } + } + } + + /// Per-graph `policy.file` is resolved relative to the config base_dir. + #[test] + fn per_graph_policy_file_is_resolved_relative_to_base_dir() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +graphs: + alpha: + uri: /tmp/alpha.omni + policy: + file: ./policies/alpha.yaml + beta: + uri: /tmp/beta.omni +"#, + ) + .unwrap(); + let settings = load_server_settings(Some(&config_path), None, None, None, true).unwrap(); + let graphs = match settings.mode { + ServerConfigMode::Multi { graphs, .. } => graphs, + _ => panic!("expected Multi"), + }; + // graphs is BTreeMap-iter order (alphabetical). + let alpha = &graphs[0]; + let beta = &graphs[1]; + assert_eq!(alpha.graph_id, "alpha"); + assert_eq!( + alpha.policy_file.as_ref().unwrap(), + &temp.path().join("policies/alpha.yaml") + ); + assert_eq!(beta.graph_id, "beta"); + assert!(beta.policy_file.is_none()); + } + + /// `server.policy.file` resolves alongside the graphs map. + #[test] + fn server_policy_file_is_resolved_relative_to_base_dir() { + let temp = tempfile::tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +server: + policy: + file: ./server-policy.yaml +graphs: + alpha: + uri: /tmp/alpha.omni +"#, + ) + .unwrap(); + let settings = load_server_settings(Some(&config_path), None, None, None, true).unwrap(); + match settings.mode { + ServerConfigMode::Multi { + server_policy_file, .. + } => { + assert_eq!( + server_policy_file.unwrap(), + temp.path().join("server-policy.yaml") + ); + } + _ => panic!("expected Multi"), + } + } + + /// `GET /graphs` must NOT leak the registry in Open mode without + /// an explicit server policy. Operators who pass `--unauthenticated` + /// opted into trusting the network for graph DATA, not for leaking + /// server topology (graph IDs + URIs, which may contain S3 bucket + /// paths or internal hostnames). Cedar gating the management + /// surface is the documented contract for `server_graphs_list` + /// ("don't leak the registry until the operator explicitly + /// authorizes it"); enforcing that contract in every runtime + /// state — not just `PolicyEnabled` — is the correct-by-design + /// closure of the open-mode hole the bot-review pass surfaced. + /// + /// Today (pre-fix) this returns 200 because `authorize_request`'s + /// no-policy fallback only denies when `actor.is_some()`, so Open + /// mode (`actor: None`) falls through to `Ok(())`. The fix in the + /// next commit tightens the fallback so server-scoped actions + /// always require explicit policy. + /// + /// Sort-order coverage previously lived here; it has moved to + /// `get_graphs_with_server_policy_authorizes_per_cedar` where + /// the response body is now non-empty and operator-authorized. + #[tokio::test(flavor = "multi_thread")] + async fn get_graphs_denied_in_open_mode_without_server_policy() { + let (_dirs, app) = build_multi_mode_app(&["beta", "alpha"]).await; + let resp = app + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/graphs") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = resp.status(); + let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap(); + let body_str = String::from_utf8_lossy(&body); + assert_eq!( + status, + StatusCode::FORBIDDEN, + "GET /graphs must require an explicit server policy in every \ + runtime state; Open-mode bypass would leak server topology. \ + Body: {body_str}", + ); + } + + /// `GET /graphs` returns 405 in single mode (resource exists in the + /// API surface, just not operational without a `graphs:` map). + #[tokio::test(flavor = "multi_thread")] + async fn get_graphs_returns_405_in_single_mode() { + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let state = AppState::open(graph.to_string_lossy().to_string()) + .await + .unwrap(); + let app = build_app(state); + let resp = app + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/graphs") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); + } + + /// `GET /graphs` requires bearer auth when tokens are configured. + #[tokio::test(flavor = "multi_thread")] + async fn get_graphs_requires_bearer_auth_when_configured() { + use omnigraph_server::{GraphHandle, GraphId, GraphKey}; + // Build a multi-mode app with bearer tokens configured. + let dir = tempfile::tempdir().unwrap(); + let graph_uri = dir.path().join("alpha").to_str().unwrap().to_string(); + let schema = fs::read_to_string(fixture("test.pg")).unwrap(); + let engine = Omnigraph::init(&graph_uri, &schema).await.unwrap(); + let handle = Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from("alpha").unwrap()), + uri: graph_uri, + engine: Arc::new(engine), + policy: None, + queries: None, + }); + let tokens = vec![("act-andrew".to_string(), "secret-token".to_string())]; + let workload = omnigraph_server::workload::WorkloadController::from_env(); + let state = AppState::new_multi(vec![handle], tokens, None, workload, None).unwrap(); + let app = build_app(state); + + // No Authorization header → 401. + let resp_no_auth = app + .clone() + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/graphs") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp_no_auth.status(), StatusCode::UNAUTHORIZED); + + // With auth but no server policy → 403 (default-deny, since + // GraphList is not Read). + let resp_authed = app + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/graphs") + .header("authorization", "Bearer secret-token") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp_authed.status(), StatusCode::FORBIDDEN); + } + + /// `GET /graphs` with a server policy that allows `graph_list` → 200 + /// and returns the registry sorted alphabetically by `graph_id`. + /// `GET /graphs` with a server policy that does NOT allow + /// `graph_list` (viewer group) → 403. + /// + /// This test owns the alphabetical-sort coverage that previously + /// lived in `get_graphs_lists_registered_graphs_in_multi_mode`. + /// That test now asserts denial in Open mode (server-scoped actions + /// require explicit policy in every runtime state), so the positive + /// body-shape assertions need a home where the response is + /// operator-authorized — here. + #[tokio::test(flavor = "multi_thread")] + async fn get_graphs_with_server_policy_authorizes_per_cedar() { + use omnigraph_policy::PolicyEngine; + use omnigraph_server::{GraphHandle, GraphId, GraphKey}; + + let dir = tempfile::tempdir().unwrap(); + + // Two graphs deliberately registered in non-alphabetical order + // so the test would fail if the handler relied on insertion + // order instead of server-side sorting. + let schema = fs::read_to_string(fixture("test.pg")).unwrap(); + let mut handles = Vec::new(); + for id in ["beta", "alpha"] { + let graph_uri = dir.path().join(id).to_str().unwrap().to_string(); + let engine = Omnigraph::init(&graph_uri, &schema).await.unwrap(); + handles.push(Arc::new(GraphHandle { + key: GraphKey::cluster(GraphId::try_from(id).unwrap()), + uri: graph_uri, + engine: Arc::new(engine), + policy: None, + queries: None, + })); + } + + // Server policy: admins can graph_list, viewers cannot. + let policy_path = dir.path().join("server-policy.yaml"); + fs::write( + &policy_path, + r#" +version: 1 +groups: + admins: [act-andrew] + viewers: [act-bruno] +rules: + - id: admins-list-graphs + allow: + actors: { group: admins } + actions: [graph_list] +"#, + ) + .unwrap(); + let server_policy = PolicyEngine::load_server(&policy_path).unwrap(); + + let tokens = vec![ + ("act-andrew".to_string(), "andrew-token".to_string()), + ("act-bruno".to_string(), "bruno-token".to_string()), + ]; + let workload = omnigraph_server::workload::WorkloadController::from_env(); + let state = + AppState::new_multi(handles, tokens, Some(server_policy), workload, None).unwrap(); + let app = build_app(state); + + // Admin → 200, body returns both graphs alphabetically sorted. + let resp_admin = app + .clone() + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/graphs") + .header("authorization", "Bearer andrew-token") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + resp_admin.status(), + StatusCode::OK, + "admin must be allowed graph_list" + ); + let body = to_bytes(resp_admin.into_body(), usize::MAX).await.unwrap(); + let json: Value = serde_json::from_slice(&body).unwrap(); + let graphs = json["graphs"].as_array().unwrap(); + assert_eq!(graphs.len(), 2, "response must list both registered graphs"); + assert_eq!( + graphs[0]["graph_id"].as_str().unwrap(), + "alpha", + "server must sort graphs alphabetically by graph_id (insertion order was 'beta', 'alpha')" + ); + assert_eq!(graphs[1]["graph_id"].as_str().unwrap(), "beta"); + + // Viewer → 403 + let resp_viewer = app + .oneshot( + Request::builder() + .method(Method::GET) + .uri("/graphs") + .header("authorization", "Bearer bruno-token") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + resp_viewer.status(), + StatusCode::FORBIDDEN, + "viewer must be denied graph_list (Cedar gate)" + ); + } + + /// Loads an `omnigraph.yaml` with two graphs and verifies multi-mode + /// inference plus graph entry resolution. Cluster-route dispatch is + /// covered by the route tests above. + #[tokio::test(flavor = "multi_thread")] + async fn server_settings_load_multi_graph_config_entries() { + let cfg_dir = tempfile::tempdir().unwrap(); + // Real graph storage dirs (the URIs in the config must point to + // a graph init-able location). + let alpha_dir = cfg_dir.path().join("alpha.omni"); + let beta_dir = cfg_dir.path().join("beta.omni"); + let schema = fs::read_to_string(fixture("test.pg")).unwrap(); + Omnigraph::init(alpha_dir.to_str().unwrap(), &schema) + .await + .unwrap(); + Omnigraph::init(beta_dir.to_str().unwrap(), &schema) + .await + .unwrap(); + + let config_path = cfg_dir.path().join("omnigraph.yaml"); + fs::write( + &config_path, + format!( + r#" +graphs: + alpha: + uri: {alpha} + beta: + uri: {beta} +"#, + alpha = alpha_dir.display(), + beta = beta_dir.display(), + ), + ) + .unwrap(); + + let settings: ServerConfig = + load_server_settings(Some(&config_path), None, None, None, true).unwrap(); + assert!(matches!(settings.mode, ServerConfigMode::Multi { .. })); + + match settings.mode { + ServerConfigMode::Multi { graphs, .. } => { + assert_eq!(graphs.len(), 2); + let ids: Vec<&str> = graphs.iter().map(|g| g.graph_id.as_str()).collect(); + assert_eq!(ids, vec!["alpha", "beta"]); + } + _ => unreachable!(), + } + } +} diff --git a/crates/omnigraph/Cargo.toml b/crates/omnigraph/Cargo.toml index a3cc5df..70f51d8 100644 --- a/crates/omnigraph/Cargo.toml +++ b/crates/omnigraph/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-engine" -version = "0.4.2" +version = "0.6.1" edition = "2024" description = "Runtime engine for the Omnigraph graph database." license = "MIT" @@ -16,8 +16,8 @@ default = [] failpoints = ["dep:fail", "fail/failpoints"] [dependencies] -omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.4.2" } -omnigraph-policy = { path = "../omnigraph-policy", version = "0.4.2" } +omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.1" } +omnigraph-policy = { path = "../omnigraph-policy", version = "0.6.1" } lance = { workspace = true } lance-datafusion = { workspace = true } datafusion = { workspace = true } @@ -51,7 +51,7 @@ chrono = { workspace = true } arc-swap = { workspace = true } [dev-dependencies] -omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.4.2" } +omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.1" } tokio = { workspace = true } lance-namespace-impls = { workspace = true } serial_test = "3" diff --git a/crates/omnigraph/examples/bench_expand.rs b/crates/omnigraph/examples/bench_expand.rs index 1b0011a..c723b24 100644 --- a/crates/omnigraph/examples/bench_expand.rs +++ b/crates/omnigraph/examples/bench_expand.rs @@ -239,7 +239,9 @@ async fn main() { let jsonl = generate_jsonl(n, avg_deg, 42); let t = Instant::now(); - load_jsonl(&mut db, &jsonl, LoadMode::Overwrite).await.unwrap(); + load_jsonl(&mut db, &jsonl, LoadMode::Overwrite) + .await + .unwrap(); let load_elapsed = t.elapsed(); println!( diff --git a/crates/omnigraph/src/db/commit_graph.rs b/crates/omnigraph/src/db/commit_graph.rs index 565bd69..9531a64 100644 --- a/crates/omnigraph/src/db/commit_graph.rs +++ b/crates/omnigraph/src/db/commit_graph.rs @@ -169,6 +169,37 @@ impl CommitGraph { self.refresh().await } + /// Idempotently drop the commit-graph branch `name`, tolerating an + /// already-absent branch (see [`TableStore::force_delete_branch`] for the + /// same semantics). Used by the best-effort reclaim in `branch_delete` and + /// the `cleanup` orphan reconciler. `RefConflict` (referencing descendants) + /// is still surfaced. + pub async fn force_delete_branch(&mut self, name: &str) -> Result<()> { + let mut ds = Dataset::open(&graph_commits_uri(&self.root_uri)) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + match ds.force_delete_branch(name).await { + Ok(()) => {} + Err(lance::Error::RefNotFound { .. }) | Err(lance::Error::NotFound { .. }) => {} + Err(e) => return Err(OmniError::Lance(e.to_string())), + } + self.refresh().await + } + + /// List the named branches present on the commit-graph dataset. The + /// `cleanup` reconciler diffs this against the manifest branch set to find + /// orphaned commit-graph branches to reclaim. + pub async fn list_branches(&self) -> Result> { + let ds = Dataset::open(&graph_commits_uri(&self.root_uri)) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + let branches = ds + .list_branches() + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + Ok(branches.into_keys().collect()) + } + pub async fn append_commit( &mut self, manifest_branch: Option<&str>, @@ -345,7 +376,7 @@ impl CommitGraph { } } -fn graph_commits_uri(root_uri: &str) -> String { +pub(crate) fn graph_commits_uri(root_uri: &str) -> String { format!("{}/{}", root_uri.trim_end_matches('/'), GRAPH_COMMITS_DIR) } diff --git a/crates/omnigraph/src/db/graph_coordinator.rs b/crates/omnigraph/src/db/graph_coordinator.rs index a721036..dfe2767 100644 --- a/crates/omnigraph/src/db/graph_coordinator.rs +++ b/crates/omnigraph/src/db/graph_coordinator.rs @@ -211,14 +211,47 @@ impl GraphCoordinator { let branch = normalize_branch_name(name)? .ok_or_else(|| OmniError::manifest("cannot create branch 'main'".to_string()))?; self.ensure_commit_graph_initialized().await?; + + // Manifest authority flip first. self.manifest.create_branch(&branch).await?; - failpoints::maybe_fail("branch_create.after_manifest_branch_create")?; - if let Some(commit_graph) = &mut self.commit_graph { - commit_graph.create_branch(&branch).await?; + + // Derived commit-graph branch. If anything after the authority flip + // fails, roll back the manifest branch so the branch never half-exists + // (a manifest branch with no commit-graph branch breaks the next write). + if let Err(err) = self.create_commit_graph_branch(&branch).await { + if let Err(rollback_err) = self.manifest.delete_branch(&branch).await { + tracing::warn!( + target: "omnigraph::branch_create", + branch = %branch, + error = %rollback_err, + "rollback of manifest branch failed after commit-graph create failure", + ); + } + return Err(err); } Ok(()) } + /// Create the derived commit-graph branch for `branch`, healing a zombie ref + /// left by an incomplete prior delete. The manifest branch was just created + /// fresh, so any existing commit-graph branch with this name is provably + /// orphaned and is force-dropped before recreating. + async fn create_commit_graph_branch(&mut self, branch: &str) -> Result<()> { + failpoints::maybe_fail("branch_create.after_manifest_branch_create")?; + let Some(commit_graph) = &mut self.commit_graph else { + return Ok(()); + }; + if commit_graph + .list_branches() + .await? + .iter() + .any(|existing| existing == branch) + { + commit_graph.force_delete_branch(branch).await?; + } + commit_graph.create_branch(branch).await + } + pub async fn branch_delete(&mut self, name: &str) -> Result<()> { let branch = normalize_branch_name(name)? .ok_or_else(|| OmniError::manifest("cannot delete branch 'main'".to_string()))?; @@ -229,20 +262,43 @@ impl GraphCoordinator { ))); } + // Manifest authority flip — the single atomic op that makes the branch + // cease to exist. Must succeed; everything after is derived state + // reclaimed best-effort. self.manifest.delete_branch(&branch).await?; + // Commit-graph branch is derived state. Reclaim best-effort with the + // idempotent force variant: a failure here (or a missing dataset) is + // reconciled by `cleanup` and must not fail the delete after the + // authority already flipped. + if let Err(err) = self.reclaim_commit_graph_branch(&branch).await { + tracing::warn!( + target: "omnigraph::branch_delete::cleanup", + branch = %branch, + error = %err, + "best-effort commit-graph branch reclaim failed; cleanup will reconcile", + ); + } + + Ok(()) + } + + /// Best-effort, idempotent reclaim of the commit-graph branch `branch`. + /// Tolerates an absent commit-graph dataset (a graph that never committed). + async fn reclaim_commit_graph_branch(&mut self, branch: &str) -> Result<()> { + failpoints::maybe_fail("branch_delete.before_commit_graph_reclaim")?; if let Some(commit_graph) = &mut self.commit_graph { - commit_graph.delete_branch(&branch).await?; + commit_graph.force_delete_branch(branch).await } else if self .storage .exists(&graph_commits_uri(self.root_uri())) .await? { let mut commit_graph = CommitGraph::open(self.root_uri()).await?; - commit_graph.delete_branch(&branch).await?; + commit_graph.force_delete_branch(branch).await + } else { + Ok(()) } - - Ok(()) } pub async fn snapshot_at_version(&self, version: u64) -> Result { diff --git a/crates/omnigraph/src/db/manifest.rs b/crates/omnigraph/src/db/manifest.rs index f31cc4f..7fcf7de 100644 --- a/crates/omnigraph/src/db/manifest.rs +++ b/crates/omnigraph/src/db/manifest.rs @@ -6,6 +6,8 @@ use lance::Dataset; use lance_namespace::models::CreateTableVersionRequest; use omnigraph_compiler::catalog::Catalog; +#[path = "manifest/graph.rs"] +mod graph; #[path = "manifest/layout.rs"] mod layout; #[path = "manifest/metadata.rs"] @@ -18,11 +20,10 @@ mod namespace; mod publisher; #[path = "manifest/recovery.rs"] mod recovery; -#[path = "manifest/repo.rs"] -mod repo; #[path = "manifest/state.rs"] mod state; +use graph::{init_manifest_graph, open_manifest_graph, snapshot_state_at}; use layout::{manifest_uri, open_manifest_dataset, type_name_hash}; pub(crate) use metadata::TableVersionMetadata; #[cfg(test)] @@ -33,11 +34,10 @@ pub(crate) use namespace::open_table_head_for_write; use namespace::{branch_manifest_namespace, staged_table_namespace}; use publisher::{GraphNamespacePublisher, ManifestBatchPublisher}; pub(crate) use recovery::{ - delete_sidecar, has_schema_apply_sidecar, new_sidecar, recover_manifest_drift, write_sidecar, RecoveryMode, RecoverySidecar, RecoverySidecarHandle, SidecarKind, SidecarTablePin, - SidecarTableRegistration, SidecarTombstone, + SidecarTableRegistration, SidecarTombstone, delete_sidecar, has_schema_apply_sidecar, + new_sidecar, recover_manifest_drift, write_sidecar, }; -use repo::{init_manifest_repo, open_manifest_repo, snapshot_state_at}; pub use state::SubTableEntry; #[cfg(test)] use state::string_column; @@ -215,12 +215,12 @@ impl ManifestCoordinator { self } - /// Create a new repo at `root_uri` from a catalog. + /// Create a new graph at `root_uri` from a catalog. /// /// Creates per-type Lance datasets and the namespace `__manifest` table. pub async fn init(root_uri: &str, catalog: &Catalog) -> Result { let root = root_uri.trim_end_matches('/'); - let (dataset, known_state) = init_manifest_repo(root, catalog).await?; + let (dataset, known_state) = init_manifest_graph(root, catalog).await?; Ok(Self::from_parts_with_default_publisher( root, @@ -230,10 +230,10 @@ impl ManifestCoordinator { )) } - /// Open an existing repo's manifest. + /// Open an existing graph's manifest. pub async fn open(root_uri: &str) -> Result { let root = root_uri.trim_end_matches('/'); - let (dataset, known_state) = open_manifest_repo(root, None).await?; + let (dataset, known_state) = open_manifest_graph(root, None).await?; Ok(Self::from_parts_with_default_publisher( root, dataset, @@ -242,14 +242,14 @@ impl ManifestCoordinator { )) } - /// Open an existing repo's manifest at a specific branch. + /// Open an existing graph's manifest at a specific branch. pub async fn open_at_branch(root_uri: &str, branch: &str) -> Result { if branch == "main" { return Self::open(root_uri).await; } let root = root_uri.trim_end_matches('/'); - let (dataset, known_state) = open_manifest_repo(root, Some(branch)).await?; + let (dataset, known_state) = open_manifest_graph(root, Some(branch)).await?; Ok(Self::from_parts_with_default_publisher( root, dataset, @@ -410,7 +410,7 @@ impl ManifestCoordinator { Ok(descendants) } - /// Root URI of the repo. + /// Root URI of the graph. pub fn root_uri(&self) -> &str { &self.root_uri } diff --git a/crates/omnigraph/src/db/manifest/repo.rs b/crates/omnigraph/src/db/manifest/graph.rs similarity index 98% rename from crates/omnigraph/src/db/manifest/repo.rs rename to crates/omnigraph/src/db/manifest/graph.rs index 90a958b..6c414aa 100644 --- a/crates/omnigraph/src/db/manifest/repo.rs +++ b/crates/omnigraph/src/db/manifest/graph.rs @@ -17,7 +17,7 @@ use super::state::{ ManifestState, SubTableEntry, entries_to_batch, manifest_schema, read_manifest_state, }; -pub(super) async fn init_manifest_repo( +pub(super) async fn init_manifest_graph( root_uri: &str, catalog: &Catalog, ) -> Result<(Dataset, ManifestState)> { @@ -47,7 +47,7 @@ pub(super) async fn init_manifest_repo( Ok((dataset, known_state)) } -pub(super) async fn open_manifest_repo( +pub(super) async fn open_manifest_graph( root_uri: &str, branch: Option<&str>, ) -> Result<(Dataset, ManifestState)> { diff --git a/crates/omnigraph/src/db/manifest/migrations.rs b/crates/omnigraph/src/db/manifest/migrations.rs index c568bef..bbb7995 100644 --- a/crates/omnigraph/src/db/manifest/migrations.rs +++ b/crates/omnigraph/src/db/manifest/migrations.rs @@ -24,8 +24,8 @@ //! Only on open-for-write paths (the publisher's `load_publish_state`). //! Reads are side-effect-free by contract; an old-shape `__manifest` reads //! fine, it just lacks the protections introduced by later versions. -//! `init_manifest_repo` stamps the current version at creation, so newly -//! initialized repos never need migration. +//! `init_manifest_graph` stamps the current version at creation, so newly +//! initialized graphs never need migration. //! //! ## Forward-version protection //! @@ -78,7 +78,7 @@ pub(super) async fn migrate_internal_schema(dataset: &mut Dataset) -> Result<()> if current > INTERNAL_MANIFEST_SCHEMA_VERSION { return Err(OmniError::manifest(format!( "__manifest is stamped at internal schema v{} but this binary expects v{} \ - — upgrade omnigraph before opening this repo for writes", + — upgrade omnigraph before opening this graph for writes", current, INTERNAL_MANIFEST_SCHEMA_VERSION, ))); } @@ -112,7 +112,10 @@ pub(super) async fn migrate_internal_schema(dataset: &mut Dataset) -> Result<()> async fn migrate_v1_to_v2(dataset: &mut Dataset) -> Result<()> { dataset .update_field_metadata() - .update("object_id", [(OBJECT_ID_PK_KEY.to_string(), "true".to_string())]) + .update( + "object_id", + [(OBJECT_ID_PK_KEY.to_string(), "true".to_string())], + ) .map_err(|e| OmniError::Lance(e.to_string()))? .await .map_err(|e| OmniError::Lance(e.to_string()))?; @@ -121,10 +124,7 @@ async fn migrate_v1_to_v2(dataset: &mut Dataset) -> Result<()> { async fn set_stamp(dataset: &mut Dataset, version: u32) -> Result<()> { dataset - .update_schema_metadata([( - INTERNAL_SCHEMA_VERSION_KEY.to_string(), - version.to_string(), - )]) + .update_schema_metadata([(INTERNAL_SCHEMA_VERSION_KEY.to_string(), version.to_string())]) .await .map_err(|e| OmniError::Lance(e.to_string()))?; Ok(()) diff --git a/crates/omnigraph/src/db/manifest/recovery.rs b/crates/omnigraph/src/db/manifest/recovery.rs index 0d42a85..4c1b987 100644 --- a/crates/omnigraph/src/db/manifest/recovery.rs +++ b/crates/omnigraph/src/db/manifest/recovery.rs @@ -2,7 +2,7 @@ //! //! This module implements the building blocks of the per-sidecar recovery //! sweep that closes the documented Phase B → Phase C residual (see -//! `docs/dev/runs.md` "Open-time recovery sweep"). The high-level shape: +//! `docs/dev/writes.md` "Open-time recovery sweep"). The high-level shape: //! //! 1. Each writer that performs a multi-table commit writes a small JSON //! sidecar at `__recovery/{ulid}.json` BEFORE its per-table @@ -58,7 +58,7 @@ use super::{ManifestChange, SubTableUpdate, TableRegistration, TableTombstone}; /// into the audit row's `recovery_for_actor` field. pub(crate) const RECOVERY_ACTOR: &str = "omnigraph:recovery"; -/// Subdirectory under the repo root holding sidecar files. +/// Subdirectory under the graph root holding sidecar files. pub(crate) const RECOVERY_DIR_NAME: &str = "__recovery"; /// Current sidecar JSON shape version. Bumping this is a breaking change: @@ -142,7 +142,7 @@ pub(crate) struct SidecarTablePin { pub(crate) struct SidecarTableRegistration { /// Stable identifier (`node:Tag`, `edge:WorksAt`, etc.). pub table_key: String, - /// Repo-relative path the manifest will register + /// Graph-relative path the manifest will register /// (e.g. `nodes/{fnv1a64-hex}`); recovery joins this with `root_uri` /// to open the dataset Lance HEAD when constructing the /// accompanying `Update`. @@ -295,7 +295,7 @@ pub(crate) enum SidecarDecision { Abort, } -/// Build the `__recovery/` directory URI under a repo root. +/// Build the `__recovery/` directory URI under a graph root. pub(crate) fn recovery_dir_uri(root_uri: &str) -> String { let trimmed = root_uri.trim_end_matches('/'); format!("{}/{}", trimmed, RECOVERY_DIR_NAME) @@ -1122,7 +1122,7 @@ async fn record_audit( /// the rename so the recovery sweep's roll-forward step sees the new /// catalog. Without this, the disambiguation logic deletes the staging /// files (since manifest still pins the old table set) and leaves the -/// repo with new-schema data on disk but the old `_schema.pg` live — +/// graph with new-schema data on disk but the old `_schema.pg` live — /// real corruption. pub(crate) async fn has_schema_apply_sidecar( root_uri: &str, diff --git a/crates/omnigraph/src/db/manifest/tests.rs b/crates/omnigraph/src/db/manifest/tests.rs index d51a882..effa0b5 100644 --- a/crates/omnigraph/src/db/manifest/tests.rs +++ b/crates/omnigraph/src/db/manifest/tests.rs @@ -1393,7 +1393,10 @@ async fn test_concurrent_publish_with_overlapping_expected_versions_one_succeeds // version (no duplicate version rows). let mc = ManifestCoordinator::open(uri).await.unwrap(); let entry = mc.snapshot().entry("node:Person").unwrap().clone(); - assert!(entry.table_version > 1, "Person should have advanced past v=1"); + assert!( + entry.table_version > 1, + "Person should have advanced past v=1" + ); } #[tokio::test] @@ -1418,7 +1421,7 @@ async fn test_publish_migrates_pre_stamp_manifest_to_current_version() { let catalog = build_test_catalog(); let mc = ManifestCoordinator::init(uri, &catalog).await.unwrap(); - // Simulate a v1 (pre-stamp) repo by removing the schema-level stamp on disk. + // Simulate a v1 (pre-stamp) graph by removing the schema-level stamp on disk. { let mut ds = open_manifest_dataset(uri, None).await.unwrap(); ds.update_schema_metadata([( @@ -1449,7 +1452,7 @@ async fn test_publish_migrates_pre_stamp_manifest_to_current_version() { assert_eq!( super::migrations::read_stamp(&post), super::migrations::INTERNAL_MANIFEST_SCHEMA_VERSION, - "publish on a v1 repo should leave the manifest stamped at the current version", + "publish on a v1 graph should leave the manifest stamped at the current version", ); // Manifest should still serve correctly post-migration. diff --git a/crates/omnigraph/src/db/mod.rs b/crates/omnigraph/src/db/mod.rs index 6bdd9ee..8702f88 100644 --- a/crates/omnigraph/src/db/mod.rs +++ b/crates/omnigraph/src/db/mod.rs @@ -10,11 +10,11 @@ pub(crate) mod write_queue; pub use commit_graph::GraphCommit; pub use graph_coordinator::{GraphCoordinator, ReadTarget, ResolvedTarget, SnapshotId}; pub use manifest::{Snapshot, SubTableEntry, SubTableUpdate}; -pub use omnigraph::{ - CleanupPolicyOptions, MergeOutcome, Omnigraph, OpenMode, SchemaApplyOptions, - SchemaApplyResult, TableCleanupStats, TableOptimizeStats, -}; pub(crate) use omnigraph::ensure_public_branch_ref; +pub use omnigraph::{ + CleanupPolicyOptions, InitOptions, MergeOutcome, Omnigraph, OpenMode, SchemaApplyOptions, + SchemaApplyResult, SkipReason, TableCleanupStats, TableOptimizeStats, +}; pub(crate) use run_registry::is_internal_run_branch; pub(crate) const SCHEMA_APPLY_LOCK_BRANCH: &str = "__schema_apply_lock__"; @@ -59,9 +59,7 @@ impl MutationOpKind { pub(crate) fn strict_pre_stage_version_check(self) -> bool { match self { MutationOpKind::Insert | MutationOpKind::Merge => false, - MutationOpKind::Update - | MutationOpKind::Delete - | MutationOpKind::SchemaRewrite => true, + MutationOpKind::Update | MutationOpKind::Delete | MutationOpKind::SchemaRewrite => true, } } } diff --git a/crates/omnigraph/src/db/omnigraph.rs b/crates/omnigraph/src/db/omnigraph.rs index 610be62..7b8a3f6 100644 --- a/crates/omnigraph/src/db/omnigraph.rs +++ b/crates/omnigraph/src/db/omnigraph.rs @@ -33,7 +33,7 @@ mod optimize; mod schema_apply; mod table_ops; -pub use optimize::{CleanupPolicyOptions, TableCleanupStats, TableOptimizeStats}; +pub use optimize::{CleanupPolicyOptions, SkipReason, TableCleanupStats, TableOptimizeStats}; pub use schema_apply::SchemaApplyOptions; use super::commit_graph::GraphCommit; @@ -67,6 +67,12 @@ pub struct SchemaApplyResult { pub steps: Vec, } +#[derive(Debug, Clone)] +pub struct SchemaApplyPreview { + pub plan: SchemaMigrationPlan, + pub catalog: Catalog, +} + /// Top-level handle to an Omnigraph database. /// /// An Omnigraph is a Lance-native graph database with git-style branching. @@ -165,31 +171,137 @@ pub enum OpenMode { ReadOnly, } +/// Options for [`Omnigraph::init_with_options`]. +/// +/// `force` controls the safety preflight that prevents an +/// accidental re-init from overwriting an existing graph's schema +/// metadata. Default behavior (`force: false`) fails fast with +/// [`OmniError::AlreadyInitialized`] if any of `_schema.pg`, +/// `_schema.ir.json`, or `__schema_state.json` already exists at +/// the target URI. With `force: true` the preflight is skipped — +/// existing schema files are overwritten in place. Force does NOT +/// purge old Lance datasets or `__manifest/`; reclaiming those +/// still requires deleting the graph directory by hand (or via a +/// future `DELETE /graphs/{id}`). +#[derive(Debug, Clone, Copy, Default)] +pub struct InitOptions { + /// Skip the existing-graph preflight. Operators set this when + /// they actually mean to overwrite — e.g. `omnigraph init --force`. + pub force: bool, +} + impl Omnigraph { - /// Create a new repo at `uri` from schema source. + /// Create a new graph at `uri` from schema source. /// - /// Creates `_schema.pg`, per-type Lance datasets, and `__manifest`. + /// Strict mode: errors with [`OmniError::AlreadyInitialized`] if + /// `uri` already holds any of the three schema artifacts. To + /// overwrite an existing graph deliberately, call + /// [`Self::init_with_options`] with `InitOptions { force: true }`. pub async fn init(uri: &str, schema_source: &str) -> Result { - Self::init_with_storage(uri, schema_source, storage_for_uri(uri)?).await + Self::init_with_options(uri, schema_source, InitOptions::default()).await + } + + /// Create a new graph at `uri`, with explicit init-time options. + /// + /// See [`InitOptions`] for the safety contract — by default this + /// behaves identically to [`Self::init`]. + pub async fn init_with_options( + uri: &str, + schema_source: &str, + options: InitOptions, + ) -> Result { + Self::init_with_storage(uri, schema_source, storage_for_uri(uri)?, options).await } pub(crate) async fn init_with_storage( uri: &str, schema_source: &str, storage: Arc, + options: InitOptions, ) -> Result { let root = normalize_root_uri(uri)?; + + // Preflight: refuse to clobber an existing graph unless the + // operator passed `force`. This runs BEFORE any parse or + // write so a misdirected `init` against an existing graph + // URI cannot reach a code path that overwrites or, on a + // later cleanup, deletes the schema files. + // + // Closes the "init is destructive against existing state" + // class: there is no longer a code path where strict-mode + // `init` can mutate a populated graph root. + if !options.force { + for candidate in [ + schema_source_uri(&root), + schema_ir_uri(&root), + schema_state_uri(&root), + ] { + if storage.exists(&candidate).await? { + return Err(OmniError::AlreadyInitialized { uri: root.clone() }); + } + } + } + let schema_ir = read_schema_ir_from_source(schema_source)?; let mut catalog = build_catalog_from_ir(&schema_ir)?; fixup_blob_schemas(&mut catalog); - // Write _schema.pg - let schema_path = join_uri(&root, SCHEMA_SOURCE_FILENAME); - storage.write_text(&schema_path, schema_source).await?; - write_schema_contract(&root, storage.as_ref(), &schema_ir).await?; + // Establish an atomic ownership claim on `_schema.pg` before + // writing the remaining init artifacts. A check-then-write preflight + // is not enough under concurrent `init` calls: two callers can both + // observe an empty root, one can successfully initialize, and the + // loser can then fail in Lance `WriteMode::Create`. Only the caller + // that atomically created `_schema.pg` may clean up schema artifacts + // on later failure. + let schema_pg_claimed = if options.force { + false + } else { + let schema_path = join_uri(&root, SCHEMA_SOURCE_FILENAME); + if !storage + .write_text_if_absent(&schema_path, schema_source) + .await? + { + return Err(OmniError::AlreadyInitialized { uri: root.clone() }); + } + if let Err(err) = crate::failpoints::maybe_fail("init.after_schema_pg_written") { + best_effort_cleanup_init_artifacts(&root, storage.as_ref()).await; + return Err(err); + } + true + }; - // Create manifest + per-type datasets - let coordinator = GraphCoordinator::init(&root, &catalog, Arc::clone(&storage)).await?; + // Run the I/O phase. On any error, best-effort-clean schema + // artifacts only when this invocation owns them: strict mode owns + // them after the atomic `_schema.pg` claim above; force mode owns + // destructive overwrite semantics by explicit operator request. + // + // Coverage gap: Lance per-type datasets and `__manifest/` + // directory created by `GraphCoordinator::init` are NOT cleaned + // up here — fully recursive directory deletion requires a + // `StorageAdapter::delete_prefix` primitive that's deferred + // along with `DELETE /graphs/{id}` (PR 2b in the MR-668 plan + // is currently deferred). If `init` fails after coordinator + // init succeeds, operators may need to remove the graph + // directory manually before retrying `init` on the same URI. + // Documented in the PR 2a commit message and `init` rustdoc. + let coordinator = match init_storage_phase( + &root, + schema_source, + &schema_ir, + &catalog, + &storage, + !schema_pg_claimed, + ) + .await + { + Ok(coordinator) => coordinator, + Err(err) => { + if schema_pg_claimed || options.force { + best_effort_cleanup_init_artifacts(&root, storage.as_ref()).await; + } + return Err(err); + } + }; Ok(Self { root_uri: root.clone(), @@ -205,7 +317,7 @@ impl Omnigraph { }) } - /// Open an existing repo (read-write). + /// Open an existing graph (read-write). /// /// Reads `_schema.pg`, parses it, builds the catalog, and opens `__manifest`. /// Runs the open-time recovery sweep before returning — see [`OpenMode`]. @@ -213,7 +325,7 @@ impl Omnigraph { Self::open_with_storage_and_mode(uri, storage_for_uri(uri)?, OpenMode::ReadWrite).await } - /// Open an existing repo for read-only consumers (NDJSON export, + /// Open an existing graph for read-only consumers (NDJSON export, /// `commit list`, etc.). Skips the recovery sweep — see [`OpenMode`]. pub async fn open_read_only(uri: &str) -> Result { Self::open_with_storage_and_mode(uri, storage_for_uri(uri)?, OpenMode::ReadOnly).await @@ -387,6 +499,14 @@ impl Omnigraph { schema_apply::plan_schema(self, desired_schema_source, options).await } + pub async fn preview_schema_apply_with_options( + &self, + desired_schema_source: &str, + options: SchemaApplyOptions, + ) -> Result { + schema_apply::preview_schema_apply(self, desired_schema_source, options).await + } + pub async fn apply_schema(&self, desired_schema_source: &str) -> Result { self.apply_schema_as(desired_schema_source, SchemaApplyOptions::default(), None) .await @@ -397,7 +517,8 @@ impl Omnigraph { desired_schema_source: &str, options: SchemaApplyOptions, ) -> Result { - self.apply_schema_as(desired_schema_source, options, None).await + self.apply_schema_as(desired_schema_source, options, None) + .await } /// Apply a schema migration with an explicit actor for engine-layer @@ -416,7 +537,28 @@ impl Omnigraph { options: SchemaApplyOptions, actor: Option<&str>, ) -> Result { - schema_apply::apply_schema(self, desired_schema_source, options, actor).await + self.apply_schema_as_with_catalog_check(desired_schema_source, options, actor, |_| Ok(())) + .await + } + + pub async fn apply_schema_as_with_catalog_check( + &self, + desired_schema_source: &str, + options: SchemaApplyOptions, + actor: Option<&str>, + validate_catalog: F, + ) -> Result + where + F: FnOnce(&Catalog) -> Result<()>, + { + schema_apply::apply_schema( + self, + desired_schema_source, + options, + actor, + validate_catalog, + ) + .await } pub(crate) async fn ensure_schema_apply_idle(&self, operation: &str) -> Result<()> { @@ -470,7 +612,7 @@ impl Omnigraph { Arc::clone(&self.merge_exclusive) } - /// Engine-level access to the repo's normalized root URI. Used by + /// Engine-level access to the graph's normalized root URI. Used by /// the recovery sidecar protocol to compute `__recovery/` paths. pub(crate) fn root_uri(&self) -> &str { &self.root_uri @@ -510,9 +652,10 @@ impl Omnigraph { let normalized = normalize_branch_name(branch.unwrap_or("main"))?; let coord = self.coordinator.read().await; if normalized.as_deref() == coord.current_branch() { - let snapshot_id = coord.head_commit_id().await?.unwrap_or_else(|| { - SnapshotId::synthetic(coord.current_branch(), coord.version()) - }); + let snapshot_id = coord + .head_commit_id() + .await? + .unwrap_or_else(|| SnapshotId::synthetic(coord.current_branch(), coord.version())); return Ok(ResolvedTarget { requested, branch: coord.current_branch().map(str::to_string), @@ -587,7 +730,7 @@ impl Omnigraph { /// exist. Required BEFORE manifest-drift recovery so a /// SchemaApply roll-forward doesn't publish the manifest while /// the staging files remain unrenamed (which would corrupt the - /// repo: data on new schema, catalog on old). + /// graph: data on new schema, catalog on old). /// 3. `recover_manifest_drift(... RollForwardOnly)` — close the /// finalize→publisher residual via roll-forward; defer rollback /// work to next ReadWrite open. @@ -668,7 +811,11 @@ impl Omnigraph { pub async fn resolve_snapshot(&self, branch: &str) -> Result { self.ensure_schema_state_valid().await?; - self.coordinator.read().await.resolve_snapshot_id(branch).await + self.coordinator + .read() + .await + .resolve_snapshot_id(branch) + .await } pub(crate) async fn resolved_target( @@ -676,7 +823,11 @@ impl Omnigraph { target: impl Into, ) -> Result { self.ensure_schema_state_valid().await?; - self.coordinator.read().await.resolve_target(&target.into()).await + self.coordinator + .read() + .await + .resolve_target(&target.into()) + .await } // ─── Change detection ──────────────────────────────────────────────── @@ -708,7 +859,9 @@ impl Omnigraph { filter: &crate::changes::ChangeFilter, ) -> Result { let coord = self.coordinator.read().await; - let from_commit = coord.resolve_commit(&SnapshotId::new(from_commit_id)).await?; + let from_commit = coord + .resolve_commit(&SnapshotId::new(from_commit_id)) + .await?; let to_commit = coord.resolve_commit(&SnapshotId::new(to_commit_id)).await?; let from_snap = coord .resolve_target(&ReadTarget::Snapshot(SnapshotId::new( @@ -753,7 +906,11 @@ impl Omnigraph { /// Create a Snapshot at any historical manifest version. pub async fn snapshot_at_version(&self, version: u64) -> Result { self.ensure_schema_state_valid().await?; - self.coordinator.read().await.snapshot_at_version(version).await + self.coordinator + .read() + .await + .snapshot_at_version(version) + .await } pub async fn export_jsonl( @@ -894,11 +1051,20 @@ impl Omnigraph { } pub(crate) async fn active_branch(&self) -> Option { - self.coordinator.read().await.current_branch().map(str::to_string) + self.coordinator + .read() + .await + .current_branch() + .map(str::to_string) } async fn ensure_branch_delete_safe(&self, branch: &str, branches: &[String]) -> Result<()> { - let descendants = self.coordinator.read().await.branch_descendants(branch).await?; + let descendants = self + .coordinator + .read() + .await + .branch_descendants(branch) + .await?; if let Some(descendant) = descendants.first() { return Err(OmniError::manifest_conflict(format!( "cannot delete branch '{}' because descendant branch '{}' still depends on it", @@ -927,11 +1093,14 @@ impl Omnigraph { Ok(()) } - async fn cleanup_deleted_branch_tables( - &self, - branch: &str, - owned_tables: &[(String, String)], - ) -> Result<()> { + /// Best-effort reclaim of the per-table Lance forks a just-deleted branch + /// owned. Runs AFTER the manifest authority flip, so the branch is already + /// gone and these forks are unreachable orphans. A failure here (transient + /// object-store error, the `branch_delete.before_table_cleanup` failpoint) + /// is logged and swallowed: the `cleanup` reconciler is the guaranteed + /// backstop that converges any leftover orphan. Uses `force_delete_branch` + /// so a partially-reclaimed retry is idempotent. + async fn cleanup_deleted_branch_tables(&self, branch: &str, owned_tables: &[(String, String)]) { let mut seen_paths = HashSet::new(); let mut cleanup_targets = owned_tables .iter() @@ -942,19 +1111,30 @@ impl Omnigraph { for (table_key, table_path) in cleanup_targets { let dataset_uri = self.table_store.dataset_uri(&table_path); - if let Err(err) = self.table_store.delete_branch(&dataset_uri, branch).await { - return Err(OmniError::manifest_internal(format!( - "branch '{}' was deleted but cleanup failed for {}: {}", - branch, table_key, err - ))); + let outcome = match crate::failpoints::maybe_fail("branch_delete.before_table_cleanup") + { + Ok(()) => self.table_store.force_delete_branch(&dataset_uri, branch).await, + Err(injected) => Err(injected), + }; + if let Err(err) = outcome { + tracing::warn!( + target: "omnigraph::branch_delete::cleanup", + branch = %branch, + table = %table_key, + error = %err, + "best-effort fork reclaim failed; cleanup will reconcile the orphan", + ); } } - - Ok(()) } async fn delete_branch_storage_only(&self, branch: &str) -> Result<()> { - let active = self.coordinator.read().await.current_branch().map(str::to_string); + let active = self + .coordinator + .read() + .await + .current_branch() + .map(str::to_string); if active.as_deref() == Some(branch) { return Err(OmniError::manifest_conflict(format!( "cannot delete currently active branch '{}'", @@ -969,9 +1149,12 @@ impl Omnigraph { .map(|entry| (entry.table_key.clone(), entry.table_path.clone())) .collect::>(); + // Authority flip (+ best-effort commit-graph reclaim) — must succeed. self.coordinator.write().await.branch_delete(branch).await?; + // Best-effort per-table fork reclaim; cleanup reconciles any leftover. self.cleanup_deleted_branch_tables(branch, &owned_tables) - .await + .await; + Ok(()) } pub(crate) fn normalize_branch_name(branch: &str) -> Result> { @@ -1013,11 +1196,7 @@ impl Omnigraph { self.coordinator.write().await.branch_create(name).await } - pub async fn branch_create_from( - &self, - from: impl Into, - name: &str, - ) -> Result<()> { + pub async fn branch_create_from(&self, from: impl Into, name: &str) -> Result<()> { self.branch_create_from_as(from, name, None).await } @@ -1134,7 +1313,9 @@ impl Omnigraph { pub async fn get_commit(&self, commit_id: &str) -> Result { self.ensure_schema_state_valid().await?; - self.coordinator.read().await + self.coordinator + .read() + .await .resolve_commit(&SnapshotId::new(commit_id)) .await } @@ -1449,6 +1630,71 @@ fn read_schema_ir_from_source(schema_source: &str) -> Result { build_schema_ir(&schema_ast).map_err(|err| OmniError::manifest(err.to_string())) } +/// I/O phase of `Omnigraph::init_with_storage`. Split out so the caller +/// can pattern-match on the result and run cleanup on error before +/// returning the original error. +/// +/// Failpoints fire at the phase boundaries: +/// * `init.after_schema_pg_written` — `_schema.pg` is on disk. In strict mode +/// this fires in the caller immediately after the atomic ownership claim; in +/// force mode it fires here after the explicit overwrite. +/// * `init.after_schema_contract_written` — `_schema.pg` + `_schema.ir.json` +/// + `__schema_state.json` are on disk. +/// * `init.after_coordinator_init` — all schema files plus Lance per-type +/// datasets and `__manifest/` are on disk. (The cleanup wrapper can only +/// remove the schema files; Lance directories need `delete_prefix` — +/// deferred along with `DELETE /graphs/{id}`.) +async fn init_storage_phase( + root: &str, + schema_source: &str, + schema_ir: &SchemaIR, + catalog: &Catalog, + storage: &Arc, + write_schema_pg: bool, +) -> Result { + if write_schema_pg { + let schema_path = join_uri(root, SCHEMA_SOURCE_FILENAME); + storage.write_text(&schema_path, schema_source).await?; + crate::failpoints::maybe_fail("init.after_schema_pg_written")?; + } + + write_schema_contract(root, storage.as_ref(), schema_ir).await?; + crate::failpoints::maybe_fail("init.after_schema_contract_written")?; + + let coordinator = GraphCoordinator::init(root, catalog, Arc::clone(storage)).await?; + crate::failpoints::maybe_fail("init.after_coordinator_init")?; + + Ok(coordinator) +} + +/// Best-effort cleanup of init-phase artifacts. Called from +/// `init_with_storage` on any error returned by `init_storage_phase`. +/// +/// Removes the three schema files: `_schema.pg`, `_schema.ir.json`, +/// `__schema_state.json`. Lance datasets and `__manifest/` are not +/// touched here — recursive directory deletion requires a +/// `StorageAdapter::delete_prefix` primitive that's deferred along +/// with `DELETE /graphs/{id}` (MR-668 PR 2b). +/// +/// Failures to delete are logged via `tracing::warn` and do not mask +/// the original init error. +async fn best_effort_cleanup_init_artifacts(root: &str, storage: &dyn StorageAdapter) { + for uri in [ + schema_source_uri(root), + schema_ir_uri(root), + schema_state_uri(root), + ] { + if let Err(err) = storage.delete(&uri).await { + tracing::warn!( + target: "omnigraph::init::cleanup", + uri = %uri, + error = %err, + "init failed; best-effort cleanup could not delete artifact", + ); + } + } +} + fn schema_table_key(type_kind: SchemaTypeKind, name: &str) -> String { match type_kind { SchemaTypeKind::Node => format!("node:{}", name), @@ -1658,7 +1904,7 @@ mod tests { use crate::db::manifest::ManifestCoordinator; use async_trait::async_trait; use serde_json::Value; - use std::sync::Mutex; + use std::sync::{Arc, Mutex}; use crate::storage::{LocalStorageAdapter, StorageAdapter, join_uri}; @@ -1712,6 +1958,11 @@ edge WorksAt: Person -> Company self.inner.write_text(uri, contents).await } + async fn write_text_if_absent(&self, uri: &str, contents: &str) -> Result { + self.writes.lock().unwrap().push(uri.to_string()); + self.inner.write_text_if_absent(uri, contents).await + } + async fn exists(&self, uri: &str) -> Result { self.exists_checks.lock().unwrap().push(uri.to_string()); self.inner.exists(uri).await @@ -1735,13 +1986,96 @@ edge WorksAt: Person -> Company } } + #[derive(Debug)] + struct InitRaceStorageAdapter { + inner: LocalStorageAdapter, + root: String, + barrier: Arc, + } + + #[async_trait] + impl StorageAdapter for InitRaceStorageAdapter { + async fn read_text(&self, uri: &str) -> Result { + self.inner.read_text(uri).await + } + + async fn write_text(&self, uri: &str, contents: &str) -> Result<()> { + self.inner.write_text(uri, contents).await + } + + async fn write_text_if_absent(&self, uri: &str, contents: &str) -> Result { + self.inner.write_text_if_absent(uri, contents).await + } + + async fn exists(&self, uri: &str) -> Result { + let exists = self.inner.exists(uri).await?; + if uri == schema_state_uri(&self.root) { + self.barrier.wait().await; + } + Ok(exists) + } + + async fn rename_text(&self, from_uri: &str, to_uri: &str) -> Result<()> { + self.inner.rename_text(from_uri, to_uri).await + } + + async fn delete(&self, uri: &str) -> Result<()> { + self.inner.delete(uri).await + } + + async fn list_dir(&self, dir_uri: &str) -> Result> { + self.inner.list_dir(dir_uri).await + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn concurrent_strict_init_does_not_delete_winning_schema_files() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap().to_string(); + let root = normalize_root_uri(&uri).unwrap(); + let storage: Arc = Arc::new(InitRaceStorageAdapter { + inner: LocalStorageAdapter, + root, + barrier: Arc::new(tokio::sync::Barrier::new(2)), + }); + + let left = Omnigraph::init_with_storage( + &uri, + TEST_SCHEMA, + Arc::clone(&storage), + InitOptions::default(), + ); + let right = Omnigraph::init_with_storage( + &uri, + TEST_SCHEMA, + Arc::clone(&storage), + InitOptions::default(), + ); + let (left, right) = tokio::join!(left, right); + let ok_count = usize::from(left.is_ok()) + usize::from(right.is_ok()); + assert_eq!(ok_count, 1, "exactly one concurrent init should win"); + + assert!( + dir.path().join("_schema.pg").exists(), + "winning init must leave _schema.pg in place" + ); + assert!( + dir.path().join("_schema.ir.json").exists(), + "winning init must leave _schema.ir.json in place" + ); + assert!( + dir.path().join("__schema_state.json").exists(), + "winning init must leave __schema_state.json in place" + ); + } + #[tokio::test] async fn test_init_and_open_route_graph_metadata_through_storage_adapter() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); let adapter = Arc::new(RecordingStorageAdapter::default()); - Omnigraph::init_with_storage(uri, TEST_SCHEMA, adapter.clone()) + Omnigraph::init_with_storage(uri, TEST_SCHEMA, adapter.clone(), InitOptions::default()) .await .unwrap(); assert!(adapter.writes().contains(&join_uri(uri, "_schema.pg"))); diff --git a/crates/omnigraph/src/db/omnigraph/export.rs b/crates/omnigraph/src/db/omnigraph/export.rs index 3fcd4f4..366f50a 100644 --- a/crates/omnigraph/src/db/omnigraph/export.rs +++ b/crates/omnigraph/src/db/omnigraph/export.rs @@ -16,7 +16,12 @@ pub(super) async fn entity_at( id: &str, version: u64, ) -> Result> { - let snap = db.coordinator.read().await.snapshot_at_version(version).await?; + let snap = db + .coordinator + .read() + .await + .snapshot_at_version(version) + .await?; entity_from_snapshot(db, &snap, table_key, id).await } diff --git a/crates/omnigraph/src/db/omnigraph/optimize.rs b/crates/omnigraph/src/db/omnigraph/optimize.rs index 4d0f0ce..fff3f54 100644 --- a/crates/omnigraph/src/db/omnigraph/optimize.rs +++ b/crates/omnigraph/src/db/omnigraph/optimize.rs @@ -1,7 +1,7 @@ //! Lance compaction + version cleanup exposed at the graph level. //! //! Lance accumulates many small `.lance` fragment files per table over the -//! life of a repo: each `write`, `load`, and `change` op appends one or more +//! life of a graph: each `write`, `load`, and `change` op appends one or more //! fragments and a new manifest. Over long timescales this hurts open times //! and S3 object counts without improving anything. //! @@ -40,6 +40,20 @@ fn maint_concurrency() -> usize { .unwrap_or(DEFAULT_MAINT_CONCURRENCY) } +/// Whether the installed Lance can compact a dataset that contains blob +/// columns. `false` today: Lance `compact_files` forces +/// `BlobHandling::AllBinary` on the read side, and the blob-v2 struct decoder +/// mis-counts columns ("there were more fields in the schema than provided +/// column indices"), failing even a pristine uniform-V2_2 multi-fragment blob +/// table. Reads are unaffected (queries use descriptor handling). +/// +/// While `false`, [`optimize_all_tables`] skips blob-bearing tables and reports +/// [`SkipReason::BlobColumnsUnsupportedByLance`] instead of aborting the whole +/// sweep. Flip to `true` once the upstream Lance fix ships — the +/// `lance_surface_guards.rs::compact_files_still_fails_on_blob_columns` guard +/// turns red on that bump and forces this flip. Tracked in `docs/dev/lance.md`. +const LANCE_SUPPORTS_BLOB_COMPACTION: bool = false; + /// Retention knobs for [`cleanup_all_tables`]. At least one must be set or /// nothing is cleaned. If both are set, Lance applies them as AND (a manifest /// is kept if it satisfies either — i.e. only manifests older than BOTH the @@ -52,8 +66,45 @@ pub struct CleanupPolicyOptions { pub older_than: Option, } -/// Per-table outcome of `optimize_all_tables`. +/// Why `optimize` did not compact a table. Typed so callers branch on the +/// reason rather than sniffing a string. One variant today, gated by +/// [`LANCE_SUPPORTS_BLOB_COMPACTION`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum SkipReason { + /// The table has one or more `Blob` columns. Lance `compact_files` forces + /// `BlobHandling::AllBinary`, which mis-decodes blob-v2 columns; see + /// [`LANCE_SUPPORTS_BLOB_COMPACTION`] and `docs/dev/lance.md`. + BlobColumnsUnsupportedByLance, +} + +impl SkipReason { + /// Stable machine-readable token for serialized output (e.g. CLI `--json`). + /// Once emitted this is part of the output contract — keep it stable. + pub fn as_str(&self) -> &'static str { + match self { + SkipReason::BlobColumnsUnsupportedByLance => "blob_columns_unsupported_by_lance", + } + } +} + +impl std::fmt::Display for SkipReason { + /// Human-readable reason for CLI and log output. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let msg = match self { + SkipReason::BlobColumnsUnsupportedByLance => { + "blob columns — Lance compaction unsupported" + } + }; + f.write_str(msg) + } +} + +/// Per-table outcome of `optimize_all_tables`. This is a returned result type, +/// not built by callers, so it is `#[non_exhaustive]`: future fields stay +/// non-breaking and downstream code reads fields rather than constructing it. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct TableOptimizeStats { pub table_key: String, /// Number of source fragments that were rewritten by Lance. @@ -62,14 +113,44 @@ pub struct TableOptimizeStats { pub fragments_added: usize, /// Did this table get a new Lance manifest version from the compaction? pub committed: bool, + /// `Some(reason)` if this table was deliberately not compacted. When set, + /// `fragments_removed == 0`, `fragments_added == 0`, and `!committed`. + pub skipped: Option, } -/// Per-table outcome of `cleanup_all_tables`. +impl TableOptimizeStats { + /// Stat for a table that Lance actually compacted. + fn compacted(table_key: String, metrics: &CompactionMetrics, committed: bool) -> Self { + Self { + table_key, + fragments_removed: metrics.fragments_removed, + fragments_added: metrics.fragments_added, + committed, + skipped: None, + } + } + + /// Stat for a table that was deliberately skipped (compaction not attempted). + fn skipped(table_key: String, reason: SkipReason) -> Self { + Self { + table_key, + fragments_removed: 0, + fragments_added: 0, + committed: false, + skipped: Some(reason), + } + } +} + +/// Per-table outcome of `cleanup_all_tables`. `error` is `Some` when this +/// table's version GC failed; cleanup is fault-isolated per table, so a single +/// table's failure is recorded here rather than aborting the whole sweep. #[derive(Debug, Clone)] pub struct TableCleanupStats { pub table_key: String, pub bytes_removed: u64, pub old_versions_removed: u64, + pub error: Option, } /// Run Lance `compact_files` on every node + edge table on `main`. @@ -81,14 +162,21 @@ pub async fn optimize_all_tables(db: &Omnigraph) -> Result = all_table_keys(&db.catalog()) - .into_iter() - .filter_map(|table_key| { - let entry = snapshot.entry(&table_key)?; + // Compute per-table state (path + whether it has blob columns) up front, in + // a scope that drops the catalog handle before the async stream starts. + let table_tasks: Vec<(String, String, bool)> = { + let catalog = db.catalog(); + let mut tasks = Vec::new(); + for table_key in all_table_keys(&catalog) { + let Some(entry) = snapshot.entry(&table_key) else { + continue; + }; let full_path = format!("{}/{}", db.root_uri, entry.table_path); - Some((table_key, full_path)) - }) - .collect(); + let has_blob = !blob_properties_for_table_key(&catalog, &table_key)?.is_empty(); + tasks.push((table_key, full_path, has_blob)); + } + tasks + }; if table_tasks.is_empty() { return Ok(Vec::new()); @@ -98,7 +186,24 @@ pub async fn optimize_all_tables(db: &Omnigraph) -> Result> = futures::stream::iter(table_tasks.into_iter()) - .map(|(table_key, full_path)| async move { + .map(|(table_key, full_path, has_blob)| async move { + // Lance `compact_files` mis-decodes blob-v2 columns under the forced + // `BlobHandling::AllBinary` read (see LANCE_SUPPORTS_BLOB_COMPACTION). + // Skip blob-bearing tables and report it rather than aborting the + // whole sweep — the other tables still compact. + if has_blob && !LANCE_SUPPORTS_BLOB_COMPACTION { + tracing::warn!( + target: "omnigraph::optimize", + table = %table_key, + "skipping compaction: table has blob columns the current Lance \ + cannot rewrite (blob-v2 AllBinary decode bug); other tables \ + unaffected — rerun after the Lance fix", + ); + return Ok(TableOptimizeStats::skipped( + table_key, + SkipReason::BlobColumnsUnsupportedByLance, + )); + } let mut ds = table_store .open_dataset_head_for_write(&table_key, &full_path, None) .await?; @@ -108,12 +213,11 @@ pub async fn optimize_all_tables(db: &Omnigraph) -> Result> = futures::stream::iter(table_tasks.into_iter()) + // Fault-isolated per table: a single table's GC failure is recorded on its + // stats row (`error: Some`) and logged, never aborting the healthy tables. + // cleanup is the convergence backstop, so it must do as much as it can and + // converge on re-run rather than fail wholesale (invariant 13). + let results: Vec = futures::stream::iter(table_tasks.into_iter()) .map(|(table_key, full_path)| async move { - let ds = table_store - .open_dataset_head_for_write(&table_key, &full_path, None) - .await?; - let before_version = keep_versions - .map(|n| ds.version().version.saturating_sub(n as u64)) - .filter(|v| *v > 0); - let policy = CleanupPolicy { - before_timestamp, - before_version, - delete_unverified: false, - error_if_tagged_old_versions: false, - clean_referenced_branches: false, - delete_rate_limit: None, - }; - let removed: RemovalStats = + let outcome: Result = async { + crate::failpoints::maybe_fail("cleanup.table_gc")?; + let ds = table_store + .open_dataset_head_for_write(&table_key, &full_path, None) + .await?; + let before_version = keep_versions + .map(|n| ds.version().version.saturating_sub(n as u64)) + .filter(|v| *v > 0); + let policy = CleanupPolicy { + before_timestamp, + before_version, + delete_unverified: false, + error_if_tagged_old_versions: false, + clean_referenced_branches: false, + delete_rate_limit: None, + }; lance::dataset::cleanup::cleanup_old_versions(&ds, policy) .await - .map_err(|e| OmniError::Lance(e.to_string()))?; - Ok(TableCleanupStats { - table_key, - bytes_removed: removed.bytes_removed, - old_versions_removed: removed.old_versions, - }) + .map_err(|e| OmniError::Lance(e.to_string())) + } + .await; + match outcome { + Ok(removed) => TableCleanupStats { + table_key, + bytes_removed: removed.bytes_removed, + old_versions_removed: removed.old_versions, + error: None, + }, + Err(err) => { + tracing::warn!( + target: "omnigraph::cleanup", + table = %table_key, + error = %err, + "version GC failed for table; other tables unaffected", + ); + TableCleanupStats { + table_key, + bytes_removed: 0, + old_versions_removed: 0, + error: Some(err.to_string()), + } + } + } }) .buffer_unordered(concurrency) .collect() .await; - results.into_iter().collect() + Ok(results) +} + +/// Outcome of [`reconcile_orphaned_branches`]: the `(owner, branch)` pairs +/// reclaimed and the `(owner, error)` pairs that failed, where `owner` is a +/// table key (e.g. `node:Person`) or `"_graph_commits"`. Per-owner failures are +/// isolated and recorded here, not propagated — the next reconcile converges. +#[derive(Debug, Clone, Default)] +pub struct BranchReconcileStats { + pub reclaimed: Vec<(String, String)>, + pub failures: Vec<(String, String)>, +} + +/// Drop every per-table and commit-graph Lance branch that the manifest no +/// longer references. +/// +/// Orphaned forks arise when a `branch_delete` flips the manifest authority +/// (atomic) but a downstream best-effort reclaim does not complete. They are +/// unreachable through any snapshot — no manifest entry can name them — yet +/// they pin their `tree/{branch}/` storage and can block reusing the branch +/// name. This is the guaranteed convergence backstop: it is idempotent and +/// derived purely from the manifest authority, so it no-ops once everything is +/// reconciled, and it would harmlessly find nothing if a future Lance atomic +/// multi-dataset branch op prevented orphans from forming. +/// +/// The keep-set is the full (unfiltered) manifest branch list, so system +/// branches' forks are never reclaimed; `main`/default is not a named Lance +/// branch and so is never a candidate. Referencing children are dropped before +/// parents (Lance refuses to delete a referenced parent) by ordering longest +/// branch names first. +pub async fn reconcile_orphaned_branches(db: &Omnigraph) -> Result { + use std::collections::HashSet; + + let keep: HashSet = db + .coordinator + .read() + .await + .all_branches() + .await? + .into_iter() + .collect(); + + let resolved = db.resolved_branch_target(None).await?; + let snapshot = resolved.snapshot; + let table_targets: Vec<(String, String)> = all_table_keys(&db.catalog()) + .into_iter() + .filter_map(|table_key| { + let entry = snapshot.entry(&table_key)?; + let full_path = format!("{}/{}", db.root_uri, entry.table_path); + Some((table_key, full_path)) + }) + .collect(); + + let mut stats = BranchReconcileStats::default(); + + // Per-table fault isolation: one table's transient failure is recorded and + // logged, never aborting the rest of the sweep. + for (table_key, full_path) in table_targets { + let listed = match db.table_store.list_branches(&full_path).await { + Ok(listed) => listed, + Err(err) => { + tracing::warn!( + target: "omnigraph::cleanup", + table = %table_key, + error = %err, + "listing branches failed during reconcile; skipping table", + ); + stats.failures.push((table_key.clone(), err.to_string())); + continue; + } + }; + for branch in orphan_branches(listed, &keep) { + let outcome = match crate::failpoints::maybe_fail("cleanup.reconcile_fork") { + Ok(()) => db.table_store.force_delete_branch(&full_path, &branch).await, + Err(injected) => Err(injected), + }; + match outcome { + Ok(()) => stats.reclaimed.push((table_key.clone(), branch)), + Err(err) => { + tracing::warn!( + target: "omnigraph::cleanup", + table = %table_key, + branch = %branch, + error = %err, + "reclaiming orphaned fork failed; will retry next cleanup", + ); + stats.failures.push((table_key.clone(), err.to_string())); + } + } + } + } + + // Commit-graph orphans (best-effort: the dataset may not exist on a graph + // that has never committed; any failure is isolated and retried next time). + if let Err(err) = reconcile_commit_graph_orphans(db, &keep, &mut stats).await { + tracing::warn!( + target: "omnigraph::cleanup", + error = %err, + "commit-graph orphan reconcile failed; will retry next cleanup", + ); + stats.failures.push(("_graph_commits".to_string(), err.to_string())); + } + + Ok(stats) +} + +/// Commit-graph half of [`reconcile_orphaned_branches`], split out so its +/// errors can be isolated. Returns `Ok` when the commit-graph dataset is absent. +async fn reconcile_commit_graph_orphans( + db: &Omnigraph, + keep: &std::collections::HashSet, + stats: &mut BranchReconcileStats, +) -> Result<()> { + let commits_uri = crate::db::commit_graph::graph_commits_uri(db.root_uri()); + if !db.storage_adapter().exists(&commits_uri).await? { + return Ok(()); + } + let mut commit_graph = crate::db::commit_graph::CommitGraph::open(db.root_uri()).await?; + for branch in orphan_branches(commit_graph.list_branches().await?, keep) { + match commit_graph.force_delete_branch(&branch).await { + Ok(()) => stats.reclaimed.push(("_graph_commits".to_string(), branch)), + Err(err) => { + tracing::warn!( + target: "omnigraph::cleanup", + branch = %branch, + error = %err, + "reclaiming orphaned commit-graph branch failed; will retry next cleanup", + ); + stats.failures.push(("_graph_commits".to_string(), err.to_string())); + } + } + } + Ok(()) +} + +/// Filter `present` Lance branches down to those absent from the manifest +/// `keep` set, ordered children-before-parents (longest name first) so Lance's +/// referenced-parent `RefConflict` cannot block reclamation. +fn orphan_branches(present: Vec, keep: &std::collections::HashSet) -> Vec { + let mut orphans: Vec = present + .into_iter() + .filter(|branch| !keep.contains(branch)) + .collect(); + orphans.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b))); + orphans } fn all_table_keys(catalog: &omnigraph_compiler::catalog::Catalog) -> Vec { @@ -198,12 +490,7 @@ fn all_table_keys(catalog: &omnigraph_compiler::catalog::Catalog) -> Vec .node_types .keys() .map(|n| format!("node:{}", n)) - .chain( - catalog - .edge_types - .keys() - .map(|n| format!("edge:{}", n)), - ) + .chain(catalog.edge_types.keys().map(|n| format!("edge:{}", n))) .collect(); keys.sort(); keys diff --git a/crates/omnigraph/src/db/omnigraph/schema_apply.rs b/crates/omnigraph/src/db/omnigraph/schema_apply.rs index 6073f6f..35fe161 100644 --- a/crates/omnigraph/src/db/omnigraph/schema_apply.rs +++ b/crates/omnigraph/src/db/omnigraph/schema_apply.rs @@ -48,12 +48,80 @@ pub(super) async fn plan_schema( Ok(plan) } -pub(super) async fn apply_schema( +struct PlannedSchemaApply { + plan: SchemaMigrationPlan, + desired_ir: SchemaIR, + desired_catalog: Catalog, +} + +async fn plan_schema_for_apply( + db: &Omnigraph, + desired_schema_source: &str, + options: SchemaApplyOptions, +) -> Result { + db.ensure_schema_state_valid().await?; + let branches = db.coordinator.read().await.all_branches().await?; + // Skip `main` and internal system branches. The schema-apply lock branch + // is excluded because it is the cluster-wide schema-apply serializer. + // `__run__*` branches are no longer created; the filter remains as + // defense-in-depth for legacy graphs with leftover staging branches. + // A future production sweep will let this guard go. + let blocking_branches = branches + .into_iter() + .filter(|branch| branch != "main" && !is_internal_system_branch(branch)) + .collect::>(); + if !blocking_branches.is_empty() { + return Err(OmniError::manifest_conflict(format!( + "schema apply requires a graph with only main; found non-main branches: {}", + blocking_branches.join(", ") + ))); + } + + let accepted_ir = read_accepted_schema_ir(db.uri(), Arc::clone(&db.storage)).await?; + let desired_ir = read_schema_ir_from_source(desired_schema_source)?; + let mut plan = plan_schema_migration(&accepted_ir, &desired_ir) + .map_err(|err| OmniError::manifest(err.to_string()))?; + promote_drops_to_hard(&mut plan, options.allow_data_loss); + if !plan.supported { + let message = plan + .steps + .iter() + .find_map(|step| step.unsupported_error_message()) + .unwrap_or_else(|| "unsupported schema migration plan".to_string()); + return Err(OmniError::manifest(message)); + } + + let mut desired_catalog = build_catalog_from_ir(&desired_ir)?; + fixup_blob_schemas(&mut desired_catalog); + Ok(PlannedSchemaApply { + plan, + desired_ir, + desired_catalog, + }) +} + +pub(super) async fn preview_schema_apply( + db: &Omnigraph, + desired_schema_source: &str, + options: SchemaApplyOptions, +) -> Result { + let planned = plan_schema_for_apply(db, desired_schema_source, options).await?; + Ok(SchemaApplyPreview { + plan: planned.plan, + catalog: planned.desired_catalog, + }) +} + +pub(super) async fn apply_schema( db: &Omnigraph, desired_schema_source: &str, options: SchemaApplyOptions, actor: Option<&str>, -) -> Result { + validate_catalog: F, +) -> Result +where + F: FnOnce(&Catalog) -> Result<()>, +{ // Engine-layer policy gate (MR-722 chassis core). // // Fires BEFORE acquiring the schema-apply lock or doing any other @@ -77,7 +145,7 @@ pub(super) async fn apply_schema( )?; acquire_schema_apply_lock(db).await?; - let result = apply_schema_with_lock(db, desired_schema_source, options).await; + let result = apply_schema_with_lock(db, desired_schema_source, options, validate_catalog).await; let release_result = release_schema_apply_lock(db).await; match (result, release_result) { (Ok(result), Ok(())) => Ok(result), @@ -87,42 +155,22 @@ pub(super) async fn apply_schema( } } -pub(super) async fn apply_schema_with_lock( +pub(super) async fn apply_schema_with_lock( db: &Omnigraph, desired_schema_source: &str, options: SchemaApplyOptions, -) -> Result { - db.ensure_schema_state_valid().await?; - let branches = db.coordinator.read().await.all_branches().await?; - // Skip `main` and internal system branches. The schema-apply lock branch - // is excluded because it is the cluster-wide schema-apply serializer. - // `__run__*` branches are no longer created; the filter remains as - // defense-in-depth for legacy repos with leftover staging branches. - // A future production sweep will let this guard go. - let blocking_branches = branches - .into_iter() - .filter(|branch| branch != "main" && !is_internal_system_branch(branch)) - .collect::>(); - if !blocking_branches.is_empty() { - return Err(OmniError::manifest_conflict(format!( - "schema apply requires a repo with only main; found non-main branches: {}", - blocking_branches.join(", ") - ))); - } - - let accepted_ir = read_accepted_schema_ir(db.uri(), Arc::clone(&db.storage)).await?; - let desired_ir = read_schema_ir_from_source(desired_schema_source)?; - let mut plan = plan_schema_migration(&accepted_ir, &desired_ir) - .map_err(|err| OmniError::manifest(err.to_string()))?; - promote_drops_to_hard(&mut plan, options.allow_data_loss); - if !plan.supported { - let message = plan - .steps - .iter() - .find_map(|step| step.unsupported_error_message()) - .unwrap_or_else(|| "unsupported schema migration plan".to_string()); - return Err(OmniError::manifest(message)); - } + validate_catalog: F, +) -> Result +where + F: FnOnce(&Catalog) -> Result<()>, +{ + let planned = plan_schema_for_apply(db, desired_schema_source, options).await?; + validate_catalog(&planned.desired_catalog)?; + let PlannedSchemaApply { + plan, + desired_ir, + desired_catalog, + } = planned; if plan.steps.is_empty() { return Ok(SchemaApplyResult { supported: true, @@ -132,9 +180,6 @@ pub(super) async fn apply_schema_with_lock( }); } - let mut desired_catalog = build_catalog_from_ir(&desired_ir)?; - fixup_blob_schemas(&mut desired_catalog); - let snapshot = db.snapshot().await; let base_manifest_version = snapshot.version(); let mut added_tables = BTreeSet::new(); @@ -780,7 +825,7 @@ pub(super) async fn acquire_schema_apply_lock(db: &Omnigraph) -> Result<()> { if !blocking_branches.is_empty() { let _ = release_schema_apply_lock(db).await; return Err(OmniError::manifest_conflict(format!( - "schema apply requires a repo with only main; found non-main branches: {}", + "schema apply requires a graph with only main; found non-main branches: {}", blocking_branches.join(", ") ))); } diff --git a/crates/omnigraph/src/db/omnigraph/table_ops.rs b/crates/omnigraph/src/db/omnigraph/table_ops.rs index 717f263..3ed9c43 100644 --- a/crates/omnigraph/src/db/omnigraph/table_ops.rs +++ b/crates/omnigraph/src/db/omnigraph/table_ops.rs @@ -22,7 +22,12 @@ pub(super) async fn graph_index_for_resolved( } pub(super) async fn ensure_indices(db: &Omnigraph) -> Result<()> { - let current_branch = db.coordinator.read().await.current_branch().map(str::to_string); + let current_branch = db + .coordinator + .read() + .await + .current_branch() + .map(str::to_string); ensure_indices_for_branch(db, current_branch.as_deref()).await } @@ -68,10 +73,7 @@ pub(super) async fn failpoint_publish_table_head_without_index_rebuild_for_test( .await } -pub(super) async fn ensure_indices_for_branch( - db: &Omnigraph, - branch: Option<&str>, -) -> Result<()> { +pub(super) async fn ensure_indices_for_branch(db: &Omnigraph, branch: Option<&str>) -> Result<()> { db.ensure_schema_state_valid().await?; db.ensure_schema_apply_idle("ensure_indices").await?; let resolved = db.resolved_branch_target(branch).await?; @@ -403,7 +405,12 @@ pub(super) async fn open_for_mutation( table_key: &str, op_kind: crate::db::MutationOpKind, ) -> Result<(Dataset, String, Option)> { - let current_branch = db.coordinator.read().await.current_branch().map(str::to_string); + let current_branch = db + .coordinator + .read() + .await + .current_branch() + .map(str::to_string); open_for_mutation_on_branch(db, current_branch.as_deref(), table_key, op_kind).await } @@ -476,6 +483,22 @@ pub(super) async fn open_owned_dataset_for_branch_write( Ok((ds, Some(active_branch.to_string()))) } source_branch => { + crate::failpoints::maybe_fail("fork.before_classify")?; + // Authority check before forking: re-read the live manifest. If this + // table is already forked on active_branch, a concurrent first-write + // won the race and our snapshot is stale — that is a retryable + // conflict, not an orphan. (A zombie fork is never in the manifest, + // so this only fires for a live concurrent fork.) + let live = db.snapshot_for_branch(Some(active_branch)).await?; + if let Some(entry) = live.entry(table_key) { + if entry.table_branch.as_deref() == Some(active_branch) { + return Err(OmniError::manifest_expected_version_mismatch( + table_key, + entry_version, + entry.table_version, + )); + } + } fork_dataset_from_entry_state( db, table_key, @@ -807,7 +830,12 @@ pub(super) async fn commit_prepared_updates_on_branch( updates: &[crate::db::SubTableUpdate], actor_id: Option<&str>, ) -> Result { - let current_branch = db.coordinator.read().await.current_branch().map(str::to_string); + let current_branch = db + .coordinator + .read() + .await + .current_branch() + .map(str::to_string); let requested_branch = branch.map(str::to_string); if requested_branch == current_branch { return commit_prepared_updates(db, updates, actor_id).await; @@ -835,7 +863,12 @@ pub(super) async fn commit_prepared_updates_on_branch_with_expected( expected_table_versions: &std::collections::HashMap, actor_id: Option<&str>, ) -> Result { - let current_branch = db.coordinator.read().await.current_branch().map(str::to_string); + let current_branch = db + .coordinator + .read() + .await + .current_branch() + .map(str::to_string); let requested_branch = branch.map(str::to_string); if requested_branch == current_branch { return commit_prepared_updates_with_expected( @@ -870,7 +903,12 @@ pub(super) async fn commit_updates( updates: &[crate::db::SubTableUpdate], ) -> Result { db.ensure_schema_apply_not_locked("write commit").await?; - let current_branch = db.coordinator.read().await.current_branch().map(str::to_string); + let current_branch = db + .coordinator + .read() + .await + .current_branch() + .map(str::to_string); let prepared = prepare_updates_for_commit(db, current_branch.as_deref(), updates).await?; commit_prepared_updates(db, &prepared, None).await } @@ -879,7 +917,11 @@ pub(super) async fn commit_manifest_updates( db: &Omnigraph, updates: &[crate::db::SubTableUpdate], ) -> Result { - db.coordinator.write().await.commit_manifest_updates(updates).await + db.coordinator + .write() + .await + .commit_manifest_updates(updates) + .await } pub(super) async fn record_merge_commit( @@ -889,7 +931,9 @@ pub(super) async fn record_merge_commit( merged_parent_commit_id: &str, actor_id: Option<&str>, ) -> Result { - db.coordinator.write().await + db.coordinator + .write() + .await .record_merge_commit( manifest_version, parent_commit_id, @@ -923,7 +967,11 @@ pub(super) async fn commit_updates_on_branch_with_expected( } pub(super) async fn ensure_commit_graph_initialized(db: &Omnigraph) -> Result<()> { - db.coordinator.write().await.ensure_commit_graph_initialized().await + db.coordinator + .write() + .await + .ensure_commit_graph_initialized() + .await } pub(super) async fn invalidate_graph_index(db: &Omnigraph) { diff --git a/crates/omnigraph/src/db/recovery_audit.rs b/crates/omnigraph/src/db/recovery_audit.rs index b7d4975..b9e8e7b 100644 --- a/crates/omnigraph/src/db/recovery_audit.rs +++ b/crates/omnigraph/src/db/recovery_audit.rs @@ -93,7 +93,7 @@ pub(crate) struct RecoveryAudit { } impl RecoveryAudit { - /// Open the recovery-audit dataset for the repo, or return a handle + /// Open the recovery-audit dataset for the graph, or return a handle /// with no dataset yet (created on first append). Mirrors the /// optional-dataset pattern from `_graph_commit_actors.lance`. pub(crate) async fn open(root_uri: &str) -> Result { @@ -205,9 +205,7 @@ fn recovery_record_to_batch(record: &RecoveryAuditRecord) -> Result vec![ Arc::new(StringArray::from(vec![record.graph_commit_id.clone()])), Arc::new(StringArray::from(vec![record.recovery_kind.as_str()])), - Arc::new(StringArray::from(vec![record - .recovery_for_actor - .clone()])), + Arc::new(StringArray::from(vec![record.recovery_for_actor.clone()])), Arc::new(StringArray::from(vec![record.operation_id.clone()])), Arc::new(StringArray::from(vec![record.sidecar_writer_kind.clone()])), Arc::new(StringArray::from(vec![outcomes_json])), @@ -221,10 +219,14 @@ fn decode_row(batch: &RecordBatch, row: usize) -> Result { let str_col = |name: &str| -> Result<&StringArray> { batch .column_by_name(name) - .ok_or_else(|| OmniError::manifest_internal(format!("missing column '{}' in recovery audit", name)))? + .ok_or_else(|| { + OmniError::manifest_internal(format!("missing column '{}' in recovery audit", name)) + })? .as_any() .downcast_ref::() - .ok_or_else(|| OmniError::manifest_internal(format!("column '{}' has wrong type", name))) + .ok_or_else(|| { + OmniError::manifest_internal(format!("column '{}' has wrong type", name)) + }) }; let ts_col = batch .column_by_name("created_at") @@ -269,9 +271,7 @@ pub(crate) fn now_micros() -> Result { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_micros() as i64) - .map_err(|e| { - OmniError::manifest_internal(format!("system clock before unix epoch: {}", e)) - }) + .map_err(|e| OmniError::manifest_internal(format!("system clock before unix epoch: {}", e))) } #[cfg(test)] @@ -307,7 +307,7 @@ mod tests { let root = dir.path().to_str().unwrap(); let mut audit = RecoveryAudit::open(root).await.unwrap(); - // Empty repo: list returns empty. + // Empty graph: list returns empty. assert!(audit.list().await.unwrap().is_empty()); // Append + list. diff --git a/crates/omnigraph/src/db/schema_state.rs b/crates/omnigraph/src/db/schema_state.rs index 13dfccc..b131a16 100644 --- a/crates/omnigraph/src/db/schema_state.rs +++ b/crates/omnigraph/src/db/schema_state.rs @@ -61,7 +61,7 @@ pub(crate) async fn load_or_bootstrap_schema_contract( .collect::>(); if !public_non_main.is_empty() { return Err(schema_lock_conflict(format!( - "repo is missing persisted schema state and has public branches ({}); public branches block schema evolution entirely", + "graph is missing persisted schema state and has public branches ({}); public branches block schema evolution entirely", public_non_main.join(", ") ))); } @@ -70,7 +70,7 @@ pub(crate) async fn load_or_bootstrap_schema_contract( Ok((current_source_ir.clone(), state)) } SchemaContractRead::PartialMissing => Err(schema_lock_conflict( - "repo schema state is incomplete (_schema.ir.json and __schema_state.json must either both exist or both be absent)", + "graph schema state is incomplete (_schema.ir.json and __schema_state.json must either both exist or both be absent)", )), } } @@ -84,7 +84,7 @@ pub(crate) async fn validate_schema_contract( SchemaContractRead::Present { ir, state } => (ir, state), SchemaContractRead::MissingAll | SchemaContractRead::PartialMissing => { return Err(schema_lock_conflict( - "repo is missing persisted schema state; manual coordination is required before schema changes are allowed", + "graph is missing persisted schema state; manual coordination is required before schema changes are allowed", )); } }; @@ -163,7 +163,7 @@ pub(crate) async fn read_accepted_schema_ir( } SchemaContractRead::MissingAll | SchemaContractRead::PartialMissing => { Err(schema_lock_conflict( - "repo is missing persisted schema state; manual coordination is required before schema changes are allowed", + "graph is missing persisted schema state; manual coordination is required before schema changes are allowed", )) } } @@ -221,7 +221,7 @@ async fn read_schema_contract( })?; let state = serde_json::from_str::(&state_json).map_err(|err| { schema_lock_conflict(format!( - "repo schema state in {} is invalid: {}", + "graph schema state in {} is invalid: {}", SCHEMA_STATE_FILENAME, err )) })?; @@ -234,7 +234,7 @@ async fn read_schema_contract( fn validate_persisted_schema_contract(ir: &SchemaIR, state: &SchemaState) -> Result<()> { if state.format_version != SCHEMA_STATE_FORMAT_VERSION { return Err(schema_lock_conflict(format!( - "repo schema state format {} is unsupported", + "graph schema state format {} is unsupported", state.format_version ))); } @@ -344,7 +344,7 @@ pub(crate) async fn recover_schema_state_files( // to the new Lance HEADs; we MUST also rename the staging files // forward so the catalog matches. Without this, the disambiguation // logic below sees actual_keys == live_keys (manifest didn't move) - // and deletes the staging files, leaving the repo with new-schema + // and deletes the staging files, leaving the graph with new-schema // data on disk but the old `_schema.pg` live — corruption. if crate::db::manifest::has_schema_apply_sidecar(root_uri, storage.as_ref()).await? { warn!( diff --git a/crates/omnigraph/src/db/write_queue.rs b/crates/omnigraph/src/db/write_queue.rs index bb03022..1f0c53a 100644 --- a/crates/omnigraph/src/db/write_queue.rs +++ b/crates/omnigraph/src/db/write_queue.rs @@ -91,10 +91,7 @@ impl WriteQueueManager { /// Empty input returns an empty Vec without touching the map. /// Duplicates in `keys` are deduped before acquisition (the same /// key acquired twice would deadlock against itself). - pub(crate) async fn acquire_many( - &self, - keys: &[TableQueueKey], - ) -> Vec> { + pub(crate) async fn acquire_many(&self, keys: &[TableQueueKey]) -> Vec> { if keys.is_empty() { return Vec::new(); } @@ -167,7 +164,10 @@ mod tests { qm2.acquire_many(&[z_clone, a_clone]).await }) .await; - assert!(result.is_err(), "acquire_many should block on `a`, the lex-first key"); + assert!( + result.is_err(), + "acquire_many should block on `a`, the lex-first key" + ); } #[tokio::test] @@ -180,9 +180,10 @@ mod tests { // Second acquire on same key should NOT complete within 200ms. let qm2 = Arc::clone(&qm); let k2 = k.clone(); - let blocked = timeout(Duration::from_millis(200), async move { - qm2.acquire(&k2).await - }) + let blocked = timeout( + Duration::from_millis(200), + async move { qm2.acquire(&k2).await }, + ) .await; assert!(blocked.is_err(), "second acquire on same key must block"); diff --git a/crates/omnigraph/src/error.rs b/crates/omnigraph/src/error.rs index 5d27fcb..11f4da0 100644 --- a/crates/omnigraph/src/error.rs +++ b/crates/omnigraph/src/error.rs @@ -92,6 +92,14 @@ pub enum OmniError { /// callers can match on this variant directly. #[error("policy: {0}")] Policy(String), + /// `Omnigraph::init` was called against a URI that already holds + /// schema artifacts from a previous init. Strict mode (the default) + /// fails fast with this error before touching disk so an existing + /// graph's metadata cannot be overwritten or destroyed. Operators + /// who actually want to overwrite pass `InitOptions { force: true }` + /// (CLI: `omnigraph init --force`). + #[error("graph already initialized at '{uri}'; pass --force to overwrite")] + AlreadyInitialized { uri: String }, } impl OmniError { diff --git a/crates/omnigraph/src/exec/mutation.rs b/crates/omnigraph/src/exec/mutation.rs index a5fc6c7..02b2a21 100644 --- a/crates/omnigraph/src/exec/mutation.rs +++ b/crates/omnigraph/src/exec/mutation.rs @@ -794,11 +794,8 @@ impl Omnigraph { // post_commit_pin) and tidies up. Failing the user // here would return an error for a write that // already landed. - if let Err(err) = crate::db::manifest::delete_sidecar( - &handle, - self.storage_adapter(), - ) - .await + if let Err(err) = + crate::db::manifest::delete_sidecar(&handle, self.storage_adapter()).await { tracing::warn!( error = %err, @@ -852,15 +849,8 @@ impl Omnigraph { assignments, predicate, } => { - self.execute_update( - type_name, - assignments, - predicate, - params, - branch, - staging, - ) - .await? + self.execute_update(type_name, assignments, predicate, params, branch, staging) + .await? } MutationOpIR::Delete { type_name, @@ -981,14 +971,8 @@ impl Omnigraph { // + iterate pending edges in-memory for the `src` column, // group-by-src. The pending side already includes the row // we just appended (above). - validate_edge_cardinality_with_pending( - self, - &ds, - staging, - &table_key, - edge_type, - ) - .await?; + validate_edge_cardinality_with_pending(self, &ds, staging, &table_key, edge_type) + .await?; self.invalidate_graph_index().await; @@ -1379,14 +1363,8 @@ async fn validate_edge_cardinality_with_pending( if edge_type.cardinality.is_default() { return Ok(()); } - let counts = super::staging::count_src_per_edge( - db, - committed_ds, - table_key, - staging, - None, - ) - .await?; + let counts = + super::staging::count_src_per_edge(db, committed_ds, table_key, staging, None).await?; super::staging::enforce_cardinality_bounds(edge_type, &counts) } diff --git a/crates/omnigraph/src/exec/projection.rs b/crates/omnigraph/src/exec/projection.rs index bcfae66..dec13a8 100644 --- a/crates/omnigraph/src/exec/projection.rs +++ b/crates/omnigraph/src/exec/projection.rs @@ -345,10 +345,7 @@ fn evaluate_projection( IRExpr::PropAccess { variable, property } => { let col_name = format!("{}.{}", variable, property); let col = wide_batch.column_by_name(&col_name).ok_or_else(|| { - OmniError::manifest(format!( - "column '{}' not found in wide batch", - col_name - )) + OmniError::manifest(format!("column '{}' not found in wide batch", col_name)) })?; Ok((col_name, col.clone())) } @@ -516,12 +513,10 @@ fn aggregate_return( } let num_groups = group_indices.len(); - let mut result_columns: Vec<(usize, String, ArrayRef)> = - Vec::with_capacity(projections.len()); + let mut result_columns: Vec<(usize, String, ArrayRef)> = Vec::with_capacity(projections.len()); for gk in &group_keys { - let first_row_indices: Vec = - group_indices.iter().map(|rows| rows[0] as u32).collect(); + let first_row_indices: Vec = group_indices.iter().map(|rows| rows[0] as u32).collect(); let take_idx = UInt32Array::from(first_row_indices); let col = arrow_select::take::take(gk.column.as_ref(), &take_idx, None) .map_err(|e| OmniError::Lance(e.to_string()))?; @@ -584,11 +579,19 @@ fn compute_aggregate( } } -fn compute_sum(arg: &ArrayRef, group_indices: &[Vec], num_groups: usize) -> Result { +fn compute_sum( + arg: &ArrayRef, + group_indices: &[Vec], + num_groups: usize, +) -> Result { macro_rules! sum_numeric { ($arr_type:ty, $arg:expr, $dt:expr) => {{ let arr = $arg.as_any().downcast_ref::<$arr_type>().ok_or_else(|| { - OmniError::manifest(format!("sum: expected {:?}, got {:?}", $dt, $arg.data_type())) + OmniError::manifest(format!( + "sum: expected {:?}, got {:?}", + $dt, + $arg.data_type() + )) })?; let mut builder = Float64Builder::with_capacity(num_groups); for group in group_indices { @@ -613,24 +616,42 @@ fn compute_sum(arg: &ArrayRef, group_indices: &[Vec], num_groups: usize) dt @ DataType::UInt64 => sum_numeric!(UInt64Array, arg, dt), dt @ DataType::Float32 => sum_numeric!(Float32Array, arg, dt), dt @ DataType::Float64 => sum_numeric!(Float64Array, arg, dt), - dt => Err(OmniError::manifest(format!("sum: unsupported type {:?}", dt))), + dt => Err(OmniError::manifest(format!( + "sum: unsupported type {:?}", + dt + ))), } } -fn compute_avg(arg: &ArrayRef, group_indices: &[Vec], num_groups: usize) -> Result { +fn compute_avg( + arg: &ArrayRef, + group_indices: &[Vec], + num_groups: usize, +) -> Result { macro_rules! avg_typed { ($arr_type:ty, $arg:expr) => {{ let arr = $arg.as_any().downcast_ref::<$arr_type>().ok_or_else(|| { - OmniError::manifest(format!("avg: expected {:?}, got {:?}", stringify!($arr_type), $arg.data_type())) + OmniError::manifest(format!( + "avg: expected {:?}, got {:?}", + stringify!($arr_type), + $arg.data_type() + )) })?; let mut builder = Float64Builder::with_capacity(num_groups); for group in group_indices { let mut sum = 0.0f64; let mut count = 0usize; for &i in group { - if !arr.is_null(i) { sum += arr.value(i) as f64; count += 1; } + if !arr.is_null(i) { + sum += arr.value(i) as f64; + count += 1; + } + } + if count > 0 { + builder.append_value(sum / count as f64); + } else { + builder.append_null(); } - if count > 0 { builder.append_value(sum / count as f64); } else { builder.append_null(); } } Ok(Arc::new(builder.finish()) as ArrayRef) }}; @@ -642,15 +663,27 @@ fn compute_avg(arg: &ArrayRef, group_indices: &[Vec], num_groups: usize) DataType::UInt64 => avg_typed!(UInt64Array, arg), DataType::Float32 => avg_typed!(Float32Array, arg), DataType::Float64 => avg_typed!(Float64Array, arg), - dt => Err(OmniError::manifest(format!("avg: unsupported type {:?}", dt))), + dt => Err(OmniError::manifest(format!( + "avg: unsupported type {:?}", + dt + ))), } } -fn compute_min_max(arg: &ArrayRef, group_indices: &[Vec], num_groups: usize, is_min: bool) -> Result { +fn compute_min_max( + arg: &ArrayRef, + group_indices: &[Vec], + num_groups: usize, + is_min: bool, +) -> Result { macro_rules! minmax_typed { ($arr_type:ty, $builder_type:ty, $arg:expr, $is_min:expr) => {{ let arr = $arg.as_any().downcast_ref::<$arr_type>().ok_or_else(|| { - OmniError::manifest(format!("min/max: expected {:?}, got {:?}", stringify!($arr_type), $arg.data_type())) + OmniError::manifest(format!( + "min/max: expected {:?}, got {:?}", + stringify!($arr_type), + $arg.data_type() + )) })?; let mut builder = <$builder_type>::with_capacity(num_groups); for group in group_indices { @@ -660,11 +693,20 @@ fn compute_min_max(arg: &ArrayRef, group_indices: &[Vec], num_groups: usi let v = arr.value(i); result = Some(match result { None => v, - Some(cur) => if $is_min { if v < cur { v } else { cur } } else { if v > cur { v } else { cur } }, + Some(cur) => { + if $is_min { + if v < cur { v } else { cur } + } else { + if v > cur { v } else { cur } + } + } }); } } - match result { Some(v) => builder.append_value(v), None => builder.append_null() } + match result { + Some(v) => builder.append_value(v), + None => builder.append_null(), + } } Ok(Arc::new(builder.finish()) as ArrayRef) }}; @@ -688,15 +730,27 @@ fn compute_min_max(arg: &ArrayRef, group_indices: &[Vec], num_groups: usi let v = arr.value(i); result = Some(match result { None => v, - Some(cur) => if is_min { if v < cur { v } else { cur } } else { if v > cur { v } else { cur } }, + Some(cur) => { + if is_min { + if v < cur { v } else { cur } + } else { + if v > cur { v } else { cur } + } + } }); } } - match result { Some(v) => builder.append_value(v), None => builder.append_null() } + match result { + Some(v) => builder.append_value(v), + None => builder.append_null(), + } } Ok(Arc::new(builder.finish()) as ArrayRef) } - dt => Err(OmniError::manifest(format!("min/max: unsupported type {:?}", dt))), + dt => Err(OmniError::manifest(format!( + "min/max: unsupported type {:?}", + dt + ))), } } @@ -715,7 +769,8 @@ fn build_empty_aggregate_result(projections: &[IRProjection]) -> Result { fields.push(Field::new(name, DataType::Float64, true)); - columns.push(Arc::new(Float64Array::from(vec![None as Option])) as ArrayRef); + columns + .push(Arc::new(Float64Array::from(vec![None as Option])) as ArrayRef); } }, _ => { diff --git a/crates/omnigraph/src/exec/query.rs b/crates/omnigraph/src/exec/query.rs index 24a8722..7590512 100644 --- a/crates/omnigraph/src/exec/query.rs +++ b/crates/omnigraph/src/exec/query.rs @@ -75,14 +75,7 @@ impl Omnigraph { None }; - execute_query( - &ir, - params, - &snapshot, - graph_index.as_deref(), - &catalog, - ) - .await + execute_query(&ir, params, &snapshot, graph_index.as_deref(), &catalog).await } } @@ -360,11 +353,23 @@ pub async fn execute_query( } let mut wide: Option = None; - execute_pipeline(&ir.pipeline, params, snapshot, graph_index, catalog, &mut wide, &search_mode).await?; + execute_pipeline( + &ir.pipeline, + params, + snapshot, + graph_index, + catalog, + &mut wide, + &search_mode, + ) + .await?; let wide_batch = wide.unwrap_or_else(|| RecordBatch::new_empty(Arc::new(Schema::empty()))); // Project return expressions - let has_aggregates = ir.return_exprs.iter().any(|p| matches!(&p.expr, IRExpr::Aggregate { .. })); + let has_aggregates = ir + .return_exprs + .iter() + .any(|p| matches!(&p.expr, IRExpr::Aggregate { .. })); let mut result_batch = project_return(&wide_batch, &ir.return_exprs, params)?; // Apply ordering (skip if search mode already ordered the results) @@ -516,9 +521,9 @@ async fn execute_rrf_query( } fn extract_id_column_by_name(batch: &RecordBatch, col_name: &str) -> Result> { - let col = batch - .column_by_name(col_name) - .ok_or_else(|| OmniError::manifest(format!("batch missing '{}' column for RRF", col_name)))?; + let col = batch.column_by_name(col_name).ok_or_else(|| { + OmniError::manifest(format!("batch missing '{}' column for RRF", col_name)) + })?; let ids = col .as_any() .downcast_ref::() @@ -653,8 +658,19 @@ fn execute_pipeline<'a>( })?; if let Some(batch) = wide.as_mut() { execute_expand( - batch, gi, snapshot, catalog, src_var, dst_var, edge_type, *direction, - dst_type, *min_hops, *max_hops, dst_filters, params, + batch, + gi, + snapshot, + catalog, + src_var, + dst_var, + edge_type, + *direction, + dst_type, + *min_hops, + *max_hops, + dst_filters, + params, ) .await?; } @@ -691,7 +707,9 @@ async fn execute_expand( let src_id_col_name = format!("{}.id", src_var); let src_ids = wide .column_by_name(&src_id_col_name) - .ok_or_else(|| OmniError::manifest(format!("wide batch missing '{}' column", src_id_col_name)))? + .ok_or_else(|| { + OmniError::manifest(format!("wide batch missing '{}' column", src_id_col_name)) + })? .as_any() .downcast_ref::() .ok_or_else(|| OmniError::manifest(format!("'{}' column is not Utf8", src_id_col_name)))? @@ -1421,22 +1439,39 @@ fn literal_to_expr(lit: &Literal) -> Option { } fn prefix_batch(batch: &RecordBatch, variable: &str) -> Result { - let fields: Vec = batch.schema().fields().iter().map(|f| { - Field::new(format!("{}.{}", variable, f.name()), f.data_type().clone(), f.is_nullable()) - }).collect(); + let fields: Vec = batch + .schema() + .fields() + .iter() + .map(|f| { + Field::new( + format!("{}.{}", variable, f.name()), + f.data_type().clone(), + f.is_nullable(), + ) + }) + .collect(); let schema = Arc::new(Schema::new(fields)); - RecordBatch::try_new(schema, batch.columns().to_vec()).map_err(|e| OmniError::Lance(e.to_string())) + RecordBatch::try_new(schema, batch.columns().to_vec()) + .map_err(|e| OmniError::Lance(e.to_string())) } fn cross_join_batches(left: &RecordBatch, right: &RecordBatch) -> Result { let n = left.num_rows(); let m = right.num_rows(); if n == 0 || m == 0 { - let mut fields: Vec = left.schema().fields().iter().map(|f| f.as_ref().clone()).collect(); + let mut fields: Vec = left + .schema() + .fields() + .iter() + .map(|f| f.as_ref().clone()) + .collect(); fields.extend(right.schema().fields().iter().map(|f| f.as_ref().clone())); return Ok(RecordBatch::new_empty(Arc::new(Schema::new(fields)))); } - let left_indices: Vec = (0..n as u32).flat_map(|i| std::iter::repeat(i).take(m)).collect(); + let left_indices: Vec = (0..n as u32) + .flat_map(|i| std::iter::repeat(i).take(m)) + .collect(); let right_indices: Vec = (0..n).flat_map(|_| 0..m as u32).collect(); let left_expanded = take_batch(left, &UInt32Array::from(left_indices))?; let right_expanded = take_batch(right, &UInt32Array::from(right_indices))?; @@ -1444,23 +1479,39 @@ fn cross_join_batches(left: &RecordBatch, right: &RecordBatch) -> Result Result { - let mut fields: Vec = left.schema().fields().iter().map(|f| f.as_ref().clone()).collect(); + let mut fields: Vec = left + .schema() + .fields() + .iter() + .map(|f| f.as_ref().clone()) + .collect(); if cfg!(debug_assertions) { let left_schema = left.schema(); - let left_names: HashSet<&str> = left_schema.fields().iter().map(|f| f.name().as_str()).collect(); + let left_names: HashSet<&str> = left_schema + .fields() + .iter() + .map(|f| f.name().as_str()) + .collect(); let right_schema = right.schema(); for f in right_schema.fields() { - debug_assert!(!left_names.contains(f.name().as_str()), "hconcat_batches: duplicate column '{}'", f.name()); + debug_assert!( + !left_names.contains(f.name().as_str()), + "hconcat_batches: duplicate column '{}'", + f.name() + ); } } fields.extend(right.schema().fields().iter().map(|f| f.as_ref().clone())); let mut columns: Vec = left.columns().to_vec(); columns.extend(right.columns().to_vec()); - RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).map_err(|e| OmniError::Lance(e.to_string())) + RecordBatch::try_new(Arc::new(Schema::new(fields)), columns) + .map_err(|e| OmniError::Lance(e.to_string())) } fn take_batch(batch: &RecordBatch, indices: &UInt32Array) -> Result { - let columns: Vec = batch.columns().iter() + let columns: Vec = batch + .columns() + .iter() .map(|col| arrow_select::take::take(col.as_ref(), indices, None)) .collect::, _>>() .map_err(|e| OmniError::Lance(e.to_string()))?; diff --git a/crates/omnigraph/src/exec/staging.rs b/crates/omnigraph/src/exec/staging.rs index ad39bc0..0d26fd3 100644 --- a/crates/omnigraph/src/exec/staging.rs +++ b/crates/omnigraph/src/exec/staging.rs @@ -26,10 +26,10 @@ use arrow_schema::SchemaRef; use lance::Dataset; use omnigraph_compiler::catalog::EdgeType; -use crate::db::{MutationOpKind, SubTableUpdate}; use crate::db::manifest::{ - new_sidecar, write_sidecar, RecoverySidecarHandle, SidecarKind, SidecarTablePin, + RecoverySidecarHandle, SidecarKind, SidecarTablePin, new_sidecar, write_sidecar, }; +use crate::db::{MutationOpKind, SubTableUpdate}; use crate::error::{OmniError, Result}; /// Whether the per-table accumulator should commit via `stage_append` @@ -119,10 +119,12 @@ impl MutationStaging { expected_version: u64, op_kind: MutationOpKind, ) { - self.paths.entry(table_key.to_string()).or_insert(StagedTablePath { - full_path, - table_branch, - }); + self.paths + .entry(table_key.to_string()) + .or_insert(StagedTablePath { + full_path, + table_branch, + }); self.expected_versions .entry(table_key.to_string()) .or_insert(expected_version); @@ -202,7 +204,8 @@ impl MutationStaging { /// Record a delete that already inline-committed at the Lance layer. pub(crate) fn record_inline(&mut self, update: SubTableUpdate) { - self.inline_committed.insert(update.table_key.clone(), update); + self.inline_committed + .insert(update.table_key.clone(), update); } /// Read-your-writes accessor: the accumulated pending batches for @@ -308,18 +311,13 @@ impl MutationStaging { // mode is exempt because no-key node and edge inserts use // ULID-generated ids that are unique within a query. let combined = match table.mode { - PendingMode::Merge => { - dedupe_merge_batches_by_id(&table.schema, table.batches)? - } + PendingMode::Merge => dedupe_merge_batches_by_id(&table.schema, table.batches)?, PendingMode::Append => { if table.batches.len() == 1 { table.batches.into_iter().next().unwrap() } else { - arrow_select::concat::concat_batches( - &table.schema, - &table.batches, - ) - .map_err(|e| OmniError::Lance(e.to_string()))? + arrow_select::concat::concat_batches(&table.schema, &table.batches) + .map_err(|e| OmniError::Lance(e.to_string()))? } } }; @@ -327,9 +325,7 @@ impl MutationStaging { // Stage produces uncommitted fragments + transaction. No // Lance HEAD advance until `commit_all` runs `commit_staged`. let staged = match table.mode { - PendingMode::Append => { - db.table_store().stage_append(&ds, combined, &[]).await? - } + PendingMode::Append => db.table_store().stage_append(&ds, combined, &[]).await?, PendingMode::Merge => { db.table_store() .stage_merge_insert( @@ -420,7 +416,7 @@ impl StagedMutation { /// /// Revalidation: between `stage_all` and `commit_all`, another /// writer (in the same process or another process sharing the - /// repo) may have committed to one of our touched tables, advancing + /// graph) may have committed to one of our touched tables, advancing /// the manifest pin past our `expected_version`. We revalidate /// under the queue and fail-fast with `manifest_conflict` before /// any `commit_staged` so the orphaned uncommitted fragments stay @@ -462,9 +458,8 @@ impl StagedMutation { // from interleaving between our delete and our publish, which // would otherwise leave a Lance-HEAD-ahead residual the // delete-only sidecar (added below) would have to recover. - let mut queue_keys: Vec<(String, Option)> = Vec::with_capacity( - staged.len() + inline_committed.len(), - ); + let mut queue_keys: Vec<(String, Option)> = + Vec::with_capacity(staged.len() + inline_committed.len()); for entry in &staged { queue_keys.push((entry.table_key.clone(), entry.path.table_branch.clone())); } @@ -565,9 +560,8 @@ impl StagedMutation { // Finding 3 hazard: delete-only mutations would otherwise skip // the sidecar, leaving any commit→publish residual unreachable // by recovery. - let mut pins: Vec = Vec::with_capacity( - staged.len() + inline_committed.len(), - ); + let mut pins: Vec = + Vec::with_capacity(staged.len() + inline_committed.len()); for entry in &staged { pins.push(SidecarTablePin { table_key: entry.table_key.clone(), @@ -899,10 +893,7 @@ pub(crate) async fn count_src_per_edge( /// Count pending edges per `src` with NO dedup. Correct when caller /// guarantees pending rows have unique primary keys (engine inserts via /// fresh ULID; loader Append mode). -fn count_pending_src_naive( - pending_batches: &[RecordBatch], - counts: &mut HashMap, -) { +fn count_pending_src_naive(pending_batches: &[RecordBatch], counts: &mut HashMap) { for batch in pending_batches { let Some(col) = batch.column_by_name("src") else { continue; @@ -947,12 +938,15 @@ fn count_pending_src_with_dedupe( dedupe_key_column ))); }; - let key_arr = key_col.as_any().downcast_ref::().ok_or_else(|| { - OmniError::Lance(format!( - "count_src_per_edge: pending '{}' column is not Utf8", - dedupe_key_column - )) - })?; + let key_arr = key_col + .as_any() + .downcast_ref::() + .ok_or_else(|| { + OmniError::Lance(format!( + "count_src_per_edge: pending '{}' column is not Utf8", + dedupe_key_column + )) + })?; let src_arr = batch .column_by_name("src") .and_then(|c| c.as_any().downcast_ref::()); diff --git a/crates/omnigraph/src/loader/mod.rs b/crates/omnigraph/src/loader/mod.rs index 878dcfe..46a46e2 100644 --- a/crates/omnigraph/src/loader/mod.rs +++ b/crates/omnigraph/src/loader/mod.rs @@ -212,12 +212,7 @@ impl Omnigraph { .await } - pub async fn load_file( - &self, - branch: &str, - path: &str, - mode: LoadMode, - ) -> Result { + pub async fn load_file(&self, branch: &str, path: &str, mode: LoadMode) -> Result { self.load_file_as(branch, path, mode, None).await } @@ -457,13 +452,7 @@ async fn load_jsonl_reader( for (edge_name, rows) in &edge_rows { let edge_type = &catalog.edge_types[edge_name]; let from_ids = if use_staging { - collect_node_ids_with_pending( - db, - branch, - &edge_type.from_type, - &staging, - ) - .await? + collect_node_ids_with_pending(db, branch, &edge_type.from_type, &staging).await? } else { collect_node_ids( db, @@ -476,13 +465,7 @@ async fn load_jsonl_reader( .await? }; let to_ids = if use_staging { - collect_node_ids_with_pending( - db, - branch, - &edge_type.to_type, - &staging, - ) - .await? + collect_node_ids_with_pending(db, branch, &edge_type.to_type, &staging).await? } else { collect_node_ids( db, @@ -581,12 +564,7 @@ async fn load_jsonl_reader( let table_key = format!("edge:{}", edge_name); if use_staging { validate_edge_cardinality_with_pending_loader( - db, - branch, - edge_type, - &table_key, - &staging, - mode, + db, branch, edge_type, &table_key, &staging, mode, ) .await?; } else if let Some(update) = overwrite_updates.iter().find(|u| u.table_key == table_key) { @@ -635,7 +613,7 @@ async fn load_jsonl_reader( } else { // LoadMode::Overwrite keeps the legacy inline-commit path — // truncate-then-append doesn't fit the staged shape (see - // `docs/runs.md` "LoadMode::Overwrite residual"). The recovery + // `docs/dev/writes.md` "LoadMode::Overwrite residual"). The recovery // sidecar is not applicable here because the writer doesn't go // through MutationStaging; per-table inline commits + a final // manifest publish handle their own residual via the documented @@ -1699,8 +1677,7 @@ async fn validate_edge_cardinality_with_pending_loader( LoadMode::Append | LoadMode::Overwrite => None, }; let counts = - crate::exec::staging::count_src_per_edge(db, &ds, table_key, staging, dedupe_key) - .await?; + crate::exec::staging::count_src_per_edge(db, &ds, table_key, staging, dedupe_key).await?; crate::exec::staging::enforce_cardinality_bounds(edge_type, &counts) } diff --git a/crates/omnigraph/src/storage.rs b/crates/omnigraph/src/storage.rs index 5d2e568..564b577 100644 --- a/crates/omnigraph/src/storage.rs +++ b/crates/omnigraph/src/storage.rs @@ -7,7 +7,8 @@ use async_trait::async_trait; use futures::TryStreamExt; use object_store::aws::AmazonS3Builder; use object_store::path::Path as ObjectPath; -use object_store::{DynObjectStore, ObjectStore, PutPayload}; +use object_store::{DynObjectStore, ObjectStore, PutMode, PutPayload}; +use tokio::io::AsyncWriteExt; use url::Url; use crate::error::{OmniError, Result}; @@ -19,6 +20,13 @@ const S3_SCHEME_PREFIX: &str = "s3://"; pub trait StorageAdapter: Debug + Send + Sync { async fn read_text(&self, uri: &str) -> Result; async fn write_text(&self, uri: &str, contents: &str) -> Result<()>; + /// Write a text object only if no object exists at `uri`. + /// + /// Returns `Ok(true)` when this call created the object, `Ok(false)` + /// when the object already existed, and propagates every other storage + /// error. Callers use this to establish ownership before running + /// best-effort cleanup on partial failure. + async fn write_text_if_absent(&self, uri: &str, contents: &str) -> Result; async fn exists(&self, uri: &str) -> Result; /// Move a file from `from_uri` to `to_uri`, replacing any existing file at /// `to_uri`. Atomic on local POSIX; on S3 implemented as copy + delete @@ -66,7 +74,7 @@ impl StorageAdapter for LocalStorageAdapter { // Ensure parent directory exists. S3 has no equivalent (PutObject // is path-agnostic). For local fs, callers like the recovery // sidecar protocol expect transparent directory creation under - // the repo root (the `__recovery/` directory doesn't pre-exist; + // the graph root (the `__recovery/` directory doesn't pre-exist; // first sidecar write creates it). if let Some(parent) = path.parent() { if !parent.as_os_str().is_empty() { @@ -77,6 +85,30 @@ impl StorageAdapter for LocalStorageAdapter { Ok(()) } + async fn write_text_if_absent(&self, uri: &str, contents: &str) -> Result { + let path = local_path_from_uri(uri)?; + if let Some(parent) = path.parent() { + if !parent.as_os_str().is_empty() { + tokio::fs::create_dir_all(parent).await?; + } + } + let mut file = match tokio::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .await + { + Ok(file) => file, + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false), + Err(err) => return Err(err.into()), + }; + if let Err(err) = file.write_all(contents.as_bytes()).await { + let _ = tokio::fs::remove_file(&path).await; + return Err(err.into()); + } + Ok(true) + } + async fn exists(&self, uri: &str) -> Result { Ok(local_path_from_uri(uri)?.exists()) } @@ -146,6 +178,24 @@ impl StorageAdapter for S3StorageAdapter { Ok(()) } + async fn write_text_if_absent(&self, uri: &str, contents: &str) -> Result { + let location = self.object_path(uri)?; + match self + .store + .put_opts( + &location, + PutPayload::from(contents.as_bytes().to_vec()), + PutMode::Create.into(), + ) + .await + { + Ok(_) => Ok(true), + Err(object_store::Error::AlreadyExists { .. }) + | Err(object_store::Error::Precondition { .. }) => Ok(false), + Err(err) => Err(storage_backend_error("write_if_absent", uri, err)), + } + } + async fn exists(&self, uri: &str) -> Result { let location = self.object_path(uri)?; match self.store.head(&location).await { @@ -398,10 +448,13 @@ mod tests { #[test] fn storage_backend_selection_is_scheme_aware() { - assert_eq!(storage_kind_for_uri("/tmp/repo"), StorageKind::Local); - assert_eq!(storage_kind_for_uri("file:///tmp/repo"), StorageKind::Local); + assert_eq!(storage_kind_for_uri("/tmp/graph"), StorageKind::Local); assert_eq!( - storage_kind_for_uri("s3://omnigraph-preview/repo"), + storage_kind_for_uri("file:///tmp/graph"), + StorageKind::Local + ); + assert_eq!( + storage_kind_for_uri("s3://omnigraph-preview/graph"), StorageKind::S3 ); } @@ -440,8 +493,20 @@ mod tests { #[test] fn parse_s3_uri_splits_bucket_and_key() { - let location = parse_s3_uri("s3://bucket/repo/_schema.pg").unwrap(); + let location = parse_s3_uri("s3://bucket/graph/_schema.pg").unwrap(); assert_eq!(location.bucket, "bucket"); - assert_eq!(location.key, "repo/_schema.pg"); + assert_eq!(location.key, "graph/_schema.pg"); + } + + #[tokio::test] + async fn local_write_text_if_absent_creates_once_without_overwrite() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().join("claim.txt"); + let uri = uri.to_str().unwrap(); + let storage = LocalStorageAdapter; + + assert!(storage.write_text_if_absent(uri, "first").await.unwrap()); + assert!(!storage.write_text_if_absent(uri, "second").await.unwrap()); + assert_eq!(storage.read_text(uri).await.unwrap(), "first"); } } diff --git a/crates/omnigraph/src/storage_layer.rs b/crates/omnigraph/src/storage_layer.rs index b0fc042..dac9482 100644 --- a/crates/omnigraph/src/storage_layer.rs +++ b/crates/omnigraph/src/storage_layer.rs @@ -94,7 +94,9 @@ impl SnapshotHandle { /// Construct from a Lance dataset. `pub(crate)` — only /// `TableStore` should produce these. pub(crate) fn new(ds: Dataset) -> Self { - Self { inner: Arc::new(ds) } + Self { + inner: Arc::new(ds), + } } /// Borrow the underlying Lance dataset. `pub(crate)` so only the @@ -242,16 +244,10 @@ pub trait TableStorage: sealed::Sealed + Send + Sync + Debug { async fn scan_batches(&self, snapshot: &SnapshotHandle) -> Result>; - async fn scan_batches_for_rewrite( - &self, - snapshot: &SnapshotHandle, - ) -> Result>; + async fn scan_batches_for_rewrite(&self, snapshot: &SnapshotHandle) + -> Result>; - async fn count_rows( - &self, - snapshot: &SnapshotHandle, - filter: Option, - ) -> Result; + async fn count_rows(&self, snapshot: &SnapshotHandle, filter: Option) -> Result; async fn count_rows_with_staged( &self, @@ -284,11 +280,8 @@ pub trait TableStorage: sealed::Sealed + Send + Sync + Debug { filter: &str, ) -> Result>; - async fn table_state( - &self, - dataset_uri: &str, - snapshot: &SnapshotHandle, - ) -> Result; + async fn table_state(&self, dataset_uri: &str, snapshot: &SnapshotHandle) + -> Result; // ── Staged writes (no HEAD advance) ──────────────────────────────── @@ -565,11 +558,7 @@ impl TableStorage for TableStore { TableStore::scan_batches_for_rewrite(self, snapshot.dataset()).await } - async fn count_rows( - &self, - snapshot: &SnapshotHandle, - filter: Option, - ) -> Result { + async fn count_rows(&self, snapshot: &SnapshotHandle, filter: Option) -> Result { TableStore::count_rows(self, snapshot.dataset(), filter).await } @@ -591,14 +580,8 @@ impl TableStorage for TableStore { filter: Option<&str>, ) -> Result> { let staged_writes = staged_handles_as_writes(staged); - TableStore::scan_with_staged( - self, - snapshot.dataset(), - &staged_writes, - projection, - filter, - ) - .await + TableStore::scan_with_staged(self, snapshot.dataset(), &staged_writes, projection, filter) + .await } async fn scan_with_pending( @@ -658,18 +641,10 @@ impl TableStorage for TableStore { when_matched: WhenMatched, when_not_matched: WhenNotMatched, ) -> Result { - let ds = Arc::try_unwrap(snapshot.into_arc()) - .unwrap_or_else(|arc| (*arc).clone()); - TableStore::stage_merge_insert( - self, - ds, - batch, - key_columns, - when_matched, - when_not_matched, - ) - .await - .map(StagedHandle::new) + let ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); + TableStore::stage_merge_insert(self, ds, batch, key_columns, when_matched, when_not_matched) + .await + .map(StagedHandle::new) } async fn commit_staged( @@ -720,8 +695,7 @@ impl TableStorage for TableStore { snapshot: SnapshotHandle, batch: RecordBatch, ) -> Result<(SnapshotHandle, TableState)> { - let mut ds = Arc::try_unwrap(snapshot.into_arc()) - .unwrap_or_else(|arc| (*arc).clone()); + let mut ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); let state = TableStore::append_batch(self, dataset_uri, &mut ds, batch).await?; Ok((SnapshotHandle::new(ds), state)) } @@ -735,8 +709,7 @@ impl TableStorage for TableStore { when_matched: WhenMatched, when_not_matched: WhenNotMatched, ) -> Result { - let ds = Arc::try_unwrap(snapshot.into_arc()) - .unwrap_or_else(|arc| (*arc).clone()); + let ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); TableStore::merge_insert_batches( self, dataset_uri, @@ -755,8 +728,7 @@ impl TableStorage for TableStore { snapshot: SnapshotHandle, batch: RecordBatch, ) -> Result<(SnapshotHandle, TableState)> { - let mut ds = Arc::try_unwrap(snapshot.into_arc()) - .unwrap_or_else(|arc| (*arc).clone()); + let mut ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); let state = TableStore::overwrite_batch(self, dataset_uri, &mut ds, batch).await?; Ok((SnapshotHandle::new(ds), state)) } @@ -767,8 +739,7 @@ impl TableStorage for TableStore { snapshot: SnapshotHandle, filter: &str, ) -> Result<(SnapshotHandle, DeleteState)> { - let mut ds = Arc::try_unwrap(snapshot.into_arc()) - .unwrap_or_else(|arc| (*arc).clone()); + let mut ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); let state = TableStore::delete_where(self, dataset_uri, &mut ds, filter).await?; Ok((SnapshotHandle::new(ds), state)) } @@ -790,8 +761,7 @@ impl TableStorage for TableStore { snapshot: SnapshotHandle, columns: &[&str], ) -> Result { - let mut ds = Arc::try_unwrap(snapshot.into_arc()) - .unwrap_or_else(|arc| (*arc).clone()); + let mut ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); TableStore::create_btree_index(self, &mut ds, columns).await?; Ok(SnapshotHandle::new(ds)) } @@ -801,8 +771,7 @@ impl TableStorage for TableStore { snapshot: SnapshotHandle, column: &str, ) -> Result { - let mut ds = Arc::try_unwrap(snapshot.into_arc()) - .unwrap_or_else(|arc| (*arc).clone()); + let mut ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); TableStore::create_inverted_index(self, &mut ds, column).await?; Ok(SnapshotHandle::new(ds)) } @@ -812,8 +781,7 @@ impl TableStorage for TableStore { snapshot: SnapshotHandle, column: &str, ) -> Result { - let mut ds = Arc::try_unwrap(snapshot.into_arc()) - .unwrap_or_else(|arc| (*arc).clone()); + let mut ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); TableStore::create_vector_index(self, &mut ds, column).await?; Ok(SnapshotHandle::new(ds)) } @@ -837,6 +805,13 @@ impl TableStorage for TableStore { // Note: existing TableStore::scan_stream is an associated fn that // takes &Dataset, so we delegate via the dataset reference held by // the snapshot. - TableStore::scan_stream(snapshot.dataset(), projection, filter, order_by, with_row_id).await + TableStore::scan_stream( + snapshot.dataset(), + projection, + filter, + order_by, + with_row_id, + ) + .await } } diff --git a/crates/omnigraph/src/table_store.rs b/crates/omnigraph/src/table_store.rs index c896b05..10123b0 100644 --- a/crates/omnigraph/src/table_store.rs +++ b/crates/omnigraph/src/table_store.rs @@ -49,7 +49,7 @@ pub struct DeleteState { /// `exec/mutation.rs`) and the bulk loader (`loader/mod.rs`). The /// intent: defer Lance commits to end-of-query so a mid-query failure /// leaves the touched table at the pre-mutation HEAD instead of -/// drifting ahead. See `docs/runs.md` for the publisher-CAS contract +/// drifting ahead. See `docs/dev/writes.md` for the publisher-CAS contract /// this builds on. /// /// `transaction` is opaque from our side — Lance owns its semantics. We @@ -177,6 +177,45 @@ impl TableStore { .map_err(|e| OmniError::Lance(e.to_string())) } + /// List the named Lance branches present on the dataset at `dataset_uri`. + /// The `cleanup` orphan reconciler diffs this against the manifest branch + /// set to find orphaned per-table forks. `main`/default is not a named + /// branch and never appears here. + pub async fn list_branches(&self, dataset_uri: &str) -> Result> { + let ds = Dataset::open(dataset_uri) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + let branches = ds + .list_branches() + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + Ok(branches.into_keys().collect()) + } + + /// Idempotently drop `branch` from the dataset at `dataset_uri`. + /// + /// Unlike [`delete_branch`](Self::delete_branch), this tolerates an + /// already-absent branch — both a missing contents ref (Lance's + /// `force_delete_branch` handles that) and a missing `tree/{branch}/` + /// directory (the local-store `NotFound` quirk pinned by + /// `lance_surface_guards::force_delete_branch_semantics`). Safe to call on a + /// possibly-orphaned or already-reclaimed fork. + /// + /// A branch that still has referencing descendants (`RefConflict`) is NOT + /// tolerated: that is a real ordering error and surfaces as `OmniError::Lance`. + /// Used by the eager best-effort reclaim in `cleanup_deleted_branch_tables` + /// and the `cleanup` orphan reconciler. + pub async fn force_delete_branch(&self, dataset_uri: &str, branch: &str) -> Result<()> { + let mut ds = Dataset::open(dataset_uri) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + match ds.force_delete_branch(branch).await { + Ok(()) => Ok(()), + Err(lance::Error::RefNotFound { .. }) | Err(lance::Error::NotFound { .. }) => Ok(()), + Err(e) => Err(OmniError::Lance(e.to_string())), + } + } + pub async fn open_dataset_at_state( &self, table_path: &str, @@ -243,21 +282,24 @@ impl TableStore { .map_err(|e| OmniError::Lance(e.to_string()))?; self.ensure_expected_version(&source_ds, table_key, source_version)?; - match source_ds + if source_ds .create_branch(target_branch, source_version, None) .await + .is_err() { - Ok(_) => {} - Err(create_err) => match self - .open_dataset_head(dataset_uri, Some(target_branch)) - .await - { - Ok(ds) => { - self.ensure_expected_version(&ds, table_key, source_version)?; - return Ok(ds); - } - Err(_) => return Err(OmniError::Lance(create_err.to_string())), - }, + // The target branch ref already exists. The caller + // (`open_owned_dataset_for_branch_write`) re-reads the live manifest + // before forking and returns a retryable error when a concurrent + // writer legitimately holds the fork, so reaching here means the + // manifest does NOT reference this fork: it is an orphan from an + // incomplete prior `branch_delete`. Surface the actionable cleanup + // error rather than guessing from Lance branch versions. + return Err(OmniError::manifest_conflict(format!( + "branch '{}' has orphaned table state for '{}' from an incomplete \ + prior delete; run `omnigraph cleanup` to reclaim it before reusing \ + this branch name", + target_branch, table_key + ))); } let ds = self @@ -901,7 +943,7 @@ impl TableStore { /// Lift path: either a Lance API extension that lets /// `MergeInsertBuilder` accept additional staged fragments, or an /// in-memory pre-merge here that folds prior staged batches into the - /// input stream. See `docs/runs.md`. + /// input stream. See `docs/dev/writes.md`. pub async fn stage_merge_insert( &self, ds: Dataset, @@ -1793,25 +1835,24 @@ mod tests { #[test] fn check_batch_unique_by_keys_errors_on_duplicate_id() { let batch = batch_with_ids(&["a", "b", "a"]); - let err = - check_batch_unique_by_keys(&batch, &["id".to_string()], "test").unwrap_err(); + let err = check_batch_unique_by_keys(&batch, &["id".to_string()], "test").unwrap_err(); let msg = err.to_string(); assert!( msg.contains("duplicate source row for key 'a'"), "unexpected error: {msg}" ); - assert!(msg.contains("MR-957"), "error should reference MR-957: {msg}"); + assert!( + msg.contains("MR-957"), + "error should reference MR-957: {msg}" + ); } #[test] fn check_batch_unique_by_keys_rejects_multi_column_keys() { let batch = batch_with_ids(&["a"]); - let err = check_batch_unique_by_keys( - &batch, - &["id".to_string(), "other".to_string()], - "test", - ) - .unwrap_err(); + let err = + check_batch_unique_by_keys(&batch, &["id".to_string(), "other".to_string()], "test") + .unwrap_err(); assert!(err.to_string().contains("single-column keys only")); } } diff --git a/crates/omnigraph/tests/composite_flow.rs b/crates/omnigraph/tests/composite_flow.rs index 63ec8b2..6c720da 100644 --- a/crates/omnigraph/tests/composite_flow.rs +++ b/crates/omnigraph/tests/composite_flow.rs @@ -56,7 +56,7 @@ async fn composite_flow_canonical_lifecycle() { let uri = dir.path().to_str().unwrap(); // ───────────────────────────────────────────────────────────────── - // Step 1: init a fresh repo with the standard test schema. + // Step 1: init a fresh graph with the standard test schema. // ───────────────────────────────────────────────────────────────── let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); let v_init = version_branch(&db, "main").await.unwrap(); @@ -70,7 +70,9 @@ async fn composite_flow_canonical_lifecycle() { // Step 2: load JSONL seed data (Person + Company nodes, // Knows + WorksAt edges). // ───────────────────────────────────────────────────────────────── - load_jsonl(&mut db, TEST_DATA, LoadMode::Append).await.unwrap(); + load_jsonl(&mut db, TEST_DATA, LoadMode::Append) + .await + .unwrap(); let v_after_load = version_branch(&db, "main").await.unwrap(); assert!( v_after_load > v_init, @@ -119,19 +121,13 @@ async fn composite_flow_canonical_lifecycle() { "feature", MUTATION_QUERIES, "insert_person_and_friend", - &mixed_params( - &[("$name", "Frank"), ("$friend", "Eve")], - &[("$age", 33)], - ), + &mixed_params(&[("$name", "Frank"), ("$friend", "Eve")], &[("$age", 33)]), ) .await .expect("multi-statement insert+edge on feature"); // After: feature has 4 + Eve + Frank = 6 Persons. - let snap = db - .snapshot_of(ReadTarget::branch("feature")) - .await - .unwrap(); + let snap = db.snapshot_of(ReadTarget::branch("feature")).await.unwrap(); let person_ds = snap.open("node:Person").await.unwrap(); assert_eq!( person_ds.count_rows(None).await.unwrap(), @@ -321,14 +317,10 @@ async fn composite_flow_canonical_lifecycle() { ); // Re-run a query to verify post-optimize correctness. - let post_optimize_total = query_main( - &mut db, - TEST_QUERIES, - "total_people", - &ParamMap::default(), - ) - .await - .unwrap(); + let post_optimize_total = + query_main(&mut db, TEST_QUERIES, "total_people", &ParamMap::default()) + .await + .unwrap(); assert!( !post_optimize_total.batches().is_empty(), "queries must still work after optimize" @@ -385,14 +377,9 @@ async fn composite_flow_canonical_lifecycle() { // post-cleanup. Post-cleanup mutation is omitted here pending // resolution of the optimize-vs-manifest-pin interaction documented // in Step 10. - let final_total = query_main( - &mut db, - TEST_QUERIES, - "total_people", - &ParamMap::default(), - ) - .await - .unwrap(); + let final_total = query_main(&mut db, TEST_QUERIES, "total_people", &ParamMap::default()) + .await + .unwrap(); assert!(!final_total.batches().is_empty()); } @@ -431,10 +418,12 @@ async fn composite_flow_schema_apply_then_branch_ops_no_deadlock_in_refresh() { // Step 1: init + load on handle A. let mut db_a = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db_a, TEST_DATA, LoadMode::Append).await.unwrap(); + load_jsonl(&mut db_a, TEST_DATA, LoadMode::Append) + .await + .unwrap(); assert_eq!(count_rows(&db_a, "node:Person").await, 4); - // Step 2: open handle B on the same repo. B's in-memory schema_source + // Step 2: open handle B on the same graph. B's in-memory schema_source // cache is now a snapshot of `_schema.pg` at open time. let db_b = Omnigraph::open(uri).await.unwrap(); @@ -444,7 +433,7 @@ async fn composite_flow_schema_apply_then_branch_ops_no_deadlock_in_refresh() { // to disk. const TEST_SCHEMA_V2: &str = "node Person {\n name: String @key\n age: I32?\n nickname: String?\n}\n\nnode Company {\n name: String @key\n}\n\nedge Knows: Person -> Person {\n since: Date?\n}\n\nedge WorksAt: Person -> Company\n"; let plan = db_a.apply_schema(TEST_SCHEMA_V2).await.unwrap(); - assert!(plan.applied, "apply_schema must succeed on a clean repo"); + assert!(plan.applied, "apply_schema must succeed on a clean graph"); assert!( !plan.steps.is_empty(), "apply_schema must record the AddProperty step" @@ -561,7 +550,9 @@ async fn composite_flow_multi_branch_sequential_merges() { // edges from test.jsonl). // ───────────────────────────────────────────────────────────────── let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, TEST_DATA, LoadMode::Append).await.unwrap(); + load_jsonl(&mut db, TEST_DATA, LoadMode::Append) + .await + .unwrap(); assert_eq!(count_rows(&db, "node:Person").await, 4); assert_eq!(count_rows(&db, "edge:Knows").await, 3); @@ -687,10 +678,7 @@ async fn composite_flow_multi_branch_sequential_merges() { "feat-a", MUTATION_QUERIES, "insert_person_and_friend", - &mixed_params( - &[("$name", "Grace"), ("$friend", "Eve")], - &[("$age", 28)], - ), + &mixed_params(&[("$name", "Grace"), ("$friend", "Eve")], &[("$age", 28)]), ) .await .expect("insert Grace + Knows(Grace → Eve) on feat-a"); @@ -821,15 +809,14 @@ async fn composite_flow_multi_branch_sequential_merges() { // `total_people` returns count(Person) = 10. Catches regressions in // group-by/count execution against a multi-fragment table whose // current shape was produced by two sequential merges. - let total_post_merges = query_main( - &mut db, - TEST_QUERIES, - "total_people", - &ParamMap::default(), - ) - .await - .unwrap(); - assert_total(&total_post_merges, 10, "post both merges, main must total 10 Persons"); + let total_post_merges = query_main(&mut db, TEST_QUERIES, "total_people", &ParamMap::default()) + .await + .unwrap(); + assert_total( + &total_post_merges, + 10, + "post both merges, main must total 10 Persons", + ); // ───────────────────────────────────────────────────────────────── // Step 14: time-travel to pre-merge-a-version. Reads must return @@ -1021,14 +1008,9 @@ async fn composite_flow_multi_branch_sequential_merges() { // correctly to disk but the reopened catalog can't bind them. // ───────────────────────────────────────────────────────────────── let mut db = db; - let post_reopen_total = query_main( - &mut db, - TEST_QUERIES, - "total_people", - &ParamMap::default(), - ) - .await - .unwrap(); + let post_reopen_total = query_main(&mut db, TEST_QUERIES, "total_people", &ParamMap::default()) + .await + .unwrap(); assert_total( &post_reopen_total, 10, diff --git a/crates/omnigraph/tests/consistency.rs b/crates/omnigraph/tests/consistency.rs index 8986ecb..26517db 100644 --- a/crates/omnigraph/tests/consistency.rs +++ b/crates/omnigraph/tests/consistency.rs @@ -292,13 +292,11 @@ node Thing { .await .expect("first merge after ensure_indices must succeed"); db.ensure_indices().await.unwrap(); - load_jsonl(&mut db, &delta, LoadMode::Merge) - .await - .expect( - "second merge after ensure_indices must succeed \ + load_jsonl(&mut db, &delta, LoadMode::Merge).await.expect( + "second merge after ensure_indices must succeed \ (Window 2 canary: drop the FirstSeen setter in table_store.rs \ only when this stays green WITHOUT it)", - ); + ); assert_eq!(count_rows(&db, "node:Thing").await, 55); } @@ -346,7 +344,7 @@ async fn explicit_target_query_sees_other_writer_commits_without_refresh() { let uri = dir.path().to_str().unwrap(); - // Two independent handles to the same repo + // Two independent handles to the same graph let mut db1 = Omnigraph::open(uri).await.unwrap(); let mut db2 = Omnigraph::open(uri).await.unwrap(); diff --git a/crates/omnigraph/tests/end_to_end.rs b/crates/omnigraph/tests/end_to_end.rs index 0d9e58e..a0fdb0e 100644 --- a/crates/omnigraph/tests/end_to_end.rs +++ b/crates/omnigraph/tests/end_to_end.rs @@ -1910,9 +1910,14 @@ query docs_with_tag($tag: String) { return { $d.slug } } "#; - let result = query_main(&mut db, queries, "docs_with_tag", ¶ms(&[("$tag", "red")])) - .await - .unwrap(); + let result = query_main( + &mut db, + queries, + "docs_with_tag", + ¶ms(&[("$tag", "red")]), + ) + .await + .unwrap(); let batch = result.concat_batches().unwrap(); let slugs = batch diff --git a/crates/omnigraph/tests/failpoints.rs b/crates/omnigraph/tests/failpoints.rs index a38f0bb..149c63a 100644 --- a/crates/omnigraph/tests/failpoints.rs +++ b/crates/omnigraph/tests/failpoints.rs @@ -41,6 +41,452 @@ async fn branch_create_failpoint_triggers() { ); } +// Branch delete flips the manifest authority first, then reclaims the per-table +// forks best-effort. A failure during that reclaim (here, the +// `branch_delete.before_table_cleanup` failpoint, standing in for a transient +// object-store error) must NOT fail the call: the branch is already gone, and +// `cleanup` reconciles the stranded fork. The branch name is reusable after. +#[tokio::test] +async fn branch_delete_partial_failure_converges_via_cleanup() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap().to_string(); + let mut main = helpers::init_and_load(&dir).await; + + main.branch_create("feature").await.unwrap(); + let mut feature = Omnigraph::open(&uri).await.unwrap(); + helpers::mutate_branch( + &mut feature, + "feature", + MUTATION_QUERIES, + "insert_person", + &mixed_params(&[("$name", "Eve")], &[("$age", 22)]), + ) + .await + .unwrap(); + drop(feature); + + let person_uri = node_table_uri(&uri, "Person"); + { + let ds = lance::Dataset::open(&person_uri).await.unwrap(); + assert!( + ds.list_branches().await.unwrap().contains_key("feature"), + "precondition: the owned table fork exists before delete" + ); + } + + // Inject a failure during per-table cleanup, AFTER the manifest authority + // flip. branch_delete must still succeed (best-effort reclaim). + { + let _fp = ScopedFailPoint::new("branch_delete.before_table_cleanup", "return"); + main.branch_delete("feature").await.expect( + "branch_delete is best-effort after the manifest flip: a cleanup-step \ + failure must not fail the call", + ); + } + + // Authority flipped: the branch is gone. + assert_eq!(main.branch_list().await.unwrap(), vec!["main".to_string()]); + + // The eager reclaim failed, so the orphan is stranded until cleanup. + { + let ds = lance::Dataset::open(&person_uri).await.unwrap(); + assert!( + ds.list_branches().await.unwrap().contains_key("feature"), + "failed eager reclaim should leave the orphan for cleanup to reconcile" + ); + } + + // cleanup converges: the orphan is reclaimed. + main.cleanup(omnigraph::db::CleanupPolicyOptions { + keep_versions: Some(1), + older_than: None, + }) + .await + .unwrap(); + { + let ds = lance::Dataset::open(&person_uri).await.unwrap(); + assert!( + !ds.list_branches().await.unwrap().contains_key("feature"), + "cleanup should reconcile the orphaned fork away" + ); + } + + // The name is reusable after cleanup reclaims the orphan. + main.branch_create("feature").await.unwrap(); + let mut feature2 = Omnigraph::open(&uri).await.unwrap(); + helpers::mutate_branch( + &mut feature2, + "feature", + MUTATION_QUERIES, + "insert_person", + &mixed_params(&[("$name", "Frank")], &[("$age", 41)]), + ) + .await + .unwrap(); +} + +// Reusing a branch name whose delete left an orphaned fork (before `cleanup` +// reconciles it) must fail with a clear, actionable error pointing at +// `cleanup`, not the opaque `ExpectedVersionMismatch` that leaks from the fork +// path. The recreate itself succeeds; the first write to the previously-forked +// table is where the stale orphan collides. +#[tokio::test] +async fn recreate_over_orphaned_fork_before_cleanup_is_actionable() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap().to_string(); + let mut main = helpers::init_and_load(&dir).await; + + main.branch_create("feature").await.unwrap(); + let mut feature = Omnigraph::open(&uri).await.unwrap(); + helpers::mutate_branch( + &mut feature, + "feature", + MUTATION_QUERIES, + "insert_person", + &mixed_params(&[("$name", "Eve")], &[("$age", 22)]), + ) + .await + .unwrap(); + drop(feature); + + // Partial delete: leaves the Person fork orphaned (cleanup not yet run). + { + let _fp = ScopedFailPoint::new("branch_delete.before_table_cleanup", "return"); + main.branch_delete("feature").await.unwrap(); + } + + // Recreate the name and write to the previously-forked table WITHOUT a + // cleanup in between. + main.branch_create("feature").await.unwrap(); + let mut feature2 = Omnigraph::open(&uri).await.unwrap(); + let err = helpers::mutate_branch( + &mut feature2, + "feature", + MUTATION_QUERIES, + "insert_person", + &mixed_params(&[("$name", "Frank")], &[("$age", 41)]), + ) + .await + .expect_err("write should collide with the stale orphaned fork"); + + let msg = err.to_string(); + assert!( + msg.contains("cleanup") + && (msg.contains("orphan") || msg.contains("incomplete prior delete")), + "expected an actionable orphaned-fork error pointing at cleanup, got: {msg}" + ); + assert!( + !msg.contains("expected manifest table version"), + "should not surface the opaque ExpectedVersionMismatch, got: {msg}" + ); +} + +// cleanup is the guaranteed convergence backstop, so one table's transient +// failure must not abort the whole sweep. Inject a one-shot version-GC failure +// for a single table and assert: cleanup still succeeds, the failure is +// surfaced per-table in the returned stats, and the independent reconcile pass +// still reclaimed an orphan. +#[tokio::test] +async fn cleanup_isolates_single_table_failure() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap().to_string(); + let mut db = helpers::init_and_load(&dir).await; + + // Forge an orphaned fork on the Person table (a reconcile target). + let person_uri = node_table_uri(&uri, "Person"); + { + let mut ds = lance::Dataset::open(&person_uri).await.unwrap(); + let base = ds.version().version; + ds.create_branch("ghost", base, None).await.unwrap(); + } + + // One table's version GC fails once; the sweep must isolate it. + let _fp = ScopedFailPoint::new("cleanup.table_gc", "1*return"); + let stats = db + .cleanup(omnigraph::db::CleanupPolicyOptions { + keep_versions: Some(1), + older_than: None, + }) + .await + .expect("a single table's GC failure must not abort cleanup"); + + let errored = stats.iter().filter(|s| s.error.is_some()).count(); + assert_eq!( + errored, 1, + "exactly one table's GC failure should be surfaced in stats, got {errored}" + ); + assert!( + stats.len() >= 4, + "every node+edge table should still appear in the stats" + ); + + // The reconcile pass is independent of the GC failure, so the orphan is gone. + { + let ds = lance::Dataset::open(&person_uri).await.unwrap(); + assert!( + !ds.list_branches().await.unwrap().contains_key("ghost"), + "reconcile should reclaim the orphan despite the GC failure" + ); + } +} + +// Companion to the version-GC isolation test, exercising the OTHER cleanup +// loop: a force-delete failure while reconciling one orphaned fork must be +// isolated (logged, not propagated) so the sweep continues, and a later +// cleanup converges. This is the loop the Devin finding was about. +#[tokio::test] +async fn cleanup_isolates_reconcile_failure() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap().to_string(); + let mut db = helpers::init_and_load(&dir).await; + + // Forge an orphaned fork the reconcile pass will try to reclaim. + let person_uri = node_table_uri(&uri, "Person"); + { + let mut ds = lance::Dataset::open(&person_uri).await.unwrap(); + let base = ds.version().version; + ds.create_branch("ghost", base, None).await.unwrap(); + } + + // Inject a one-shot failure into the reconcile force-delete. The sweep must + // not abort. + { + let _fp = ScopedFailPoint::new("cleanup.reconcile_fork", "1*return"); + db.cleanup(omnigraph::db::CleanupPolicyOptions { + keep_versions: Some(1), + older_than: None, + }) + .await + .expect("a reconcile force-delete failure must not abort cleanup"); + } + // The blocked orphan is still present (the failure was isolated, not retried). + { + let ds = lance::Dataset::open(&person_uri).await.unwrap(); + assert!( + ds.list_branches().await.unwrap().contains_key("ghost"), + "the orphan whose reclaim was injected-to-fail should remain" + ); + } + // A second cleanup with no injected failure converges. + db.cleanup(omnigraph::db::CleanupPolicyOptions { + keep_versions: Some(1), + older_than: None, + }) + .await + .unwrap(); + { + let ds = lance::Dataset::open(&person_uri).await.unwrap(); + assert!( + !ds.list_branches().await.unwrap().contains_key("ghost"), + "the second cleanup should reconcile the orphan" + ); + } +} + +// The cleanup reconciler must reclaim orphaned commit-graph branches, not just +// per-table forks. A delete whose best-effort commit-graph reclaim fails leaves +// a commit-graph orphan; the next cleanup must drop it. +#[tokio::test] +async fn cleanup_reclaims_orphaned_commit_graph_branch() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap().to_string(); + let mut db = helpers::init_and_load(&dir).await; + + db.branch_create("feature").await.unwrap(); + // Delete, failing the commit-graph reclaim → commit-graph "feature" orphan + // (manifest branch gone, commit-graph branch left behind). + { + let _fp = ScopedFailPoint::new("branch_delete.before_commit_graph_reclaim", "return"); + db.branch_delete("feature").await.unwrap(); + } + + let commits_uri = format!("{}/_graph_commits.lance", uri.trim_end_matches('/')); + { + let ds = lance::Dataset::open(&commits_uri).await.unwrap(); + assert!( + ds.list_branches().await.unwrap().contains_key("feature"), + "precondition: the commit-graph branch should be orphaned after the failed reclaim" + ); + } + + db.cleanup(omnigraph::db::CleanupPolicyOptions { + keep_versions: Some(1), + older_than: None, + }) + .await + .unwrap(); + + { + let ds = lance::Dataset::open(&commits_uri).await.unwrap(); + assert!( + !ds.list_branches().await.unwrap().contains_key("feature"), + "cleanup should reclaim the orphaned commit-graph branch" + ); + } +} + +// A branch_delete whose best-effort commit-graph reclaim fails leaves a +// commit-graph "zombie" branch. Recreating that name must heal the zombie and +// succeed (branch_create force-deletes a stale commit-graph ref since the +// manifest branch is created fresh), instead of dying on the leftover ref. +#[tokio::test] +async fn branch_create_recreates_over_commit_graph_zombie() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let db = Omnigraph::init(dir.path().to_str().unwrap(), helpers::TEST_SCHEMA) + .await + .unwrap(); + + db.branch_create("feature").await.unwrap(); + { + // Fail the best-effort commit-graph reclaim → commit-graph "feature" + // zombie survives the delete (manifest authority still flips). + let _fp = ScopedFailPoint::new("branch_delete.before_commit_graph_reclaim", "return"); + db.branch_delete("feature").await.unwrap(); + } + assert_eq!(db.branch_list().await.unwrap(), vec!["main".to_string()]); + + db.branch_create("feature") + .await + .expect("branch_create should heal the zombie commit-graph branch and succeed"); + assert!( + db.branch_list() + .await + .unwrap() + .contains(&"feature".to_string()) + ); +} + +// branch_create is authority-then-derived: if the derived commit-graph branch +// cannot be created, the manifest branch (the authority) must be rolled back so +// the branch does not half-exist. The existing failpoint fires right after the +// manifest create, standing in for any post-authority failure. +#[tokio::test] +async fn branch_create_rolls_back_manifest_on_commit_graph_failure() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let db = Omnigraph::init(dir.path().to_str().unwrap(), helpers::TEST_SCHEMA) + .await + .unwrap(); + + let err = { + let _fp = ScopedFailPoint::new("branch_create.after_manifest_branch_create", "return"); + db.branch_create("feature").await.unwrap_err() + }; + assert!( + !db.branch_list() + .await + .unwrap() + .contains(&"feature".to_string()), + "branch_create must roll back the manifest branch when the derived \ + commit-graph branch fails, got error: {err}" + ); +} + +// A fork collision must be classified by the manifest authority, not by Lance +// branch versions. When a concurrent first-write legitimately wins the fork +// race, the loser sees a version mismatch — but that is a stale snapshot, not +// an orphan, so it must be a retryable "refresh and retry", never a misleading +// "run cleanup". +// +// Ordering is made deterministic (no sleeps) via a callback at the fork point: +// `compare_exchange` lets only the FIRST arrival (writer A) record readiness and +// block until released; later arrivals (writer B) fall through. The test waits +// on the readiness flag, lets B win and commit the fork, then releases A. +static FORK_A_AT_POINT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static FORK_RELEASE_A: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[tokio::test(flavor = "multi_thread")] +async fn fork_collision_with_live_concurrent_fork_is_retryable() { + use std::sync::atomic::Ordering::SeqCst; + + let _scenario = FailScenario::setup(); + FORK_A_AT_POINT.store(false, SeqCst); + FORK_RELEASE_A.store(false, SeqCst); + + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap().to_string(); + let main = helpers::init_and_load(&dir).await; + main.branch_create("feature").await.unwrap(); + + // First arrival (A) records readiness and blocks until released; the rest + // (B) fall through immediately. Bounded spin so a mistake can't hang forever. + fail::cfg_callback("fork.before_classify", || { + if FORK_A_AT_POINT + .compare_exchange(false, true, SeqCst, SeqCst) + .is_ok() + { + for _ in 0..2000 { + if FORK_RELEASE_A.load(SeqCst) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + }) + .unwrap(); + + let uri_a = uri.clone(); + let writer_a = tokio::spawn(async move { + let mut a = Omnigraph::open(&uri_a).await.unwrap(); + helpers::mutate_branch( + &mut a, + "feature", + MUTATION_QUERIES, + "insert_person", + &mixed_params(&[("$name", "Eve")], &[("$age", 22)]), + ) + .await + }); + + // Wait (bounded) until A is parked at the fork point. + for _ in 0..600 { + if FORK_A_AT_POINT.load(SeqCst) { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + assert!( + FORK_A_AT_POINT.load(SeqCst), + "writer A never reached the fork point" + ); + + // B wins the fork and commits it. + let mut b = Omnigraph::open(&uri).await.unwrap(); + helpers::mutate_branch( + &mut b, + "feature", + MUTATION_QUERIES, + "insert_person", + &mixed_params(&[("$name", "Frank")], &[("$age", 41)]), + ) + .await + .unwrap(); + + // Release A; it resumes, re-reads the manifest, and sees the fork is live. + FORK_RELEASE_A.store(true, SeqCst); + let err = writer_a + .await + .unwrap() + .expect_err("A's stale-snapshot fork should be a retryable conflict"); + fail::remove("fork.before_classify"); + + let msg = err.to_string(); + assert!( + !msg.contains("cleanup"), + "a live concurrent fork must not be misclassified as an orphan, got: {msg}" + ); + assert!( + msg.contains("refresh and retry") || msg.contains("expected manifest table version"), + "expected a retryable stale-view error, got: {msg}" + ); +} + #[tokio::test(flavor = "multi_thread")] async fn graph_publish_failpoint_triggers_before_commit_append() { let _scenario = FailScenario::setup(); @@ -66,7 +512,7 @@ async fn graph_publish_failpoint_triggers_before_commit_append() { // Atomic schema apply: schema apply writes staging files first, then commits // the manifest, then renames staging → final. Tests below inject crashes at -// the two boundaries and assert that reopening the repo yields a consistent +// the two boundaries and assert that reopening the graph yields a consistent // state. #[tokio::test] @@ -303,14 +749,10 @@ async fn inline_delete_conflict_writes_sidecar_before_rejecting() { let person_uri = node_table_uri(&uri, "Person"); { - let _pause_delete = ScopedFailPoint::new("mutation.delete_node_pre_primary_delete", "pause"); + let _pause_delete = + ScopedFailPoint::new("mutation.delete_node_pre_primary_delete", "pause"); let delete_params = helpers::params(&[("$name", "Alice")]); - let delete = db.mutate( - "main", - MUTATION_QUERIES, - "remove_person", - &delete_params, - ); + let delete = db.mutate("main", MUTATION_QUERIES, "remove_person", &delete_params); tokio::pin!(delete); let mut concurrent_update_succeeded = false; @@ -325,15 +767,18 @@ async fn inline_delete_conflict_writes_sidecar_before_rejecting() { "set_age", &mixed_params(&[("$name", "Bob")], &[("$age", 26)]), ) - .await - .is_ok() + .await + .is_ok() { concurrent_update_succeeded = true; break; } tokio::time::sleep(std::time::Duration::from_millis(20)).await; } - assert!(concurrent_update_succeeded, "concurrent update must land while delete is paused"); + assert!( + concurrent_update_succeeded, + "concurrent update must land while delete is paused" + ); fail::remove("mutation.delete_node_pre_primary_delete"); let err = delete.await.unwrap_err(); @@ -925,13 +1370,13 @@ async fn ensure_indices_stage_btree_failure_leaves_existing_tables_writable() { .expect("Person mutation must succeed after the failed schema apply — existing tables are not drifted"); } -fn assert_no_staging_files(repo: &std::path::Path) { +fn assert_no_staging_files(graph: &std::path::Path) { for name in [ "_schema.pg.staging", "_schema.ir.json.staging", "__schema_state.json.staging", ] { - let path = repo.join(name); + let path = graph.join(name); assert!( !path.exists(), "staging file {} still exists after recovery", @@ -1164,7 +1609,7 @@ edge WorksAt: Person -> Company // NEW schema (city column on Person, Tag node type) — not the old. // Without the schema-staging coordination, the schema-state // recovery would have deleted the staging files (because manifest - // hadn't advanced when it ran), leaving a corrupt repo with new- + // hadn't advanced when it ran), leaving a corrupt graph with new- // schema data on disk but old-schema catalog. let live_schema = std::fs::read_to_string(dir.path().join("_schema.pg")).unwrap(); assert!( @@ -1667,3 +2112,143 @@ async fn ensure_indices_phase_b_failure_does_not_leak_sidecar_when_no_work_neede "_graph_commit_recoveries.lance must NOT exist when no sidecar was processed" ); } + +// ─── MR-668 PR 2a: Omnigraph::init cleanup on partial failure ────────────── +// +// `init_with_storage` writes three schema artifacts before invoking +// `GraphCoordinator::init`. Without cleanup, a failure between any of those +// steps left orphan files behind, making the URI unusable for a retry of +// `init` (it would refuse because `_schema.pg` already exists). The tests +// below pin: on failpoint trigger at each of the three phase boundaries, +// the three schema files are removed before the error is returned. +// +// Coverage note: the third boundary (`init.after_coordinator_init`) only +// asserts cleanup of the schema files. Lance per-type directories and +// `__manifest/` are NOT cleaned up — that requires a recursive +// `StorageAdapter::delete_prefix` primitive deferred along with +// `DELETE /graphs/{id}` (MR-668 PR 2b). The orphan Lance directories +// after a coordinator-init-phase failure are documented as a known +// limitation. + +#[tokio::test] +async fn init_failpoint_after_schema_pg_written_cleans_up_schema_file() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let _failpoint = ScopedFailPoint::new("init.after_schema_pg_written", "return"); + + let err = match Omnigraph::init(uri, helpers::TEST_SCHEMA).await { + Ok(_) => panic!("expected Omnigraph::init to fail at the configured failpoint"), + Err(e) => e, + }; + assert!( + err.to_string() + .contains("injected failpoint triggered: init.after_schema_pg_written"), + "got: {err}" + ); + + // Only `_schema.pg` was written at this phase boundary, but the + // cleanup attempts all three — `delete` treats not-found as Ok, + // so the other two deletes are no-ops. + assert!( + !dir.path().join("_schema.pg").exists(), + "_schema.pg must be cleaned up after init failure" + ); +} + +#[tokio::test] +async fn init_failpoint_after_schema_contract_written_cleans_up_all_schema_files() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let _failpoint = ScopedFailPoint::new("init.after_schema_contract_written", "return"); + + let err = match Omnigraph::init(uri, helpers::TEST_SCHEMA).await { + Ok(_) => panic!("expected Omnigraph::init to fail at the configured failpoint"), + Err(e) => e, + }; + assert!( + err.to_string() + .contains("injected failpoint triggered: init.after_schema_contract_written"), + "got: {err}" + ); + + assert!( + !dir.path().join("_schema.pg").exists(), + "_schema.pg must be cleaned up" + ); + assert!( + !dir.path().join("_schema.ir.json").exists(), + "_schema.ir.json must be cleaned up" + ); + assert!( + !dir.path().join("__schema_state.json").exists(), + "__schema_state.json must be cleaned up" + ); +} + +#[tokio::test] +async fn init_failpoint_after_coordinator_init_cleans_up_schema_files() { + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let _failpoint = ScopedFailPoint::new("init.after_coordinator_init", "return"); + + let err = match Omnigraph::init(uri, helpers::TEST_SCHEMA).await { + Ok(_) => panic!("expected Omnigraph::init to fail at the configured failpoint"), + Err(e) => e, + }; + assert!( + err.to_string() + .contains("injected failpoint triggered: init.after_coordinator_init"), + "got: {err}" + ); + + // Schema files are cleaned up by `best_effort_cleanup_init_artifacts`. + assert!( + !dir.path().join("_schema.pg").exists(), + "_schema.pg must be cleaned up after late-phase init failure" + ); + assert!( + !dir.path().join("_schema.ir.json").exists(), + "_schema.ir.json must be cleaned up after late-phase init failure" + ); + assert!( + !dir.path().join("__schema_state.json").exists(), + "__schema_state.json must be cleaned up after late-phase init failure" + ); + + // Documented limitation: Lance per-type datasets and `__manifest/` + // created by `GraphCoordinator::init` are NOT cleaned up — recursive + // deletion requires the deferred `delete_prefix` primitive. This + // assertion does NOT check for their absence; it merely documents + // the boundary by noting we don't validate orphan directories here. + // When PR 2b lands, this test can be tightened to assert the graph + // root is fully empty. +} + +#[tokio::test] +async fn init_failpoint_returns_original_error_not_cleanup_error() { + // The cleanup is best-effort. If `storage.delete` fails (e.g. transient + // network blip on S3), the original init failpoint error must still + // surface — not be masked by a cleanup failure. This test triggers the + // failpoint and asserts the returned error references the failpoint, + // not the cleanup. (The cleanup currently logs via `tracing::warn`; + // we can't easily fault-inject delete failures without another seam, + // so this is a smoke test for the precedence contract.) + let _scenario = FailScenario::setup(); + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let _failpoint = ScopedFailPoint::new("init.after_schema_pg_written", "return"); + + let err = match Omnigraph::init(uri, helpers::TEST_SCHEMA).await { + Ok(_) => panic!("expected Omnigraph::init to fail at the configured failpoint"), + Err(e) => e, + }; + // Failpoint message wins; no "cleanup" substring expected. + let msg = err.to_string(); + assert!( + msg.contains("init.after_schema_pg_written"), + "init error must surface the failpoint cause, got: {msg}" + ); +} diff --git a/crates/omnigraph/tests/forbidden_apis.rs b/crates/omnigraph/tests/forbidden_apis.rs index cc9f163..1936815 100644 --- a/crates/omnigraph/tests/forbidden_apis.rs +++ b/crates/omnigraph/tests/forbidden_apis.rs @@ -95,11 +95,11 @@ const FORBIDDEN_PATTERNS: &[&str] = &[ /// provide the staged primitives or to maintain the system tables /// (commit graph, manifest). const ALLOW_LIST_FILES: &[&str] = &[ - "table_store.rs", // The storage layer itself. - "storage_layer.rs", // The trait module. - "commit_graph.rs", // Maintains `_graph_commits.lance` system table. - "graph_coordinator.rs", // Drives the manifest publisher / branch coordinator. - "recovery_audit.rs", // Maintains `_graph_commit_recoveries.lance` (recovery audit trail). + "table_store.rs", // The storage layer itself. + "storage_layer.rs", // The trait module. + "commit_graph.rs", // Maintains `_graph_commits.lance` system table. + "graph_coordinator.rs", // Drives the manifest publisher / branch coordinator. + "recovery_audit.rs", // Maintains `_graph_commit_recoveries.lance` (recovery audit trail). ]; /// Directories exempt from the guard. Files under these paths may use @@ -168,10 +168,7 @@ fn engine_code_does_not_call_forbidden_lance_apis() { // comments are documentation, not code use. The trait // surface (sealed + trait-only) is the actual enforcement; // this test only catches code use. - if trimmed.starts_with("//") - || trimmed.starts_with("/*") - || trimmed.starts_with("*") - { + if trimmed.starts_with("//") || trimmed.starts_with("/*") || trimmed.starts_with("*") { continue; } // Allow lines marked with the sentinel on the SAME line or diff --git a/crates/omnigraph/tests/helpers/mod.rs b/crates/omnigraph/tests/helpers/mod.rs index e7e1efb..c97ff72 100644 --- a/crates/omnigraph/tests/helpers/mod.rs +++ b/crates/omnigraph/tests/helpers/mod.rs @@ -44,7 +44,7 @@ query insert_person_and_friend($name: String, $age: I32, $friend: String) { } "#; -/// Init a repo and load the standard test data. +/// Init a graph and load the standard test data. pub async fn init_and_load(dir: &tempfile::TempDir) -> Omnigraph { let uri = dir.path().to_str().unwrap(); let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); @@ -249,7 +249,7 @@ pub fn vector_and_string_params( map } -pub fn s3_test_repo_uri(suite: &str) -> Option { +pub fn s3_test_graph_uri(suite: &str) -> Option { let bucket = std::env::var("OMNIGRAPH_S3_TEST_BUCKET").ok()?; let prefix = std::env::var("OMNIGRAPH_S3_TEST_PREFIX") .ok() diff --git a/crates/omnigraph/tests/helpers/recovery.rs b/crates/omnigraph/tests/helpers/recovery.rs index 3a8505f..c76009e 100644 --- a/crates/omnigraph/tests/helpers/recovery.rs +++ b/crates/omnigraph/tests/helpers/recovery.rs @@ -110,8 +110,8 @@ impl FollowUpMutation { } } -pub fn single_sidecar_operation_id(repo_root: &Path) -> String { - let ids = sidecar_operation_ids(repo_root); +pub fn single_sidecar_operation_id(graph_root: &Path) -> String { + let ids = sidecar_operation_ids(graph_root); assert_eq!( ids.len(), 1, @@ -121,8 +121,8 @@ pub fn single_sidecar_operation_id(repo_root: &Path) -> String { ids.into_iter().next().unwrap() } -pub fn sidecar_operation_ids(repo_root: &Path) -> Vec { - let dir = repo_root.join("__recovery"); +pub fn sidecar_operation_ids(graph_root: &Path) -> Vec { + let dir = graph_root.join("__recovery"); if !dir.exists() { return Vec::new(); } @@ -143,10 +143,10 @@ pub fn sidecar_operation_ids(repo_root: &Path) -> Vec { ids } -pub async fn branch_head_commit_id(repo_root: &Path, branch: &str) -> Result { +pub async fn branch_head_commit_id(graph_root: &Path, branch: &str) -> Result { let graph = match branch { - "main" => CommitGraph::open(&repo_uri(repo_root)).await?, - branch => CommitGraph::open_at_branch(&repo_uri(repo_root), branch).await?, + "main" => CommitGraph::open(&graph_uri(graph_root)).await?, + branch => CommitGraph::open_at_branch(&graph_uri(graph_root), branch).await?, }; graph.head_commit_id().await?.ok_or_else(|| { OmniError::manifest_internal(format!("commit graph for branch {branch} has no head")) @@ -154,52 +154,52 @@ pub async fn branch_head_commit_id(repo_root: &Path, branch: &str) -> Result Result<()> { match expectation { RecoveryExpectation::RolledForward { tables } => { - assert_sidecar_absent(repo_root, operation_id); - let audit = read_audit_row(repo_root, operation_id).await?; + assert_sidecar_absent(graph_root, operation_id); + let audit = read_audit_row(graph_root, operation_id).await?; assert_eq!( audit.recovery_kind, "RolledForward", "audit row for {operation_id} recorded the wrong recovery_kind", ); - assert_manifest_pins_match_lance_heads(repo_root, &tables).await?; - assert_audit_to_versions_match_lance_heads(repo_root, &audit, &tables).await?; - assert_recovery_commit_shape(repo_root, &audit, &tables).await?; - assert_non_main_did_not_move_main(repo_root, &tables).await?; - assert_idempotent_reopen(repo_root, operation_id).await?; - run_follow_up_mutations(repo_root, tables).await?; + assert_manifest_pins_match_lance_heads(graph_root, &tables).await?; + assert_audit_to_versions_match_lance_heads(graph_root, &audit, &tables).await?; + assert_recovery_commit_shape(graph_root, &audit, &tables).await?; + assert_non_main_did_not_move_main(graph_root, &tables).await?; + assert_idempotent_reopen(graph_root, operation_id).await?; + run_follow_up_mutations(graph_root, tables).await?; } RecoveryExpectation::RolledBack { tables } => { - assert_sidecar_absent(repo_root, operation_id); - let audit = read_audit_row(repo_root, operation_id).await?; + assert_sidecar_absent(graph_root, operation_id); + let audit = read_audit_row(graph_root, operation_id).await?; assert_eq!( audit.recovery_kind, "RolledBack", "audit row for {operation_id} recorded the wrong recovery_kind", ); assert_rollback_outcomes_record_drift(&audit); - assert_recovery_commit_shape(repo_root, &audit, &tables).await?; - assert_non_main_did_not_move_main(repo_root, &tables).await?; - assert_idempotent_reopen(repo_root, operation_id).await?; - run_follow_up_mutations(repo_root, tables).await?; + assert_recovery_commit_shape(graph_root, &audit, &tables).await?; + assert_non_main_did_not_move_main(graph_root, &tables).await?; + assert_idempotent_reopen(graph_root, operation_id).await?; + run_follow_up_mutations(graph_root, tables).await?; } RecoveryExpectation::Deferred => { assert!( - sidecar_path(repo_root, operation_id).exists(), + sidecar_path(graph_root, operation_id).exists(), "deferred recovery must leave sidecar {operation_id} on disk", ); assert!( - read_audit_row(repo_root, operation_id).await.is_err(), + read_audit_row(graph_root, operation_id).await.is_err(), "deferred recovery must not record an audit row for {operation_id}", ); } RecoveryExpectation::NoOp => { - assert_sidecar_absent(repo_root, operation_id); + assert_sidecar_absent(graph_root, operation_id); assert!( - read_audit_row(repo_root, operation_id).await.is_err(), + read_audit_row(graph_root, operation_id).await.is_err(), "no-op recovery must not record an audit row for {operation_id}", ); } @@ -216,24 +216,24 @@ fn branch_context(tables: &[TableExpectation]) -> Option { .map(str::to_string) } -fn sidecar_path(repo_root: &Path, operation_id: &str) -> PathBuf { - repo_root +fn sidecar_path(graph_root: &Path, operation_id: &str) -> PathBuf { + graph_root .join("__recovery") .join(format!("{operation_id}.json")) } -fn assert_sidecar_absent(repo_root: &Path, operation_id: &str) { +fn assert_sidecar_absent(graph_root: &Path, operation_id: &str) { assert!( - !sidecar_path(repo_root, operation_id).exists(), + !sidecar_path(graph_root, operation_id).exists(), "recovery sidecar {operation_id} must be deleted after successful recovery", ); } async fn assert_manifest_pins_match_lance_heads( - repo_root: &Path, + graph_root: &Path, tables: &[TableExpectation], ) -> Result<()> { - let uri = repo_uri(repo_root); + let uri = graph_uri(graph_root); let db = Omnigraph::open(&uri).await?; for table in tables { let (entry, lance_head) = entry_and_lance_head(&db, &uri, table).await?; @@ -254,11 +254,11 @@ async fn assert_manifest_pins_match_lance_heads( } async fn assert_audit_to_versions_match_lance_heads( - repo_root: &Path, + graph_root: &Path, audit: &RecoveryAuditRow, tables: &[TableExpectation], ) -> Result<()> { - let uri = repo_uri(repo_root); + let uri = graph_uri(graph_root); let db = Omnigraph::open(&uri).await?; for table in tables { let (_, lance_head) = entry_and_lance_head(&db, &uri, table).await?; @@ -301,10 +301,10 @@ fn assert_rollback_outcomes_record_drift(audit: &RecoveryAuditRow) { } async fn assert_non_main_did_not_move_main( - repo_root: &Path, + graph_root: &Path, tables: &[TableExpectation], ) -> Result<()> { - let uri = repo_uri(repo_root); + let uri = graph_uri(graph_root); let db = Omnigraph::open(&uri).await?; let main = db.snapshot_of(ReadTarget::branch("main")).await?; for table in tables { @@ -327,14 +327,14 @@ async fn assert_non_main_did_not_move_main( } async fn assert_recovery_commit_shape( - repo_root: &Path, + graph_root: &Path, audit: &RecoveryAuditRow, tables: &[TableExpectation], ) -> Result<()> { let branch = branch_context(tables); let expected_parent = expected_recovery_parent(tables)?; let branch = branch.as_deref(); - let commit = read_recovery_commit(repo_root, audit, branch).await?; + let commit = read_recovery_commit(graph_root, audit, branch).await?; assert_eq!( commit.actor_id.as_deref(), @@ -362,7 +362,7 @@ async fn assert_recovery_commit_shape( ); if let Some(branch) = branch { - let graph = CommitGraph::open_at_branch(&repo_uri(repo_root), branch).await?; + let graph = CommitGraph::open_at_branch(&graph_uri(graph_root), branch).await?; let commits = graph.load_commits().await?; let parent = commit.parent_commit_id.as_deref().ok_or_else(|| { OmniError::manifest_internal(format!( @@ -403,12 +403,12 @@ fn expected_recovery_parent(tables: &[TableExpectation]) -> Result Result<()> { - let before = matching_audit_rows(repo_root, operation_id).await?; - let uri = repo_uri(repo_root); +async fn assert_idempotent_reopen(graph_root: &Path, operation_id: &str) -> Result<()> { + let before = matching_audit_rows(graph_root, operation_id).await?; + let uri = graph_uri(graph_root); let _db = Omnigraph::open(&uri).await?; - assert_sidecar_absent(repo_root, operation_id); - let after = matching_audit_rows(repo_root, operation_id).await?; + assert_sidecar_absent(graph_root, operation_id); + let after = matching_audit_rows(graph_root, operation_id).await?; assert_eq!( after.len(), before.len(), @@ -417,14 +417,14 @@ async fn assert_idempotent_reopen(repo_root: &Path, operation_id: &str) -> Resul Ok(()) } -async fn run_follow_up_mutations(repo_root: &Path, tables: Vec) -> Result<()> { +async fn run_follow_up_mutations(graph_root: &Path, tables: Vec) -> Result<()> { let mut db: Option = None; for table in tables { let Some(mutation) = table.follow_up_mutation else { continue; }; if db.is_none() { - db = Some(Omnigraph::open(&repo_uri(repo_root)).await?); + db = Some(Omnigraph::open(&graph_uri(graph_root)).await?); } let db = db.as_mut().unwrap(); db.mutate( @@ -480,11 +480,11 @@ async fn lance_head_for_entry(root_uri: &str, entry: &SubTableEntry) -> Result, ) -> Result { - let uri = repo_uri(repo_root); + let uri = graph_uri(graph_root); let graph = match branch { Some(branch) => CommitGraph::open_at_branch(&uri, branch).await?, None => CommitGraph::open(&uri).await?, @@ -502,8 +502,8 @@ async fn read_recovery_commit( }) } -async fn read_audit_row(repo_root: &Path, operation_id: &str) -> Result { - let mut rows = matching_audit_rows(repo_root, operation_id).await?; +async fn read_audit_row(graph_root: &Path, operation_id: &str) -> Result { + let mut rows = matching_audit_rows(graph_root, operation_id).await?; if rows.len() != 1 { return Err(OmniError::manifest_internal(format!( "expected exactly one recovery audit row for {operation_id}, got {}", @@ -514,10 +514,10 @@ async fn read_audit_row(repo_root: &Path, operation_id: &str) -> Result Result> { - let recoveries_dir = repo_root.join("_graph_commit_recoveries.lance"); + let recoveries_dir = graph_root.join("_graph_commit_recoveries.lance"); if !recoveries_dir.exists() { return Ok(Vec::new()); } @@ -575,6 +575,6 @@ fn string_column<'a>(batch: &'a RecordBatch, name: &str) -> Result<&'a StringArr }) } -fn repo_uri(repo_root: &Path) -> String { - repo_root.to_str().unwrap().to_string() +fn graph_uri(graph_root: &Path) -> String { + graph_root.to_str().unwrap().to_string() } diff --git a/crates/omnigraph/tests/lance_surface_guards.rs b/crates/omnigraph/tests/lance_surface_guards.rs index b65a808..1d60c08 100644 --- a/crates/omnigraph/tests/lance_surface_guards.rs +++ b/crates/omnigraph/tests/lance_surface_guards.rs @@ -242,3 +242,136 @@ async fn _compile_delete_result_field_shape() -> lance::Result<()> { let _num_deleted: u64 = result.num_deleted_rows; Ok(()) } + +// --- Guard 9: force_delete_branch semantics -------------------------------- +// +// The branch-delete reconciler (`db/omnigraph/optimize.rs::reconcile_orphaned_branches`) +// and the eager best-effort reclaim in `cleanup_deleted_branch_tables` call +// `force_delete_branch` to drop orphaned branch refs. The single-authority +// design relies on three facts pinned here: +// 1. plain `delete_branch` errors on a missing ref (so the design uses the +// force variant instead); +// 2. `force_delete_branch` removes an existing (forked) branch — the orphan +// case, where a `tree/{branch}/` exists; +// 3. `force_delete_branch` on a *fully-absent* branch (no tree dir) still +// errors on the local store, because `remove_dir_all`'s NotFound is not +// caught for Lance's native error variant. `TableStore::force_delete_branch` +// wraps this to be fully idempotent. Pin the raw quirk so a future Lance +// fix (which would let us simplify the wrapper) is noticed. + +#[tokio::test] +async fn force_delete_branch_semantics() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().join("guard9.lance"); + let uri = uri.to_str().unwrap(); + let mut ds = fresh_dataset(uri).await; + + // (1) Plain delete of a never-created branch errors (RefNotFound). + assert!( + ds.delete_branch("nope").await.is_err(), + "Dataset::delete_branch on a missing ref should error; if this is now \ + Ok, the reconciler could drop the force variant." + ); + + // (2) force_delete_branch removes an existing (forked) branch. + let base = ds.version().version; + ds.create_branch("feature", base, None).await.unwrap(); + ds.force_delete_branch("feature").await.unwrap(); + assert!( + !ds.list_branches().await.unwrap().contains_key("feature"), + "force_delete_branch should remove an existing branch ref" + ); + + // (3) Quirk: force_delete on a fully-absent branch errors on the local + // store (worked around by TableStore::force_delete_branch). + assert!( + ds.force_delete_branch("never").await.is_err(), + "force_delete_branch on a fully-absent branch no longer errors — \ + TableStore::force_delete_branch's NotFound tolerance can be simplified." + ); +} + +// --- Guard 10: blob-column compaction is still broken in this Lance -------- +// +// `db/omnigraph/optimize.rs` skips tables with blob columns while +// `LANCE_SUPPORTS_BLOB_COMPACTION = false`: Lance `compact_files` forces +// `BlobHandling::AllBinary`, and the blob-v2 struct decoder mis-counts columns +// ("more fields in the schema than provided column indices"), failing even a +// pristine uniform-V2_2 multi-fragment blob table. Reads are unaffected (they +// use descriptor handling). +// +// WHEN THIS TEST TURNS RED (compact_files no longer errors), the Lance bug is +// fixed: flip `LANCE_SUPPORTS_BLOB_COMPACTION` to true in optimize.rs, drop the +// blob-skip branch + the `optimize_skips_blob_table_and_reports_skip` +// skip assertions in maintenance.rs, and re-pin docs/dev/lance.md. + +#[tokio::test] +async fn compact_files_still_fails_on_blob_columns() { + use arrow_array::{LargeBinaryArray, StructArray}; + + fn blob_batch(start: i32, n: i32) -> RecordBatch { + let ids: Vec = (start..start + n).map(|i| format!("n{i}")).collect(); + let data = + LargeBinaryArray::from_iter_values((start..start + n).map(|i| format!("blob{i}"))); + let blob_uri = StringArray::from(vec![None::<&str>; n as usize]); + let DataType::Struct(fields) = lance::blob::blob_field("content", true).data_type().clone() + else { + unreachable!("blob_field is always a Struct"); + }; + let content = StructArray::new( + fields, + vec![Arc::new(data) as _, Arc::new(blob_uri) as _], + None, + ); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Utf8, false), + lance::blob::blob_field("content", true), + ])); + RecordBatch::try_new( + schema, + vec![Arc::new(StringArray::from(ids)) as _, Arc::new(content) as _], + ) + .unwrap() + } + + async fn write(uri: &str, batch: RecordBatch, mode: WriteMode) { + let schema = batch.schema(); + let reader = RecordBatchIterator::new(vec![Ok(batch)], schema); + // Blob v2 requires file version >= 2.2; without the pin the *write* + // would fail with a different error, masking the guard's intent. + let params = WriteParams { + mode, + enable_stable_row_ids: true, + data_storage_version: Some(LanceFileVersion::V2_2), + ..Default::default() + }; + Dataset::write(reader, uri, Some(params)).await.unwrap(); + } + + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().join("guard10-blob.lance"); + let uri = uri.to_str().unwrap(); + + // Uniform V2_2, two fragments → forces compaction to actually rewrite. + write(uri, blob_batch(0, 2), WriteMode::Create).await; + write(uri, blob_batch(100, 2), WriteMode::Append).await; + + let mut ds = Dataset::open(uri).await.unwrap(); + assert!( + ds.get_fragments().len() >= 2, + "guard needs a multi-fragment table to trigger a real compaction rewrite" + ); + + let result = compact_files(&mut ds, CompactionOptions::default(), None).await; + let err = result.expect_err( + "compact_files unexpectedly SUCCEEDED on a blob table — the Lance blob-v2 \ + compaction bug is fixed. Flip LANCE_SUPPORTS_BLOB_COMPACTION to true in \ + db/omnigraph/optimize.rs, remove the blob-skip branch, and re-pin docs/dev/lance.md.", + ); + assert!( + err.to_string() + .contains("more fields in the schema than provided column indices"), + "blob compaction failed with an unexpected error (Lance internals may have \ + shifted): {err}" + ); +} diff --git a/crates/omnigraph/tests/lifecycle.rs b/crates/omnigraph/tests/lifecycle.rs index d555cbe..a56a80c 100644 --- a/crates/omnigraph/tests/lifecycle.rs +++ b/crates/omnigraph/tests/lifecycle.rs @@ -2,14 +2,14 @@ mod helpers; use std::fs; -use omnigraph::db::{Omnigraph, ReadTarget}; -use omnigraph_compiler::{build_schema_ir, schema_ir_pretty_json}; +use omnigraph::db::{InitOptions, Omnigraph, ReadTarget}; use omnigraph_compiler::schema::parser::parse_schema; +use omnigraph_compiler::{build_schema_ir, schema_ir_pretty_json}; use helpers::*; #[tokio::test] -async fn init_creates_repo() { +async fn init_creates_graph() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -34,7 +34,7 @@ async fn init_creates_repo() { } #[tokio::test] -async fn open_reads_existing_repo() { +async fn open_reads_existing_graph() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -49,7 +49,7 @@ async fn open_reads_existing_repo() { } #[tokio::test] -async fn open_bootstraps_legacy_schema_state_for_main_only_repo() { +async fn open_bootstraps_legacy_schema_state_for_main_only_graph() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); @@ -64,7 +64,7 @@ async fn open_bootstraps_legacy_schema_state_for_main_only_repo() { } #[tokio::test] -async fn open_rejects_legacy_repo_with_public_branch() { +async fn open_rejects_legacy_graph_with_public_branch() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); @@ -74,7 +74,7 @@ async fn open_rejects_legacy_repo_with_public_branch() { fs::remove_file(dir.path().join("__schema_state.json")).unwrap(); let err = match Omnigraph::open(uri).await { - Ok(_) => panic!("expected legacy repo with public branch to fail schema bootstrap"), + Ok(_) => panic!("expected legacy graph with public branch to fail schema bootstrap"), Err(err) => err, }; assert!( @@ -185,3 +185,122 @@ async fn snapshot_version_is_pinned() { assert_eq!(snap1.version(), v1); } + +/// Regression for the `Omnigraph::init` re-init footgun (MR-668 +/// follow-up): a second `init` against a URI that already holds a +/// graph must NOT modify or destroy the existing graph's schema +/// artifacts. Today's behavior is destructive either way — the +/// `write_text(_schema.pg, ...)` call at the top of +/// `init_storage_phase` overwrites the existing file before any +/// preflight, and `best_effort_cleanup_init_artifacts` will later +/// delete all three files if the inner `GraphCoordinator::init` +/// fails. Both outcomes corrupt an existing graph. +/// +/// After the fix: strict-mode `init` (no `force` flag) errors out +/// before touching any file, and the original schema artifacts +/// match their pre-attempt contents byte-for-byte. +#[tokio::test] +async fn init_on_existing_graph_uri_does_not_destroy_existing_schema() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + + // Establish the first graph and snapshot its three schema files. + Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); + let original_schema_pg = fs::read_to_string(dir.path().join("_schema.pg")).unwrap(); + let original_schema_ir = fs::read_to_string(dir.path().join("_schema.ir.json")).unwrap(); + let original_schema_state = fs::read_to_string(dir.path().join("__schema_state.json")).unwrap(); + + // Attempt a re-init with a deliberately different schema so any + // overwrite would be observable in the file contents. + let different_schema = "node Other { id: String @key }\n"; + let result = Omnigraph::init(uri, different_schema).await; + + // The new init must report the conflict, not silently mutate. + assert!( + result.is_err(), + "init against an existing graph URI must error, not silently overwrite" + ); + + // The three schema files must remain present and byte-identical to + // their pre-attempt contents. + assert!( + dir.path().join("_schema.pg").exists(), + "_schema.pg must not be deleted by a failed re-init" + ); + assert!( + dir.path().join("_schema.ir.json").exists(), + "_schema.ir.json must not be deleted by a failed re-init" + ); + assert!( + dir.path().join("__schema_state.json").exists(), + "__schema_state.json must not be deleted by a failed re-init" + ); + assert_eq!( + fs::read_to_string(dir.path().join("_schema.pg")).unwrap(), + original_schema_pg, + "_schema.pg contents must be preserved when re-init is rejected" + ); + assert_eq!( + fs::read_to_string(dir.path().join("_schema.ir.json")).unwrap(), + original_schema_ir, + "_schema.ir.json contents must be preserved when re-init is rejected" + ); + assert_eq!( + fs::read_to_string(dir.path().join("__schema_state.json")).unwrap(), + original_schema_state, + "__schema_state.json contents must be preserved when re-init is rejected" + ); +} + +/// Happy-path sibling to the strict re-init regression above: +/// `InitOptions { force: true }` must skip the schema-file preflight +/// when the operator deliberately wants to recover from orphan +/// schema artifacts (e.g. files left behind by a failed prior init). +/// +/// Documented semantics per `InitOptions::force`: skips the preflight +/// only. Force does NOT purge existing Lance datasets or `__manifest/` +/// — that needs `StorageAdapter::delete_prefix`, which is tracked +/// separately. The realistic recovery scenario is "schema files +/// exist but Lance state doesn't," which this test reproduces. +/// +/// Without this test, a future refactor could invert the `if !force` +/// branch and silently break the operator-facing escape hatch. +#[tokio::test] +async fn init_with_force_recovers_from_orphan_schema_files() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + + // Simulate orphan schema files: write `_schema.pg` to disk + // without running a full init. The preflight will see it and + // bail in strict mode. + fs::write(dir.path().join("_schema.pg"), TEST_SCHEMA).unwrap(); + + // Strict mode refuses because `_schema.pg` exists. + let strict_err = match Omnigraph::init(uri, TEST_SCHEMA).await { + Ok(_) => panic!("strict init must refuse when orphan _schema.pg exists"), + Err(e) => e, + }; + assert!( + strict_err.to_string().contains("already initialized"), + "strict init must surface AlreadyInitialized (sanity check); got: {strict_err}" + ); + + // Force init succeeds: it skips the preflight, overwrites the + // orphan file, and proceeds to initialize Lance state (which + // didn't exist, so `GraphCoordinator::init` is unblocked). + let db = Omnigraph::init_with_options(uri, TEST_SCHEMA, InitOptions { force: true }) + .await + .expect("force init must succeed when only orphan schema files block strict init"); + + // Confirm the catalog is populated as expected — proves the + // graph is functional after force-recovery, not just that the + // call returned Ok. + assert!( + db.catalog().node_types.contains_key("Person"), + "force-recovered graph must have the new catalog installed" + ); + assert!( + dir.path().join("__schema_state.json").exists(), + "force-recovered graph must have full schema state written" + ); +} diff --git a/crates/omnigraph/tests/maintenance.rs b/crates/omnigraph/tests/maintenance.rs index 6bb81f2..3e61677 100644 --- a/crates/omnigraph/tests/maintenance.rs +++ b/crates/omnigraph/tests/maintenance.rs @@ -1,19 +1,32 @@ // Maintenance tests: `optimize` (Lance compact_files) and `cleanup` // (Lance cleanup_old_versions) at the graph level. Covers no-op edges -// (empty repo, already-optimized repo), the policy-validation contract on +// (empty graph, already-optimized graph), the policy-validation contract on // `cleanup`, and the keep-versions cap that protects head. mod helpers; use std::time::Duration; -use omnigraph::db::{CleanupPolicyOptions, Omnigraph}; +use lance::Dataset; +use omnigraph::db::{CleanupPolicyOptions, Omnigraph, SkipReason}; use omnigraph::loader::{LoadMode, load_jsonl}; use helpers::{TEST_DATA, TEST_SCHEMA, count_rows, init_and_load}; +/// Filesystem URI of a node sub-table, mirroring the engine's layout +/// (FNV-1a of the type name under `nodes/`). Matches the helper in +/// `failpoints.rs`; used to inspect/forge Lance branches directly in tests. +fn node_table_uri(root: &str, type_name: &str) -> String { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in type_name.as_bytes() { + hash ^= b as u64; + hash = hash.wrapping_mul(0x100_0000_01b3); + } + format!("{}/nodes/{hash:016x}", root.trim_end_matches('/')) +} + #[tokio::test] -async fn optimize_on_empty_repo_returns_stats_per_table_with_no_changes() { +async fn optimize_on_empty_graph_returns_stats_per_table_with_no_changes() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); @@ -37,7 +50,7 @@ async fn optimize_after_load_then_again_is_idempotent() { // First pass may compact (load wrote real fragments). let _first = db.optimize().await.unwrap(); - // Second pass should be a no-op: already-compacted repo produces no + // Second pass should be a no-op: already-compacted graph produces no // fragments_removed / fragments_added. let second = db.optimize().await.unwrap(); for s in &second { @@ -59,6 +72,97 @@ async fn optimize_after_load_then_again_is_idempotent() { } } +// Regression: `optimize` must not crash on a graph that has a `Blob` table. +// +// Lance `compact_files` forces `BlobHandling::AllBinary`, which mis-decodes +// blob-v2 columns ("more fields in the schema than provided column indices"), +// failing even a pristine uniform-V2_2 multi-fragment blob table. `optimize` +// must skip blob-bearing tables (and report the skip) rather than aborting the +// whole sweep. +// +// Before the skip fix, `optimize()` returned that Lance error here and aborted +// the whole sweep; it now skips the blob table (`doc.skipped == Some(..)`) +// while the sibling non-blob `Tag` table still compacts. The skip is gated by +// `LANCE_SUPPORTS_BLOB_COMPACTION`; the surface guard +// `compact_files_still_fails_on_blob_columns` flags when the upstream Lance fix +// makes the skip (and this test's blob arm) removable. +#[tokio::test] +async fn optimize_skips_blob_table_and_reports_skip() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + // One Blob node type (`Doc`) + one plain node type (`Tag`): proves the blob + // table is skipped while a non-blob table in the same sweep still compacts. + let schema = "\ +node Doc {\n slug: String @key\n content: Blob\n}\n\ +node Tag {\n slug: String @key\n}\n"; + let mut db = Omnigraph::init(uri, schema).await.unwrap(); + + // Multi-fragment blob table: Overwrite creates fragment 1; each Merge of + // new keys appends another. A >=2-fragment blob table is exactly what + // crashes `compact_files` today (single fragment would no-op and not crash). + load_jsonl( + &mut db, + "{\"type\":\"Doc\",\"data\":{\"slug\":\"d1\",\"content\":\"base64:aGVsbG8x\"}}\n{\"type\":\"Doc\",\"data\":{\"slug\":\"d2\",\"content\":\"base64:aGVsbG8y\"}}", + LoadMode::Overwrite, + ) + .await + .unwrap(); + load_jsonl( + &mut db, + "{\"type\":\"Doc\",\"data\":{\"slug\":\"d3\",\"content\":\"base64:aGVsbG8z\"}}", + LoadMode::Merge, + ) + .await + .unwrap(); + load_jsonl( + &mut db, + "{\"type\":\"Doc\",\"data\":{\"slug\":\"d4\",\"content\":\"base64:aGVsbG80\"}}", + LoadMode::Merge, + ) + .await + .unwrap(); + // Plain table, also multi-fragment so it has something to compact. + load_jsonl( + &mut db, + "{\"type\":\"Tag\",\"data\":{\"slug\":\"t1\"}}\n{\"type\":\"Tag\",\"data\":{\"slug\":\"t2\"}}", + LoadMode::Merge, + ) + .await + .unwrap(); + load_jsonl( + &mut db, + "{\"type\":\"Tag\",\"data\":{\"slug\":\"t3\"}}", + LoadMode::Merge, + ) + .await + .unwrap(); + + let stats = db + .optimize() + .await + .expect("optimize must not crash on a graph with a Blob table"); + + let doc = stats + .iter() + .find(|s| s.table_key == "node:Doc") + .expect("Doc stat present"); + let tag = stats + .iter() + .find(|s| s.table_key == "node:Tag") + .expect("Tag stat present"); + // The blob table is skipped (and reported), not compacted. + assert_eq!( + doc.skipped, + Some(SkipReason::BlobColumnsUnsupportedByLance), + "blob table must be reported as skipped", + ); + assert!(!doc.committed, "skipped blob table is not compacted"); + assert_eq!(doc.fragments_removed, 0); + assert_eq!(doc.fragments_added, 0); + // The plain (non-blob) table is unaffected by the skip. + assert_eq!(tag.skipped, None, "non-blob table must not be skipped"); +} + #[tokio::test] async fn cleanup_without_any_policy_option_errors() { let dir = tempfile::tempdir().unwrap(); @@ -119,7 +223,9 @@ async fn cleanup_older_than_zero_preserves_head() { // Smoke test: after aggressive cleanup, we can still read and write the // graph — head wasn't pruned. - load_jsonl(&mut db, TEST_DATA, LoadMode::Merge).await.unwrap(); + load_jsonl(&mut db, TEST_DATA, LoadMode::Merge) + .await + .unwrap(); } #[tokio::test] @@ -151,6 +257,64 @@ async fn cleanup_then_optimize_preserves_rows_and_table_remains_writable() { assert_eq!(count_rows(&db, "node:Company").await, companies_before); // Table is still writable after the cleanup+optimize sequence. - load_jsonl(&mut db, TEST_DATA, LoadMode::Merge).await.unwrap(); + load_jsonl(&mut db, TEST_DATA, LoadMode::Merge) + .await + .unwrap(); assert_eq!(count_rows(&db, "node:Person").await, people_before); } + +#[tokio::test] +async fn cleanup_reconciles_orphaned_branch_forks() { + // An incomplete prior `branch_delete` can leave a per-table Lance branch + // that the manifest no longer references (a "zombie" fork). It is + // unreachable through any snapshot but pins its `tree/{branch}/` storage. + // `cleanup` must reconcile it away: drop every Lance branch absent from the + // manifest authority, without touching `main`. + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap().to_string(); + let mut db = init_and_load(&dir).await; + + let people_before = count_rows(&db, "node:Person").await; + assert!(people_before > 0, "fixture should seed Person rows"); + + // Forge an orphaned fork the manifest never knew about. + let person_uri = node_table_uri(&uri, "Person"); + { + let mut ds = Dataset::open(&person_uri).await.unwrap(); + let base = ds.version().version; + ds.create_branch("ghost", base, None).await.unwrap(); + assert!( + ds.list_branches().await.unwrap().contains_key("ghost"), + "precondition: orphaned fork staged" + ); + } + + db.cleanup(CleanupPolicyOptions { + keep_versions: Some(1), + older_than: None, + }) + .await + .unwrap(); + + // Orphan reclaimed; main untouched. + { + let ds = Dataset::open(&person_uri).await.unwrap(); + assert!( + !ds.list_branches().await.unwrap().contains_key("ghost"), + "cleanup should reconcile the orphaned 'ghost' fork away" + ); + } + assert_eq!( + count_rows(&db, "node:Person").await, + people_before, + "cleanup must not disturb main while reconciling orphans" + ); + + // Idempotent: a second cleanup with the orphan already gone is a no-op. + db.cleanup(CleanupPolicyOptions { + keep_versions: Some(1), + older_than: None, + }) + .await + .unwrap(); +} diff --git a/crates/omnigraph/tests/policy_engine_chassis.rs b/crates/omnigraph/tests/policy_engine_chassis.rs index b1f43d9..def5349 100644 --- a/crates/omnigraph/tests/policy_engine_chassis.rs +++ b/crates/omnigraph/tests/policy_engine_chassis.rs @@ -23,8 +23,8 @@ use std::path::Path; use std::sync::Arc; use omnigraph::db::{Omnigraph, ReadTarget, SchemaApplyOptions}; -use omnigraph::loader::LoadMode; use omnigraph::error::OmniError; +use omnigraph::loader::LoadMode; use omnigraph_policy::{PolicyChecker, PolicyEngine}; use helpers::*; @@ -58,13 +58,16 @@ rules: "#; fn additive_schema() -> String { - helpers::TEST_SCHEMA.replace(" age: I32?\n}", " age: I32?\n nickname: String?\n}") + helpers::TEST_SCHEMA.replace( + " age: I32?\n}", + " age: I32?\n nickname: String?\n}", + ) } fn install_policy(db: Omnigraph, dir_path: &Path) -> (Omnigraph, Arc) { let policy_path = dir_path.join("policy.yaml"); fs::write(&policy_path, POLICY_YAML).unwrap(); - let engine = PolicyEngine::load(&policy_path, dir_path.to_str().unwrap()).unwrap(); + let engine = PolicyEngine::load_graph(&policy_path, dir_path.to_str().unwrap()).unwrap(); let engine = Arc::new(engine); let db = db.with_policy(Arc::clone(&engine) as Arc); (db, engine) @@ -238,7 +241,12 @@ async fn load_as_denies_when_policy_rejects_actor() { let (db, _engine) = init_with_policy(&dir).await; let result = db - .load_as("main", ONE_PERSON_JSONL, LoadMode::Merge, Some("act-denied")) + .load_as( + "main", + ONE_PERSON_JSONL, + LoadMode::Merge, + Some("act-denied"), + ) .await; assert_denied(result, "load_as"); } diff --git a/crates/omnigraph/tests/recovery.rs b/crates/omnigraph/tests/recovery.rs index 5ad87e8..a090178 100644 --- a/crates/omnigraph/tests/recovery.rs +++ b/crates/omnigraph/tests/recovery.rs @@ -22,16 +22,16 @@ use helpers::recovery::{RecoveryExpectation, TableExpectation, assert_post_recov const TEST_SCHEMA: &str = include_str!("fixtures/test.pg"); -fn write_sidecar_file(repo_root: &Path, operation_id: &str, json: &str) { - let dir = repo_root.join("__recovery"); +fn write_sidecar_file(graph_root: &Path, operation_id: &str, json: &str) { + let dir = graph_root.join("__recovery"); if !dir.exists() { std::fs::create_dir(&dir).unwrap(); } std::fs::write(dir.join(format!("{}.json", operation_id)), json).unwrap(); } -fn list_recovery_dir(repo_root: &Path) -> Vec { - let dir = repo_root.join("__recovery"); +fn list_recovery_dir(graph_root: &Path) -> Vec { + let dir = graph_root.join("__recovery"); if !dir.exists() { return Vec::new(); } @@ -41,7 +41,7 @@ fn list_recovery_dir(repo_root: &Path) -> Vec { .collect() } -/// Full URI of a node-type Lance dataset under a fresh Omnigraph repo. +/// Full URI of a node-type Lance dataset under a fresh Omnigraph graph. /// Mirrors the `nodes/{fnv1a64-hex(type_name)}` layout in `db/manifest/layout.rs`. fn node_table_uri(root: &str, type_name: &str) -> String { let h: u64 = fnv1a64(type_name.as_bytes()); @@ -283,8 +283,8 @@ async fn recovery_rolls_back_synthetic_drift_on_open() { // ===================================================================== /// Helper: count rows in `_graph_commit_recoveries.lance` at the given root. -async fn count_recovery_audit_rows(repo_root: &Path) -> usize { - let recoveries_dir = repo_root.join("_graph_commit_recoveries.lance"); +async fn count_recovery_audit_rows(graph_root: &Path) -> usize { + let recoveries_dir = graph_root.join("_graph_commit_recoveries.lance"); if !recoveries_dir.exists() { return 0; } @@ -306,9 +306,9 @@ async fn count_recovery_audit_rows(repo_root: &Path) -> usize { /// Helper: read the most recent recovery audit row's `recovery_kind`, /// `recovery_for_actor`, and `operation_id`. Returns `None` if no rows. async fn read_latest_recovery_audit( - repo_root: &Path, + graph_root: &Path, ) -> Option<(String, Option, String, String)> { - let recoveries_dir = repo_root.join("_graph_commit_recoveries.lance"); + let recoveries_dir = graph_root.join("_graph_commit_recoveries.lance"); if !recoveries_dir.exists() { return None; } @@ -357,8 +357,8 @@ async fn read_latest_recovery_audit( /// storage order (multiple batches concatenated). Used by the /// multi-sidecar fresh-snapshot test as a diagnostic alongside the /// post-recovery Lance HEAD assertion. -async fn list_recovery_audit_kinds(repo_root: &Path) -> Vec { - let recoveries_dir = repo_root.join("_graph_commit_recoveries.lance"); +async fn list_recovery_audit_kinds(graph_root: &Path) -> Vec { + let recoveries_dir = graph_root.join("_graph_commit_recoveries.lance"); if !recoveries_dir.exists() { return Vec::new(); } @@ -391,8 +391,8 @@ async fn list_recovery_audit_kinds(repo_root: &Path) -> Vec { } /// Helper: count `_graph_commits.lance` rows tagged with the recovery actor. -async fn count_recovery_actor_commits(repo_root: &Path) -> usize { - let actors_dir = repo_root.join("_graph_commit_actors.lance"); +async fn count_recovery_actor_commits(graph_root: &Path) -> usize { + let actors_dir = graph_root.join("_graph_commit_actors.lance"); if !actors_dir.exists() { return 0; } @@ -908,7 +908,7 @@ async fn recovery_ensure_indices_steady_state_no_sidecar() { /// ran) and rolls back any sibling table's legitimate index work. /// /// Integration verification: after a real init + ensure_indices on a -/// repo where every table is empty, the recovery sweep must complete +/// graph where every table is empty, the recovery sweep must complete /// cleanly (no leftover sidecar) AND the next ensure_indices must also /// leave no sidecar — proving the empty-table-scoping behavior lets /// steady-state runs incur zero sidecar I/O. The @@ -930,7 +930,7 @@ async fn recovery_ensure_indices_handles_empty_tables() { db.ensure_indices().await.unwrap(); assert!( list_recovery_dir(dir.path()).is_empty(), - "ensure_indices on an all-empty repo must not leave a sidecar" + "ensure_indices on an all-empty graph must not leave a sidecar" ); // Reopen + ensure_indices — still steady state, still no sidecar. drop(db); @@ -938,7 +938,7 @@ async fn recovery_ensure_indices_handles_empty_tables() { db.ensure_indices().await.unwrap(); assert!( list_recovery_dir(dir.path()).is_empty(), - "second ensure_indices on an all-empty repo must also not leave a sidecar" + "second ensure_indices on an all-empty graph must also not leave a sidecar" ); } diff --git a/crates/omnigraph/tests/s3_storage.rs b/crates/omnigraph/tests/s3_storage.rs index 5b90022..7e4f0a3 100644 --- a/crates/omnigraph/tests/s3_storage.rs +++ b/crates/omnigraph/tests/s3_storage.rs @@ -7,8 +7,8 @@ use omnigraph::loader::{LoadMode, load_jsonl}; use helpers::*; #[tokio::test(flavor = "multi_thread")] -async fn s3_compatible_repo_lifecycle_works() { - let Some(uri) = s3_test_repo_uri("omnigraph-runtime") else { +async fn s3_compatible_graph_lifecycle_works() { + let Some(uri) = s3_test_graph_uri("omnigraph-runtime") else { eprintln!("skipping s3 runtime test: OMNIGRAPH_S3_TEST_BUCKET is not set"); return; }; @@ -81,7 +81,7 @@ async fn s3_compatible_repo_lifecycle_works() { #[tokio::test(flavor = "multi_thread")] async fn s3_branch_change_merge_flow_works() { - let Some(uri) = s3_test_repo_uri("omnigraph-branching") else { + let Some(uri) = s3_test_graph_uri("omnigraph-branching") else { eprintln!("skipping s3 branch test: OMNIGRAPH_S3_TEST_BUCKET is not set"); return; }; @@ -135,7 +135,7 @@ async fn s3_branch_change_merge_flow_works() { #[tokio::test(flavor = "multi_thread")] async fn s3_public_load_uses_hidden_run_and_publishes() { - let Some(uri) = s3_test_repo_uri("omnigraph-public-load") else { + let Some(uri) = s3_test_graph_uri("omnigraph-public-load") else { eprintln!("skipping s3 public load test: OMNIGRAPH_S3_TEST_BUCKET is not set"); return; }; diff --git a/crates/omnigraph/tests/schema_apply.rs b/crates/omnigraph/tests/schema_apply.rs index 6862c84..cc0cae2 100644 --- a/crates/omnigraph/tests/schema_apply.rs +++ b/crates/omnigraph/tests/schema_apply.rs @@ -74,7 +74,7 @@ async fn apply_schema_rejects_when_non_main_branch_exists() { let err = db.apply_schema(&desired).await.unwrap_err(); assert!( err.to_string() - .contains("schema apply requires a repo with only main") + .contains("schema apply requires a graph with only main") ); } @@ -402,10 +402,7 @@ async fn apply_schema_rejects_adding_a_required_property_without_backfill() { // Add `email: String` (required, non-nullable, no @rename_from). Existing // rows have no value to fill in, so this is unsupported in v1. - let desired = TEST_SCHEMA.replace( - " age: I32?\n}", - " age: I32?\n email: String\n}", - ); + let desired = TEST_SCHEMA.replace(" age: I32?\n}", " age: I32?\n email: String\n}"); let err = db.apply_schema(&desired).await.unwrap_err(); let msg = err.to_string(); assert!( @@ -437,7 +434,10 @@ async fn plan_schema_for_property_type_narrowing_is_not_supported() { .unwrap(); let plan = db.plan_schema(TEST_SCHEMA).await.unwrap(); - assert!(!plan.supported, "narrowing I64 -> I32 must not be supported"); + assert!( + !plan.supported, + "narrowing I64 -> I32 must not be supported" + ); assert!(plan.steps.iter().any(|step| matches!( step, SchemaMigrationStep::UnsupportedChange { code, .. } diff --git a/crates/omnigraph/tests/staged_writes.rs b/crates/omnigraph/tests/staged_writes.rs index 30ef28b..5335057 100644 --- a/crates/omnigraph/tests/staged_writes.rs +++ b/crates/omnigraph/tests/staged_writes.rs @@ -2,7 +2,7 @@ //! exercise `stage_append`, `stage_merge_insert`, `scan_with_staged`, //! and `count_rows_with_staged` directly against a Lance dataset — no //! Omnigraph engine involved. The engine-level use of these primitives -//! is exercised by `tests/runs.rs`. +//! is exercised by `tests/writes.rs`. //! //! Test surface here: //! 1. `stage_append` + `scan_with_staged` shows committed + staged data @@ -132,7 +132,11 @@ async fn stage_merge_insert_dedupes_superseded_committed_fragment() { .await .unwrap(); let ids = collect_ids(&batches); - assert_eq!(ids, vec!["alice"], "merge_insert must not surface duplicates"); + assert_eq!( + ids, + vec!["alice"], + "merge_insert must not surface duplicates" + ); // Confirm the visible row is the rewritten one. let total: usize = batches.iter().map(|b| b.num_rows()).sum(); @@ -382,12 +386,7 @@ async fn scan_with_staged_with_filter_silently_drops_staged_rows() { // Actual: dave (staged, age=35) is dropped — only the committed matches // come back. let batches = store - .scan_with_staged( - &ds, - std::slice::from_ref(&staged), - None, - Some("age >= 30"), - ) + .scan_with_staged(&ds, std::slice::from_ref(&staged), None, Some("age >= 30")) .await .unwrap(); assert_eq!( @@ -403,12 +402,7 @@ async fn scan_with_staged_with_filter_silently_drops_staged_rows() { // Without filter, staged data IS visible — confirms the issue is // specifically filter pushdown, not fragment scanning per se. let unfiltered = store - .scan_with_staged( - &ds, - std::slice::from_ref(&staged), - None, - None, - ) + .scan_with_staged(&ds, std::slice::from_ref(&staged), None, None) .await .unwrap(); assert_eq!( @@ -686,10 +680,7 @@ async fn stage_create_inverted_index_does_not_advance_head_until_commit() { .unwrap(); let pre_version = ds.version().version; - let staged = store - .stage_create_inverted_index(&ds, "id") - .await - .unwrap(); + let staged = store.stage_create_inverted_index(&ds, "id").await.unwrap(); assert_eq!( ds.version().version, pre_version, @@ -718,7 +709,7 @@ async fn stage_create_inverted_index_does_not_advance_head_until_commit() { /// /// **When Lance #6658 lands**: this test will need to flip — replace /// the assertion with a `stage_delete` + `commit_staged` round-trip -/// and remove the residual line in `docs/runs.md`. +/// and remove the residual line in `docs/dev/writes.md`. #[tokio::test] async fn delete_where_advances_head_inline_documents_residual() { let dir = tempfile::tempdir().unwrap(); @@ -781,13 +772,9 @@ async fn create_vector_index_advances_head_inline_documents_residual() { let id_arr = StringArray::from(ids); let flat: Vec = (0..(n_rows * dim)).map(|i| i as f32).collect(); let values = arrow_array::Float32Array::from(flat); - let vec_arr = - FixedSizeListArray::new(item_field, dim as i32, Arc::new(values), None); - let batch = RecordBatch::try_new( - schema.clone(), - vec![Arc::new(id_arr), Arc::new(vec_arr)], - ) - .unwrap(); + let vec_arr = FixedSizeListArray::new(item_field, dim as i32, Arc::new(values), None); + let batch = + RecordBatch::try_new(schema.clone(), vec![Arc::new(id_arr), Arc::new(vec_arr)]).unwrap(); let mut ds = TableStore::write_dataset(&uri, batch).await.unwrap(); let pre_version = ds.version().version; diff --git a/crates/omnigraph/tests/traversal.rs b/crates/omnigraph/tests/traversal.rs index 6b6fbe3..6efe7de 100644 --- a/crates/omnigraph/tests/traversal.rs +++ b/crates/omnigraph/tests/traversal.rs @@ -504,9 +504,21 @@ query fof_chain($name: String) { let batch = result.concat_batches().unwrap(); assert_eq!(batch.num_rows(), 1); - let col0 = batch.column(0).as_any().downcast_ref::().unwrap(); - let col1 = batch.column(1).as_any().downcast_ref::().unwrap(); - let col2 = batch.column(2).as_any().downcast_ref::().unwrap(); + let col0 = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let col1 = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + let col2 = batch + .column(2) + .as_any() + .downcast_ref::() + .unwrap(); assert_eq!(col0.value(0), "Alice"); assert_eq!(col1.value(0), "Bob"); assert_eq!(col2.value(0), "Diana"); @@ -574,8 +586,16 @@ query at_acme_named() { let batch = result.concat_batches().unwrap(); assert_eq!(batch.num_rows(), 1); - let person = batch.column(0).as_any().downcast_ref::().unwrap(); - let company = batch.column(1).as_any().downcast_ref::().unwrap(); + let person = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let company = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); assert_eq!(person.value(0), "Alice"); assert_eq!(company.value(0), "Acme"); } @@ -608,8 +628,16 @@ query at_company($company: String) { let batch = result.concat_batches().unwrap(); assert_eq!(batch.num_rows(), 1); - let person = batch.column(0).as_any().downcast_ref::().unwrap(); - let company = batch.column(1).as_any().downcast_ref::().unwrap(); + let person = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let company = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); assert_eq!(person.value(0), "Bob"); assert_eq!(company.value(0), "Globex"); } @@ -633,19 +661,22 @@ query fan_out($name: String) { "#; // Alice knows Bob and Charlie, works at Acme. // Each friend paired with her company → 2 rows. - let result = query_main( - &mut db, - queries, - "fan_out", - ¶ms(&[("$name", "Alice")]), - ) - .await - .unwrap(); + let result = query_main(&mut db, queries, "fan_out", ¶ms(&[("$name", "Alice")])) + .await + .unwrap(); let batch = result.concat_batches().unwrap(); assert_eq!(batch.num_rows(), 2); - let friends = batch.column(0).as_any().downcast_ref::().unwrap(); - let companies = batch.column(1).as_any().downcast_ref::().unwrap(); + let friends = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let companies = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); let mut pairs: Vec<(&str, &str)> = (0..batch.num_rows()) .map(|i| (friends.value(i), companies.value(i))) diff --git a/crates/omnigraph/tests/validators.rs b/crates/omnigraph/tests/validators.rs index 96483d3..4c7a2f3 100644 --- a/crates/omnigraph/tests/validators.rs +++ b/crates/omnigraph/tests/validators.rs @@ -76,7 +76,9 @@ async fn init_with(schema: &str, data: &str) -> (tempfile::TempDir, Omnigraph) { let uri = dir.path().to_str().unwrap(); let mut db = Omnigraph::init(uri, schema).await.unwrap(); if !data.is_empty() { - load_jsonl(&mut db, data, LoadMode::Overwrite).await.unwrap(); + load_jsonl(&mut db, data, LoadMode::Overwrite) + .await + .unwrap(); } (dir, db) } diff --git a/crates/omnigraph/tests/runs.rs b/crates/omnigraph/tests/writes.rs similarity index 96% rename from crates/omnigraph/tests/runs.rs rename to crates/omnigraph/tests/writes.rs index f2d7dc3..13cb10f 100644 --- a/crates/omnigraph/tests/runs.rs +++ b/crates/omnigraph/tests/writes.rs @@ -1,7 +1,7 @@ -//! Tests for the direct-to-target write path (Run state machine -//! removed). The Run/`__run__` staging branch / RunRecord state machine no -//! longer exists; mutations and loads write directly to target tables and -//! commit once via the publisher's `expected_table_versions` CAS. +//! Tests for the direct-publish write path: mutations and loads write +//! directly to target tables and commit once via the publisher's +//! `expected_table_versions` CAS. (History: this replaced the removed Run +//! state machine / `__run__` staging branches / RunRecord — MR-771.) //! //! What this file covers: //! - No `__run__*` branches are created by load or mutate. @@ -127,10 +127,7 @@ async fn multi_statement_mutation_is_atomic_with_read_your_writes() { "main", MUTATION_QUERIES, "insert_person_and_friend", - &mixed_params( - &[("$name", "Eve"), ("$friend", "Alice")], - &[("$age", 22)], - ), + &mixed_params(&[("$name", "Eve"), ("$friend", "Alice")], &[("$age", 22)]), ) .await .unwrap(); @@ -187,10 +184,7 @@ async fn partial_failure_leaves_target_queryable_and_unblocks_next_mutation() { "main", MUTATION_QUERIES, "insert_person_and_friend", - &mixed_params( - &[("$name", "Eve"), ("$friend", "Missing")], - &[("$age", 22)], - ), + &mixed_params(&[("$name", "Eve"), ("$friend", "Missing")], &[("$age", 22)]), ) .await .expect_err("op-2 must fail"); @@ -543,10 +537,7 @@ async fn mutation_rejects_mixed_insert_and_delete_at_parse_time() { "main", STAGED_QUERIES, "mixed_insert_and_delete", - &mixed_params( - &[("$name", "Eve"), ("$victim", "Alice")], - &[("$age", 22)], - ), + &mixed_params(&[("$name", "Eve"), ("$victim", "Alice")], &[("$age", 22)]), ) .await .expect_err("D₂ must reject mixed insert+delete"); @@ -559,7 +550,9 @@ async fn mutation_rejects_mixed_insert_and_delete_at_parse_time() { manifest_err.message, ); assert!( - manifest_err.message.contains("split into separate mutations"), + manifest_err + .message + .contains("split into separate mutations"), "error message should direct user to split: {}", manifest_err.message, ); @@ -668,11 +661,7 @@ async fn multiple_appends_to_same_edge_coalesce_to_one_append() { "main", STAGED_QUERIES, "insert_two_friends", - ¶ms(&[ - ("$from", "Alice"), - ("$a", "Bob"), - ("$b", "Eve"), - ]), + ¶ms(&[("$from", "Alice"), ("$a", "Bob"), ("$b", "Eve")]), ) .await .unwrap(); @@ -782,8 +771,14 @@ async fn load_with_bad_edge_reference_unblocks_next_load() { // No write made it to disk: counts unchanged. let mid_persons = count_rows(&db, "node:Person").await; let mid_edges = count_rows(&db, "edge:Knows").await; - assert_eq!(mid_persons, pre_persons, "failed load must not advance Person count"); - assert_eq!(mid_edges, pre_edges, "failed load must not advance Knows count"); + assert_eq!( + mid_persons, pre_persons, + "failed load must not advance Person count" + ); + assert_eq!( + mid_edges, pre_edges, + "failed load must not advance Knows count" + ); // Second load against the same tables — succeeds (no HEAD drift). let good = r#"{"type": "Person", "data": {"name": "Pat", "age": 55}}"#; @@ -824,7 +819,9 @@ edge WorksAt: Person -> Company @card(0..1) {"type": "Company", "data": {"name": "Acme"}} {"type": "Company", "data": {"name": "Bigco"}} "#; - load_jsonl(&mut db, seed, LoadMode::Overwrite).await.unwrap(); + load_jsonl(&mut db, seed, LoadMode::Overwrite) + .await + .unwrap(); let pre_works = count_rows(&db, "edge:WorksAt").await; @@ -1014,7 +1011,10 @@ query cascade_then_explicit($name: String, $other: String) { // — Bob→Diana would survive. The exact-count check makes both ops // independently observable. let pre_knows = count_rows(&db, "edge:Knows").await; - assert_eq!(pre_knows, 3, "fixture invariant: TEST_DATA seeds 3 Knows edges"); + assert_eq!( + pre_knows, 3, + "fixture invariant: TEST_DATA seeds 3 Knows edges" + ); db.mutate( "main", @@ -1066,7 +1066,9 @@ query add_friend($from: String, $to: String) { let seed = r#"{"type": "Person", "data": {"name": "Alice"}} {"type": "Person", "data": {"name": "Bob"}} "#; - load_jsonl(&mut db, seed, LoadMode::Overwrite).await.unwrap(); + load_jsonl(&mut db, seed, LoadMode::Overwrite) + .await + .unwrap(); // Single insert: count=1 < min=2 → reject with clear message. let err = db @@ -1082,8 +1084,7 @@ query add_friend($from: String, $to: String) { panic!("expected Manifest error, got {err:?}"); }; assert!( - manifest_err.message.contains("@card violation") - && manifest_err.message.contains("min 2"), + manifest_err.message.contains("@card violation") && manifest_err.message.contains("min 2"), "unexpected error: {}", manifest_err.message, ); @@ -1121,7 +1122,9 @@ edge WorksAt: Person -> Company @card(0..1) {"type": "Company", "data": {"name": "Bigco"}} {"edge": "WorksAt", "from": "Alice", "to": "Acme", "data": {"id": "w1"}} "#; - load_jsonl(&mut db, seed, LoadMode::Overwrite).await.unwrap(); + load_jsonl(&mut db, seed, LoadMode::Overwrite) + .await + .unwrap(); // Merge-update the same edge id w1 to point at Bigco. Counted naively // as union, Alice has 2 WorksAt (committed Acme + pending Bigco) which @@ -1167,7 +1170,9 @@ edge WorksAt: Person -> Company @card(0..1) {"type": "Company", "data": {"name": "Acme"}} {"type": "Company", "data": {"name": "Bigco"}} "#; - load_jsonl(&mut db, seed, LoadMode::Overwrite).await.unwrap(); + load_jsonl(&mut db, seed, LoadMode::Overwrite) + .await + .unwrap(); // Merge load with the SAME edge id twice — the second row supersedes // the first in the finalize-time dedupe. If pending-counting doesn't @@ -1364,7 +1369,11 @@ query insert_then_update_note( ) .await .unwrap(); - assert_eq!(qr.num_rows(), 0, "letter must not be visible after early error"); + assert_eq!( + qr.num_rows(), + 0, + "letter must not be visible after early error" + ); } /// MR-920 regression: two sequential `update T set {f:v} where x=y` @@ -1446,5 +1455,9 @@ async fn second_sequential_update_on_same_row_succeeds() { } } } - assert_eq!(alice_age, Some(42), "Alice's age must reflect the second update"); + assert_eq!( + alice_age, + Some(42), + "Alice's age must reflect the second update" + ); } diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 83b7d34..a5fb275 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -9,8 +9,14 @@ fi bind="${OMNIGRAPH_BIND:-0.0.0.0:8080}" +# URI comes from the env var (the positional arg wins over any config +# `graphs` block in resolve_target_uri). OMNIGRAPH_CONFIG, when also set, +# is forwarded as --config purely to supply a policy file — the two +# compose. Without OMNIGRAPH_CONFIG the behavior is unchanged. if [ -n "${OMNIGRAPH_TARGET_URI:-}" ]; then - exec "$SERVER_BIN" "${OMNIGRAPH_TARGET_URI}" --bind "${bind}" + exec "$SERVER_BIN" "${OMNIGRAPH_TARGET_URI}" \ + ${OMNIGRAPH_CONFIG:+--config "$OMNIGRAPH_CONFIG"} \ + --bind "${bind}" fi if [ -n "${OMNIGRAPH_CONFIG:-}" ]; then @@ -28,5 +34,7 @@ omnigraph-server container startup requires one of: Optional: - OMNIGRAPH_BIND (default: 0.0.0.0:8080) - OMNIGRAPH_TARGET (used with OMNIGRAPH_CONFIG) + - OMNIGRAPH_CONFIG (may also accompany OMNIGRAPH_TARGET_URI to add a + policy file; the URI still comes from OMNIGRAPH_TARGET_URI) EOF exit 64 diff --git a/docker/entrypoint_test.sh b/docker/entrypoint_test.sh new file mode 100755 index 0000000..01fbee2 --- /dev/null +++ b/docker/entrypoint_test.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# Self-contained test for docker/entrypoint.sh argument composition. +# Runs the entrypoint against a stub server that echoes its args, and +# asserts the forwarded argv for each startup mode. No Docker required. +# +# sh docker/entrypoint_test.sh +# +# Exits 0 on success, 1 on the first mismatch. +set -eu + +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +entrypoint="$here/entrypoint.sh" + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/bin" +cat > "$work/bin/omnigraph-server" <<'EOF' +#!/bin/sh +echo "ARGS: $*" +EOF +chmod +x "$work/bin/omnigraph-server" + +# Run the real entrypoint with SERVER_BIN pointed at the stub. +ep="$work/entrypoint.sh" +sed "s#SERVER_BIN=\"/usr/local/bin/omnigraph-server\"#SERVER_BIN=\"$work/bin/omnigraph-server\"#" \ + "$entrypoint" > "$ep" + +fail=0 +check() { + desc=$1; want=$2; got=$3 + if [ "$got" != "$want" ]; then + echo "FAIL: $desc" + echo " want: $want" + echo " got: $got" + fail=1 + else + echo "ok: $desc" + fi +} + +got=$(OMNIGRAPH_TARGET_URI="s3://b/g" OMNIGRAPH_BIND="0.0.0.0:8080" sh "$ep") +check "TARGET_URI only (legacy)" \ + "ARGS: s3://b/g --bind 0.0.0.0:8080" "$got" + +got=$(OMNIGRAPH_TARGET_URI="s3://b/g" OMNIGRAPH_CONFIG="/etc/omnigraph/omnigraph.yaml" OMNIGRAPH_BIND="0.0.0.0:8080" sh "$ep") +check "TARGET_URI + CONFIG composes (policy)" \ + "ARGS: s3://b/g --config /etc/omnigraph/omnigraph.yaml --bind 0.0.0.0:8080" "$got" + +got=$(OMNIGRAPH_CONFIG="/etc/omnigraph/omnigraph.yaml" OMNIGRAPH_BIND="0.0.0.0:8080" sh "$ep") +check "CONFIG only" \ + "ARGS: --config /etc/omnigraph/omnigraph.yaml --bind 0.0.0.0:8080" "$got" + +got=$(OMNIGRAPH_CONFIG="/etc/omnigraph/omnigraph.yaml" OMNIGRAPH_TARGET="active" OMNIGRAPH_BIND="0.0.0.0:8080" sh "$ep") +check "CONFIG + TARGET" \ + "ARGS: --config /etc/omnigraph/omnigraph.yaml --target active --bind 0.0.0.0:8080" "$got" + +got=$(sh "$ep" some-uri --bind 1.2.3.4:9 --extra) +check "explicit args passthrough" \ + "ARGS: some-uri --bind 1.2.3.4:9 --extra" "$got" + +if [ "$fail" -ne 0 ]; then + echo "entrypoint_test: FAILED" + exit 1 +fi +echo "entrypoint_test: all cases passed" diff --git a/docs/dev/architecture.md b/docs/dev/architecture.md index 16cda04..813f30c 100644 --- a/docs/dev/architecture.md +++ b/docs/dev/architecture.md @@ -10,7 +10,7 @@ Three views, increasing zoom: 2. **Layer view** — the eight-layer stack inside one OmniGraph process. 3. **Component zoom-ins** — what's inside each layer. -For runtime flows (read query, mutation), see [`docs/dev/execution.md`](execution.md). For the on-disk layout of a repo, see [`docs/user/storage.md`](../user/storage.md). +For runtime flows (read query, mutation), see [`docs/dev/execution.md`](execution.md). For the on-disk layout of a graph, see [`docs/user/storage.md`](../user/storage.md). L1 (orange in the diagrams) is what we inherit from Lance; L2 (blue) is what OmniGraph adds. The L1/L2 framing is also called out in prose at the bottom of this doc. @@ -63,7 +63,7 @@ flowchart TB subgraph engine[omnigraph engine] plan[exec query and mutation]:::l2 gi[graph index CSR/CSC
RuntimeCache LRU 8]:::l2 - coord[coordinator
ManifestRepo · CommitGraph]:::l2 + coord[coordinator
ManifestCoordinator · CommitGraph]:::l2 end subgraph storage[storage trait — wraps Lance] @@ -132,7 +132,7 @@ flowchart TB subgraph state[graph state] coord[GraphCoordinator]:::l2 - mr[ManifestRepo
db/manifest.rs]:::l2 + mr[ManifestCoordinator
db/manifest.rs]:::l2 cg[CommitGraph
_graph_commits.lance]:::l2 stg[MutationStaging
per-query in-memory accumulator
exec/staging.rs]:::l2 end @@ -166,7 +166,7 @@ Code paths: - Read entry: `Omnigraph::query` at `crates/omnigraph/src/exec/query.rs:7` - Mutation entry: `Omnigraph::mutate` at `crates/omnigraph/src/exec/mutation.rs:511` -- Manifest commit: `ManifestRepo::commit` at `crates/omnigraph/src/db/manifest.rs:280` +- Manifest commit: `ManifestCoordinator::commit` at `crates/omnigraph/src/db/manifest.rs:280` - Graph index: `crates/omnigraph/src/graph_index/` - Loader: `Omnigraph::ingest` at `crates/omnigraph/src/loader/mod.rs:74` @@ -207,7 +207,7 @@ contracts: This pattern realizes read-your-writes within a multi-statement mutation and keeps failure scope bounded for inserts/updates by construction at the writer layer. See [docs/dev/invariants.md](invariants.md) and -[docs/dev/runs.md](runs.md) for the publisher CAS contract this builds on. +[docs/dev/writes.md](writes.md) for the publisher CAS contract this builds on. ### Storage trait — today vs. roadmap @@ -278,7 +278,7 @@ flowchart LR eng --> wq ``` -The server applies Cedar policy at the HTTP boundary today. The roadmap, called out in [docs/dev/invariants.md](invariants.md) as a known gap, is to push policy into the planner as predicates. After Cedar, mutating handlers go through `WorkloadController` (per-actor admission cap + byte budget; PR 2 / MR-686) before reaching the engine. The engine itself holds an `Arc` so concurrent mutations on the same `(table, branch)` serialize at the queue, while disjoint keys run in parallel — see [docs/user/server.md](../user/server.md) "Per-actor admission control" and [docs/dev/runs.md](runs.md). The CLI bypasses the HTTP layer (and admission) and calls the engine API directly. +The server applies Cedar policy at the HTTP boundary today. The roadmap, called out in [docs/dev/invariants.md](invariants.md) as a known gap, is to push policy into the planner as predicates. After Cedar, mutating handlers go through `WorkloadController` (per-actor admission cap + byte budget; PR 2 / MR-686) before reaching the engine. The engine itself holds an `Arc` so concurrent mutations on the same `(table, branch)` serialize at the queue, while disjoint keys run in parallel — see [docs/user/server.md](../user/server.md) "Per-actor admission control" and [docs/dev/writes.md](writes.md). The CLI bypasses the HTTP layer (and admission) and calls the engine API directly. Code paths: diff --git a/docs/dev/branch-protection.md b/docs/dev/branch-protection.md index d1225dc..2b6cc37 100644 --- a/docs/dev/branch-protection.md +++ b/docs/dev/branch-protection.md @@ -8,7 +8,7 @@ This page explains what the policy says and how to change it. | Setting | Value | Why | |---|---|---| -| **Required status checks (strict)** | `Classify Changes`, `Check AGENTS.md Links`, `Test Workspace`, `Test omnigraph-server --features aws`, `CODEOWNERS / drift`, `CODEOWNERS / noedit` | Every PR must pass workspace tests, AGENTS.md link integrity, and the CODEOWNERS hygiene checks. `strict: true` requires the branch to be up-to-date with `main` before merge. | +| **Required status checks (strict)** | `Classify Changes`, `Check AGENTS.md Links`, `Test Workspace`, `Test omnigraph-server --features aws`, `CODEOWNERS matches source`, `CODEOWNERS not hand-edited` | Every PR must pass workspace tests, AGENTS.md link integrity, and the CODEOWNERS hygiene checks. The two CODEOWNERS contexts must equal the job `name:` values in `.github/workflows/codeowners.yml` **verbatim** — a context naming a job that never reports (the old `CODEOWNERS / drift` used the job *id*, and the job was path-filtered) leaves every PR permanently pending and forces admin overrides. `strict: true` requires the branch to be up-to-date with `main` before merge. | | **Required approving reviews** | `1` | At least one reviewer. With a 2-person team, going higher would block all merges when one person is unavailable. | | **Require code-owner reviews** | `true` | The reviewer must be a code owner per `.github/CODEOWNERS`. This is what makes the codeowners chassis enforced. | | **Dismiss stale reviews on new commits** | `true` | A push after approval invalidates the prior review. Prevents the "approve, then sneak in unreviewed changes" pattern. | @@ -16,12 +16,12 @@ This page explains what the policy says and how to change it. | **Disallow force pushes** | `true` | No history rewrites on `main`. | | **Disallow branch deletions** | `true` | `main` cannot be deleted. | | **Required conversation resolution** | `true` | All review comment threads must be resolved before merge. | -| **Enforce on admins** | `true` | Even repo admins go through the gates. The point is no bypasses. | +| **Enforce on admins** | `false` | Admins can override the gates (`enforce_admins: false` in the JSON). This is the intended escape hatch for the 2-person team; tightening to `true` is tracked under hardening below. | | **Required signed commits** | not yet | Not enabled. Would lock out maintainers until everyone enrolls GPG/SSH commit signing. Tracked as a follow-up. | ## How to apply -Run from the repo root: +Run from the repository root: ```bash ./scripts/apply-branch-protection.sh @@ -29,7 +29,7 @@ Run from the repo root: The script reads `.github/branch-protection.json`, strips the human-readable `_comment` field (the GitHub API rejects unknown keys), and PUTs to `repos/ModernRelay/omnigraph/branches/main/protection`. -Requires `gh` authenticated with a token that has admin permissions on the repo. +Requires `gh` authenticated with a token that has admin permissions on the repository. To preview without applying: @@ -57,7 +57,7 @@ Outputs the live policy. Compare against `.github/branch-protection.json` to det - **Audit trail**: `git log .github/branch-protection.json` shows every change with a reviewable diff and a merge commit. - **Disaster recovery**: if branch protection is accidentally removed or weakened via the UI, the JSON is the canonical recovery point. -- **Consistency**: pairs with `.github/codeowners-roles.yml` (the CODEOWNERS source of truth). Repo policy lives in the repo. +- **Consistency**: pairs with `.github/codeowners-roles.yml` (the CODEOWNERS source of truth). Repository policy lives in the repository. ## What this gates @@ -69,7 +69,7 @@ After branch protection is applied, every PR targeting `main` must: 4. Have all review conversations resolved. 5. Be squash- or rebase-merged (no merge commits). -Even repo admins are subject to these rules. +Even repository admins are subject to these rules. ## Subsequent hardening (not in this PR) diff --git a/docs/dev/ci.md b/docs/dev/ci.md index d9855b0..1124cb4 100644 --- a/docs/dev/ci.md +++ b/docs/dev/ci.md @@ -2,9 +2,10 @@ `.github/workflows/`: -- **ci.yml**: text-only changes skip; otherwise `cargo test --workspace --locked` on ubuntu-latest with protobuf compiler. OpenAPI-drift check that auto-commits the regenerated `openapi.json` for same-repo PRs. Also runs the AGENTS.md cross-link integrity check (`scripts/check-agents-md.sh`). +- **ci.yml**: text-only changes skip; otherwise `cargo test --workspace --locked` on ubuntu-latest with protobuf compiler. OpenAPI-drift check that auto-commits the regenerated `openapi.json` for same-repository PRs. Also runs the AGENTS.md cross-link integrity check (`scripts/check-agents-md.sh`). - **AWS feature build job**: `cargo build/test -p omnigraph-server --features aws` on ubuntu-latest. -- **RustFS S3 integration**: spins up RustFS in Docker, runs `s3_storage`, `server_opens_s3_repo_directly_and_serves_snapshot_and_read`, and `local_cli_s3_end_to_end_init_load_read_flow`. -- **release-edge.yml**: on every push to main, retags `edge`, builds Linux/macOS-Intel/macOS-arm64 archives + sha256, publishes a rolling prerelease. -- **release.yml**: on `v*` tags, builds the 3-platform matrix and updates the Homebrew tap (`scripts/update-homebrew-formula.sh`) by pushing the regenerated formula to `ModernRelay/homebrew-tap`. +- **Windows binary build job**: `cargo build --release --locked -p omnigraph-cli -p omnigraph-server` on windows-latest with smoke checks for `omnigraph.exe version`, `omnigraph-server.exe --help`, and PowerShell installer syntax. +- **RustFS S3 integration**: spins up RustFS in Docker, runs `s3_storage`, `server_opens_s3_graph_directly_and_serves_snapshot_and_read`, and `local_cli_s3_end_to_end_init_load_read_flow`. +- **release-edge.yml**: on every push to main, retags `edge`, builds Linux x86_64 / macOS arm64 archives and Windows x86_64 zip + sha256, publishes a rolling prerelease, then smoke-tests the Windows PowerShell installer against `edge`. +- **release.yml**: on `v*` tags, builds the Linux x86_64 / macOS arm64 archives and Windows x86_64 zip release matrix, updates the Homebrew tap (`scripts/update-homebrew-formula.sh`) by pushing the regenerated formula to `ModernRelay/homebrew-tap`, and smoke-tests the Windows PowerShell installer against the tag. - **package.yml**: manual ECR image build; emits two image tags per commit (``, `-aws`) via CodeBuild. diff --git a/docs/dev/codeowners.md b/docs/dev/codeowners.md index ad388ea..14bba0b 100644 --- a/docs/dev/codeowners.md +++ b/docs/dev/codeowners.md @@ -2,26 +2,47 @@ `.github/CODEOWNERS` is **generated** — not hand-edited. The source of truth is `.github/codeowners-roles.yml`, expanded by `.github/scripts/render-codeowners.py`. CI rejects drift between the two and rejects direct edits to `CODEOWNERS` that don't accompany a yml change. -This setup gives every role change a reviewable PR and a permanent in-repo audit trail (`git log .github/codeowners-roles.yml`). +This setup gives every role change a reviewable PR and a permanent in-repository audit trail (`git log .github/codeowners-roles.yml`). -## Current roles +## Who owns what -| Role | Members | Scope | +The tables below are **generated** from `.github/codeowners-roles.yml` by `.github/scripts/render-codeowners.py` (the same render that produces `.github/CODEOWNERS`). They are the always-current "who owns what at this commit" view — don't edit them by hand; edit the yml and re-render. + + + +**Path → owners** (GitHub applies *last match wins*; the `*` catch-all is listed first and is overridden by the specific patterns below it): + +| Path | Owners | Role(s) | |---|---|---| -| `engineering` | `@aaltshuler` | All code under `crates/**`, repo infrastructure, default for unmapped paths | -| `docs` | `@aaltshuler`, `@ragnorc` | `docs/**`, README.md, AGENTS.md, CLAUDE.md, SECURITY.md | +| `*` | @ragnorc | engineering | +| `crates/**` | @ragnorc | engineering | +| `docs/**` | @ragnorc | docs | +| `README.md` | @ragnorc | docs | +| `AGENTS.md` | @ragnorc | docs | +| `CLAUDE.md` | @ragnorc | docs | +| `SECURITY.md` | @ragnorc | docs | -GitHub treats multiple owners in a CODEOWNERS line as **"any one of them satisfies the review requirement"**. For docs, either named member can approve. To require N distinct approvers on a specific path, layer a CI check on top (not currently configured). +**Roles**: + +| Role | Members | Description | +|---|---|---| +| `engineering` | @ragnorc | All production code under crates/**. Engine, CLI, server, compiler. | +| `docs` | @ragnorc | Documentation under docs/**, plus repo-level docs (README.md, AGENTS.md, CLAUDE.md symlink, SECURITY.md). | + + + +GitHub treats multiple owners on a CODEOWNERS line as **"any one of them satisfies the review requirement"**. To require N distinct approvers on a specific path, layer a CI check on top (not currently configured). ## How to change role membership or path mappings 1. Edit `.github/codeowners-roles.yml`. -2. Run `python3 .github/scripts/render-codeowners.py` (requires PyYAML; `pip install pyyaml`). -3. Commit both files in the same PR. +2. Open a PR. **CI re-renders for you**: the `CODEOWNERS` workflow regenerates `.github/CODEOWNERS` and the ownership tables above and auto-commits them back to your PR branch on same-repository PRs — you don't have to run the script locally (though you can: `python3 .github/scripts/render-codeowners.py`, requires PyYAML). + +On a fork (where CI can't push back), the workflow instead fails with the diff so you can run the script and commit it yourself. CI fails the PR if: -- `CODEOWNERS` was edited without a corresponding yml change, or -- The yml was changed but the rendered `CODEOWNERS` doesn't match. +- a fork PR left a generated artifact out of sync, or +- `CODEOWNERS` was edited without a corresponding yml change (the `CODEOWNERS not hand-edited` check). ## How to add a new role @@ -34,4 +55,4 @@ CI fails the PR if: - **Audit trail**: `git log .github/codeowners-roles.yml` is the canonical record of every role change. The rendered `CODEOWNERS` is a derived artifact. - **Roles are first-class**: paths reference roles, not raw handles. Renaming a person or rotating a role updates one place, not every path. - **Future extension**: scheduled rotation (weekly on-call, quarterly leads) plugs into the same yml without changing the path mappings. Not enabled today. -- **Consistency with the product**: omnigraph itself enforces auditable Cedar policy. The repo's code-owner policy follows the same "policy as reviewed code" pattern. +- **Consistency with the product**: omnigraph itself enforces auditable Cedar policy. The repository's code-owner policy follows the same "policy as reviewed code" pattern. diff --git a/docs/dev/execution.md b/docs/dev/execution.md index f5c2840..3a108d7 100644 --- a/docs/dev/execution.md +++ b/docs/dev/execution.md @@ -147,7 +147,7 @@ sequenceDiagram - End-of-query Lance commit: `TableStore::stage_append`, `stage_merge_insert`, `commit_staged` at `crates/omnigraph/src/table_store.rs` - Manifest commit primitive: `commit_updates_on_branch_with_expected` at `crates/omnigraph/src/db/omnigraph/table_ops.rs` -Atomicity guarantee for multi-statement mutations: a mid-query failure leaves Lance HEAD untouched on staged tables (no inline commit happened during op execution), so the next mutation proceeds normally with no `ExpectedVersionMismatch`. The publisher CAS at the very end either succeeds (manifest advances atomically across all touched sub-tables) or fails with a typed `ManifestConflictDetails::ExpectedVersionMismatch` (no partial publish). See [docs/dev/invariants.md](invariants.md) and [docs/dev/runs.md](runs.md). +Atomicity guarantee for multi-statement mutations: a mid-query failure leaves Lance HEAD untouched on staged tables (no inline commit happened during op execution), so the next mutation proceeds normally with no `ExpectedVersionMismatch`. The publisher CAS at the very end either succeeds (manifest advances atomically across all touched sub-tables) or fails with a typed `ManifestConflictDetails::ExpectedVersionMismatch` (no partial publish). See [docs/dev/invariants.md](invariants.md) and [docs/dev/writes.md](writes.md). ## Bulk loader (`loader/mod.rs`) diff --git a/docs/dev/index.md b/docs/dev/index.md index 26339b8..1fee062 100644 --- a/docs/dev/index.md +++ b/docs/dev/index.md @@ -21,7 +21,7 @@ constraints. User-facing behavior should still be documented through |---|---| | System structure, L1/L2 framing, component diagrams | [architecture.md](architecture.md) | | On-disk layout, manifest schema, URI behavior | [storage.md](../user/storage.md) | -| Direct-publish writes, D2, staged writes, recovery sidecars | [runs.md](runs.md) | +| Direct-publish writes, D2, staged writes, recovery sidecars | [writes.md](writes.md) | | Query execution, mutation execution, loader flow | [execution.md](execution.md) | | DataFusion: current state, passive wins, future improvements | [datafusion-future-improvements.md](datafusion-future-improvements.md) | | Index lifecycle and graph topology indexes | [indexes.md](../user/indexes.md) | @@ -59,6 +59,9 @@ Working documents for in-flight feature work. Removed when the work lands. | Area | Read | |---|---| | Schema-lint chassis v1 (MR-694) — `--allow-data-loss`, soft/hard drops | [schema-lint-v1-plan.md](schema-lint-v1-plan.md) | +| Inline + stored queries, request/response envelope, MCP (MR-656 / MR-976 / MR-969) | [rfc-001-queries-envelope-mcp.md](rfc-001-queries-envelope-mcp.md) | +| Config & CLI architecture — layered config, client targeting, file naming (MR-973 / MR-974 / MR-981) | [rfc-002-config-cli-architecture.md](rfc-002-config-cli-architecture.md) | +| MCP server surface — full tool parity, stored queries, modular auth (MR-969 / MR-956 / MR-974) | [rfc-003-mcp-server-surface.md](rfc-003-mcp-server-surface.md) | ## Boundary diff --git a/docs/dev/invariants.md b/docs/dev/invariants.md index 958042f..5ee4f17 100644 --- a/docs/dev/invariants.md +++ b/docs/dev/invariants.md @@ -38,7 +38,7 @@ Use it this way: publishes one manifest update. Do not commit per statement. Delete-only queries are the documented inline residual; the parse-time D2 rule prevents mixing deletes with insert/update until Lance exposes two-phase delete. - Read [runs.md](runs.md) and [execution.md](execution.md). + Read [writes.md](writes.md) and [execution.md](execution.md). 5. **Recovery is part of the commit protocol.** Writers that can advance Lance HEAD before manifest publish must write `__recovery/{ulid}.json` sidecars. @@ -56,7 +56,7 @@ Use it this way: branch they read even when index coverage is partial. Expensive index work should converge from manifest state instead of extending the critical write path. Scalar staged index builds and vector inline residuals are documented - in [runs.md](runs.md) and [indexes.md](../user/indexes.md). + in [writes.md](writes.md) and [indexes.md](../user/indexes.md). 8. **Schema identity survives renames.** Accepted schema identity must remain stable across type and property renames. Rename support belongs in migration @@ -96,17 +96,25 @@ Use it this way: | Area | Current state | Source | |---|---|---| -| Multi-table commit | Manifest CAS plus recovery sidecars; not a single Lance primitive | [runs.md](runs.md), [architecture.md](architecture.md) | -| Constructive mutations | In-memory `MutationStaging`, one end-of-query table commit per touched table, then one manifest publish | [runs.md](runs.md), [execution.md](execution.md) | -| Deletes | Inline-commit residual; delete-only queries allowed, mixed insert/update/delete rejected by D2 | [query-language.md](../user/query-language.md), [runs.md](runs.md) | +| Multi-table commit | Manifest CAS plus recovery sidecars; not a single Lance primitive | [writes.md](writes.md), [architecture.md](architecture.md) | +| Constructive mutations | In-memory `MutationStaging`, one end-of-query table commit per touched table, then one manifest publish | [writes.md](writes.md), [execution.md](execution.md) | +| Deletes | Inline-commit residual; delete-only queries allowed, mixed insert/update/delete rejected by D2 | [query-language.md](../user/query-language.md), [writes.md](writes.md) | +| Branch delete | Manifest is the single authority, flipped atomically first; per-table forks + commit-graph branch are derived state, reclaimed best-effort (`force_delete_branch`) with the `cleanup` reconciler as the guaranteed backstop. Reusing a name whose reclaim failed before `cleanup` surfaces an actionable error | [branches-commits.md](../user/branches-commits.md), [maintenance.md](../user/maintenance.md) | | Schema validation | Type checks, required fields, defaults, edge endpoint checks, and edge cardinality are enforced on write paths | [schema-language.md](../user/schema-language.md), [execution.md](execution.md) | | Unique constraints | Intra-batch and write-path checks exist; full cross-version uniqueness is still a gap | [schema-language.md](../user/schema-language.md) | -| Storage trait | `TableStorage` exists as the sealed staged-write surface; full call-site migration and capability/stat surfaces are incomplete | [runs.md](runs.md), [architecture.md](architecture.md) | +| Storage trait | `TableStorage` exists as the sealed staged-write surface; full call-site migration and capability/stat surfaces are incomplete | [writes.md](writes.md), [architecture.md](architecture.md) | | Index lifecycle | `ensure_indices` is explicit today; reconciler-based convergence is roadmap | [indexes.md](../user/indexes.md), [maintenance.md](../user/maintenance.md) | | Traversal IDs | Runtime still builds `TypeIndex`; Lance stable row-id based graph IDs are roadmap | [architecture.md](architecture.md), [query-language.md](../user/query-language.md) | | Auth | Bearer token hashing and server-side actor resolution are implemented at the HTTP boundary | [server.md](../user/server.md), [policy.md](../user/policy.md) | | Tests | Tempdir-backed Lance tests are the current substrate; there is no `MemStorage` test backend | [testing.md](testing.md) | +The branch-delete reconciler is authority-derived: it reclaims orphaned forks +today and degrades to a no-op if Lance ships an atomic multi-dataset branch +operation, so the design composes with that future rather than blocking it. This +is the same shape as invariant 7 (indexes are derived state); prefer it over a +recovery-sidecar-style approach for any new multi-dataset metadata operation, +since the sidecar would be scaffolding to remove once the substrate closes the gap. + ## Known Gaps Do not hide these behind invariant wording. Either move them forward or keep @@ -122,6 +130,15 @@ them explicit. - **Deletes and vector indexes:** `delete_where` and vector index creation still advance Lance HEAD inline because the required public Lance APIs are missing. Keep D2 and recovery coverage in place until those residuals are removed. +- **Blob-column compaction:** Lance `compact_files` mis-decodes blob-v2 columns + under its forced `BlobHandling::AllBinary` read ("more fields in the schema + than provided column indices"), so `optimize` skips any table with a `Blob` + property — reporting `SkipReason::BlobColumnsUnsupportedByLance` (loud, not a + silent drop) behind the `LANCE_SUPPORTS_BLOB_COMPACTION` gate. Reads and writes + are unaffected; only space/fragment reclamation on blob tables is deferred. + Remove the skip when the upstream Lance fix lands — the + `lance_surface_guards.rs::compact_files_still_fails_on_blob_columns` guard + turns red on that bump to force it. - **Planner capability/stat surfaces:** cost-aware planning, complete capability advertisement, and explain-with-cost are roadmap. Do not describe them as implemented. diff --git a/docs/dev/lance.md b/docs/dev/lance.md index 4017dea..9d2b990 100644 --- a/docs/dev/lance.md +++ b/docs/dev/lance.md @@ -1,6 +1,6 @@ # Lance Docs Index (for OmniGraph agents) -OmniGraph sits on top of Lance. Many problems — index lifecycle, branching, transactions, fragments, compaction, vector/FTS internals — are answered upstream in Lance's docs, not in this repo. +OmniGraph sits on top of Lance. Many problems — index lifecycle, branching, transactions, fragments, compaction, vector/FTS internals — are answered upstream in Lance's docs, not in this codebase. This file is the curated entry point. **When you hit a Lance-shaped problem, find the matching topic below and fetch the listed URL(s) before guessing.** Don't grep our codebase for behavior that is documented authoritatively in Lance. @@ -175,7 +175,9 @@ Migration from Lance 4.0.0 → 6.0.1 landed in this cycle (DataFusion 52 → 53, - **Lance #6658 closed** (2026-05-14) but `DeleteBuilder::execute_uncommitted` did **not** ship in v6.0.1 — binary search across the release stream shows it first appears in `v7.0.0-beta.10` (the closing commits landed on main but didn't backport to the 6.x line). Tracked as MR-A: migrate `delete_where` to staged, retire the parse-time D2 mutation rule, extend recovery sidecar coverage. **Gated on the Lance v7.x bump**, not this PR. v7.0.0-rc.1 dropped 2026-05-21. - **Lance #6666 still open** (`build_index_metadata_from_segments` public): vector-index two-phase blocked; inline `create_vector_index` residual retained. - **Lance #6877 still open** (`MergeInsertBuilder` dup-rowid): PR #109's `SourceDedupeBehavior::FirstSeen` + `check_batch_unique_by_keys` precondition stay load-bearing. +- **`Dataset::force_delete_branch`** (`branches().delete(name, force=true)`, dataset.rs:524) tolerates a missing branch-*contents* ref (vs plain `delete_branch`'s `RefNotFound`), but on the local store still errors `NotFound` if the branch `tree/` directory is fully absent (`remove_dir_all`'s NotFound is not caught for Lance's native error variant, refs.rs:526-549). Both variants still refuse a branch with referencing descendants (`RefConflict`). `TableStore::force_delete_branch` wraps this to be fully idempotent (tolerates already-absent). The single-authority branch-delete redesign uses it for orphan reclamation (eager best-effort reclaim + cleanup reconciler). Pinned by `lance_surface_guards.rs::force_delete_branch_semantics`. Branch delete is "flip the ref atomically, then `remove_dir_all(tree/{branch})`"; branch-exclusive data lives under `tree/{branch}/` so a drop reclaims it immediately without touching `main`. +- **Lance blob-v2 `compact_files` bug** (no public issue found as of 2026-06): `compact_files` disables binary-copy for blob datasets and forces `BlobHandling::AllBinary` on the read side; the v2.1+ structural decoder then mis-counts column infos for the blob-v2 struct and fails with `Invalid user input: there were more fields in the schema than provided column indices / infos` (`lance-encoding/src/decoder.rs::ColumnInfoIter::expect_next`). This fails even a pristine uniform-V2_2 multi-fragment blob table; vector/list/scalar/ragged columns and mixed file versions all compact fine. Reads/queries use descriptor handling (`BlobHandling::default()`) and are unaffected. `optimize` skips blob-bearing tables behind `LANCE_SUPPORTS_BLOB_COMPACTION = false` (`db/omnigraph/optimize.rs`), reporting `SkipReason::BlobColumnsUnsupportedByLance`. Pinned by `lance_surface_guards.rs::compact_files_still_fails_on_blob_columns`, which turns red when the bug is fixed → flip the gate, remove the skip branch + the `maintenance.rs::optimize_skips_blob_table_and_reports_skip` skip assertions. -Surface guards added: `crates/omnigraph/tests/lance_surface_guards.rs` (8 named guards; 3 runtime + 5 compile-only). Future Lance bumps re-run this file first as the smoke check. Two additional guards from the original plan deferred to follow-up (`manifest_cas_returns_row_level_contention_variant` needs full publisher-race harness; `table_version_metadata_byte_compatible_with_v4` needs `pub(crate)` reach extension). +Surface guards added: `crates/omnigraph/tests/lance_surface_guards.rs` (10 named guards; 5 runtime + 5 compile-only). Future Lance bumps re-run this file first as the smoke check. Two additional guards from the original plan deferred to follow-up (`manifest_cas_returns_row_level_contention_variant` needs full publisher-race harness; `table_version_metadata_byte_compatible_with_v4` needs `pub(crate)` reach extension). Bump this date stanza on the next alignment pass. diff --git a/docs/dev/rfc-001-queries-envelope-mcp.md b/docs/dev/rfc-001-queries-envelope-mcp.md new file mode 100644 index 0000000..b5d62d4 --- /dev/null +++ b/docs/dev/rfc-001-queries-envelope-mcp.md @@ -0,0 +1,351 @@ +# RFC: Inline + Stored Queries, Request/Response Envelope, MCP + +**Status:** Proposed +**Date:** 2026-05-28 +**Tickets:** MR-656 (inline `-e` + URL rename), MR-668 (multi-graph, shipped), MR-976 (Phase 1 envelope parent: MR-977 / MR-978 / MR-979 / MR-980), MR-969 (stored queries + MCP) +**Target release:** v0.6.x patch series (MR-656 + Phase 1) → v0.7.0 (MR-969 PRs 1-3) + +## Summary + +OmniGraph today exposes `POST /read` and `POST /change` with a weakly-contracted body (counts only on writes) and no per-query authorization. This RFC consolidates the work landing across three Linear tickets into one coherent design: + +1. **MR-656**: rename `/read` → `/query` and `/change` → `/mutate`, add inline `-e` CLI flag, ship three-channel deprecation on the legacy URLs. **In flight, PR #110.** +2. **Envelope hardening** (this RFC adds it as a Phase 1 before MR-969): make today's mutation surface agent-grade with idempotency keys, preconditions, deadlines, and a structured response envelope carrying `audit_id`, `commit_id`, `snapshot_id`, and cost stats. +3. **MR-969**: add a stored-query registry, `POST /queries/{name}`, a new `InvokeQuery` Cedar action with per-query scope, inline pragmas in `.gq` (`@description`, `@returns`, `@mcp`), and MCP transport over the same routing primitive. + +The bet: inline and stored queries serve different stages of the same lifecycle, run through the same engine code, and are gated by different Cedar actions. HelixDB collapsed to stored-only. Postgres has neither stored-query Cedar nor MCP. The window for an OSS, declarative, agent-grade graph query surface is open. + +## Motivation + +Three problems today: + +- **Mutation responses are too thin.** `ChangeOutput { node_count, edge_count }` is the entire memory the API has of what just happened. No `commit_id`, no `audit_id`, no `snapshot_id`. Agents reporting results have nothing to cite. Humans can't reproduce a read. +- **No agent-safe surface.** Cedar gates `read` and `change` at the action level. A token either runs *any* query or *no* query of that kind. There is no way to express "this agent can invoke `find_user` and nothing else." +- **No discovery primitive.** Agents need a tool list. SDKs need a stable contract per operation. Both are absent. + +The MR-656 rename solves the cosmetic asymmetry (`/read` was a poor pair for the future `/queries/{name}`). The envelope work and MR-969 solve the substantive gaps. + +## Non-Goals + +- Compiled query bundles (HelixDB's `queries.json` shape). `.gq` files are already declarative; the file *is* the artifact. +- Hot reload of the registry. Restart-only matches the multi-graph operational model from MR-668. +- Per-query rate limits in v1. Existing `WorkloadController` covers the bulk of the risk. Punt to a future ticket. +- Cross-graph tool listing in MCP. Agents loop over per-graph endpoints when they need multi-graph access. Avoid namespacing in the contract. +- Web dashboard / control-plane management of the registry. Operators edit `.gq` + `policy.yaml` and restart. +- Schema introspection through MCP. Schema is an operator concern; agents see types through declared return shapes on the queries they're allowed to invoke. +- Per-environment override files. Environment-specific differences live in `policy.yaml`, which already has per-env variants. + +## Background + +OmniGraph runs on Lance 6.x with a property graph layered on top: typed nodes/edges in per-type Lance datasets, atomic multi-table commits via a `__manifest` table, branchable and time-travelable through Lance versioning. The HTTP server (`omnigraph-server`) is Axum + utoipa with bearer-token auth and Cedar policy enforcement at every `_as` writer. + +MR-668 shipped multi-graph mode in v0.6.0. One server process can host 1-10 graphs, with per-graph endpoints under `/graphs/{id}/...`. Cedar policy resolves against `Server::"root"` (for management actions) and `Graph::"prod"` (for per-graph actions). + +MR-656 is currently in PR #110 (CONFLICTING / DIRTY against main; rebase planned). It renames the URL surface, adds inline source support, and ships three-channel deprecation (OpenAPI `deprecated: true`, RFC 9745 `Deprecation: true` header, RFC 8288 successor `Link`). + +## Design + +### Two paths, one engine + +| Dimension | Inline (`/query`, `/mutate`) | Stored (`/queries/{name}`) | +|---|---|---| +| Source location | Request body | `queries/*.gq` on disk | +| Parse + typecheck | Per request | Once at server boot | +| Cedar action | `read` / `change` | `invoke_query` (per-name scope) | +| MCP-exposed | No (not enumerable) | Yes (when `@mcp(expose=true)`) | +| Output schema | Inferred | Declared via `@returns`, asserted at boot | +| Audit log shape | Records query hash | Records query name | +| Failure visibility | Runtime 400 | Boot-time refusal | + +Both paths converge in the engine: + +``` +POST /query ─parse→─┐ +POST /mutate ─parse→─┤ + ├─→ run_query / run_mutate(ast, params, branch) ─→ envelope +POST /queries/{name} ───────┤ +POST /mcp/invoke ───────────┘ (MCP adapter on top of the same call) +``` + +The MR-656 rebase widens `run_query` / `run_mutate` to accept a parsed AST or source string. Inline parses on each call. Stored looks up the pre-parsed AST in the registry. Same execution path beyond that point. + +### Cedar split (the LLM-safe wedge) + +Inline and stored coexist safely because they're gated by different actions: + +```yaml +# Production policy — agents locked to a curated stored-query set +- deny: + actors: { group: agents } + actions: [read, change] # blocks /query, /mutate, /read, /change + +- allow: + actors: { group: agents } + actions: [invoke_query] + resource: Graph::"prod" + query_scope: { names: [find_user, list_orders, search_docs] } +``` + +The agent's effective surface: three stored queries by name. Cannot compose inline. Cannot enumerate schema. Cannot read arbitrary entities. A developer in the same deployment with `dev-engineers` group membership might have `[read, change, invoke_query]` allowed — full access to both paths. + +Same server, same data, two completely different API surfaces depending on token. This is the posture MR-969 calls "LLM-safe API surface." + +### `.gq` pragmas + +Stored queries self-describe at the top of the source file: + +```gq +@description("Look up a user by ID. Returns name, email, last_login.") +@returns({ name: String, email: String, last_login: DateTime? }) +@mcp(expose=true) + +query find_user($id: String) { + match { $u: User { id: $id } } + return { $u.name, $u.email, $u.last_login } +} +``` + +Three pragmas in v1: + +- `@description("...")` — string surfaced in `omnigraph queries explain` and MCP tool descriptions. +- `@returns({...})` — optional output type assertion. Compiler verifies the inferred type matches; mismatch fails server startup. +- `@mcp(expose=true|false, tool_name="alt_name"?)` — controls MCP visibility. Default is `expose=false` (callable via HTTP, hidden from MCP). `tool_name` defaults to the query name. + +Pragmas live in source, not in a separate YAML registry. Drop a file in `queries/`, restart, the registry picks it up. The full agent contract is reviewable in one diff. + +### Request envelope ("before") + +Today's request carries auth + body. The envelope adds five fields, all optional: + +```http +POST /graphs/prod/queries/find_user +Authorization: Bearer +Idempotency-Key: 01HXYZ... # mutations only +If-Match: 01HABC... # optimistic concurrency +X-Deadline: 2026-05-28T19:30:00Z # or X-Timeout-Ms: 5000 +X-Trace-Id: 01HDEF... +Content-Type: application/json + +{ + "params": { "id": "u-42" }, + "branch": "main", + "expect": "read_only", # scope assertion + "dry_run": false, # mutations only + "fields": ["name", "email"] # result projection +} +``` + +Field semantics: + +| Field | Applies to | Purpose | +|---|---|---| +| `Idempotency-Key` | Mutations | Server caches `(token, key)` → response for 10 minutes. Replays return cached response with `Idempotency-Replay: true` header. Prevents double-write on retry. | +| `If-Match` | Mutations | Run only if branch HEAD matches the given commit ID. 412 Precondition Failed otherwise. Enables read-then-write without races. | +| `X-Deadline` / `X-Timeout-Ms` | All | Server respects; returns 504-typed error past the deadline. Bounds execution for context-budget-constrained callers. | +| `X-Trace-Id` | All | Caller-supplied; server echoes back. Lets agents correlate multi-call sequences. | +| `expect` | All | Caller asserts shape: `"read_only"`, `{"max_rows_scanned": 10000}`. Server validates against parsed AST or planner estimate; rejects before running. | +| `dry_run` | Mutations | Returns what *would* happen without committing. Implemented via scratch branch + diff + discard. | +| `fields` | Reads | Server returns only listed columns. Saves bandwidth + agent context window. | + +All five fields are optional; today's call shape continues working. + +### Response envelope ("after") + +The response envelope replaces today's bare-result shape with a structured wrapper. Every endpoint (inline, stored, MCP) returns the same envelope: + +```json +{ + "result": { "name": "Alice", "email": "alice@..." }, + "audit_id": "01HGHI...", + "snapshot_id": "01HJKL...", + "commit_id": null, + "stats": { + "rows_scanned": 1, + "ms_elapsed": 4, + "bytes_read": 128 + }, + "warnings": [] +} +``` + +Response headers: + +| Header | When | Purpose | +|---|---|---| +| `Idempotency-Replay: true\|false` | Mutations | Was this response served from the idempotency cache? | +| `X-Trace-Id` | All | Echo of the request's trace ID, or server-minted if absent. | +| `Deprecation: true` | `/read`, `/change` only | RFC 9745 signal from MR-656. | +| `Link: ; rel="successor-version"` | `/read`, `/change` only | RFC 8288 successor pointer from MR-656. | + +Body envelope fields: + +| Field | When | Purpose | +|---|---|---| +| `result` | All | The actual response payload. Shape determined by the query's return type. | +| `audit_id` | All | ULID for the audit log entry. Lets the caller cite exactly what ran. | +| `snapshot_id` | All | Manifest snapshot the query observed. Reproducibility — replay with `?snapshot=`. | +| `commit_id` | Mutations | ULID of the new commit. Null for reads. Lets the caller cite what changed. | +| `stats` | All | `{rows_scanned, ms_elapsed, bytes_read}`. Lets agents learn what's expensive. | +| `warnings` | All | Non-fatal observations: deprecated property access, full-scan despite available index, scan exceeded soft row limit. Empty array when none. | + +The envelope is the API's *memory of what happened*. Without `audit_id` + `commit_id` + `snapshot_id`, agent reports are hearsay and reads are not reproducible. With them, provenance is a first-class property of every response. + +### MCP integration with multi-graph + +MCP routes are per-graph, matching the rest of MR-668's hierarchy: + +``` +GET /graphs/{id}/mcp/tools # tool list for this graph, this token +POST /graphs/{id}/mcp/invoke # invoke a tool on this graph +``` + +Single-mode collapses to `/mcp/tools` and `/mcp/invoke` at the root (same shape, no `/graphs/{id}` prefix). Both modes route through identical handler code. + +Tool list response: + +```json +{ + "tools": [ + { + "name": "find_user", + "description": "Look up a user by ID.", + "inputSchema": { "id": { "type": "string", "required": true } }, + "outputSchema": { "name": "string", "email": "string", "last_login": "datetime?" }, + "read_only": true + } + ], + "graph_id": "prod", + "snapshot_id": "01HJKL..." +} +``` + +The tool list is the subset of registered queries where (a) `@mcp(expose=true)` in source and (b) Cedar permits `invoke_query` for this token on this name on this graph. Computed per request — cheap because it's just iterating the registry + one Cedar evaluation per name. + +**Token scoping.** Most tokens carry one graph claim. Cross-graph access requires multiple Cedar rules (one per graph) and is uncommon. Agents that genuinely operate across graphs loop over `/graphs/{id}/mcp/tools` themselves. The contract stays clean; graph renames don't break tool names. + +**Discovery.** Agents are told their MCP URL at provisioning: `https://omnigraph.example.com/graphs/prod/mcp`. Token authorizes; URL identifies. Same model as every OAuth-style API. + +**`/mcp/invoke` is a protocol adapter.** Unwrap MCP protocol envelope, call the same code path as `/queries/{name}`, wrap the response in MCP shape. No new execution semantics. + +### CLI surface + +The CLI mirrors the HTTP routes. Post-MR-656 and post-MR-969: + +```bash +# Inline (MR-656) +omnigraph query -e 'query test() { ... }' # /query +omnigraph mutate -e 'query bump() { update ... }' # /mutate + +# Stored (MR-969) +omnigraph queries list # GET /queries (future) +omnigraph queries explain find_user # show params + return shape + source +omnigraph queries invoke find_user --param id=u-42 # POST /queries/find_user + +# Pragma + registry validation +omnigraph lint queries/find_user.gq # parses + verifies pragmas +omnigraph queries lint # validates the whole registry +``` + +`omnigraph queries invoke` reads bearer + URL from `omnigraph.yaml` like the other remote commands. Local invocations work the same way the existing `omnigraph query`/`mutate` do. + +### Lifecycle + +The promotion path from inline to stored is the load-bearing DX story: + +``` +1. EXPLORE omnigraph query -e 'query find_user($id: String) { ... }' --params '{"id": "u-42"}' + └─ POST /query, iterate freely + +2. STABILIZE write queries/find_user.gq with @description, @returns, @mcp pragmas + └─ git diff shows the full agent contract in one file + +3. AUTHORIZE add Cedar rule allowing invoke_query for the appropriate actor group + └─ scope_names: [find_user] + +4. DEPLOY restart server + └─ /queries/find_user goes live + └─ /mcp/tools auto-lists it for any token with invoke_query[find_user] + +5. RETIRE deny: read change for the agent group + └─ inline access closed; stored remains + └─ MR-969's "LLM-safe API surface" reached +``` + +Same `.gq` source through all five steps. No rewrite. No language shift. The pragmas are the only added syntax between exploration and production. + +## Migration + +Existing callers see no breakage: + +- `POST /read` and `POST /change` keep working, now with `Deprecation: true` headers (MR-656). +- `ChangeRequest` field names `query_source` / `query_name` accepted as serde aliases (MR-656). +- `aliases:` block in `omnigraph.yaml` unchanged; both `read`/`change` and `query`/`mutate` accepted as `command:` values (MR-656). +- New envelope fields are additive; old clients ignoring them keep working. +- `Idempotency-Key`, `If-Match`, `X-Deadline` are opt-in headers; absence is the current behavior. + +Callers move at their own pace. The envelope upgrades + URL rename ship in v0.6.x (small PRs). Stored queries + MCP ship in v0.7.0. + +## Sequencing + +**Phase 1: envelope (v0.6.x, before MR-969).** Four small PRs, ~100-200 LOC each. + +1. Wrap responses in the structured envelope. Add `audit_id`, `snapshot_id`, `commit_id`, `stats`, `warnings`. Backward-compatible if we keep today's top-level fields and add new ones alongside; cleaner break if we move to nested `result.*`. Pick one and live with it. +2. Honor `Idempotency-Key` on `/mutate` (and the deprecated `/change`). Server-side cache keyed by `(token, key)`. +3. Honor `If-Match` on `/mutate`. Wire through to the publisher CAS layer. +4. Honor `X-Deadline` / `X-Timeout-Ms` on every endpoint. Return 504-typed error past deadline. + +**Phase 2: MR-969 PR 1 (registry).** The stored-query registry, `/queries/{name}` route, `InvokeQuery` Cedar action with per-name scope, `.gq` pragma parsing (`@description`, `@returns`, `@mcp`), read-vs-mutate classification at registry load. Inline keeps working unchanged. + +**Phase 3: MR-969 PR 2 (MCP).** `/graphs/{id}/mcp/tools` and `/graphs/{id}/mcp/invoke`. Tool schemas projected from declared return types and parameter declarations. Single-graph-scoped tokens. + +**Phase 4: MR-969 PR 3 (Cedar deny-on-ad-hoc sugar).** Small Cedar-language addition so operators can lock down `/read` / `/query` while keeping `/queries/*` open. Independent of PRs 1-2. + +**Phase 5: deferred.** +- Cross-graph MCP namespacing (wait for usage signal). +- Per-query rate limits (extend `WorkloadController`). +- Schema introspection as a separate Cedar action (3-line PR). +- CLI verb consolidation (`omnigraph call `). +- Cache warming (HelixDB-style; not load-bearing). + +## Rejected Alternatives + +**Per-environment override files (`_overrides.yaml`).** Initial design had a sparse YAML file for per-env tweaks: MCP exposure, row caps, kill-switch, param locks. Rejected because every override candidate either belongs in source (`@mcp` flag), Cedar policy (per-actor visibility, per-env), or `omnigraph.yaml` (operator config). Splitting query metadata across files makes it harder to review what an agent can see. Keep source authoritative; let Cedar express the per-env differences. + +**Compiled query bundle (HelixDB's `queries.json`).** HelixDB compiles their Rust-DSL queries to JSON. Rejected because `.gq` files are already declarative. The file is the artifact. Reviewers diff source, not bytecode. + +**Stored-queries-only (HelixDB's posture).** Rejected because the personal-graph / dev-iteration use case dies without inline. Inline `-e` is the REPL for human exploration; stored is the contract for production agents. Both first-class. + +**Cross-graph tool-name prefixing (`prod.find_user`).** Rejected because graph renames would break agent contracts. Per-graph URLs let graph identity live in the URL, not in tool names. + +**Body-field graph dispatch (`{tool, graph, params}`).** Rejected because it doubles the contract surface (every tool is identified by two fields). Per-graph URLs are simpler. + +**Pragmas in YAML instead of source.** Rejected because two-file definitions (source + metadata YAML) make diffs harder to review and create drift opportunities. Source is the source of truth. + +**Pragmas as in-source comments (`#[mcp]` HelixDB-style).** Considered; chose `@mcp(...)` because comment-flavored pragmas conflate documentation and machine-readable metadata. The `@` prefix makes the pragma's role explicit. + +## Open Questions + +1. **Envelope breakage vs additive.** Phase 1.1 wraps responses in a structured envelope. Do we keep today's top-level fields *and* add new ones (additive, ugly), or move result to `result.*` (clean break, requires SDK updates)? Lean toward additive — let the new envelope coexist with the old shape until v0.7.0, then collapse. + +2. **`@returns` strictness.** Should mismatched declared-vs-inferred return type be a boot-time error or a warning? Lean toward error — silent drift defeats the assertion's purpose. Operators who want flexibility omit `@returns`. + +3. **MCP protocol transport.** Streamable HTTP (the new MCP standard) vs stdio (Anthropic's original). Both have Rust crates. Lean toward streamable HTTP since we're already an HTTP server. + +4. **Stored mutation routing.** A `.gq` file that contains both reads and writes — does the registry reject it at load (parse-time D2 rule from MR-656), or accept and classify as "mixed"? Lean toward reject. Mixed queries are a footgun; force operators to split. + +5. **`expect` field strictness.** `expect: "read_only"` against a parsed mutating query is an obvious 400. But `expect: {max_rows_scanned: 10000}` requires planner estimates that don't exist today. Either ship `expect` with only the "read_only" assertion in v1 and grow it, or wait for the planner. Lean toward shipping the partial form. + +6. **CLI `queries invoke` shape.** Today's `omnigraph query` takes a file or alias. `omnigraph queries invoke find_user` takes a stored query name. Should `omnigraph query --name find_user` also work (auto-detect)? Cleaner to keep them separate verbs — the stored vs inline distinction is part of the contract. + +## References + +- MR-656: [Support inline query strings in CLI and HTTP server](https://linear.app/modernrelay/issue/MR-656) +- MR-668: [Multi-graph server mode](https://linear.app/modernrelay/issue/MR-668) (shipped, PR #119) +- MR-969: [Stored queries with MCP exposure and per-query Cedar authorization](https://linear.app/modernrelay/issue/MR-969) +- PR #110: [feat: inline query strings in CLI and HTTP server](https://github.com/ModernRelay/omnigraph/pull/110) +- HelixDB docs: [docs.helix-db.com/llms-full.txt](https://docs.helix-db.com/llms-full.txt) — `#[mcp]` macro, scoped API keys, stored query model +- RFC 9745 (`Deprecation` header) +- RFC 8288 (`Link` relations, `successor-version`) +- MCP spec: [modelcontextprotocol.io](https://modelcontextprotocol.io) +- [invariants.md](./invariants.md) — substrate boundaries this work respects +- [../user/server.md](../user/server.md) — current HTTP surface (post-MR-656 picks up the `/query`+`/mutate` rename and deprecation) diff --git a/docs/dev/rfc-002-config-cli-architecture.md b/docs/dev/rfc-002-config-cli-architecture.md new file mode 100644 index 0000000..0a8e573 --- /dev/null +++ b/docs/dev/rfc-002-config-cli-architecture.md @@ -0,0 +1,590 @@ +# RFC: Config & CLI Architecture — Layered Config, Client Targeting, File Naming + +**Status:** Proposed +**Date:** 2026-05-30 +**Tickets:** MR-668 (multi-graph server, shipped — the dependency this builds on), MR-969 (stored queries + MCP — supplies the in-repo agent tool surface), MR-973 (quickstart / onboarding), MR-974 (agent setup surface), MR-981 (agent-friendly CLI hardening) +**Target release:** v0.8.x (tentative; phased — see Rollout) + +## Summary + +OmniGraph today has a single config file, `omnigraph.yaml`, read both by the CLI (operating the embedded engine) and by `omnigraph-server` (hosting graphs). There is **no client-side configuration that targets a *running server*** — to talk to a deployed `omnigraph-server` you drop to `curl` or the `omnigraph-ts` client. This is the one real gap in an otherwise coherent design (storage-URI addressing, multi-graph routing, per-graph policy). + +This RFC defines the config and CLI architecture that closes that gap, derived from first principles — *working backwards from what OmniGraph uniquely enables* rather than copying kubeconfig / `helix.toml`. The result: + +1. A **global-first layered config** — user-global (`~/.omnigraph/`) is the **primary, self-sufficient default**; per-project (`./omnigraph.yaml`) is an *optional* override + deployment manifest. One uniform schema, both layers optional; the CLI works from any directory with **no project file** (the `kubectl`/`aws`/`gh` posture), unlike today's project-anchored behavior. +2. A single unifying noun — the **target** — that resolves a name to a concrete `(locus, graph, sub-state, credential)` tuple, where the locus is **embedded (storage URI) XOR remote (server endpoint)**. +3. A **multi-server × multi-graph** client model (OmniGraph hosts N graphs per server and there are M servers — unlike Helix's one-cluster-one-graph). +4. **Credentials by reference, keyed by server name** (the AWS/gh/kube model) — OS keychain `omnigraph:` (preferred) → a `[]` profile in `~/.omnigraph/credentials` → `OMNIGRAPH_TOKEN[_]` env (CI). `servers.` is endpoint-only by default but may carry an explicit, secret-free `auth: { token: { env|file|command|keychain } }` source; no `credentials.yaml`; the shipped `bearer_token_env` + dotenv stay as a legacy compat path. Every committed/GitOps'd surface stays secret-free. +5. A **file-naming** decision: project and server config are **the same artifact, same name** (`omnigraph.yaml`); the only differently-named file is the user-global `config.yaml`, justified by **scope, not role**. + +The design optimizes jointly for **DX** (one command surface across embedded and remote; clone-and-go) and **AX** (agent experience: one flat resolved context, secrets structurally unreachable, branch-pinned reproducible reads, and a GitOps'd capability surface). + +## Reconciliation with shipped / planned CLI work + +Verified **against the code**, not ticket statuses (which are unreliable — e.g. MR-581 is marked done but is stale and unbuilt). Findings and the corrections they force: + +- **Noun is `graph`/`graphs`, NOT `target`/`targets`.** The config key is `graphs:` in `config.rs` and the flag is `--graph`. **This RFC uses `graphs:`/`--graph` throughout**; the unifying noun is a **`graphs:` entry** that is *embedded* (`storage:`, formerly `uri:`) XOR *remote* (`server:` + `graph_id:` defaulting to the entry key) — a typed locator (§1.1). Read any lingering `targets:`/`--target` below as `graphs:`/`--graph`. +- **`~/.omnigraph/` stands on its own merits** (Helix/aws/kube peer convention), **not** on precedent — there is **no `~/.omnigraph/` usage in the code** today. (MR-581 / MR-531 templates-into-`~/.omnigraph/` are *stale tickets, unbuilt*.) +- **Templates do not exist** in the code (no `template` command). The template mechanism is a *design question for this RFC / the init family*, not an existing foothold. +- **What actually exists in the CLI** (verified): `init, query(read), mutate(change), load, ingest, branch, schema, lint, snapshot, export, commit, policy, optimize, cleanup, graphs`. **Not built:** `serve, quickstart, template, prune, login`. `omnigraph init` exists (with `scaffold_config_if_missing`, `main.rs:1415`); the rest of the "init family" (`quickstart` MR-973, `serve` MR-970, `prune`/`init --force` MR-972/975, `mcp install`/skills MR-974, agent-mode MR-981) are **unbuilt tickets**, some stale. +- **Config still uses `aliases:`** (no `operations:` in code; MR-839 unbuilt). §6's reconciliation talks about `aliases:` as-is, noting `operations:` is a *proposed* rename. +- **`bearer_token_env` exists** (per-graph, `config.rs`); MR-971 flags a CLI-parity / server-side gap. The per-`servers.` extension lands on top of that. +- **A top-level `omnigraph lint` command exists** (verified). A stored-query *registry* validator must pick a verb that doesn't read as a competing lint/check. + +## Motivation + +Three problems, in priority order: + +- **No client→server targeting config.** The moment an operator stands up `omnigraph-server` — for bearer auth + Cedar at a network boundary + admission control + multi-graph routing — the CLI can't address it. `curl` is the fallback. There is no named, switchable, credential-carrying way to say "run this against `prod` on the team server." +- **Multi-server × multi-graph has no first-class expression.** OmniGraph genuinely runs N graphs per server across M servers. The same graph is **multi-homed** — `s3://b/prod` may be `prod` on server A, `production` on server B, and opened directly by the CLI. Today's flat `graphs:` map (name→storage-URI) can't express "graph `production` on server `prod-eu`." +- **Solo-first and embedded-first are unserved by the remote story.** A solo developer with no projects should define everything in `~`. A developer iterating locally (embedded, no server) and then pointing at staging (remote) should change *one word*, not learn a second command surface. + +MR-668 shipped the server side (multiple graphs per server). MR-969 ships the in-repo agent tool surface (stored queries / MCP). This RFC supplies the **client and config layer** that lets humans and agents target that surface coherently — the foundation under MR-973 / MR-974 / MR-981. + +## Non-Goals + +- **A control plane / dashboard for config.** Operators edit files and (for servers) restart. No runtime config-mutation API. Matches the MR-668 / MR-969 operational model. +- **Hot reload.** Restart-only for server-side config, matching MR-668 and MR-969. +- **Embedding secrets in any config file.** Credentials are by-reference; the git-ignored `auth.env_file` dotenv (or, later, the OS keychain) holds tokens. Never a committable `*.yaml`. +- **Renaming the project manifest by role.** No `omnigraph.server.yaml` / `omnigraph.client.yaml`. Role lives in sections, not filenames (see Design §3). +- **Dropping embedded mode.** Embedded-first is load-bearing for the file-naming decision; this RFC assumes it stays. +- **Cross-graph / cross-server tool listing in MCP.** Clients loop over per-graph catalogs (a MR-969 non-goal, restated). + +## Background + +OmniGraph runs on Lance 6.x: typed nodes/edges in per-type Lance datasets, atomic multi-table commits via a `__manifest` table, branchable and time-travelable. The CLI (`omnigraph`) operates the **embedded engine** directly against a storage URI — no HTTP client in its runtime dependencies. `omnigraph-server` (Axum) is a *separate* HTTP front-end over the same engine, with bearer auth + per-graph Cedar (MR-668). The two read the same `omnigraph.yaml` but never connect to each other. + +OmniGraph **already has a credentials-by-reference mechanism**, which this RFC builds on rather than replacing: `TargetConfig.bearer_token_env` names the env var holding a graph's bearer token, and `auth.env_file` points at a git-ignored dotenv (`.env.omni`) that the CLI auto-loads into the process (`load_env_file_into_process`) with real-env-vars-win precedence; `resolve_remote_bearer_token` resolves a token via env var then dotenv named lookup. `.env.omni` is already in `.gitignore`. + +The six **irreducible enablers** that drive the design (referenced as E1–E6 below): + +| # | Enabler | Consequence | +|---|---|---| +| E1 | A graph is a **self-contained storage URI**; the substrate (object store + manifest CAS) is the source of truth — no server required to read/write. | A graph is addressable **directly (embedded)**, not only via a server. | +| E2 | A server hosts **many graphs**; **many servers** exist. | The remote address space is **`{server} × {graph_id}`**. | +| E3 | The same graph is **multi-homed** under different per-locus names. | **Name ≠ identity.** Resolution is mandatory. | +| E4 | **Branch / commit / snapshot** are first-class addressable sub-state. | An address is *graph @ branch/snapshot*, not just graph. | +| E5 | Enforcement is **two-layered**: engine-layer Cedar (`_as` writers, works embedded) + HTTP-boundary bearer+Cedar (server only). | *How* you reach a graph determines *which* enforcement applies. | +| E6 | **Stored queries / MCP tools are a per-graph registry defined in the project config** (MR-969). | The **agent tool surface is version-controlled in the repo**. | + +Competitors collapse dimensions OmniGraph keeps live: **Helix** fuses E2+E3 (one cluster = one graph); **namidb** fuses E1+E3 into the URI (`s3://b?ns=prod`) and serves one namespace per process. OmniGraph has all of E1–E6 at once, so its config resolves a richer space — but the richness is *earned* by capability. + +## Design + +### 1. The address space and the `target` abstraction + +Every OmniGraph address is a tuple: + +``` +(locus, graph, sub-state, credential) + locus = embedded(URI) XOR remote(server-endpoint) # E1, E2 + graph = a URI (embedded) | a graph_id on a server (remote) # E3 + sub-state = branch | snapshot # E4 + credential = cloud-storage creds (embedded) | bearer token (remote) # E5 +``` + +The config's only job is **name → this tuple**. Define one noun — a **target** — that resolves to either shape: + +```yaml +targets: + dev: # embedded — substrate-direct (E1) + storage: s3://team-bucket/dev.omni + branch: main # sub-state (E4) + staging: # remote — resolves a server by reference (E2/E3) + server: staging # → looked up in `servers` + graph_id: prod # the graph's id on that server (defaults to the entry key) + branch: review +``` + +`--target staging` resolves: project `targets.staging` → `{server: staging, graph_id: prod, branch: review}` → `servers.staging` → `{endpoint, token-by-ref}` → final `(remote(https://…), prod, review, $TOKEN)`. Embedded targets skip the server hop and use cloud-storage credentials. + +**Two concepts, not kubeconfig's three.** kube splits cluster / user / context; that 3-way split is its most-cursed UX. A target *bundles* server+graph+branch+defaults under one name; the **only** thing split out is `servers`, because endpoints+credentials are shared across many targets and are secret-bearing (different ownership and rate-of-change; see §2). Result: **2 nouns — `servers` and `targets`.** Embedded `targets` (`storage:`) subsume today's `graphs:` entries. + +### 1.1 The resolved address is a typed *locator*, not a `uri` string + +The shipped config models a graph as a single `uri: String`, and code branches on `is_remote_uri(uri)`. That conflates two structurally different addresses: an **embedded** graph is a *complete, self-contained* address — one storage URI = one graph, opened directly via the embedded engine; a **remote** graph is a *server endpoint + a `graph_id`* — one server hosts N graphs. A bare server URL **is not a graph**; it lacks the `graph_id`. The cost of the string model, in the code today: + +- the CLI re-decides "server or file?" via `is_remote_uri` at ~16 call sites; +- `TargetConfig` (one `uri` field) **cannot express** multi-server × multi-graph or a multi-homed graph (E2/E3) — "graph `production` on server `prod-eu`" has no representation; +- the CLI **bails on remote URIs** for most operations, precisely because the string can't carry the `graph_id`; +- the `omnigraph-ts` SDK had to model `baseUrl` **+** `graphId` *separately* (rewriting `/graphs/{graphId}/…`) — it invented the structure the string lacks. + +So the *resolved* address is a **typed locator**, not a string: + +```rust +enum GraphLocator { + Embedded { storage: StorageUri }, // file:// , s3:// — a complete graph + Remote { server: ServerId, graph_id: GraphId }, // which server + which graph (+ bearer creds) +} +``` + +A `graphs:` entry resolves into this **once**; downstream code dispatches on the variant (the breadboard's `GraphConn = Embedded(engine) | Remote(http)`) instead of re-sniffing a scheme at each call site. The `uri` string becomes an *input format* for the embedded variant, never the address itself. + +**YAML naming follows the locator — the *key* names the locus**, so neither the value's scheme nor a comment is load-bearing: + +| Locus | Key | Value | +|---|---|---| +| Embedded | **`storage:`** (shipped `uri:` is a deprecated alias) | a storage URI (`s3://…`, `file://…`) | +| Remote | **`server:`** | a name in `servers:` (its `endpoint` + creds resolve by name, §5) | +| Remote graph id | **`graph_id:`** | the id on that server — **defaults to the entry key**; set only when the local alias differs | + +An entry has `storage:` **xor** `server:` — the deserializer rejects *both* and *neither* (no silent ambiguity). This removes two prior confusions: `graphs:` (the map) vs `graph:` (the remote id), and `uri:`-might-be-a-server. + +```yaml +servers: + prod-eu: { endpoint: https://og-eu.internal:8080 } +graphs: + dev: { storage: s3://team-bucket/dev.omni } # embedded + production: { server: prod-eu } # remote — graph_id = "production" (the key) + staging: { server: prod-eu, graph_id: prod } # remote — alias ≠ server's id +``` + +### 1.2 Invalid configs are rejected by design + +The DX rule is: **a config field is either honored or rejected, never silently ignored**. The loader therefore has two phases: + +1. Parse YAML into a loose/raw shape that preserves origin (`base_dir`, layer, line/path when available). +2. Convert once into a typed, role-aware resolved config. Every command receives the resolved form, not the raw YAML structs. + +The typed graph shape is: + +```rust +enum GraphEntry { + Embedded(EmbeddedGraphEntry), + Remote(RemoteGraphEntry), +} + +struct EmbeddedGraphEntry { + storage: StorageUri, + branch: Option, + policy: Option, + queries: QueryRegistrySpec, +} + +struct RemoteGraphEntry { + server: ServerId, + graph_id: GraphId, + branch: Option, +} +``` + +That makes these rules structural rather than advisory: + +- A graph entry must specify **exactly one** locator: `storage:`/legacy `uri:` xor `server:`. +- `policy:` and `queries:` are valid only on `Embedded` graph entries, because they define the capability surface of a graph this process opens directly. A `Remote` graph entry points at a server; that server owns policy and stored-query definitions. +- `omnigraph-server` may serve only `Embedded` graph entries. A server manifest entry with `server:` is rejected: a server should not "host" a graph by proxying another server. +- A named graph uses its own graph entry. Top-level `policy:` / `queries:` are a legacy anonymous-bare-URI compatibility path only; if a named graph is selected while top-level blocks would be ignored, config validation errors with a migration hint. +- A client-defined remote graph discovers stored queries from the server (`GET /queries`) and invokes them (`POST /queries/{name}`); it does not define `queries:` locally for that remote graph. + +Examples that must fail fast: + +```yaml +graphs: + prod: + storage: s3://team-bucket/prod.omni + server: prod-us # invalid: storage xor server +``` + +```yaml +graphs: + prod: + server: prod-us + graph_id: production + policy: { file: ./policies/prod.yaml } # invalid: remote graph policy lives on the server + queries: + find_user: { file: ./queries/find_user.gq } # invalid: remote graph queries are discovered +``` + +`omnigraph config view --resolved --show-origin` is the user-facing debugger for this boundary: it shows the final `Embedded` or `Remote` graph and where every honored field came from. Fields that cannot be honored never make it into the resolved view; they fail validation first. + +### 2. Layered config — global-first, uniform schema, project-optional + +**Posture: global-first, project-optional.** OmniGraph's CLI is primarily a *client* (it operates against graphs and servers, embedded or remote), so it sits on the **global-first** side of the CLI-config axis — like `kubectl` / `aws` / `gh` / `docker`, and unlike *project-first* tools (`git` / `cargo` / `terraform`) whose primary config is per-repo. The **global user config is the primary, self-sufficient default**; the project file is an *optional* repo-scoped override (and, when present, the deployment manifest). `omnigraph query --target prod` must work from **any directory with no project file**, exactly as `kubectl get pods --context prod` works from anywhere. *(This is a deliberate flip from today, where the CLI reads `./omnigraph.yaml` and does not even walk parent dirs — i.e. today it is project-anchored.)* + +**Rule: the two layers share ONE raw schema, and each is fully self-sufficient** (the git-layering mechanism — same schema at both levels; you never need a repo to have a working config). Do **not** specialize the file format by layer. Instead, run the same role-aware validation everywhere (§1.2): the global and project layers may both define graph locators, defaults, servers, and aliases, but fields that are meaningless for a resolved graph variant are rejected rather than ignored. For example, `queries:` is valid for an embedded graph this config opens directly; it is invalid on a remote graph entry because remote stored queries are server-owned and discovered. + +This makes the **zero-project case the default, not an edge case**: a solo user (or an agent) defines everything needed for client work in `~/.omnigraph/config.yaml` — servers, embedded + remote graph locators, defaults, aliases, and optionally personal embedded-graph query registries — and **never creates a project file**. A team adds `./omnigraph.yaml` only when it wants repo-scoped overrides or a committed, GitOps'd deployment manifest. Global-first does **not** forbid project files; it stops *requiring* them (the kubectl model: `~/.kube/config` is sufficient and default; per-project kubeconfigs are opt-in via `KUBECONFIG`). + +| Layer | Required? | Typical use | Path | +|---|---|---|---| +| Global | no | **the default** — solo/agent's entire config; shared servers+creds for teams; even a personal server's graphs/queries | `~/.omnigraph/config.yaml` | +| Project | no | **opt-in** — repo-scoped overrides + the committed deployment manifest (graphs, queries, policy) | `./omnigraph.yaml` | + +**Precedence (low → high):** built-in defaults < global < project < env vars < CLI flags. With no project file it collapses to **built-in < global < env < flags** — the common global-only path. + +**Merge semantics — "closest layer wins, at the smallest meaningful unit"** (the field consensus: git / kubeconfig / cargo / Helm / VS Code): +- **Settings objects** (`defaults`, `auth`, `server`) → **deep-merge per field**: a project sets `defaults.graph` and *inherits* the global `defaults.output_format`. (VS Code / cargo behavior.) +- **Named-resource maps** (`servers`, `graphs` / compat `targets`, `queries`, `aliases`) → **union by key; on a collision the higher layer's entry REPLACES the lower wholesale** — *no field-level deep-merge within an entry*. (kubeconfig: union contexts by name.) The footgun this avoids: global `servers.prod = {endpoint, policy}`, project `servers.prod = {endpoint: other}` — deep-merge would silently retain the old fields; replace makes the project's `prod` self-contained and predictable. +- **Lists/arrays** → **replace, never append** (Helm convention; appending is order-sensitive and surprising). +- **Scalars** → higher layer wins. +- **Relative paths carry their origin's base_dir.** A `queries:` entry's `.gq` path, or a `policy.file`, resolves against the directory of the layer it was *defined in* — global entries under `~/.omnigraph/`, project entries under the project dir. +- **Inspectable (non-negotiable):** `omnigraph config view --resolved --show-origin` prints each final value *and which layer set it* (the `git config --show-origin` / `kubectl config view` rule). A layered config without origin-tracing is a debugging trap. + +### 3. Roles, and the file-naming decision (same name for project = server) + +`omnigraph.yaml` carries two *roles* that diverge in prod and collapse on a laptop: + +- **Server role** (read by `omnigraph-server`): `graphs:` entries that are **embedded storage locators**, per-graph `policy.file`, **`queries:` — the stored-query/MCP registry lives here**, plus serving knobs. Remote graph locators are rejected in this role. +- **Client role** (read by the CLI/agent): `servers:`, embedded or remote `graphs:` locators, `defaults:`, `aliases:`. A remote graph locator points at server-owned capabilities; it cannot define local `policy:` or `queries:`. + +**Project config and server config are the same artifact, hence the same name.** The server *serves the project*: the file that says "these graphs exist, with these stored queries and this policy" is simultaneously the project manifest and the server's deploy config. Role is distinguished by which *sections* are populated, never by filename. Readers ignore sections that are not theirs (today's file already does this with `cli:` vs `server:`). + +**Why not kube's role-split.** Two coherent models exist: (A) one project file with role-sections (Helix `helix.toml` holds both `[local.dev]` and `[enterprise.production]`; compose; Cargo), and (B) deployment-manifest strictly separate from client config (kubectl — you never put a context in `deployment.yaml`). kube is the sharpest topological analog (multi-server × multi-graph, one client targeting many), so B has a real claim. The tiebreaker is **E1: OmniGraph is embedded-first.** In embedded mode the manifest's `graphs:` *is* the local target list — manifest and local-client-view are the same object, so splitting them (B) fights the grain and forces two files for local work. kube splits because it has **no** embedded mode (client always remote+global). So: take the half kube is right about — *remote* client targeting (`servers:`, endpoints, creds) is a separate concern in a separate **user-global** file (`config.yaml`, like `~/.kube/config`); reject the half it is wrong about for us — do **not** split the *project* layer by role. **The second name (`config.yaml`) is justified by scope (user-global), not role.** *(If OmniGraph ever dropped embedded mode and went pure-remote, model B's strict split would become cleanest.)* + +### 4. File naming + +Principles from the field: **one global dir** `~/.omnigraph/` (like `~/.aws`/`~/.kube`/`~/.helix`), with config/cache/state as **subdirectories** (separation without XDG's three-root scatter); **secrets keyed by server name in the OS keychain or a separate git-ignored profile file** (AWS/gh model, not a new `credentials.yaml`); **project-root manifest keeps the app-named file** (`Cargo.toml`, `package.json`); **`.yaml`, not `.yml`**; keep OmniGraph's established names. The genuinely *new* decisions are the **global** dir's existence and keyed-by-name resolution with an explicit `auth.token` override (MR-971); the shipped `bearer_token_env` + `auth.env_file` mechanism remains as legacy compat. + +| Artifact | Path / name | Why | +|---|---|---| +| Project = server config (one artifact) | `./omnigraph.yaml` | **Keep.** Root manifest like `Cargo.toml` / `compose.yaml` / `helix.toml`. Same name for both roles because it is one file. In prod the server's deploy repo and an app repo each have their own `omnigraph.yaml` — same name, different repos. | +| Global user config | `~/.omnigraph/config.yaml` | **One dir** (`~/.omnigraph/`, like `~/.aws`/`~/.kube`/`~/.helix`). Named `config.yaml` *not* `omnigraph.yaml` — the name signals scope (and `~/.aws/config`, `~/.kube/config`, `~/.helix/config` all do this). Holds the full schema so a solo user needs nothing else. | +| Credentials | OS keychain (`omnigraph:`, preferred) → `~/.omnigraph/credentials` profile file (`[]`, `0600`, git-ignored). **Keyed by server name**, inside the one dir. | **Key by name, AWS/gh model** — `~/.aws/credentials [profile]`, `~/.kube/config users:`, `~/.helix/credentials`. *Not* a `credentials.yaml`, and *not* a per-server hand-named env var; the secret lives under the server name (no indirection). Legacy `bearer_token_env` + `.env.omni` dotenv remain as a compat path. See §5. | +| Cache / state | `~/.omnigraph/cache/`, `~/.omnigraph/state/` | Subdirs of the one dir (like `~/.aws/sso/cache/`, `~/.kube/cache/`) — cache is `rm -rf`-safe and backup-excludable without scattering across XDG roots. | +| Cedar policy | `./policies/.yaml` + `.tests.yaml` | **Keep.** Referenced by `policy.file`. | +| Schema | `./*.pg` (e.g. `schema.pg`) | **Keep.** | +| Stored queries | `./queries/*.gq` | **Keep.** `.gq` sources referenced by the `queries:` registry. | + +**Global dir: `~/.omnigraph/` — one place, with subdirectories.** Everything OmniGraph keeps for a user lives under a single `~/.omnigraph/` directory, matching the peer group (`~/.aws`, `~/.kube`, `~/.docker`) and the direct competitor (`~/.helix`). This is what DB/cloud-CLI users expect and the lowest-cognitive-load shape. + +*Separation and "one place" are not in conflict* — the decisive realization. The peer tools get config/cache/state separation via **subdirectories inside the one dir**, not via XDG's three scattered roots: `~/.aws/sso/cache/`, `~/.kube/cache/`. So OmniGraph keeps `~/.omnigraph/config.yaml`, `~/.omnigraph/credentials`, `~/.omnigraph/cache/` (catalogs — `rm -rf`-safe, backup-excludable), `~/.omnigraph/state/` (session, logs) — getting cache hygiene **and** a single discoverable location, without the XDG scatter. An earlier draft argued XDG on a false dichotomy (it assumed single-dir ⇒ mixed); subdirs dissolve it. `~/.omnigraph/` is canonical and documented; `$XDG_CONFIG_HOME` may optionally be honored if a user has set it, but XDG is not part of the mental model. + +**Env / override precedence (the `KUBECONFIG` analog):** +- `OMNIGRAPH_CONFIG=/path` — explicit config file, highest precedence. +- `OMNIGRAPH_HOME=/path` → the global dir (default `~/.omnigraph/`); `$XDG_CONFIG_HOME` optionally honored if a user has set it, but `~/.omnigraph/` is canonical. +- Cache and state are subdirs of the one dir: `~/.omnigraph/cache/` (cached remote catalogs), `~/.omnigraph/state/` (session, logs). +- Per-server token resolution: an explicit `auth: { token: {...} }` source (env/file/command/keychain) wins if set; otherwise **keyed by the server name** — `OMNIGRAPH_TOKEN_` (or `OMNIGRAPH_TOKEN` for the active server) → OS keychain `omnigraph:` → the `[]` profile in `~/.omnigraph/credentials`; legacy `bearer_token_env` still honored. See §5. + +### 5. Credentials, connection tiers, and bind portability (12-factor) + +**Credentials are by-reference everywhere, never inlined — and keyed by the *server name*, not by a hand-invented env-var name.** This is the one place the design departs from simply reusing the shipped `bearer_token_env` mechanism, because that mechanism is sub-optimal for a multi-server client: it forces the operator to invent and coordinate an env-var name per server (three steps to add a server: pick a var, name it in config, set it in the store). The peer group (AWS profiles, `gh` hosts, kubeconfig users, docker auths) instead keys the secret **by the server's name** — no indirection. OmniGraph should match that. + +**Resolution for server `` (no config field required):** +1. **`OMNIGRAPH_TOKEN_`** env var (name-derived, upper-snake), else **`OMNIGRAPH_TOKEN`** for the active server — the CI/headless override (12-factor). +2. **OS keychain** entry `omnigraph:` — the preferred interactive store (no plaintext on disk); written by `omnigraph login `. +3. **`~/.omnigraph/credentials`** — an AWS-style profile file keyed by server name (mode `0600`, git-ignored), the fallback when no keychain: + ```ini + [prod-us] + token = … + [prod-eu] + token = … + ``` +So a `servers.` with no token field resolves by name — adding a server is one step (`omnigraph login `), and "multiple servers, multiple tokens" falls out for free. + +**But implicit must not be the *only* path — explicit sourcing is a first-class option** (the DX/AX lesson). Pure-convention is invisible (you must *know* `OMNIGRAPH_TOKEN_`), can't integrate with a secrets-manager's fixed var name, and can't do dynamic/short-lived tokens. So a server may declare an explicit `auth:` block — a **method-agnostic wrapper** (today only `token:` for bearer; `mtls:`/`oidc:` are the future siblings, so the credential model never has to be re-keyed) holding a tagged token *source*. Secrets are *still* never inlined (every source is a reference): + +```yaml +servers: + prod-us: + endpoint: https://og-us… + auth: { token: { env: OG_PROD_US_TOKEN } } # explicit env var — self-documenting (= legacy bearer_token_env) + prod-eu: + endpoint: https://og-eu… + auth: { token: { command: [vault, read, -field=token, secret/og] } } # dynamic / short-lived + edge: + endpoint: https://og-edge… + auth: { token: { file: /run/secrets/og-token } } # k8s/docker mounted secret + staging: + endpoint: https://og-staging… # no auth: → implicit chain (below) +``` + +| `auth.token:` source | when | DX/AX value | +|---|---|---| +| *(auth omitted)* | the common case | zero-config; `omnigraph login` populates keychain `omnigraph:` | +| `{ env: VAR }` | secrets-manager / CI injects a fixed var | **self-documenting** — config states the source; = the legacy `bearer_token_env` | +| `{ file: PATH }` | k8s/docker secret mounted as a file | no env plumbing | +| `{ command: [...] }` | Vault, cloud IAM, `gh auth token` | **dynamic tokens** — first-class exec, the capability pure-env/keychain can't give (kube `exec` / AWS `credential_process`) | +| `{ keychain: ENTRY }` | pin a non-default keychain entry | explicit override of the name-derived default | + +**Resolution per server:** if `auth.token:` is set, use that source (no fallthrough). Else the **implicit chain**: `OMNIGRAPH_TOKEN_` (or `OMNIGRAPH_TOKEN` for the active server) → keychain `omnigraph:` → `[]` in `~/.omnigraph/credentials` (`0600`, git-ignored). `omnigraph login ` writes/rotates only that server's secret; per-server precedence is independent; sharing is opt-in (same env var or source). The `command` source runs locally with the operator's own privileges and is defined only in operator-owned config (never server-supplied), so it adds no remote-execution surface. The `auth:` wrapper is method-agnostic so adding mTLS/OIDC later is a new sibling key, not a breaking re-key (Hyrum's Law: the field name is a contract once shipped). There is **no `credentials.yaml`** and **no inlined secret**. *Convention for the floor, explicit for control — and explicit is legible to agents and never inlines a secret.* + +**Back-compat.** The shipped per-graph `bearer_token_env` + `auth.env_file` dotenv (`resolve_remote_bearer_token`, real-env-wins) keeps working unchanged for existing single-server setups; `bearer_token_env` is just the legacy flat alias for `auth: { token: { env } }`. Resolution tries an explicit `auth.token:` (or legacy `bearer_token_env`) first, then the keyed-by-name chain — so nothing breaks, but the zero-config default is the no-boilerplate keyed-by-name path. (MR-971 — the `bearer_token_env` parity gap — is where this resolver work lands.) + +**Three connection tiers** (Supabase/Prisma teach the zero-config floor): +1. **Env vars** — `OMNIGRAPH_SERVER=https://…` + `OMNIGRAPH_TOKEN=…`: zero-config remote, no file (the `DATABASE_URL` floor). +2. **Global `config.yaml`** — named `servers:` + `graphs:` for multi-server setups (the AWS-profiles convenience). +3. **Project `omnigraph.yaml`** — project-pinned targets/graphs, committed. + +**Keep `omnigraph.yaml` a *portable* manifest (12-factor).** Deploy-specific runtime that varies per environment — the **bind host/port**, worker counts — should be supplied by **`--bind` / `OMNIGRAPH_BIND` (flags/env)**, *not* a committed `server.bind:` baked into the manifest. A manifest that hardcodes `0.0.0.0:8080` is not portable across deploys and leaks an environment detail into a version-controlled file. The same-named `omnigraph.yaml` stays portable across deploys precisely because the volatile, per-environment knobs live in env/flags (12-factor config), while the stable, portable definition (graphs, queries, policy) lives in the file. This is the one concrete lesson taken from kube's model-B without adopting its file split: portability via env/flags, not via a second file. + +### 6. Where stored queries live: defined locally, invoked remotely + +A stored query splits across two axes; do not conflate them: +- **Definition** (`.gq` source + `queries:` entry) lives next to the **embedded graph entry that owns it**. For a hosted remote graph, that is the **deployment manifest** read by `omnigraph-server`; for a personal embedded graph, it may be the user's own config. It never lives on a client-side `Remote` graph entry. +- **Discovery** ("what tools exist for me?") is fetched from the **server** (Cedar-filtered `GET /queries` / MCP catalog) at connect time. +- **Invocation** is **remote** (client → server, HTTP/MCP) — or **embedded** (the CLI opens the graph directly and reads the same manifest). + +For remote use, the client carries *pointers to servers*, not query definitions; it **discovers and invokes**, never defines. This is the **capability-as-code guarantee for agents**: an agent can only invoke tools the server's *committed, reviewed* config exposes — it **cannot define a new tool at runtime**. Definition is structurally outside the agent's reach. + +`queries:` (graph-capability registry, Cedar-gated when served remotely, MCP-visible when exposed) and `aliases:` (client CLI shortcut) overlap — both can name `.gq`-backed operations. This RFC keeps them siblings (the MR-969 decision); the clean long-term is **one registry, two invocation surfaces** (embedded + remote), with `aliases:` subsumed. Out of scope here. + +#### Reconciling `aliases:` with the role model + +`aliases:` is the pre-MR-969, **client-role, embedded-only, ungated** ancestor of `queries:`. An alias bundles `command` (read/change), `query` (`.gq` path), `name` (symbol), `args` (positional param names), and `graph`/`branch`/`format` defaults; the CLI runs it embedded. The server never reads it. So: + +- **Role:** `aliases:` is **client-role** (CLI behavior) → it may live in **both** the user-global `config.yaml` and the project manifest, layered. `queries:` is **graph-capability role** → it lives only on an `Embedded` graph entry, and for remote server graphs that means the server deployment manifest. *Who opens the graph determines where query definitions can live.* +- **Difference:** `aliases:` = embedded invocation, no gating, explicit `command`, bundles client defaults + positional args. `queries:` = remote (+future embedded), Cedar + `mcp.expose`, **infers** read/mutate, bundles only MCP settings. +- **Convergence:** decompose an alias — *definition* (name→.gq+symbol) → `queries:` (the superset: typed, validated, gated, multi-surface, no redundant `command`); *target/branch/format* → client invocation context (`--target`/`--branch`/`--format` or `defaults:`), not baked per-query; *positional `args`* → thin CLI sugar or dropped (agents/services use named JSON params). End-state: one `queries:` registry + the client config model subsumes `aliases:`. +- **Validation:** a file-backed alias (`query: ./foo.gq`) may target only an embedded graph. A remote graph shortcut must be explicit that it invokes a server-owned stored query, e.g. `invoke: find_user`, so the client cannot smuggle a new `.gq` definition into a remote capability surface. +- **v1:** keep `aliases:` unchanged. Footgun worth a load-time warn: an alias and a query with the same name in one manifest are different namespaces invoked differently (`--alias X` vs `POST /queries/X`). + +```yaml +aliases: + local_owner: + command: query + query: ./queries/owner.gq + name: owner + graph: dev # valid only if `dev` resolves Embedded + + remote_owner: + invoke: find_user + graph: prod # valid only if `prod` resolves Remote; source lives on the server + args: [name] +``` + +### 7. CLI surface + +- `omnigraph login ` — interactive auth; stores the token keyed by server name in the OS keychain (`omnigraph:`) or the `[]` profile of `~/.omnigraph/credentials` (0600). The `gh auth login` analog. +- `omnigraph use ` — set the active graph (writes the appropriate layer). The `kubectl config use-context` analog. +- `omnigraph config view [--resolved] [--show-origin] []` — print the merged config and, with `--resolved`, the final tuple **plus the origin layer of every field** (the `git config --show-origin` / `kubectl config view` analog). Resolution is never a mystery. +- All existing verbs (`query`, `mutate`, `load`, `schema`, `branch`, …) gain `--graph `; resolution decides embedded vs remote transparently. + +### 7.5 Init, login, and bootstrap — three tiers (folds in the Q2 design) + +Scaffolding splits into three tiers by *scope* and *fatness*, mirroring the field (supabase `init` vs `login`; HelixDB thin `init` vs fat `chef`). Most of this lives in sibling tickets; this RFC owns only the **user route**. + +| Tier | Command | Scope | What it does | Model | Status | +|---|---|---|---|---|---| +| **User route** | `omnigraph login []` | user (`~/.omnigraph/`) | auth + write `~/.omnigraph/config.yaml` / `credentials`; first-run global setup | gh / supabase `login` | **this RFC** (unbuilt) | +| **Thin project init** | `omnigraph init` | project, in-place | create graph + `scaffold_config_if_missing` (`omnigraph.yaml` + minimal `.pg`/`.gq`); refuse-if-exists or `--force` | `cargo init`, `prisma init` | exists; `--force` purge = MR-975 | +| **Fat bootstrap** | `omnigraph quickstart [--template ] [--auto]` | project, possibly new-dir | scaffold + seed data + `serve start` + agent prompt file | HelixDB `chef`, `create-next-app` | MR-973 (unbuilt) | + +**Design positions** (first-principles, since none of the fat tier is built): +- **Split `init` (project) from `login` (user)** — never one command writing to both `$HOME` and the project (the supabase line, not the dbt line). `init`=project scaffold; `login`=user credential + global config. +- **`init` is in-place + refuse-if-exists** (cargo/prisma/terraform default): don't clobber; adopt existing files; require `--force` to overwrite (and `--force` purges Lance state per MR-975). +- **Interactive for humans, `--auto`/agent-mode for automation** (npm `-y`, create-* `--CI`, MR-981 `--machine`). In `OMNIGRAPH_AGENT_MODE` any prompt → fail with a repair hint. +- **Templates are a `--template ` flag on the fat tier** (create-vite model), with the *content* (schema + queries + seed) coming from a template source. Mechanism is a design question (bundled-in vs `og template pull` from a repo vs `npm create-*`-style delegation) — **not** an existing foothold (MR-581 stale). Lean: a small set of bundled templates first (generic `Person→Knows`, plus promote `omnigraph-intel-bootstrap`), `--template ` later. +- **`init`/`quickstart` can scaffold the `graphs:` map with one or more entries**; "init with specific graphs" = the scaffolded `graphs:` block (embedded `storage:` locally; the agent/operator adds remote `server:` entries via `login` + editing). +- **Secrets-on-scaffold rule** (prisma/dbt/supabase all do this): anything that writes a token also keeps it out of VCS. `login` prefers the OS keychain (no file); the `~/.omnigraph/credentials` profile fallback is `0600` and git-ignored, and any project-local `.env`-shaped file gets a `.gitignore` entry. + +### 8. Concrete shape + +**Global** `~/.omnigraph/config.yaml` (per-user, secret-free): +```yaml +servers: # endpoint only — token is keyed by the server name + prod-us: { endpoint: https://og-us.internal:8080 } + prod-eu: { endpoint: https://og-eu.internal:8080 } + staging: { endpoint: https://og-staging.internal:8080 } +graphs: + personal: { storage: ~/graphs/personal.omni } +defaults: + graph: personal +aliases: + my_people: + command: query + query: ~/queries/people.gq + name: list_people + graph: personal +``` + +**Project client** `./omnigraph.yaml` (committed, secret-free, portable — no `server.bind`). Note the shipped noun is `graphs:` (MR-603); an entry is embedded (`storage:`) XOR remote (`server:` + `graph_id:`, §1.1): +```yaml +graphs: + dev: { storage: s3://team-bucket/dev.omni, branch: main } # embedded + staging: { server: staging, graph_id: prod, branch: review } # remote → graph `prod` on server `staging` + prod-us: { server: prod-us, graph_id: production } + prod-eu: { server: prod-eu, graph_id: production } # multi-homed: same graph, another server +defaults: { graph: dev, output_format: table } +aliases: + owner: + command: query + query: ./queries/owner.gq + name: owner + args: [name] + graph: dev +``` +Select with `--graph ` (shipped flag, MR-603). + +**Server deployment** `./omnigraph.yaml` (committed in the deploy repo, read by `omnigraph-server`). Every served graph is an embedded storage locator; server-owned policy and stored-query definitions live here: +```yaml +graphs: + production: + storage: s3://team-bucket/prod.omni + policy: + file: ./policies/prod.yaml + queries: + find_user: + file: ./queries/find_user.gq + mcp: { expose: true, tool_name: lookup_user } + +server: + policy: + file: ./policies/server.yaml +``` + +**Credentials** are keyed by server name — `omnigraph login prod-us` writes the OS keychain entry `omnigraph:prod-us` (or a `[prod-us]` profile in `~/.omnigraph/credentials`, 0600, git-ignored); `OMNIGRAPH_TOKEN_PROD_US` overrides for CI. No token fields in any config file; no committable secrets. + +## DX + +1. **One command surface, two loci.** `query --graph dev` (embedded) and `--graph staging` (remote) are the same command; only resolution differs. Change one word, not a mental model. +2. **Clone-and-go.** Project config names servers+graphs; teammate runs `omnigraph login staging` once and every target resolves. The git + `gh auth login` model. +3. **Multi-server × multi-graph is the default.** Remote graph entries reference `server` by name; `servers` is a global named map; graphs are per-server. `prod-us` and `prod-eu` both serving `production` is two graph entries — Helix cannot express this. +4. **Solo-first.** Everything in `~`, no project required. +5. **Laptop-to-fleet on one schema.** Local = one `omnigraph.yaml` (both roles); prod = role-split across repos. No second format to learn. + +## AX (agent experience) + +1. **One flat resolved context, never a config to navigate.** target→server→endpoint→token resolves *before* the agent sees anything. The agent reasons about tools, not topology (the LLM-safe-surface principle extended to config). +2. **Secrets are structurally outside the agent's reach.** The repo it operates in has no tokens; they are in the global layer / keychain, outside its view. An agent *cannot* exfiltrate a prod token from project config because it is not there. +3. **Branch/snapshot-pinned contexts** (E4) — hand an agent a `branch: review` / `--snapshot v42` target and its reads are reproducible and cannot see uncommitted main-line state. No kubeconfig analog. +4. **The agent's capabilities are a GitOps'd artifact** (E6) — which graphs exist, which stored-query tools it may call, and which Cedar rules gate them are all in the version-controlled server config. Powers change only via a reviewed PR, deployed by restart. Infrastructure-as-code for what the AI can do. +5. **Config + policy compose.** Config = "where am I pointed + which token"; Cedar = "what may I do there." Orthogonal; no enforcement logic leaks into config. + +## GitOps — three surfaces, secrets in none + +| Surface | Repo | Contents | Deploy | Secrets | +|---|---|---|---|---| +| Server deployment config | infra/deploy repo | `graphs:`, policy, **`queries:` + `.gq` files** | commit → CI → **server restart** (no hot reload) | none — by-reference | +| Project client config | app repo | `graphs:` → embedded storage or remote server+graph | committed, read by CLI/agent | none | +| Global user config | **not GitOps'd** — machine-local `~` | `servers:` + creds-by-ref | `omnigraph login` writes it | refs only (like `~/.kube/config`) | + +## Comparison + +| Property | kubeconfig | Helix | git | compose | **OmniGraph (this RFC)** | +|---|---|---|---|---|---| +| Named remote endpoints + creds-by-ref | ✅ | ✅ | partial | partial | ✅ (global `servers`) | +| Global + project layering, uniform schema | ✗ | ✗ | ✅ | ✗ | ✅ | +| Embedded OR remote under one name | ✗ | ✗ | n/a | ✗ | ✅ (E1) | +| Multi-server × multi-graph | ✅ | ✗ | n/a | n/a | ✅ (E2) | +| Branch/snapshot in the address | ✗ | ✗ | partial | ✗ | ✅ (E4) | +| Agent tool surface in the repo | ✗ | ✗ (separate bundle) | n/a | n/a | ✅ (E6) | +| Project manifest renamed by role | — | no | — | no | **no** | +| Concept count | 3 | 1 | 2 | 1 | **2 (servers/targets)** | + +## Migration / backwards compatibility + +- **Additive.** Today's `omnigraph.yaml` (`graphs:`, `cli:`, `server:`, `aliases:`, `policy:`) keeps working unchanged. `graphs:` entries are equivalent to embedded `targets:` with a `storage:` (shipped `uri:` is a deprecated alias); both resolve. +- **`targets:` is new** and optional. `servers:` is new and optional. Absent → today's behavior. +- **Global `~/.omnigraph/config.yaml` is new.** Absent → only project + env + flags, exactly as now. Its addition is the **global-first posture flip**: today the CLI is project-anchored (reads `./omnigraph.yaml`, no parent walk); the global config becomes the new primary discovery path so the CLI works with no project file. Existing project-only workflows are unchanged (project still overrides global); the flip is additive — it adds a fallback layer below the project file, it does not remove the project file. +- **`graphs:` → `targets:` is an evolution, not a break.** Both can coexist; `targets:` is the superset (adds remote + branch pinning). A future cleanup may alias `graphs:` to embedded `targets:`. +- **`server.bind` stays supported** but documentation steers operators to `--bind` / `OMNIGRAPH_BIND` for portability; no removal. +- **Credentials: keyed-by-name is new; `bearer_token_env` is the compat path.** The primary design (keychain / `[]` profile / `OMNIGRAPH_TOKEN_`) is new resolver work (lands on MR-971). The shipped `bearer_token_env` + `auth.env_file` dotenv (`resolve_remote_bearer_token`) is **unchanged and still honored** — existing single-server dotenv setups keep working, and the resolver honors an explicit `auth: { token: {...} }` source (env/file/command/keychain) with `bearer_token_env` as its flat legacy alias. No `credentials.yaml`. +- **Validation tightens invalid mixes, not valid legacy use.** Top-level `policy:` / `queries:` remain only for anonymous bare-URI compatibility. Named graphs use per-entry fields. Remote graph entries with local `policy:` / `queries:` and server manifests with `server:` graph locators are rejected because there is no correct way to honor those fields. + +## Open questions + +- **`graphs:` vs `targets:` naming churn.** Do we rename `graphs:` → `targets:` (with a deprecation alias) or keep `graphs:` for embedded and add `targets:` for remote? Leaning: keep both, document `targets:` as the superset. +- **Keychain integration scope.** Keychain is now the *primary* credential store (§5), so this is on the critical path, not optional: macOS Keychain first (matches operator practice) with the `0600` `[]` profile file as fallback; Linux Secret Service / `pass` later. Open: which keyring crate, and the exact `OMNIGRAPH_TOKEN_` name-derivation (upper-snake, non-alnum → `_`). +- **Project-local `servers:`.** Allowed (e.g. a localhost dev server), merged with global. Confirm creds stay by-reference even for project-local servers (yes). +- **`aliases:` ⇄ `queries:` convergence.** Out of scope here; tracked separately. One registry with embedded + remote invocation surfaces is the target end state. +- **Single-file `KUBECONFIG`-style list.** Do we support `OMNIGRAPH_CONFIG` pointing at multiple files (colon-joined), or a single file only? Start single; revisit if demand appears. + +## Implementation — breadboard + slices (Shape A) + +Shaped via requirements + a fit check (Shape A — global-first layered config + unified `graphs:` entry + three-tier init — selected over a project-first minimal option and a Helix-clone). This section breadboards A and slices it. **Bold** = NEW. + +### Places + +| # | Place | What | +|---|---|---| +| P1 | Disk | `~/.omnigraph/{config.yaml, credentials, cache/, state/}` + project `omnigraph.yaml` + `.env.omni` | +| P2 | Config resolution | runs on every command: load layers → merge → resolve `--graph` | +| P3 | Command execution | embedded engine OR remote HTTP client | +| P4 | Remote `omnigraph-server` | existing HTTP surface (`/query`, `/mutate`, `/queries/{name}`) | +| P5 | Scaffold | `login` / `init` / `quickstart` | + +### Affordances + +| # | Place | Affordance | NEW? | Wires | +|---|---|---|---|---| +| U1 | P1 | `~/.omnigraph/config.yaml` (operator edits) | **N** | → N1 | +| U2 | P1 | project `./omnigraph.yaml` | — | → N1 | +| U3 | P1 | `~/.omnigraph/credentials` / `.env.omni` dotenv (secrets, git-ignored) | — | → N4 | +| U4 | P3 | `omnigraph --graph ` (any command) | — | → N14 | +| U5 | P5 | `omnigraph login []` | **N** | → N11 | +| U6 | P5 | `omnigraph init` / `quickstart [--template]` | partly | → N12 / N13 | +| U7 | P2 | `omnigraph config view --resolved --show-origin` | **N** | → N10 | +| N1 | P2 | `load_layered_config()` — global (N3) + project (cwd), serde each | **N** | → N2 | +| N2 | P2 | **merge engine** — deep-merge settings; replace named-resource entries; replace lists; **retain provenance** and raw field origins | **N⚠️** | → N5, → S_merged | +| N3 | P2 | global-dir resolver — `OMNIGRAPH_HOME` else `~/.omnigraph/` | **N** | → N1 | +| N4 | P2 | `load_env_file_into_process` — dotenv, real-env-wins (existing) | — | → N9 | +| N5 | P2 | `resolve_graph(name, merged)` → typed `Embedded`/`Remote` locator; rejects invalid role/field combinations before execution | **N⚠️** | → N6 | +| N6 | P3 | `GraphConn` — `Embedded(engine)` \| `Remote(http)` dispatch | **N⚠️** | → N7, → N8 | +| N7 | P3 | embedded path — `Omnigraph::open(uri)` (existing) | — | → engine | +| N8 | P3 | **HTTP-client path** — POST `/query`/`/mutate`/`/queries/{name}` | **N⚠️** | → P4, → N9 | +| N9 | P2 | `resolve_bearer_token(server)` — explicit `auth.token` source if set, else **keyed by name**: `OMNIGRAPH_TOKEN_`/`OMNIGRAPH_TOKEN` → keychain `omnigraph:` → `[]` profile; legacy `bearer_token_env`/dotenv (MR-971) | **N⚠️** | → N8 | +| N10 | P2 | `config view` handler — merged + per-field origin (needs N2 provenance) | **N** | → U7 | +| N11 | P5 | `login` handler — interactive auth → write `config.yaml` + `credentials` (0600) + `.gitignore` | **N⚠️** | → S_global | +| N12 | P5 | `init` handler — `scaffold_config_if_missing` + create graph; refuse-if-exists/`--force` purge (MR-975) | partly | → S_project | +| N13 | P5 | `quickstart` handler — scaffold + `--template` + seed + `serve start` + agent prompt (MR-973; needs serve MR-970) | **N⚠️** | → S_project | +| N14 | P3 | agent-mode wrapper — `--machine`/`OMNIGRAPH_AGENT_MODE`: JSON, structured errors, never-prompt, typed exit codes (MR-981) | **N⚠️** | → N1 | +| S_global | P1 | `~/.omnigraph/config.yaml` + `credentials` | **N** | read by N1/N9 | +| S_project | P1 | `./omnigraph.yaml` + `.env.omni` | — | read by N1/N4 | +| S_merged | P2 | in-memory resolved config (per command, with provenance) | **N** | read by N5/N10 | +| S_cache | P1 | `~/.omnigraph/cache/` (remote catalogs) | **N** | read by N8 | + +```mermaid +flowchart TB + subgraph P1["P1: Disk"] + U1["U1: ~/.omnigraph/config.yaml"] + U2["U2: ./omnigraph.yaml"] + U3["U3: credentials dotenv"] + end + subgraph P2["P2: Config resolution"] + N3["N3: global-dir (OMNIGRAPH_HOME)"] + N1["N1: load_layered_config"] + N2["N2: merge engine (+provenance)"] + N4["N4: dotenv loader"] + N5["N5: resolve_graph(--graph)"] + N9["N9: resolve_bearer_token"] + N10["N10: config view"] + end + subgraph P3["P3: Command execution"] + U4["U4: omnigraph --graph"] + N14["N14: agent-mode wrapper"] + N6["N6: GraphConn embedded|remote"] + N7["N7: embedded Omnigraph::open"] + N8["N8: HTTP-client POST"] + end + subgraph P5["P5: Scaffold"] + U5["U5: login"]; U6["U6: init/quickstart"] + N11["N11: login handler"]; N12["N12: init"]; N13["N13: quickstart"] + end + P4["P4: remote omnigraph-server"] + U1-->N1; U2-->N1; N3-->N1; N1-->N2-->N5-->N6 + U3-->N4-->N9-->N8 + U4-->N14-->N1 + N6-->N7; N6-->N8-->P4 + N2-->N10-->U7["U7: config view --resolved"] + U5-->N11; U6-->N12; U6-->N13 + classDef ui fill:#ffb6c1,stroke:#d87093,color:#000 + classDef n fill:#d3d3d3,stroke:#808080,color:#000 + class U1,U2,U3,U4,U5,U6,U7 ui + class N1,N2,N3,N4,N5,N6,N7,N8,N9,N10,N11,N12,N13,N14 n +``` + +### Slices (vertical, each demo-able) + +| # | Slice | Parts/affordances | Demo | +|---|---|---|---| +| **V1** | **Global layer + merge + `config view`** | A1–A4 · N1,N2,N3,N10 · U1,U7,S_global,S_merged | Put config in `~/.omnigraph/`, run `omnigraph config view --resolved --show-origin` from any dir → merged result with per-field origin; existing embedded commands work global-first with no project file | +| **V2** | **Remote graphs + HTTP client + creds** | A5–A7 · N5,N6,N8,N9 · S_cache | Define a `server:` graph entry; `omnigraph query --graph prod` hits the remote server (`curl`-free); embedded `--graph dev` still local | +| **V3** | **`omnigraph login`** | A8 · N11,U5 | `omnigraph login prod` writes `~/.omnigraph/credentials` (0600) + `.gitignore`; V2 remote query now works with no manual env | +| **V4** | **Thin-init hardening + quickstart + templates** | A9 · N12,N13,U6 (needs serve MR-970) | `omnigraph quickstart --template person-knows` scaffolds + seeds + serves; `init --force` purges (MR-975) | +| **V5** | **Agent-mode** | A10 · N14,U4 (MR-981) | `OMNIGRAPH_AGENT_MODE=1 omnigraph query …` → JSON + structured errors + typed exit codes; never-prompt | + +V1 is the foundation (global-first + merge + view). V2 closes the substantive client→server gap. V3 is credential ergonomics. V4/V5 ride sibling tickets (MR-970/973/981). MR-969 (stored queries) ships independently and is reached by N8's `/queries/{name}` once V2 lands. + +## Rollout + +The slices above are the rollout order: **V1 (global layer + merge) → V2 (remote graphs + HTTP client) → V3 (login) → V4 (quickstart/templates, on MR-970) → V5 (agent-mode, MR-981).** V1–V2 close the substantive gap (global-first config + `curl`-free server access); V3–V5 are ergonomics that ride sibling tickets. Evaluate after V2 against early-adopter and agent-onboarding (MR-973 / MR-974) signal. The spikes (X1 HTTP-client, X2 merge engine, X3 resolver+provenance, X4 login) resolve before their owning slice. + +## Prior art + +- kubeconfig (clusters / users / contexts; `KUBECONFIG`; `kubectl config view`) +- Helix CLI v2 (`helix.toml` local+enterprise instance blocks; `~/.helix/config`; `~/.helix/credentials`) +- AWS CLI (`~/.aws/config` + `~/.aws/credentials` split; named profiles; `credential_process`) +- git (`~/.gitconfig` + `.git/config`; `--show-origin`) +- Cargo (`Cargo.toml` manifest + `~/.cargo/config.toml`) +- Supabase / Prisma (one project manifest; connection via `DATABASE_URL` env) +- 12-factor app (config that varies by deploy lives in the environment) diff --git a/docs/dev/rfc-003-mcp-server-surface.md b/docs/dev/rfc-003-mcp-server-surface.md new file mode 100644 index 0000000..32fbce5 --- /dev/null +++ b/docs/dev/rfc-003-mcp-server-surface.md @@ -0,0 +1,270 @@ +# RFC: MCP Server Surface for `omnigraph-server` — Full Tool Parity, Stored Queries, Modular Auth + +**Status:** Proposed +**Date:** 2026-06-01 +**Tickets:** MR-969 (stored queries + MCP exposure — the surface this completes), MR-956 (federated auth / WorkOS OAuth — the auth substrate this consumes), MR-971 (per-server credential resolver), MR-974 (agent setup surface — the installer that wires this), MR-668 (multi-graph server — shipped, the routing this builds on) +**Builds on:** [omnigraph#128](https://github.com/ModernRelay/omnigraph/pull/128) (`ragnorc/stored-queries-mcp`) — the shipped stored-query registry, `GET /queries`, `POST /queries/{name}`, and the coarse `invoke_query` gate. +**Supersedes:** the MCP-transport portion of [rfc-001-queries-envelope-mcp.md](rfc-001-queries-envelope-mcp.md) (`/mcp/tools` + `/mcp/invoke`). See [Relationship to RFC-001](#relationship-to-rfc-001). +**Target release:** v0.8.x (phased — see Rollout) + +## Summary + +Add a first-class **MCP (Model Context Protocol) server surface to `omnigraph-server`**, exposed over **Streamable HTTP**, that projects the server's operations as MCP tools and resources for LLM clients (Claude Code/Desktop/web, Cursor, etc.). Two populations of tools share one projection path: + +1. **Built-in operational tools** — parity with the existing `@modernrelay/omnigraph-mcp` stdio package's **13 tools** (`health`, `snapshot`, `read`, `schema_get`, `branches_list`, `commits_list`, `commits_get`, `change`, `ingest`, `branches_create`, `branches_delete`, `branches_merge`, `schema_apply`) and its **2 resources** (`omnigraph://schema`, `omnigraph://branches`), plus a new server-scoped `graphs_list` tool and an `omnigraph://graphs` resource (multi-graph mode). +2. **Dynamic stored-query tools** — one MCP tool per `mcp.expose: true` entry in the `queries:` registry (MR-969 / #128), with parameters typed from the `.gq` declaration via the shipped `query_catalog_entry` / `param_descriptor` projection. + +Every tool is **authorized by the server's existing Cedar policy engine**. The MCP layer never implements its own authentication: it consumes an **already-resolved `ResolvedActor`** from the server's bearer middleware (`require_bearer_auth` today; the `TokenVerifier` seam when MR-956 lands), so the **same MCP endpoint serves on-prem (static or customer-OIDC tokens) and our cloud (WorkOS OAuth) by configuration only**. Cloud OAuth is an additive layer (RFC 9728 protected-resource metadata) that slots in with zero MCP changes. + +The end-state collapses two diverging tool implementations into one: the in-server MCP is the canonical, Cedar-gated, remotely-reachable surface; the stdio package becomes a thin stdio↔HTTP proxy (local on-ramp) over it. + +> **Key caveat, stated up front (see §5.9 below):** the headline "a token scoped via Cedar to a *specific set* of stored queries" requires **per-query `invoke_query` scope**, which is *designed* (rfc-001) but **not yet implemented** — the shipped action is coarse (any stored query on the graph, or none). Per-actor Cedar curation works today for *built-in vs ad-hoc vs admin* tools and for *stored-vs-ad-hoc*; sub-selecting individual stored queries per actor is gated on a prerequisite (PR 0b). Until then, stored-query curation is graph-level (registry membership + `mcp.expose`). + +## Relationship to RFC-001 + +[rfc-001-queries-envelope-mcp.md](rfc-001-queries-envelope-mcp.md) (MR-656 / MR-976 / MR-969) is the parent design for stored queries + the response envelope + MCP. This RFC is the **detailed MCP-transport design** that #128 left for a follow-up, and it **revises rfc-001 in three places where the shipped code or the MCP wire protocol diverged from rfc-001's sketch**: + +1. **Transport shape.** rfc-001 sketched `GET /mcp/tools` + `POST /mcp/invoke` (a bespoke REST pair). **That is not the MCP wire protocol — real MCP clients cannot connect to it.** This RFC implements actual MCP JSON-RPC over Streamable HTTP and reuses `query_catalog_entry` as a *projection source*, not a parallel surface. (rfc-001's own Open Question already leaned toward Streamable HTTP.) +2. **Exposure config.** rfc-001 specified inline `.gq` pragmas (`@mcp(expose=…)`, default `expose=false`). **#128 shipped a different mechanism:** YAML `queries..mcp.expose` in `omnigraph.yaml`, **default `true`** (declaring a query in the manifest *is* the opt-in). This RFC builds on the shipped YAML form; the `.gq`-pragma design in rfc-001 is superseded for exposure. +3. **Schema introspection.** rfc-001 lists "Schema introspection through MCP" as a **non-goal** ("agents see types through declared return shapes"). This RFC **revises that**: the operational-parity tools include `schema_get` and `omnigraph://schema` — *because the shipped stdio package already exposes both*. The non-goal is achieved by *policy*, not omission: `schema_get`/`omnigraph://schema` are Cedar-gated by `Read`, and the recommended locked-down agent policy denies `Read`, so a curated agent still never sees the schema. (rfc-001's intent is preserved; the mechanism moves from "don't build it" to "build it, gate it.") + +Everything else in rfc-001 (two-paths-one-engine, per-query `invoke_query` *as the intended scope*, the response envelope, multi-graph per-graph endpoints) this RFC consumes unchanged. + +> **Numbering note:** the `TokenVerifier`/WorkOS auth design is referred to in code (`crates/omnigraph-server/src/identity.rs`) as "RFC 0001," which is a *different* document from this repo's `docs/dev/rfc-001-queries-envelope-mcp.md`. To avoid the collision this RFC cites the auth substrate as **MR-956** throughout, never "RFC 0001." + +## Reconciliation with shipped code (verified against `ragnorc/stored-queries-mcp` HEAD) + +Verified against `crates/omnigraph-server/src/{lib.rs,api.rs}` and `crates/omnigraph-policy/src/lib.rs` at the current branch head (not the #128 PR body, and not `api.rs` alone): + +- ✅ `GET /queries` returns the `mcp.expose == true` subset as `QueriesCatalogOutput { queries: [QueryCatalogEntry] }`, each with typed `ParamDescriptor`s, `tool_name`, `description`, `instruction`, and a `mutation` flag. **MCP-ready projection, but exposed as bespoke REST/JSON — not the MCP wire protocol.** +- ✅ `POST /queries/{name}` route exists (`server_invoke_query`, `lib.rs`). +- ✅ `query_catalog_entry()` / `param_descriptor()` with an exhaustive `ScalarType → ParamKind` map (a new scalar is a compile error). +- ✅ `InvokeQuery` Cedar action defined in `omnigraph-policy`. +- ✅ **`InvokeQuery` IS enforced** at `POST /queries/{name}`: `server_invoke_query` calls `authorize(PolicyAction::InvokeQuery)` and **masks a denial to a 404 identical to "unknown query"** so the catalog isn't probeable (the denial-masking the previous draft of this RFC reported as missing is shipped — it lives in `lib.rs`, not `api.rs`). The stored-mutation path is already double-gated: `InvokeQuery` outer, then `Change` inside `run_mutate`. +- ✅ **Reuse path exists:** `run_query` / `run_mutate` are already decoupled from their HTTP request bodies and take registry-supplied `(source, name, params, branch/snapshot)`. MCP `tools/call` for both stored and ad-hoc tools delegates to these — no new business logic. +- ❌ **Per-query (`invoke_query[name]`) scope is NOT implemented.** `PolicyRequest` carries only `{action, branch, target_branch}` — **no query-name dimension** — and the action is documented coarse ("permits *any* stored query on the graph"). rfc-001 *designed* per-name scope; it is unbuilt. This RFC's per-query Cedar filtering (§5.4) and recommended agent policy (§5.9) depend on it → tracked as **PR 0b**. +- ❌ No MCP protocol surface (`initialize`/`tools/list`/`tools/call`, JSON-RPC, transport). +- ❌ No `TokenVerifier` trait yet — `require_bearer_auth` resolves a `ResolvedActor` inline (static-hash). The trait/`OidcJwtVerifier` are MR-956 (draft). The MCP layer's only requirement — *consume `ResolvedActor`* — is satisfiable today. + +Stack (verified `Cargo.toml`): Axum + utoipa (OpenAPI) + `omnigraph-policy` (Cedar) + `futures` + `tokio`. **No MCP crate present.** `edition = "2024"`. + +## Motivation + +- **One curated, safe, remotely-reachable tool surface.** MR-969's thesis: hand an LLM a token Cedar-scoped to a set of tools and it sees exactly those typed tools — cannot construct ad-hoc queries it isn't permitted, cannot read the schema it isn't permitted, cannot reach other graphs. Today the only MCP is the stdio package: local-only, full surface, ungated. +- **Parity, so the in-server MCP can be the single implementation.** Operators/agents already depend on the operational tools. Supporting them server-side behind one Cedar gate lets the stdio package degrade to a proxy and removes two diverging tool sets. +- **On-prem and cloud from one endpoint.** A managed cloud (WorkOS OAuth) and an on-prem/air-gapped deploy (static or customer-OIDC tokens) must serve the same MCP without forks or MCP-specific auth. +- **Foundation for the agent on-ramp (MR-974).** `omnigraph mcp install --agent ` needs a decided transport + a stable endpoint. + +## Goals + +- Project built-in tools + stored queries as MCP tools through **one** registry abstraction. +- `tools/list` and the callable set are **identical for argument-independent authorization**, both driven by Cedar (see §5.4 for the branch-scoped caveat). +- The MCP layer is **auth-method-agnostic**: it consumes `ResolvedActor`, never a raw token, never branches on how auth happened. +- The same endpoint works on-prem (static/OIDC) and cloud (WorkOS OAuth), switched by config; cloud OAuth is additive (RFC 9728). +- No new business logic: MCP tools delegate to the same `run_query`/`run_mutate`/branch/schema functions the HTTP routes call. +- Behaviour-neutral when unused: no MCP traffic = no change. + +## Non-Goals + +- **Building/hosting an OAuth authorization server.** The server is a Resource Server; WorkOS AuthKit+Connect is the AS (MR-956). The MCP endpoint validates tokens, never issues them, never holds client secrets. +- **OAuth/WorkOS implementation itself** — MR-956's work. This RFC leaves a clean RFC-9728 hook and consumes `ResolvedActor`. +- **MCP prompts, elicitation, `tools/list_changed`, resource subscriptions, server-initiated messages.** None needed → enables a stateless POST-only transport (§5.6). +- **stdio transport inside the server.** stdio stays in the TS package (now a proxy). +- **Cross-graph tool listing.** Per-graph catalogs only (MR-969 + RFC-002 non-goal). +- **Hot reload of the query registry.** Restart-only (MR-969). + +## Background + +`omnigraph-server` (Axum) already implements every operation this RFC exposes as an authenticated HTTP route; each authorizes via a `PolicyAction` against the Cedar policy for a server-resolved actor and calls into the engine. The existing stdio MCP package is a *client* of these routes (it owns no business logic). MR-956 will introduce a `TokenVerifier` trait (`StaticHashTokenVerifier` today inline, `OidcJwtVerifier` for OIDC/WorkOS) producing the `ResolvedActor { actor_id, tenant_id: Option, scopes: Vec, source }` that already exists in `identity.rs` and is consumed by Cedar — token *validation* is offline (cached JWKS), so on-prem/air-gapped has no request-path dependency on the cloud. + +## Design + +### 5.1 One tool model: a `McpTool` trait, two populators + +Both built-in and stored-query tools implement one trait so `tools/list` / `tools/call` never special-case: + +```rust +trait McpTool: Send + Sync { + fn name(&self) -> &str; // MCP tool id (stable) + fn title(&self) -> Option<&str>; + fn description(&self) -> &str; + fn input_schema(&self) -> serde_json::Value; // JSON Schema (draft 2020-12) + fn annotations(&self) -> ToolAnnotations; // readOnlyHint / destructiveHint / idempotentHint + /// The Cedar request(s) this call requires, given parsed args. Used BOTH at + /// list-time (dry-run filter, default args) and call-time (enforce, real args). + fn authorization(&self, args: &ToolArgs) -> Vec; + async fn call(&self, ctx: &GraphCtx, args: ToolArgs) -> Result; +} +``` + +- **Built-ins**: ~14 static impls, each delegating to the *same* function its HTTP route calls (`run_query`, `run_mutate`, branch ops, `apply_schema_as`, …). `input_schema` authored once (or derived from each route's existing `utoipa`/`ToSchema` DTO). +- **Stored queries**: generated `McpTool` instances, one per `mcp.expose` entry; `input_schema` from `param_descriptor` (§5.3); `authorization` → `InvokeQuery` (coarse today; `InvokeQuery{name}` after PR 0b) then the inner `Read`/`Change`. + +`ToolRegistry` for a graph = the static built-ins + the dynamic stored-query tools resolved from that graph's `GraphHandle` registry. + +### 5.2 Tool catalog (parity) and Cedar mapping + +Each built-in **reuses the exact `PolicyAction` its HTTP route already enforces** — verified against the handlers in `lib.rs`, not invented: + +| MCP tool | Scope | Read/Mutate | Cedar action (verified from route) | +|---|---|---|---| +| `health` | server | read | none (liveness/version) | +| `graphs_list` *(new)* | server | read | `GraphList` | +| `snapshot` | graph | read | `Read` | +| `schema_get` | graph | read | `Read` | +| `branches_list` | graph | read | `Read` | +| `commits_list`, `commits_get` | graph | read | `Read` | +| `read` (ad-hoc `.gq`) / `query` *(alias)* | graph | read | `Read` | +| `change` (ad-hoc `.gq`) / `mutate` *(alias)* | graph | mutate | `Change` | +| `ingest` (NDJSON) | graph | mutate | `Change` (+ `BranchCreate` when forking a new branch) | +| `branches_create` | graph | mutate | `BranchCreate` | +| `branches_delete` | graph | mutate | `BranchDelete` | +| `branches_merge` | graph | mutate | `BranchMerge` | +| `schema_apply` (`allow_data_loss`) | graph | mutate | `SchemaApply` | +| **stored query** (`find_user`, …) | graph | inferred | `InvokeQuery` (coarse; `InvokeQuery{name}` after PR 0b) + inner `Read`/`Change` | + +There is **no `Ingest` and no separate `snapshot`/`Export` action** — `ingest` enforces `Change`, `snapshot` enforces `Read`. (`Export` exists but maps to the `/export` route, which this RFC does not expose as a tool.) + +**Tool id parity vs. canonicalization.** The shipped stdio package uses tool ids **`read`/`change`** (and calls the deprecated `/read`,`/change` routes). The server HTTP surface canonicalized to `/query`,`/mutate` with `/read`,`/change` deprecated (MR-656). To keep existing package clients working *and* align with the server, the MCP exposes **`query`/`mutate` as canonical with `read`/`change` retained as deprecated-but-live aliases** (both dispatch to the same handler). Open Q7 asks whether to drop the aliases later. + +Resources (§5.5): `omnigraph://schema`, `omnigraph://branches` (parity), plus `omnigraph://graphs` *(new)* — each gated by the same action as its list/get route (`Read`, `Read`, `GraphList`). + +### 5.3 `ParamDescriptor → JSON Schema` (stored-query tools) + +| `ParamKind` | JSON Schema | Notes | +|---|---|---| +| String | `{"type":"string"}` | | +| Bool | `{"type":"boolean"}` | | +| Int (i32/u32) | `{"type":"integer"}` | | +| BigInt (i64/u64) | `{"type":"string","pattern":"^-?\\d+$"}` | JSON numbers lose precision >2⁵³ → string (matches the shipped `api.rs` rationale). (Open Q1) | +| Float (f32/f64) | `{"type":"number"}` | | +| Date | `{"type":"string","format":"date"}` | | +| DateTime | `{"type":"string","format":"date-time"}` | | +| Blob | `{"type":"string","contentEncoding":"base64"}` | | +| Vector | `{"type":"array","items":{"type":"number"},"minItems":dim,"maxItems":dim}` | uses `vector_dim` | +| List | `{"type":"array","items":}` | scalar items only (grammar guarantees) | + +`nullable == false` → param is in `required`. Annotations: `mutation` → `{readOnlyHint:false, destructiveHint:true}`; else `{readOnlyHint:true}`. `description` → tool description; `instruction` → appended to description (or `_meta`). (The shipped `check()` already warns when an `mcp.expose` query declares a `Vector` param an LLM can't supply.) + +For built-in tools the schema is hand-authored from the route DTO; e.g. `query` → `{source: string, branch?: string, params?: object}`; `schema_apply` → `{schema: string, allow_data_loss?: boolean}`; `ingest` → `{ndjson: string, mode?: "merge"|"append"|"overwrite", branch?: string}`. + +### 5.4 `tools/list` (Cedar-filtered) and `tools/call` (dispatch + masking) + +- **`tools/list`**: build the `ToolRegistry`; for each tool evaluate `authorization(default_args)` against the actor's Cedar policy; **emit only tools that authorize**. Authz decisions memoized per request. Stored-query tools additionally require `mcp.expose: true`. + - **Exactness caveat (R7 is conditional):** the listed set equals the callable set **only for tools whose authorization is argument-independent** (`health`, `graphs_list`, `snapshot`, `schema_get`, `branches_list`, `commits_*`, ad-hoc `query`/`mutate`, and stored queries under the *coarse* action). For **branch-scoped tools** (`branches_create`/`merge` with `target_branch_scope`, and any branch-scoped `Read`/`Change` rule), list-time uses `default_args` (e.g. branch `main`) and cannot know the real target, so the listed set is a *best-effort approximation* of callability — a call may still be denied (or, rarely, a hidden tool would have been allowed). `tools/call` is always the authoritative gate. The contract is: **list never shows a tool the actor can't ever call; for branch-scoped tools it may show one the actor can call only on some branches.** +- **`tools/call`**: resolve `name` → `McpTool` (masked-404 if unknown *or* `mcp.expose:false`); parse+validate args against `input_schema`; enforce `authorization(args)` (mutations stay double-gated: `InvokeQuery` then `Change`); on success `call`. **Denial masking** lives in one place (the dispatcher): an authz denial is returned identically to "unknown tool" (§5.10), reusing the same deny≡missing principle already shipped at `POST /queries/{name}`. + +### 5.5 Resources + +Advertise `resources` capability (`subscribe:false, listChanged:false`). `resources/list` → the URIs the actor may read; `resources/read` → schema `.pg` text / branches JSON / (multi-graph) graphs JSON, each gated by the corresponding action (`Read`, `Read`, `GraphList`). A locked-down agent denied `Read` simply never sees `omnigraph://schema` or `omnigraph://branches` — this is how rfc-001's "agents don't introspect schema" intent is met *by policy* (§Relationship-to-RFC-001). + +### 5.6 Transport: Streamable HTTP, stateless, POST-only + +- **Streamable HTTP** (MCP's current standard; we're already an HTTP server). One endpoint per scope (§5.7). +- Because the server emits **no** server-initiated messages, implement the **minimal conformant** shape: client `POST`s JSON-RPC, server replies `application/json`. **No SSE channel, no `Mcp-Session-Id`, stateless** — each request authenticated independently via the bearer middleware. Honour the `MCP-Protocol-Version` header. SSE/sessions can be added later if subscriptions land. +- **JSON-RPC methods:** `initialize` (advertise `{tools:{listChanged:false}, resources:{listChanged:false, subscribe:false}}` + serverInfo/version), `notifications/initialized` (no-op ack), `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`. `prompts/list` returns empty if probed. +- **Library decision (Open Q2):** spike `rmcp` (official Rust MCP SDK) for conformance + Streamable-HTTP/Axum on edition 2024; **fall back to a hand-rolled ~150 LOC JSON-RPC-over-POST** (only the methods above) on friction. Given the tiny surface, hand-roll is an acceptable default. + +### 5.7 Endpoint routing (server- vs graph-scoped) + +- **Single-graph mode:** `POST /mcp` — graph tools + server tools (`health`, `graphs_list`). +- **Multi-graph mode (MR-668):** `POST /graphs/{graph_id}/mcp` — graph-scoped tools for that graph; plus a server-level `POST /mcp` exposing only server-scoped tools (`health`, `graphs_list`). A per-graph endpoint never lists another graph's tools (isolation, tested). Mirrors the shipped `/graphs/{graph_id}/…` cluster routing. (Open Q5: confirm naming + whether server tools also appear on the per-graph endpoint.) + +### 5.8 Modular / decoupled auth (the cross-cutting requirement) + +**Invariant (load-bearing, satisfiable today):** the MCP handler receives an **already-resolved `ResolvedActor`** and **branches on nothing** about how the token was verified. No token parsing, no method check, no OAuth inside the MCP module. Today that actor comes from `require_bearer_auth`; when MR-956 lands it comes from a `TokenVerifier` — the MCP code is identical either way. + +``` +request → [auth middleware: ResolvedActor] → [MCP route] → Cedar → McpTool +``` + +**Server side — auth is config, not code:** + +| Deployment | Verifier | MCP change | +|---|---|---| +| On-prem, static bearer | `require_bearer_auth` / `StaticHashTokenVerifier` | none | +| On-prem, customer IdP | `OidcJwtVerifier` → customer issuer (MR-956) | none | +| Our cloud | `OidcJwtVerifier` → WorkOS, `tenant_id = Some(org_id)` (MR-956) | none | + +Token validation is offline (cached JWKS) — on-prem/air-gapped keeps working with no request-path cloud dependency. The MCP endpoint never terminates OAuth and never holds a client secret (Resource Server only). + +**Cloud client negotiation — additive, no MCP changes:** when MR-956 lands, the server publishes RFC 9728 `/.well-known/oauth-protected-resource` and returns `WWW-Authenticate: Bearer ..., resource_metadata="..."` on 401. A compliant MCP client (Claude) then auto-negotiates: static bearer to an on-prem endpoint; on a cloud 401 it discovers the WorkOS AS and runs OAuth/PKCE itself — **same endpoint URL, zero client-side branching.** This RFC only requires that MCP routes flow through the standard 401 path so that hook can be added later without touching MCP. + +**Multi-user identity pass-through (cloud):** the *caller's* token (a WorkOS JWT, audience-bound per-tenant) must reach the server so Cedar enforces per-user/per-tenant policy — never a shared service token. The MCP endpoint validates it offline and maps `org_id → tenant_id`. This is why the **remote path is the in-server HTTP MCP that Claude connects to directly** (its token flows through), not a stdio bridge impersonating a user. + +**Client-side credential acquisition (CLI/SDK/proxy) — pluggable `CredentialSource`** (RFC-002 §5, MR-971), keyed by server name, so OAuth is a future *sibling key*, not a re-key: + +```yaml +servers: + onprem: { endpoint: https://og.internal:8080, auth: { token: { env: OG_TOKEN } } } + edge: { endpoint: https://og-edge, auth: { token: { command: [vault, read, -field=token, secret/og] } } } + cloud: { endpoint: https://api.omnigraph.cloud, auth: { oauth: { issuer: workos } } } # future sibling +``` + +Implicit chain when `auth:` omitted: `OMNIGRAPH_TOKEN_` → keychain `omnigraph:` → `[]` in `~/.omnigraph/credentials`; legacy `bearer_token_env` honoured. Secrets never inlined. + +### 5.9 Safety model — Cedar is the gate, default-deny is the floor + +With ad-hoc `query`/`mutate`/`schema_apply` present as tools, the **only** thing protecting an untrusted agent is the Cedar policy. Therefore: + +- **Default-deny when tokens are configured** (MR-723, shipped) is the floor — an actor with no grants sees an empty tool list. +- **What works today (coarse action):** a policy can hide all ad-hoc tools and admin tools per-actor (`deny Read, Change, SchemaApply, Branch*`) while allowing stored queries (`allow InvokeQuery`). That already reproduces "can't run ad-hoc, can't read schema, can only call stored queries" — the agent sees *every* exposed stored query plus nothing else. +- **What needs PR 0b (per-query scope):** selecting *which* stored queries an actor may call (`allow InvokeQuery [find_user, list_orders]`, deny the rest). The shipped `invoke_query` is coarse (all stored queries or none). Until PR 0b adds a query-name dimension to `PolicyRequest` + the Cedar schema (rfc-001's intended design), per-actor sub-selection of stored queries is **not expressible**; curation is graph-level (which `.gq` files are registered + `mcp.expose`). +- `schema_apply`, `branches_delete`, ad-hoc `mutate` require an explicit admin-tier grant; never in a default agent policy. +- (Open Q3) Optional `mcp.allow_adhoc` server switch defaulting **off** for the ad-hoc `query`/`mutate` tools — defence-in-depth independent of Cedar, and independent of PR 0b. + +### 5.10 Result shaping and error mapping + +- **Success:** `tools/call` returns `content: [{type:"text", text:}]` where `` is the route's existing output envelope (read rows / mutation summary, i.e. `ReadOutput` / `ChangeOutput`). (Open Q4: also emit `structuredContent` + `outputSchema` — defer; text-JSON for v1.) +- **Tool execution error** (bad params after schema validation, engine error): result with `isError:true` + a text content block. +- **Authorization denial / unknown tool / `mcp.expose:false`:** a single JSON-RPC error (`-32602`, message `"unknown tool"`) — identical for all three so policy isn't probeable (same principle as the shipped `POST /queries/{name}` 404 masking). +- **Auth failure** (bad/absent bearer): HTTP 401 from the middleware *before* MCP — carries `WWW-Authenticate` (the RFC 9728 hook), never masked as a tool error. (This is exactly the path the shipped `authorize`/`authorize_request` split preserves: operational failures keep their status; only *denials* are masked.) + +## Relationship to the `@modernrelay/omnigraph-mcp` stdio package + +Verified surface of the package (`omnigraph-ts`, pkg version `0.3.0`, `@modelcontextprotocol/sdk@^1.29.0`, **stdio only**): **13 tools** (`health`, `snapshot`, `read`, `schema_get`, `branches_list`, `commits_list`, `commits_get`, `change`, `ingest`, `branches_create`, `branches_delete`, `branches_merge`, `schema_apply`) and **2 resources** (`omnigraph://schema`, `omnigraph://branches`). It is a thin client over the SDK → HTTP routes and **forwards the caller's bearer verbatim** (no inspection). + +Once parity lands, **collapse to one implementation**: the in-server MCP is canonical (Cedar-gated, remote-capable, the path that becomes a Claude-web connector via MR-956). The stdio package degrades to a **thin stdio↔HTTP proxy** forwarding JSON-RPC (and the incoming `Authorization`) to `/mcp` — staying the local on-ramp for Claude Code/Desktop while sharing one tool set, one Cedar gate. Transition: keep the current independent stdio package on its `0.3.x`/`0.6.x` line; ship proxy mode in a later TS minor once the server endpoint is GA. (Note: the package is currently several minors behind the server — its vendored `spec/openapi.json` predates the stored-query routes — so it needs the standard re-sync regardless of MCP work.) + +## Testing + +- **Protocol conformance:** `initialize` handshake + advertised capabilities; `tools/list` shape; `tools/call` happy path; JSON-RPC error envelopes (`-32601` unknown method, `-32602` invalid params / unknown tool); `resources/list` + `resources/read`. +- **Cedar filtering (coarse, today):** an actor with `allow InvokeQuery` + `deny Read/Change` sees *all* exposed stored queries but **not** `query`/`mutate`/`schema_get`; `tools/call query` returns masked "unknown tool"; an admin sees the full catalog. +- **Cedar filtering (per-query, gated on PR 0b):** actor scoped to `InvokeQuery [find_user]` sees *only* `find_user`; `tools/call list_orders` masks. **This test ships with PR 0b**, not PR 1 — it cannot pass against the coarse action. +- **Parity per built-in:** each tool round-trips against the same expectations as its HTTP route (reuse route tests); `read`/`change` aliases dispatch identically to `query`/`mutate`. +- **Double-gating:** a stored mutation requires both `InvokeQuery` and `Change`; `schema_apply` requires `SchemaApply`. +- **`mcp.expose:false`:** absent from `GET /queries` and MCP `tools/list`; still service-callable by name through `POST /queries/{name}` when the actor has `invoke_query`, but not MCP-callable. +- **Schema generation:** table-driven over every `ParamKind` incl. nullable / list / vector(dim). +- **Branch-scoped list approximation:** assert the documented R7 caveat — a branch-scoped policy lists `branches_create`, and `tools/call` is the authoritative gate (a denied target still 403s/masks). +- **Multi-graph isolation:** `/graphs/a/mcp` never lists graph `b`'s tools; server `/mcp` exposes only server tools. +- **Auth decoupling:** the MCP suite is green under the current `require_bearer_auth` and under a mock OIDC `ResolvedActor` source — proving verifier-agnosticism. A 401 carries `WWW-Authenticate`. +- **OpenAPI:** the JSON-RPC endpoint is not REST — document only the envelope in utoipa (or exclude); keep `openapi.json` drift test green (`OMNIGRAPH_UPDATE_OPENAPI=1` to regenerate on intentional change). +- **Cross-repo smoke (optional):** point `@modelcontextprotocol/sdk` (TS) at the HTTP endpoint in an `omnigraph-ts` integration test. + +## Rollout — phased by risk + +- **PR 0a — extract the reusable invoke path (small).** The coarse `invoke_query` gate + 404 denial-masking are **already shipped** in `server_invoke_query`. Extract the read/mutate dispatch into `invoke_stored_query(handle, name, params, branch/snapshot, actor)` so MCP `tools/call` and the HTTP route share one path. No behaviour change. *(Replaces the previous draft's "PR 0 — wire the gate", which was already done.)* +- **PR 0b — per-query `invoke_query` scope (the safety prerequisite).** Add a query-name dimension to `PolicyRequest` + the Cedar schema (rfc-001's intended design), wire it at `POST /queries/{name}` and in the stored-query `McpTool::authorization`. Independently useful (the `allow InvokeQuery [find_user]` policy). **Gates the per-query Cedar-filtering test and §5.9's recommended agent policy.** +- **PR 1 — MCP transport + read-only parity + stored-query reads.** Endpoint(s), `initialize`/`tools/list`/`tools/call`/`resources/*`, the `McpTool` registry, Cedar-filtered listing, the read-only built-ins (`health`, `graphs_list`, `snapshot`, `read`/`query`, `schema_get`, `branches_list`, `commits_*`) + resources + stored-query *reads*. All auth-agnostic. +- **PR 2 — mutating parity + stored-query mutations.** `change`/`mutate`, `ingest`, `branches_create/delete/merge`, `schema_apply`, stored-query mutations + the `mcp.allow_adhoc` switch. +- **PR 3 — docs + agent on-ramp hook.** `docs/user/server.md` MCP section (incl. the recommended agent policy + the coarse-vs-per-query caveat), `openapi.json` sync, the `omnigraph mcp install` config target (MR-974), and the downstream `omnigraph-ts` re-sync/proxy follow-up. +- **Later (separate, MR-956):** RFC 9728 protected-resource metadata + WorkOS — slots in with zero MCP changes. +- **Later (TS minor):** stdio package → proxy mode. + +## Migration / backwards compatibility + +- **Additive.** No `queries:` and no MCP traffic → today's behaviour unchanged. New endpoints are new routes. +- **Cedar default-deny** (when tokens configured) means MCP exposes nothing until an actor is granted — safe by default. +- The stdio package keeps working unchanged; proxy mode is opt-in later. +- `openapi.json` only gains the documented MCP envelope; existing REST routes untouched. + +## Open Questions + +1. **BigInt/u64 as JSON string** (recommended, precision-safe) vs number. +2. **`rmcp` vs hand-rolled** JSON-RPC (spike `rmcp` on edition 2024; default to hand-roll on friction). +3. **Default-off `mcp.allow_adhoc`** for ad-hoc `query`/`mutate` (recommended) vs always-on + Cedar-only. +4. **`structuredContent` + `outputSchema`** now vs text-JSON v1 (recommend v1 text-JSON). +5. **Endpoint paths:** `/mcp` + `/graphs/{id}/mcp` — confirm naming and whether server-scoped tools also appear on the per-graph endpoint. +6. **Stateless POST-only** confirmed (no near-term server-initiated messages) — revisit only if subscriptions land. +7. **Legacy alias tools** (`read`/`change`): keep for client compat (the shipped package uses them), or drop and rely on `query`/`mutate`? +8. **PR 0b shape:** per-query scope as a Cedar *resource* (`StoredQuery::"find_user"`) vs a `query_name` *context attribute* + policy condition — affects how `allow InvokeQuery [list]` is authored. diff --git a/docs/dev/testing.md b/docs/dev/testing.md index 14b66ed..425fcee 100644 --- a/docs/dev/testing.md +++ b/docs/dev/testing.md @@ -20,9 +20,9 @@ The engine's `tests/` is the principal coverage surface; most graph-shaped behav | `end_to_end.rs` | Full init → load → query/mutate flow | | `branching.rs` | Branch create / list / delete, lazy fork | | `merge_truth_table.rs` | Merge-pair truth table (MR-786): all 9×9 `(left_op, right_op)` cells from `{noop, addNode, removeNode, addEdge, removeEdge, setProperty, dropProperty, addLabel, removeLabel}`. Adding a new op to `OpVariant` forces a compile error in `build_case` until the new row + column are dispositioned. 36 executable cells run through real `branch_merge` with a structured oracle (`MergeOutcome` / `MergeConflictKind` + graph-state assert); 45 cells involving `dropProperty`/`addLabel`/`removeLabel` are recorded as `Unsupported` until the mutation grammar grows. | -| `runs.rs` | Direct-publish writes: cancellation, concurrent-writer CAS, multi-statement atomicity, MR-794 staged-write rewire (D₂ rejection, insert+update coalesce, multi-append coalesce, partial-failure recovery, load RI/cardinality recovery) | +| `writes.rs` | Direct-publish writes: cancellation, concurrent-writer CAS, multi-statement atomicity, MR-794 staged-write rewire (D₂ rejection, insert+update coalesce, multi-append coalesce, partial-failure recovery, load RI/cardinality recovery) | | `staged_writes.rs` | TableStore staged-write primitives (`stage_append`, `stage_merge_insert`, `commit_staged`, `scan_with_staged`, `count_rows_with_staged`) — primitive-level only; engine code uses the in-memory `MutationStaging` accumulator instead | -| `lifecycle.rs` | Repo lifecycle, schema state | +| `lifecycle.rs` | Graph lifecycle, schema state | | `point_in_time.rs` | Snapshots, time travel (`snapshot_at_version`, `entity_at`) | | `changes.rs` | `diff_between` / `diff_commits` | | `consistency.rs` | Cross-table snapshot isolation, atomic publish | @@ -31,7 +31,7 @@ The engine's `tests/` is the principal coverage surface; most graph-shaped behav | `traversal.rs` | `Expand`, variable-length hops, anti-join | | `aggregation.rs` | `count`, `sum`, `avg`, `min`, `max` | | `export.rs` | NDJSON streaming export filters | -| `s3_storage.rs` | S3-backed repo (skipped unless `OMNIGRAPH_S3_TEST_BUCKET` is set) | +| `s3_storage.rs` | S3-backed graph (skipped unless `OMNIGRAPH_S3_TEST_BUCKET` is set) | | `lance_version_columns.rs` | Per-row `_row_last_updated_at_version` behavior | | `validators.rs` | Schema constraint enforcement (enum, range, unique, cardinality) across JSONL, insert, update paths | | `maintenance.rs` | `optimize` (compaction) + `cleanup` (version GC): empty/idempotent/no-op edges, policy validation, head preservation | @@ -45,7 +45,7 @@ The engine's `tests/` is the principal coverage surface; most graph-shaped behav ## Test helpers -- **Engine** — `crates/omnigraph/tests/helpers/mod.rs`: `init_and_load()` (bootstrap a temp repo + load standard fixture), `snapshot_main()`, `snapshot_branch()`, query/mutation runners, row collection and counting. Use these instead of hand-rolling. +- **Engine** — `crates/omnigraph/tests/helpers/mod.rs`: `init_and_load()` (bootstrap a temp graph + load standard fixture), `snapshot_main()`, `snapshot_branch()`, query/mutation runners, row collection and counting. Use these instead of hand-rolling. - **CLI** — `crates/omnigraph-cli/tests/support/mod.rs`: `Command`-style wrapper for invoking `omnigraph`, server-process spawning, fixture resolution, output assertion helpers. - **Server** — no shared helpers; server tests call the `Omnigraph` engine API directly and exercise endpoints over the wire. @@ -63,14 +63,14 @@ The engine's `tests/` is the principal coverage surface; most graph-shaped behav CI runs three S3-backed tests against a containerized RustFS server (`.github/workflows/ci.yml` → `rustfs_integration` job): - `cargo test -p omnigraph-engine --test s3_storage` -- `cargo test -p omnigraph-server --test server server_opens_s3_repo_directly_and_serves_snapshot_and_read` +- `cargo test -p omnigraph-server --test server server_opens_s3_graph_directly_and_serves_snapshot_and_read` - `cargo test -p omnigraph-cli --test system_local local_cli_s3_end_to_end_init_load_read_flow` Locally, set `OMNIGRAPH_S3_TEST_BUCKET` (and the usual `AWS_*` vars including `AWS_ENDPOINT_URL_S3` for non-AWS) before running. Without those, S3 tests skip gracefully. ## OpenAPI drift -`crates/omnigraph-server/tests/openapi.rs` regenerates `openapi.json` and diffs against the checked-in copy. CI auto-commits the regeneration on same-repo PRs and otherwise runs in strict-check mode (env: `OMNIGRAPH_UPDATE_OPENAPI`). +`crates/omnigraph-server/tests/openapi.rs` regenerates `openapi.json` and diffs against the checked-in copy. CI auto-commits the regeneration on same-repository PRs and otherwise runs in strict-check mode (env: `OMNIGRAPH_UPDATE_OPENAPI`). ## Examples & benches @@ -79,7 +79,7 @@ Locally, set `OMNIGRAPH_S3_TEST_BUCKET` (and the usual `AWS_*` vars including `A ## Coverage tooling — what's missing -There is **no** coverage tooling in the repo today: no `tarpaulin.toml`, no `codecov.yml`, no coverage CI step. If you want to know whether your change is covered, the answer comes from reading and running the relevant integration tests, not from a tool. +There is **no** coverage tooling in the repository today: no `tarpaulin.toml`, no `codecov.yml`, no coverage CI step. If you want to know whether your change is covered, the answer comes from reading and running the relevant integration tests, not from a tool. If introducing coverage tooling is in scope for your task, the natural first step is `cargo-llvm-cov` wired into a separate CI job, and a per-crate threshold rather than a global one. @@ -89,7 +89,7 @@ If introducing coverage tooling is in scope for your task, the natural first ste How to check: -1. **Map the change to an area** — use the engine integration-test table above (`branching.rs`, `runs.rs`, `search.rs`, etc.). The filename usually names the area. +1. **Map the change to an area** — use the engine integration-test table above (`branching.rs`, `writes.rs`, `search.rs`, etc.). The filename usually names the area. 2. **Open the file and skim every test fn name.** Test fn names are the index — read them all, not just the first few. 3. **Grep for the symbol or path you're changing.** `rg ` or `rg ` across all `tests/` directories surfaces existing coverage you might miss. 4. **Decide one of three outcomes**, in this order of preference: @@ -97,7 +97,7 @@ How to check: - *Existing test covers the area but not your case* → **add an assertion or a fixture row to the existing test**, don't write a new function with `init_and_load()` again. - *No existing coverage in any test file* → only then write a new test; put it in the file that owns the area, or open a new file only if the area itself is new. -Three duplicated `init_and_load() → run_query → assert_eq` blocks where one parameterized test would do is the most common form of test rot in this repo. Don't add to it. +Three duplicated `init_and_load() → run_query → assert_eq` blocks where one parameterized test would do is the most common form of test rot in this repository. Don't add to it. ## Before-every-task checklist @@ -106,7 +106,7 @@ When you pick up any change, walk through this: 1. **Find existing coverage** (per the principle above). Don't just look at the first test file by name — grep for the symbol you're touching across every crate's `tests/`. 2. **Run those tests locally before editing.** `cargo test --workspace --locked` for the broad pass; `-p --test ` for a focused loop. Confirm a clean baseline. 3. **Decide extend-vs-new** explicitly. If you can extend an existing test (assertion, fixture row, parameterization), do that. Only add a new test fn or new file if no existing one owns the area. -4. **Reuse the helpers.** `init_and_load()`, fixture files, the CLI `support` harness — re-use them. Don't bootstrap a fresh repo by hand if a helper exists. +4. **Reuse the helpers.** `init_and_load()`, fixture files, the CLI `support` harness — re-use them. Don't bootstrap a fresh graph by hand if a helper exists. 5. **Mind the boundary.** Per [docs/dev/invariants.md](invariants.md), test at the layer the change lives at — planner-level changes deserve planner-level tests, not just end-to-end. 6. **For substrate-touching changes** (Lance behavior), reach for `failpoints` or fixture-driven scenarios, not stubbed-out mocks. 7. **For server / API changes**, confirm the OpenAPI regeneration happens in `openapi.rs` and that the diff lands in `openapi.json`. diff --git a/docs/dev/runs.md b/docs/dev/writes.md similarity index 98% rename from docs/dev/runs.md rename to docs/dev/writes.md index 816f2ac..974f7a6 100644 --- a/docs/dev/runs.md +++ b/docs/dev/writes.md @@ -1,7 +1,10 @@ -# Runs — REMOVED (MR-771) +# Direct-Publish Write Path -The Run state machine and `__run__` staging branches were removed in -MR-771. `mutate_as` and `load` now write **directly to the target table** +> History: the Run state machine and `__run__` staging branches were +> removed in MR-771 (shipped v0.4.0). Writes now go directly to the target +> table; this document specifies that direct-publish path. + +`mutate_as` and `load` write **directly to the target table** and call `ManifestBatchPublisher::publish` once at the end with `expected_table_versions` (the per-table manifest versions captured before the first write). Cross-table OCC is enforced inside the publisher; the diff --git a/docs/releases/v0.4.0.md b/docs/releases/v0.4.0.md index efb2da7..d3a8244 100644 --- a/docs/releases/v0.4.0.md +++ b/docs/releases/v0.4.0.md @@ -65,7 +65,7 @@ manifest. The next mutation against that table fails with `ExpectedVersionMismatch`. Most validation runs before any Lance write, so single-statement mutations are unaffected; the narrow path is multi-statement queries with late-op failures. Tracked as a follow-up; -see [docs/dev/runs.md](../dev/runs.md#known-limitation-mid-query-partial-failure-on-the-same-table) +see [docs/dev/writes.md](../dev/writes.md#mid-query-partial-failure-closed-by-mr-794) for the workaround. ## Upgrade notes diff --git a/docs/releases/v0.4.1.md b/docs/releases/v0.4.1.md index 78211e4..4983015 100644 --- a/docs/releases/v0.4.1.md +++ b/docs/releases/v0.4.1.md @@ -19,7 +19,7 @@ mutation proceeds normally. HEAD on every staged table is untouched and the next mutation proceeds normally. A narrowed residual remains at the finalize→publisher boundary (multi-table `commit_staged` is not - atomic with the manifest commit) — see [docs/dev/runs.md](../dev/runs.md) + atomic with the manifest commit) — see [docs/dev/writes.md](../dev/writes.md) "Finalize → publisher residual" for details. - **D₂ parse-time rule**: a single mutation query is either insert/update-only or delete-only. Mixed → rejected with a clear @@ -75,14 +75,14 @@ mutation proceeds normally. ## Tests added -- `tests/runs.rs::partial_failure_leaves_target_queryable_and_unblocks_next_mutation` +- `tests/writes.rs::partial_failure_leaves_target_queryable_and_unblocks_next_mutation` (replaces the old `partial_failure_observably_rolls_back_but_blocks_next_mutation_on_same_table`) -- `tests/runs.rs::mutation_rejects_mixed_insert_and_delete_at_parse_time` -- `tests/runs.rs::mixed_insert_and_update_on_same_person_coalesces_to_one_merge` -- `tests/runs.rs::multiple_appends_to_same_edge_coalesce_to_one_append` -- `tests/runs.rs::multi_statement_inserts_publish_exactly_once` -- `tests/runs.rs::load_with_bad_edge_reference_unblocks_next_load` -- `tests/runs.rs::load_with_cardinality_violation_unblocks_next_load` +- `tests/writes.rs::mutation_rejects_mixed_insert_and_delete_at_parse_time` +- `tests/writes.rs::mixed_insert_and_update_on_same_person_coalesces_to_one_merge` +- `tests/writes.rs::multiple_appends_to_same_edge_coalesce_to_one_append` +- `tests/writes.rs::multi_statement_inserts_publish_exactly_once` +- `tests/writes.rs::load_with_bad_edge_reference_unblocks_next_load` +- `tests/writes.rs::load_with_cardinality_violation_unblocks_next_load` ## Files changed @@ -105,7 +105,7 @@ mutation proceeds normally. - `Cargo.toml` (workspace) + `crates/omnigraph/Cargo.toml` — added `datafusion = "52"` direct dep (transitively pulled by Lance already; required for `MemTable`). -- `docs/dev/runs.md` — removed "Known limitation" section; documented +- `docs/dev/writes.md` — removed "Known limitation" section; documented the new accumulator + D₂ + LoadMode::Overwrite residual. - `docs/dev/invariants.md` — mutation atomicity / read-your-writes status flipped to `upheld for inserts/updates`. @@ -127,7 +127,7 @@ mutation proceeds normally. as legacy. - `docs/user/cli.md` — replaced the legacy `omnigraph run *` quickstart block with `omnigraph commit list/show`. -- `docs/dev/testing.md` — extended the `runs.rs` row to cover the new +- `docs/dev/testing.md` — extended the `writes.rs` row to cover the new staged-write contract tests; added the `staged_writes.rs` row. - `AGENTS.md` (CLAUDE.md symlink) — updated the atomic-per-query description and the L2 capability matrix row. diff --git a/docs/releases/v0.5.0.md b/docs/releases/v0.5.0.md new file mode 100644 index 0000000..16e284e --- /dev/null +++ b/docs/releases/v0.5.0.md @@ -0,0 +1,171 @@ +# Omnigraph v0.5.0 + +Omnigraph v0.5.0 is a substrate, security, and migration-safety release. It +jumps the storage substrate from Lance 4 to Lance 6.0.1 (DataFusion 52 → 53, +Arrow 57 → 58), introduces engine-wide Cedar policy enforcement on every +authoring path, and ships a structured schema-lint v1 chassis with +code-tagged diagnostics, soft drops, and an explicit `--allow-data-loss` +flag for destructive migrations. + +## Highlights + +- **Lance 6.0.1 substrate**: bump from Lance 4.0.0 → 6.0.1, DataFusion 52 → + 53, Arrow 57 → 58. New optimizer rules (vectorized `IN`-list eq kernel, + `PhysicalExprSimplifier`, push-limit-into-hash-join, CASE-NULL shortcut) + reach predicates that flow through the engine. `lance-tokenizer` replaces + tantivy internally; FTS behavior preserved. +- **Cedar policy engine**: a new `omnigraph-policy` crate wires + `Omnigraph::enforce(action, scope, actor)` into every `_as` writer + (`mutate_as`, `load_as`, `apply_schema_as`, `branch_create_as`, + `branch_merge_as`, `branch_delete_as`, plus the load and change + variants). The HTTP server defaults to deny-all when no Cedar policy is + configured; a YAML policy file is required to enable writes. Actor + identity comes only from signed token claims — clients cannot set actor + identity directly. +- **Schema lint v1 chassis**: diagnostics now carry stable codes of the form + `OG-XXX-NNN` instead of free-form messages. `omnigraph schema plan` and + `apply` understand soft drops on properties and types — destructive drops + require the new `--allow-data-loss` flag (Hard mode) at the CLI and an + equivalent JSON flag over HTTP. +- **Structured filter pushdown**: query-language predicates lower to + DataFusion `Expr` and push down through Lance's `Scanner::filter_expr` + instead of being flattened to SQL strings. This unlocks `CompOp::Contains` + pushdown (via `array_has`), which previously fell through to in-memory + post-scan filtering, and lets the DataFusion 53 optimizer rules above act + on our predicates. +- **HTTP `allow_data_loss` parity**: the destructive-drop guard now exists + on both the CLI (`--allow-data-loss`) and HTTP (`allow_data_loss: true` in + the schema-apply request body). +- **Inline query strings on CLI and HTTP**: `omnigraph read` / + `omnigraph mutate` and the corresponding HTTP endpoints accept inline + `.gq` source, not just a file path. Easier ad-hoc queries, clearer + request logs. +- **Browser CORS layer**: optional CORS layer on `omnigraph-server` for + browser-based UIs, gated by `OMNIGRAPH_CORS_ORIGINS`. +- **Merge-insert dup-rowid fix**: Lance's `MergeInsertBuilder` could surface + spurious `"Ambiguous merge inserts"` errors on sequential merges against + rows previously rewritten by `merge_insert`. The engine now opts into + `SourceDedupeBehavior::FirstSeen` with a `check_batch_unique_by_keys` + fail-fast precondition that guarantees source-side dedup happens before + Lance sees the batch. +- **Branch-merge error-path recovery**: a branch merge that failed + mid-flight could leave the in-process coordinator pointing at a stale + active branch. The error path now restores the prior coordinator, + matching the success path's invariant. +- **Branch merge with blob columns**: external blob URIs are now + materialized correctly during branch merge instead of being dropped or + pointing at the source branch. +- **Lance API surface guards**: a new test file + (`crates/omnigraph/tests/lance_surface_guards.rs`) pins eight specific + Lance API surfaces (`LanceError::TooMuchWriteContention`, + `ManifestLocation` fields, `MergeInsertBuilder` return shape, + `WriteParams::default`, `compact_files` signature, etc.) so the next + Lance bump fails compile or runtime on any silent drift rather than + producing wrong-state recovery in production. + +## Behavior changes + +- **On-disk format unchanged**: existing v0.4.2 datasets open unchanged. + The Lance file format pin stays at V2_2 (required by Lance's blob v2 + feature). +- **`omnigraph-server` defaults to deny-all under `--policy`**: starting a + server with the policy feature enabled but no Cedar YAML policy + configured rejects every write. Operators must supply a policy file to + authorize anything. +- **Schema-lint diagnostics carry stable codes**: messages now lead with + `OG-XXX-NNN`. CI parsers or tooling that keyed off the v0.4.2 free-form + text need to switch to code-based matching. +- **Destructive schema drops require `--allow-data-loss`**: dropping a + property or type returns a structured diagnostic by default. + `omnigraph schema apply --allow-data-loss` (CLI) or + `{"allow_data_loss": true}` (HTTP) opts into Hard mode. +- **`HashJoinExec` null-aware semantics on anti-join**: a side effect of + the DataFusion 53 bump — `NOT IN` semantics under null-valued anti-join + columns are now correct per SQL standard. Queries that depended on the + prior behavior would have been incorrect. + +## Upgrade Notes + +### Migration + +- No data migration. v0.4.2 repos open directly on v0.5.0. + +### Clients + +- HTTP and SDK clients should switch any string-matching schema-lint + parsing to code-based matching against the `OG-XXX-NNN` prefix. +- Clients exercising destructive schema drops (`DropProperty`, `DropType`) + must add the `allow_data_loss` request field (HTTP) or + `--allow-data-loss` flag (CLI). Default is soft-drop-or-reject. +- Clients consuming `mutate_as` / `load_as` / `apply_schema_as` / branch + authoring APIs now flow through the policy enforcer. Anything bypassing + authorization on v0.4.2 will be rejected on v0.5.0 once a policy is + configured. + +### Operators + +- Configure a Cedar policy YAML for production servers before enabling + writes; deny-all is the new default. The `omnigraph policy validate` / + `test` / `explain` CLI commands are unchanged. +- Bearer tokens continue to be the actor-identity source; review the + signed-token-claim-only invariant in `docs/dev/invariants.md` if you've + built custom authentication. +- If your local CI uses RustFS for S3-compatible storage testing, our CI + pins `rustfs/rustfs:1.0.0-beta.3` (the last known-good tag before the + upstream credentials-policy change). Mirror the pin or set + `RUSTFS_ALLOW_INSECURE_DEFAULT_CREDENTIALS=true` for the new image + versions. + +## Tests added or strengthened + +- `crates/omnigraph/tests/lance_surface_guards.rs` — 8 named guards pinning + Lance API surfaces against silent drift on future bumps. +- `crates/omnigraph/tests/policy_engine_chassis.rs` — engine-level policy + enforcement coverage; complements the existing HTTP policy tests. +- Policy chassis e2e gap-fills — branch-merge, branch-create, branch-delete + policy paths now have explicit end-to-end tests over HTTP and CLI. +- Merge-pair truth table — exhaustive op-variant matrix for three-way + merge across `noop`, `addNode`, `removeNode`, `addEdge`, `removeEdge`, + `setProperty`, `dropProperty`, `addLabel`, `removeLabel`; the build + fails to compile when a new op variant is added without dispositioning + every pairing. +- Merge-insert: regression for the dup-rowid bug class on the load surface + (`load_merge_repeated_against_overlapping_keys_succeeds`), the update + surface (`second_sequential_update_on_same_row_succeeds`), and the + upstream-Lance-gap canary + (`load_merge_window_2_documents_upstream_lance_gap`). +- Maintenance + destructive-migration coverage — `omnigraph optimize` / + `cleanup` boundary cases, plus schema-apply soft-drop and Hard-mode + paths. +- Stable-row-id preservation across `stage_overwrite` — pins the invariant + that staged overwrites carry stable row IDs through to the committed + fragment set. +- `CompOp::Contains` pushdown regression + (`ir_filter_with_list_contains_pushes_down`) — pins the new structured + Expr pushdown path that retired the in-memory fallback. + +## Included Changes + +- Lance 4 → 6.0.1, DataFusion 52 → 53, Arrow 57 → 58 substrate upgrade. +- `omnigraph-policy` crate with engine-wide Cedar enforcement and + signed-token-claim-only actor identity. +- Schema-lint v1 chassis with `OG-XXX-NNN` codes, soft `DropProperty` / + `DropType` semantics, and `--allow-data-loss` for Hard mode. +- HTTP `allow_data_loss` request field parity with the CLI flag. +- Structured DataFusion `Expr` filter pushdown via + `Scanner::filter_expr`, with `CompOp::Contains` lowered through + `array_has`. +- Inline `.gq` source acceptance on CLI and HTTP read/mutate endpoints. +- Optional CORS layer on `omnigraph-server` for browser UIs. +- Bug fixes: merge-insert dup-rowid (FirstSeen + uniqueness precondition), + branch-merge coordinator restore on error, blob-column materialization + during branch merge. +- New Lance API surface-guard test file as the canary for future Lance + bumps. +- Recovery-sidecar coverage extended across the four write paths + (`MutationStaging::finalize`, `schema_apply`, `branch_merge`, + `ensure_indices`) with failpoint regression tests. +- CI: pinned `rustfs/rustfs:1.0.0-beta.3` after the upstream `:latest` + introduced a credentials-policy change. +- Version bump to `0.5.0` across workspace crates, `Cargo.lock`, + `openapi.json`, and the `AGENTS.md` surveyed version. diff --git a/docs/releases/v0.6.0.md b/docs/releases/v0.6.0.md new file mode 100644 index 0000000..7984056 --- /dev/null +++ b/docs/releases/v0.6.0.md @@ -0,0 +1,141 @@ +# Omnigraph v0.6.0 + +Three pieces of work land in this release: + +1. The **graph terminology rename** (renamed `Repo` → `Graph` across the Cedar resource model, policy API, and query-lint schema source). +2. **Multi-graph server mode** — one `omnigraph-server` process can now serve 1–10 graphs concurrently behind cluster routes (`/graphs/{graph_id}/...`), with per-graph and server-level Cedar policy, read-only `GET /graphs` enumeration, and CLI parity (`omnigraph graphs list`). +3. **Inline + canonical-named queries and mutations.** New `POST /query` and `POST /mutate` endpoints pair with the CLI's new `-e/--query-string` flag for ad-hoc execution without a temp file. `POST /read` and `POST /change` continue serving indefinitely as deprecated aliases that carry RFC 9745 `Deprecation: true` and RFC 8288 `Link: ; rel="successor-version"` response headers, plus `deprecated: true` in `openapi.json`. Same canonicalization on the CLI: `omnigraph query`, `omnigraph mutate`, and top-level `omnigraph lint` / `omnigraph check` replace `omnigraph read`, `omnigraph change`, and the nested `omnigraph query lint` / `omnigraph query check`. Every deprecated spelling remains a `visible_alias` that warns to stderr once per invocation. + +Runtime add/remove (`POST /graphs`, `DELETE /graphs/{id}`, `omnigraph graphs create`) is **not** in v0.6.0. Operators add or remove graphs by editing `omnigraph.yaml` and restarting. The first cut of `POST /graphs` shipped behind an atomic-YAML-rewrite design that we pulled before release once its concurrency guarantees were challenged (flock-on-renamed-inode race, duplicate-check outside the critical section, and an init-cleanup path that could destroy an existing graph's schema on re-init). The correct fix is a Lance-style cluster catalog (reserve → init → publish with recovery sidecars); that work is deferred. + +## Breaking Changes + +### Graph terminology rename + +- Renamed the Cedar resource entity from `Omnigraph::Repo` to `Omnigraph::Graph`. +- Renamed policy API terminology from `repo_id` to `graph_id` on `PolicyCompiler::compile` (and on the new `PolicyEngine::load_graph` / `PolicyEngine::load_server` loaders described below). +- Renamed query-lint schema source JSON from `"repo"` to `"graph"` for `schema_source.kind`. + +### Multi-graph server mode + +- **Multi-graph deployments lose flat routes.** Single-graph invocation (`omnigraph-server `) is unchanged — same flat `/snapshot`, `/read`, `/branches`, etc. Multi-graph deployments serve those routes under `/graphs/{graph_id}/...`; bare flat paths return 404 in multi mode. +- **`ServerConfig` shape change** (programmatic embedders only): `ServerConfig { uri, policy_file }` is replaced by `ServerConfig { mode: ServerConfigMode }`, where `ServerConfigMode = Single { uri, policy_file } | Multi { graphs, config_path, server_policy_file }`. Callers that use `load_server_settings` are unaffected; callers that construct `ServerConfig` directly need to wrap their fields in `ServerConfigMode::Single`. +- **`AppState`'s routing surface** is `AppState::routing() -> &GraphRouting`, where `GraphRouting = Single { handle } | Multi { registry, config_path }`. The previous `AppState::uri()`, `AppState::mode()`, `AppState::registry()` accessors and the `ServerMode` enum are gone — embedders read `state.routing()` and match on the arm they need. Per-graph URIs live on `handle.uri`. +- **`AppState::new_multi`** is the new multi-graph constructor. Single-mode `new_*` / `open_*` constructors are unchanged. +- **`AuthenticatedActor(Arc)` → `ResolvedActor { actor_id, tenant_id, scopes, source }`** (programmatic embedders only). The struct shape changes, but the HTTP contract — bearer auth and the bearer-derived-actor-identity guarantee — is unchanged. Cluster-mode call sites construct with `tenant_id: None`, `scopes: vec![Scope::Full]`, `source: AuthSource::Static`. The new fields are forward-compat seams for future multi-tenant and OAuth deployments; they're inert in this release. +- **`PolicyEngine::load(path, graph_id)` removed** in favor of two kind-typed loaders: `PolicyEngine::load_graph(path, graph_id)` for per-graph policies and `PolicyEngine::load_server(path)` for server-level policies. Each loader rejects rules whose action `resource_kind()` doesn't match the engine kind — operators who put a `graph_list` rule in a per-graph file (or a `read` rule in a server file) now get a load-time error instead of a silently-never-matching rule. +- **`PolicyRequest::actor_id` field removed.** Actor identity is now a separate parameter on `PolicyEngine::authorize(actor_id, &request)`. The type system enforces the server-authoritative-actor invariant: actor identity is always sourced from the bearer-token match resolved at the auth boundary; handlers cannot smuggle identity through the request body. +- **`Omnigraph::init` is strict by default.** Initialization at a URI that already holds schema files now errors with `OmniError::AlreadyInitialized` instead of silently overwriting. Operators who actually want to overwrite use `InitOptions { force: true }` (CLI: `omnigraph init --force`). Closes the destructive-cleanup footgun where a failed re-init would delete an existing graph's schema files. +- **Top-level `policy.file` is rejected in multi-graph server mode.** It remains valid for single-graph / CLI-local policy. Multi-graph deployments must move graph rules to `graphs..policy.file` and server-scoped `graph_list` rules to `server.policy.file`. +- **Open server startup requires explicit opt-in.** A server with no bearer tokens and no policy now refuses to start unless passed `--unauthenticated` or `OMNIGRAPH_UNAUTHENTICATED=1`. +- **Policy requires bearer tokens.** Configuring any policy file without bearer tokens now refuses startup; otherwise every protected request would 401 before Cedar could evaluate it. +- **Tokens without policy default-deny non-read actions.** Existing authenticated deployments that relied on writes or admin routes without Cedar policy must add policy rules for those actions. +- **`GET /graphs` requires `server.policy.file` in every runtime state.** Even `--unauthenticated` mode keeps server topology closed until the operator explicitly authorizes `graph_list`. + +### Query / mutation rename + +- **`ChangeRequest` field rename**: `query_source` → `query`, `query_name` → `name`. Both legacy names continue to deserialize via `#[serde(alias = "...")]`, so existing clients sending the old JSON keys keep working. CLI remote calls against `/change` still emit the legacy keys verbatim through the `legacy_change_request_body` helper so a newer CLI talking to an older server keeps working byte-for-byte. +- **CLI `omnigraph query lint` / `omnigraph query check`** are now top-level — canonical name is **`omnigraph lint`**. The three deprecated invocations (`omnigraph query lint`, `omnigraph query check`, and bare `omnigraph check`) remain as argv-level shims that rewrite to `omnigraph lint` and print a one-line stderr deprecation warning. `check` is deliberately **not** a clap `visible_alias` on `lint` — two equivalent canonical names would split agent emissions between them depending on training-data drift, so the deprecation pattern (rewrite + warn) gives one unambiguous canonical name in `omnigraph --help`. + +## New + +- **Multi-graph mode**. Invoke with `omnigraph-server --config omnigraph.yaml` where the YAML has a non-empty `graphs:` map and no single-mode selector (no `server.graph`, no CLI `` or `--target`). At startup the server opens every configured graph in parallel (bounded concurrency, fail-fast). +- **`GET /graphs`**. Lists every registered graph, sorted alphabetically by `graph_id`. Auth-required when bearer tokens are configured; Cedar-gated by `PolicyAction::GraphList` against `Omnigraph::Server::"root"`. Returns 405 in single mode. Server-scoped actions require an explicit `server.policy.file` in every runtime state — the management surface is closed by default even in `--unauthenticated` mode so that server topology is never exposed without operator opt-in. +- **CLI `omnigraph graphs list`**. Mirrors the HTTP surface. Rejects local URI targets with a clear message — for remote multi-graph servers only. +- **CLI `omnigraph init --force`**. Bypasses the strict-init preflight when an operator deliberately wants to recover from orphan schema files. Does NOT purge existing Lance datasets; recursive deletion needs `StorageAdapter::delete_prefix` (deferred — see below). +- **Per-graph Cedar policy**. Each entry in the `graphs:` map can carry a `policy.file` path, loaded at startup via `PolicyEngine::load_graph`. Cedar's `Omnigraph::Graph::""` resource is per-graph; the new `Omnigraph::Server::"root"` resource governs server-level actions. +- **Server-level Cedar policy**. `server.policy.file` in the config governs the `graph_list` action on `Omnigraph::Server::"root"`. Required to expose `GET /graphs` in every runtime state — without a server policy the default-deny posture rejects `graph_list`, including in `--unauthenticated` mode. +- **Cedar action vocabulary**: `graph_list` (server-scoped). Runtime `graph_create` / `graph_delete` are reserved but not shipped — see "Deferred." +- **Canonical graph URI identity.** Server startup normalizes graph root URIs before registry insertion and response output, so aliases such as `/tmp/g`, `/tmp/g/`, and `file:///tmp/g` cannot register as distinct graphs that actually share one Lance root. +- **`POST /query`** and **`POST /mutate`**. Canonical inline endpoints. `/query` rejects mutations with a typed 400 (the D2 rule lives at the URL — read-only contract enforced before execution); body uses the clean `{ query, name, params, branch, snapshot }` shape. `/mutate` accepts the same shape for mutations. Both available in single mode and per-graph multi mode (`/graphs/{id}/query`, `/graphs/{id}/mutate`). Internal call sites share two helpers (`run_query`, `run_mutate`) that take decoupled args, not request bodies — the seam MR-969's future stored-query handler plugs into. +- **CLI `omnigraph query` / `omnigraph mutate`** as top-level canonical subcommands. Pairs with new top-level **`omnigraph lint` (alias `check`)** so query validation no longer sits under `omnigraph query`. +- **CLI `-e, --query-string `** on both `omnigraph query` and `omnigraph mutate`. 3-way mutex with `--query ` and `--alias ` — exactly one is required. Empty string rejected. Suits ad-hoc exploration, REPL workflows, and agent tool-use without temp files. +- **Three-channel deprecation signal on `/read` and `/change`**: OpenAPI `deprecated: true` on the operation (every codegen flags the generated SDK method), RFC 9745 `Deprecation: true` response header, and RFC 8288 `Link: ; rel="successor-version"` (or ``) response header. Auto-discoverable; no SDK breakage. +- **`omnigraph.yaml` `aliases..command`** now accepts `query` and `mutate` as canonical values alongside the legacy `read` and `change`. The internal `AliasCommand` enum retains the legacy variant names so serialized configs stay byte-stable. + +## Configuration + +`omnigraph.yaml` schema additions (all optional, single-mode unaffected): + +```yaml +server: + bind: 0.0.0.0:8080 + policy: + file: ./server-policy.yaml # server-level Cedar (graph_list) + +graphs: + alpha: + uri: s3://tenant-bucket/alpha + policy: + file: ./policies/alpha.yaml # per-graph Cedar + beta: + uri: s3://tenant-bucket/beta + # no per-graph policy → engine-layer enforcement is a no-op +``` + +## Deferred + +- **`POST /graphs` runtime graph creation** and **CLI `omnigraph graphs create`**. Pulled before release after the YAML-rewrite design's correctness story didn't survive review. A future release will add a managed cluster catalog (Lance-backed reserve → init → publish with recovery sidecars) and re-expose runtime creation on top of it. Until then, operators add graphs by editing `omnigraph.yaml` and restarting. +- **`DELETE /graphs/{id}`**. Never shipped in v0.6.0; deferred with the same cluster-catalog work. +- **`StorageAdapter::delete_prefix`**. The substrate primitive a managed catalog would need. Will land alongside runtime mutation. +- **`omnigraph init --force` purging Lance state.** Today `--force` only bypasses the schema-file preflight; recursive deletion of existing Lance datasets needs `delete_prefix`. +- **`X-Actor-Id` service delegation forwarding**. Needs durable both-actor audit on `_graph_commits.lance` — out of scope. +- **Hot policy reload**. Restart is cheap at N≤10 graphs. + +## User Impact + +- **No on-disk migration is required.** Existing `.omni` graphs from v0.5.0 (and earlier) open cleanly under v0.6.0 — Lance datasets, `__manifest`, `_schema.pg`, `_schema.ir.json`, `__schema_state.json`, `_graph_commits.lance`, `_graph_commit_recoveries.lance` all use unchanged formats. No conversion step. +- **Existing single-graph storage upgrades without migration.** Server deployments may need auth/policy config changes: explicitly pass `--unauthenticated` for local open mode, configure tokens when using policy, and add Cedar policy for non-read authenticated actions. +- **Multi-graph adoption is opt-in.** Add a `graphs:` map to `omnigraph.yaml` (and remove `server.graph`) to switch a deployment to multi mode. +- **Cluster routes are breaking for client SDKs targeting multi mode.** Generated clients from previous v0.5.0 OpenAPI specs will hit 404 on flat paths against a multi-mode server. Regenerate against the v0.6.0 `openapi.json`. +- **Supported YAML policy authoring is unchanged.** The Cedar `Omnigraph::Graph` and `Omnigraph::Server` entities are internally generated by `compile_policy_source` — operator YAML only references actions and groups. +- **Operators with unsupported raw Cedar policy files** should update `Omnigraph::Repo` resource references to `Omnigraph::Graph`. +- **Endpoint and CLI rename is cosmetic on the client side.** Existing callers on `/read`, `/change`, `omnigraph read`, `omnigraph change`, and `omnigraph query lint` keep working — they pick up the `Deprecation` + `Link` headers (or stderr deprecation warning on the CLI) so SDKs and proxies can surface the successor name automatically. New integrations should target the canonical names. ChangeRequest field names migrate at the caller's pace — both `query_source`/`query_name` and `query`/`name` accepted indefinitely. + +## Migration: single → multi + +```yaml +# Before (v0.5.0 single-mode invocation) +server: + graph: my-graph +graphs: + my-graph: + uri: /var/lib/omnigraph/my-graph +policy: + file: ./policy.yaml +``` + +```yaml +# After (v0.6.0 multi-mode — drop `server.graph` and the top-level `policy`) +server: + policy: + file: ./server-policy.yaml # NEW: governs GET /graphs +graphs: + my-graph: + uri: /var/lib/omnigraph/my-graph + policy: + file: ./policy.yaml # MOVED: was top-level +``` + +Same `omnigraph.yaml` file; restart the server. Clients targeting the old flat routes (`/snapshot`, `/read`, …) must update to `/graphs/my-graph/snapshot`, etc. + +To add a new graph after rollout: stop the server, append a new `graphs.` entry, restart. + +## Documentation + +- Public docs, CLI help, examples, server docs, and test helpers now consistently use "graph" for the OmniGraph data artifact. +- GitHub/source repository terminology remains spelled out as "repository" where needed. +- New: `docs/user/cli.md` documents `omnigraph graphs list`; `docs/user/server.md` documents the multi-graph mode and the cluster route convention; `docs/user/policy.md` documents the per-graph vs server-scoped action distinction. +- New: `docs/user/server.md` documents `POST /query` / `POST /mutate` and the three-channel deprecation signal on `/read` / `/change`. `docs/user/cli.md` documents the `-e/--query-string` flag with examples. `docs/user/cli-reference.md` shows the canonical CLI verbs (`query`, `mutate`, `lint`, `check`) with legacy spellings as visible aliases. +- New: `docs/dev/rfc-001-queries-envelope-mcp.md` is the cross-cutting design doc for the inline / stored query work that started landing in this release. It sequences the v0.6.x patch series (request/response envelope hardening) and the v0.7.0 stored-query + MCP work. + +## Test coverage + +- `GraphId` newtype validation, registry race tests, init failpoints (still reachable from `omnigraph init` CLI). +- Mode-inference four-rule matrix, parallel multi-graph startup, cluster routing. +- Cedar `Server` resource refactor, backwards-compat for graph-only policies, kind-alignment rejection (server actions in graph files / vice versa). +- `GET /graphs` enumeration, 405-in-single-mode, 403-in-Open-mode-without-server-policy, Cedar admin/viewer authorization. +- Cluster routes with inner path params (`/branches/{branch}`, `/commits/{commit_id}`) deserialize correctly under axum 0.8 nested routing. +- Policy-requires-tokens startup invariant enforced uniformly across single and multi mode. +- The bearer-auth-derived-actor-identity regression test (client-supplied identity headers are ignored; the server-resolved actor is the only identity Cedar sees) stays green across the entire refactor. + diff --git a/docs/releases/v0.6.1.md b/docs/releases/v0.6.1.md new file mode 100644 index 0000000..aafe1af --- /dev/null +++ b/docs/releases/v0.6.1.md @@ -0,0 +1,26 @@ +# Omnigraph v0.6.1 + +v0.6.1 focuses on operational polish after v0.6.0: stored-query registries, safer branch cleanup, more complete release artifacts, and a Lance blob-compaction workaround. + +## Highlights + +- **Stored-query registries.** `omnigraph.yaml` can declare curated `queries:` blocks per graph. Servers load and type-check them at startup, `omnigraph queries validate` checks them offline, `omnigraph queries list` shows exposed queries and typed params, `GET /queries` exposes a typed catalog, and `POST /queries/{name}` invokes a stored query without accepting ad hoc `.gq` source from the client. +- **Stored-query policy gate.** New Cedar action `invoke_query` gates the stored-query invocation surface. Stored mutations are double-gated: `invoke_query` to reach the stored query and `change` for the actual write. +- **Safer branch deletion.** `branch_delete` now treats the manifest as the authority, flips branch visibility atomically, and reclaims per-table/commit-graph forks as derived state. If best-effort reclaim is interrupted, `cleanup` reconciles orphaned forks; reusing a branch name before cleanup reports an actionable error. +- **Blob-safe optimize.** `omnigraph optimize` skips tables with `Blob` properties instead of failing the whole sweep on Lance's blob-v2 compaction decode bug. Skips are visible in human output, `--json` as `skipped`, `TableOptimizeStats.skipped`, and logs; non-blob tables still compact normally. +- **Deployment improvements.** The container entrypoint now composes `OMNIGRAPH_TARGET_URI` with `OMNIGRAPH_CONFIG`, so operators can keep the graph URI in env while loading policy/query config from a mounted file. The local RustFS bootstrap pins RustFS beta.3 and allows the current insecure local-dev default credentials. +- **Windows release support.** Tagged and edge releases now publish Windows x86_64 archives containing `omnigraph.exe` and `omnigraph-server.exe`, with a PowerShell installer and Windows install docs. +- **Release tooling.** Homebrew formula generation was tightened to produce audit-clean formulas. + +## Compatibility Notes + +- A graph selected by name (`--target` or `server.graph`) now uses `graphs..policy` and `graphs..queries`. Top-level `policy` / `queries` blocks are only for anonymous bare-URI single-graph mode; using them with a named graph now fails loudly with migration guidance. +- `mcp.expose` defaults to `true` for stored-query registry entries. Set `mcp: { expose: false }` for service-only queries that should not appear in the catalog. +- `invoke_query` is graph-scoped, not branch-scoped. Branch/snapshot access remains enforced by the inner `read` / `change` gate. +- Blob tables are not compacted until the upstream Lance fix lands, so fragment count and deleted-row space on blob tables are not reclaimed by `optimize`. Reads, writes, and query results are unaffected; no on-disk migration is required. +- `TableOptimizeStats` is now `#[non_exhaustive]` and gains a `skipped: Option` field (so does the new `SkipReason` enum). This is a source-level change only for downstream code that built this returned result struct by literal — rare, since it is produced by `optimize` and consumed by reading its fields; field access is unaffected, and `#[non_exhaustive]` keeps future additions non-breaking. + +## Docs And Cleanup + +- Public docs were updated for stored queries, policy, server routes, deployment, Windows installation, branch deletion, maintenance, and the `runs` docs rename to `writes`. +- README copy and release documentation were refreshed; older release notes had small typo/wording fixes. diff --git a/docs/user/audit.md b/docs/user/audit.md index 80ac137..e8abe5b 100644 --- a/docs/user/audit.md +++ b/docs/user/audit.md @@ -4,4 +4,4 @@ - `_as` variants of every write API let callers override the actor: `mutate_as`, `ingest_as`, `branch_merge_as`, `apply_schema_as`, etc. - Actor IDs are persisted on `GraphCommit.actor_id` with split storage in `_graph_commit_actors.lance` (the commit graph is split into `_graph_commits.lance` for the linkage and `_graph_commit_actors.lance` for the actor map). - HTTP server uses the bearer-token actor automatically; CLI uses the local user / explicit env (no implicit actor). -- Pre-v0.4.0 repos also stored actor IDs on `RunRecord.actor_id` in `_graph_runs.lance` / `_graph_run_actors.lance`. The Run state machine was removed in MR-771; those files are inert post-v0.4.0 and reclaimed by MR-770's production sweep. +- Pre-v0.4.0 graphs also stored actor IDs on `RunRecord.actor_id` in `_graph_runs.lance` / `_graph_run_actors.lance`. The Run state machine was removed in MR-771; those files are inert post-v0.4.0 and reclaimed by MR-770's production sweep. diff --git a/docs/user/branches-commits.md b/docs/user/branches-commits.md index de6c653..c1894f9 100644 --- a/docs/user/branches-commits.md +++ b/docs/user/branches-commits.md @@ -8,10 +8,10 @@ Lance supports branching at the dataset level: a branch is a named lineage of ve OmniGraph builds *graph branches* on top by branching every sub-table coherently: -- `branch_create(name)` / `branch_create_from(target, name)` — disallowed name `main`; fails if branch exists; ensures the schema-apply lock is idle. +- `branch_create(name)` / `branch_create_from(target, name)` — disallowed name `main`; fails if branch exists; ensures the schema-apply lock is idle. Atomic and authority-first like `branch_delete`: it flips the `__manifest` branch (authority), then creates the derived commit-graph branch, force-dropping any orphaned commit-graph ref left by an incomplete prior delete (the manifest branch is fresh, so a same-named commit-graph branch is provably a zombie). If commit-graph creation fails, the manifest branch is rolled back so the name never half-exists. - `branch_list()` — returns public branches, **filters internal** `__run__…` and `__schema_apply_lock__` prefixes. -- `branch_delete(name)` — refuses if there are descendants or active runs on the branch; cleans up owned per-branch fragments. -- **Lazy forking**: a branch only forks a sub-table when that sub-table is first mutated on it. Pure-read branches share fragments with their source. +- `branch_delete(name)` — refuses if there are descendants or active runs on the branch. The manifest is the single authority for branch existence: deletion flips the `__manifest` branch ref first (one atomic op), after which the branch is gone from every snapshot. The owned per-table forks and the commit-graph branch are derived state, reclaimed best-effort with `force_delete_branch` after the flip. A failure during that reclaim (transient object-store error) does not fail the call or block the authority flip; the leftover forks are unreachable orphans that the [`cleanup`](maintenance.md) reconciler converges. One consequence: if a delete's best-effort reclaim fails, reusing that branch name before the next `cleanup` surfaces a clear error pointing at `cleanup` (the stale fork would otherwise collide on first write). +- **Lazy forking**: a branch only forks a sub-table when that sub-table is first mutated on it. Pure-read branches share fragments with their source. A fork collision is classified by the manifest authority, not by Lance branch versions: if the live manifest already records the fork on the active branch, a concurrent first-write won and the caller gets a retryable "refresh and retry"; if the manifest does not, a physical branch there is an orphan and the caller is pointed at `cleanup`. - `sync_branch(branch)` — re-binds the in-memory handle to the latest head of the branch. ## L2 — Commit graph (`db/commit_graph.rs`) diff --git a/docs/user/cli-reference.md b/docs/user/cli-reference.md index 599ee13..8263919 100644 --- a/docs/user/cli-reference.md +++ b/docs/user/cli-reference.md @@ -8,22 +8,23 @@ A reference for the `omnigraph` binary's command surface and `omnigraph.yaml` sc | Command | Purpose | |---|---| -| `init` | `--schema ` → initialize a repo (also scaffolds `omnigraph.yaml` if missing) | +| `init` | `--schema ` → initialize a graph (also scaffolds `omnigraph.yaml` if missing) | | `load` | bulk load a branch (`--mode overwrite\|append\|merge`) | | `ingest` | branch-creating transactional load (`--from `) | -| `read` | run named query (params via `--params`, `--params-file`, or alias args) | -| `change` | run mutation query | +| `query` (alias: `read`) | run named read query; source via `--query `, `-e`/`--query-string `, or `--alias ` (exactly one). `read` is the deprecated previous name and prints a one-line warning to stderr | +| `mutate` (alias: `change`) | run mutation query; same `--query` / `-e` / `--alias` mutual-exclusion as `query`. `change` is the deprecated previous name and prints a one-line warning to stderr | | `snapshot` | print current snapshot (per-table version + row count) | | `export` | dump to JSONL on stdout (`--type T`, `--table K` filters) | | `branch create \| list \| delete \| merge` | branching ops | | `commit list \| show` | inspect commit graph | | `run list \| show \| publish \| abort` | transactional run ops | | `schema plan \| apply \| show (alias: get)` | migrations | -| `query lint \| check` | offline / repo-backed validation | -| `optimize` | non-destructive Lance compaction | +| `lint` (alias: `check`) | offline / graph-backed query validation. Replaces `query lint` / `query check`, which are kept as deprecated argv-level shims that print a one-line warning and rewrite to `omnigraph lint` | +| `queries validate \| list` | operate on the server-side stored-query registry (the `queries:` block). `validate` type-checks every stored query against the live schema offline (opens the selected graph; exits non-zero on any breakage), catching schema drift without restarting the server; `list` prints the selected registry's query names, MCP exposure, and typed params. For per-graph registries, pass `--target ` or set `cli.graph`; with no graph selection, `list` shows only top-level `queries:`. Distinct from `lint`, which validates a single `.gq` file | +| `optimize` | non-destructive Lance compaction (skips tables with `Blob` columns; `--json` reports a `skipped` field) | | `cleanup --keep N --older-than 7d --confirm` | destructive version GC | | `embed` | offline JSONL embedding pipeline | -| `policy validate \| test \| explain` | Cedar tooling | +| `policy validate \| test \| explain` | Cedar tooling. Selects `cli.graph`, else `server.graph`, else top-level `policy.file` | | `version` / `-v` | print `omnigraph 0.3.x` | ## `omnigraph.yaml` schema @@ -34,6 +35,13 @@ graphs: : uri: bearer_token_env: + queries: # per-graph stored-query registry (server-role; multi-graph mode) + : # key MUST equal the `query ` symbol inside the .gq + file: # relative to this config's directory + mcp: + expose: true # default true: listed in the MCP catalog (GET /queries); set false to hide (still HTTP-callable) + tool_name: # optional MCP tool-name override (defaults to ; + # must be unique across exposed queries) server: graph: bind: @@ -49,18 +57,23 @@ auth: env_file: ./.env.omni aliases: : - command: read|change + # accepted values: `read` / `query` (read alias), `change` / `mutate` + # (write alias). `query` and `mutate` are recommended; `read` and + # `change` remain accepted forever for back-compat. + command: read|change|query|mutate query: name: args: [, …] graph: branch: format: +queries: # top-level registry — applies only to a bare-URI (anonymous) graph; a graph served by name uses its `graphs..queries`. Mirrors top-level `policy`. + : { file: } # mcp.expose defaults to true policy: file: ./policy.yaml ``` -## Output formats (read command) +## Output formats (`query` command, alias: `read`) - `json` — pretty-printed object with metadata + rows - `jsonl` — one metadata line then one JSON object per row diff --git a/docs/user/cli.md b/docs/user/cli.md index ae8c152..b6f2c09 100644 --- a/docs/user/cli.md +++ b/docs/user/cli.md @@ -1,40 +1,65 @@ # CLI Guide -## Core Repo Flow +## Core Graph Flow ```bash -omnigraph init --schema ./schema.pg ./repo.omni -omnigraph load --data ./data.jsonl --mode overwrite ./repo.omni -omnigraph snapshot ./repo.omni --branch main --json -omnigraph read --uri ./repo.omni --query ./queries.gq --name get_person --params '{"name":"Alice"}' -omnigraph change --uri ./repo.omni --query ./queries.gq --name insert_person --params '{"name":"Mina","age":28}' +omnigraph init --schema ./schema.pg ./graph.omni +omnigraph load --data ./data.jsonl --mode overwrite ./graph.omni +omnigraph snapshot ./graph.omni --branch main --json +omnigraph query --uri ./graph.omni --query ./queries.gq --name get_person --params '{"name":"Alice"}' +omnigraph mutate --uri ./graph.omni --query ./queries.gq --name insert_person --params '{"name":"Mina","age":28}' ``` +`omnigraph query` is the canonical read command (pairs with `POST /query`); +`omnigraph mutate` is the canonical write command (pairs with `POST /mutate`). +The previous names `omnigraph read` and `omnigraph change` keep working as +visible aliases — invocations emit a one-line deprecation warning to stderr +and otherwise behave identically. See [Deprecated names](#deprecated-names) +for the migration table. + +For ad-hoc reads and mutations (REPLs, AI agents, one-off scripts), pass the +GQ source inline with `-e` / `--query-string` instead of a file path: + +```bash +omnigraph query --uri ./graph.omni \ + -e 'query find($name: String) { match { $p: Person { name: $name } } return { $p.name, $p.age } }' \ + --params '{"name":"Alice"}' + +omnigraph mutate --uri ./graph.omni \ + -e 'query add($name: String, $age: I32) { insert Person { name: $name, age: $age } }' \ + --params '{"name":"Inline","age":42}' +``` + +`-e` is mutually exclusive with `--query ` and `--alias `; exactly +one of the three must be provided. The inline source travels through the same +parser, lint, params binding, and commit machinery as a file-based query — +only the source loader changes. + ## Branching And Reviewable Data Flows ```bash -omnigraph branch create --uri ./repo.omni --from main feature-x -omnigraph branch list --uri ./repo.omni -omnigraph branch merge --uri ./repo.omni feature-x --into main +omnigraph branch create --uri ./graph.omni --from main feature-x +omnigraph branch list --uri ./graph.omni +omnigraph branch merge --uri ./graph.omni feature-x --into main -omnigraph ingest --data ./batch.jsonl --branch review/import-2026-04-09 ./repo.omni -omnigraph export ./repo.omni --branch main --type Person > people.jsonl -omnigraph commit list ./repo.omni --branch main --json -omnigraph commit show --uri ./repo.omni --json +omnigraph ingest --data ./batch.jsonl --branch review/import-2026-04-09 ./graph.omni +omnigraph export ./graph.omni --branch main --type Person > people.jsonl +omnigraph commit list ./graph.omni --branch main --json +omnigraph commit show --uri ./graph.omni --json ``` ## Remote Server Mode -Serve a repo: +Serve a graph: ```bash -omnigraph-server ./repo.omni --bind 127.0.0.1:8080 +omnigraph-server ./graph.omni --bind 127.0.0.1:8080 ``` Read through the HTTP API: ```bash -omnigraph read \ +omnigraph query \ --target http://127.0.0.1:8080 \ --query ./queries.gq \ --name get_person \ @@ -44,26 +69,47 @@ omnigraph read \ If the server requires auth, set `OMNIGRAPH_SERVER_BEARER_TOKEN` on the server and configure the matching `bearer_token_env` in `omnigraph.yaml`. +## Multi-graph servers (v0.6.0+) + +Against a multi-graph server (started with `--config omnigraph.yaml` referencing a non-empty `graphs:` map), use `omnigraph graphs list` to enumerate the registered graphs. The server must configure bearer tokens and `server.policy.file` with a rule that allows `graph_list`; `/graphs` is closed by default even when the server runs with `--unauthenticated`. + +```bash +OMNIGRAPH_BEARER_TOKEN=admin-token \ + omnigraph graphs list --uri http://server.example.com --json +``` + +For config-driven clients, set the remote graph's `bearer_token_env` to an environment variable containing a token whose actor is authorized by `server.policy.file`. + +`list` rejects local URI targets — it's for remote multi-graph servers only. + +Runtime add/remove is **not** in v0.6.0. To add a graph, stop the server, add a `graphs.` entry to `omnigraph.yaml`, then restart. To remove, stop the server, delete the entry, restart. + +Per-graph URLs: hit a graph's cluster route from any subcommand by pointing `--uri` at it: + +```bash +omnigraph read --uri http://server.example.com/graphs/beta --query ./q.gq ... +``` + ## Runs, Policy, And Diagnostics ```bash -omnigraph query lint --query ./queries.gq --schema ./schema.pg --json -omnigraph query check --query ./queries.gq ./repo.omni --json +omnigraph lint --query ./queries.gq --schema ./schema.pg --json +omnigraph check --query ./queries.gq ./graph.omni --json -omnigraph schema plan --schema ./next.pg ./repo.omni --json -omnigraph schema apply --schema ./next.pg ./repo.omni --json +omnigraph schema plan --schema ./next.pg ./graph.omni --json +omnigraph schema apply --schema ./next.pg ./graph.omni --json omnigraph policy validate --config ./omnigraph.yaml omnigraph policy test --config ./omnigraph.yaml omnigraph policy explain --config ./omnigraph.yaml --actor act-alice --action read --branch main -omnigraph commit list ./repo.omni --json -omnigraph commit show --uri ./repo.omni --json +omnigraph commit list ./graph.omni --json +omnigraph commit show --uri ./graph.omni --json ``` (The legacy `omnigraph run list/show/publish/abort` subcommands were removed in MR-771; mutations and loads publish atomically and the commit graph (`omnigraph commit list`) is the audit surface.) -`query lint` and `query check` are the same command surface. In v1, repo-backed -lint uses local or `s3://` repo URIs; HTTP targets are only supported when you +`query lint` and `query check` are the same command surface. In v1, graph-backed +lint uses local or `s3://` graph URIs; HTTP targets are only supported when you also pass `--schema`. ## Config @@ -98,3 +144,21 @@ The config file can also define: When policy is enabled, `schema apply` is authorized through the `schema_apply` action and is typically limited to admins on protected `main`. + +## Deprecated names + +The CLI was renamed to align with the HTTP server's canonical endpoint +names (`POST /query`, `POST /mutate`) and the `query` keyword in the GQ +language. The previous spellings keep working forever; invocations emit a +one-line warning to stderr and otherwise behave identically. + +| Old (deprecated) | New (canonical) | Migration | +|--------------------------|---------------------|----------------------------------------------------------| +| `omnigraph read` | `omnigraph query` | Same flags and behavior. `read` is a visible clap alias. | +| `omnigraph change` | `omnigraph mutate` | Same flags and behavior. `change` is a visible clap alias. | +| `omnigraph query lint` | `omnigraph lint` | Same flags. The argv-level shim rewrites `query lint` to `lint`. | +| `omnigraph query check` | `omnigraph check` | `check` is a visible alias of `omnigraph lint`. | + +The `command:` field in `aliases.` in `omnigraph.yaml` accepts both +`read` / `change` (legacy) and `query` / `mutate` (canonical); the two +spellings are interchangeable on the wire via serde aliases. diff --git a/docs/user/constants.md b/docs/user/constants.md index 527aaea..8f13555 100644 --- a/docs/user/constants.md +++ b/docs/user/constants.md @@ -11,6 +11,7 @@ | Internal manifest schema version | `INTERNAL_MANIFEST_SCHEMA_VERSION = 2` | `db/manifest/migrations.rs` | | Merge stage batch | `MERGE_STAGE_BATCH_ROWS = 8192` | `exec/merge.rs` | | Maintenance concurrency | `OMNIGRAPH_MAINTENANCE_CONCURRENCY=8` | `db/omnigraph/optimize.rs` | +| Lance blob compaction support | `LANCE_SUPPORTS_BLOB_COMPACTION = false` | `db/omnigraph/optimize.rs` | | Graph index cache size | `8` (LRU) | `runtime_cache.rs` | | Default body limit | `1 MB` | `omnigraph-server/lib.rs` | | Ingest body limit | `32 MB` | `omnigraph-server/lib.rs` | diff --git a/docs/user/deployment.md b/docs/user/deployment.md index e611245..9a4466c 100644 --- a/docs/user/deployment.md +++ b/docs/user/deployment.md @@ -8,8 +8,8 @@ internal deploy automation. Omnigraph supports two broad deployment shapes: -- local directory repos -- `s3://` repos on AWS S3 or S3-compatible object stores +- local directory graphs +- `s3://` graphs on AWS S3 or S3-compatible object stores The server binary and container image expose the same HTTP surface. @@ -20,18 +20,20 @@ Build or install: - `omnigraph` - `omnigraph-server` -Run against a local repo: +On Windows, the binaries are `omnigraph.exe` and `omnigraph-server.exe`. + +Run against a local graph: ```bash -omnigraph-server ./repo.omni --bind 0.0.0.0:8080 +omnigraph-server ./graph.omni --bind 0.0.0.0:8080 ``` -Run against an object-store-backed repo: +Run against an object-store-backed graph: ```bash OMNIGRAPH_SERVER_BEARER_TOKEN="change-me" \ AWS_REGION="us-east-1" \ -omnigraph-server s3://my-bucket/repos/example/releases/2026-04-10-v0.1.0 \ +omnigraph-server s3://my-bucket/graphs/example/releases/2026-04-10-v0.1.0 \ --bind 0.0.0.0:8080 ``` @@ -46,7 +48,7 @@ curl -fsSL https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/ The bootstrap: - starts a local RustFS-backed object store -- creates a bucket and S3-backed Omnigraph repo +- creates a bucket and S3-backed Omnigraph graph - loads the checked-in context fixture - starts `omnigraph-server` on `127.0.0.1:8080` @@ -60,8 +62,8 @@ Useful overrides: - `WORKDIR=/path/to/state` - `BUCKET=omnigraph-local` -- `PREFIX=repos/context` -- `RESET_REPO=1` to delete an existing partially initialized repo prefix before recreating it +- `PREFIX=graphs/context` +- `RESET_REPO=1` to delete an existing partially initialized graph prefix before recreating it - `BIND=127.0.0.1:8080` - `RUSTFS_CONTAINER_NAME=omnigraph-rustfs-demo` @@ -76,7 +78,7 @@ If `aws` is not installed, the script attempts a user-local AWS CLI install via running. If a previous bootstrap left objects behind under the selected `PREFIX` but did -not finish initializing the repo, rerun with `RESET_REPO=1` or choose a new +not finish initializing the graph, rerun with `RESET_REPO=1` or choose a new `PREFIX`. ## Container Deployment @@ -87,29 +89,59 @@ Build the image: docker build -t omnigraph-server:local . ``` -Run against a local repo: +Run against a local graph: ```bash docker run --rm -p 8080:8080 \ - -v "$PWD/repo.omni:/data/repo.omni" \ + -v "$PWD/graph.omni:/data/graph.omni" \ omnigraph-server:local \ - /data/repo.omni --bind 0.0.0.0:8080 + /data/graph.omni --bind 0.0.0.0:8080 ``` -Run against an S3-backed repo: +Run against an S3-backed graph: ```bash docker run --rm -p 8080:8080 \ -e OMNIGRAPH_SERVER_BEARER_TOKEN="change-me" \ -e AWS_REGION="us-east-1" \ omnigraph-server:local \ - s3://my-bucket/repos/example/releases/2026-04-10-v0.1.0 \ + s3://my-bucket/graphs/example/releases/2026-04-10-v0.1.0 \ --bind 0.0.0.0:8080 ``` +### Container entrypoint env vars + +When no positional args are given, the image entrypoint +(`docker/entrypoint.sh`) builds the server command from env vars: + +| Var | Effect | +|---|---| +| `OMNIGRAPH_TARGET_URI` | Graph URI, passed as the positional argument. | +| `OMNIGRAPH_CONFIG` | Path to an `omnigraph.yaml`, passed as `--config`. Used to supply a `policy.file` (Cedar authorization). The config file and any relative `policy.file` must be mounted into the container. | +| `OMNIGRAPH_TARGET` | Graph name to select from the config's `graphs:` block (with `OMNIGRAPH_CONFIG`, when no `OMNIGRAPH_TARGET_URI`). | +| `OMNIGRAPH_BIND` | Listen address (default `0.0.0.0:8080`). | + +`OMNIGRAPH_TARGET_URI` and `OMNIGRAPH_CONFIG` **compose**: set both to keep the +graph URI in the env var while loading policy from the config file (the +positional URI wins over any `graphs:` entry). To enable Cedar policy on a +container otherwise driven by `OMNIGRAPH_TARGET_URI`, mount the config dir and +add `OMNIGRAPH_CONFIG`: + +```bash +docker run --rm -p 8080:8080 \ + -e OMNIGRAPH_SERVER_BEARER_TOKEN="change-me" \ + -e OMNIGRAPH_TARGET_URI="s3://my-bucket/graphs/example/releases/2026-04-10-v0.1.0" \ + -e OMNIGRAPH_CONFIG="/etc/omnigraph/omnigraph.yaml" \ + -v "$PWD/config:/etc/omnigraph:ro" \ + omnigraph-server:local +# /etc/omnigraph/omnigraph.yaml contains `policy: { file: ./policy.yaml }`; +# policy.yaml (+ optional policy.tests.yaml) sit beside it in the mount. +``` + ## Auth -The server can run unauthenticated for local development, but any shared or +The server can run unauthenticated for local development only when explicitly +started with `--unauthenticated` or `OMNIGRAPH_UNAUTHENTICATED=1`. Any shared or internet-facing deployment should set a bearer token source. ### Token sources @@ -139,9 +171,11 @@ The server binary ships in two flavors: | **Default** (on-prem / local dev) | `cargo build --release` | Core server, no AWS SDK | | **AWS** | `cargo build --release --features aws` | Adds AWS Secrets Manager backend for bearer tokens | -Release artifacts are published with matching suffixes — -`omnigraph-server--.tar.gz` for the default build and -`omnigraph-server---aws.tar.gz` for the AWS-enabled build. +Tagged release archives contain the default `omnigraph` and +`omnigraph-server` binaries on macOS / Linux, and `omnigraph.exe` plus +`omnigraph-server.exe` on Windows. AWS-enabled server binaries are built from +source with `cargo build --release --features aws -p omnigraph-server` when +needed. The AWS build adds ~150 transitive deps and ~30-60s of first-build compile time. Default builds don't pay that cost. @@ -154,7 +188,7 @@ Manager secret whose `SecretString` is a JSON object of `{"actor_id": "token", ...}`: ```bash -omnigraph-server-aws s3://my-bucket/repos/example ... +omnigraph-server-aws s3://my-bucket/graphs/example ... # Environment: # OMNIGRAPH_SERVER_BEARER_TOKENS_AWS_SECRET=arn:aws:secretsmanager:us-east-1:123456789012:secret:omnigraph-tokens-AbCdEf ``` diff --git a/docs/user/embeddings.md b/docs/user/embeddings.md index 596a6a0..382e683 100644 --- a/docs/user/embeddings.md +++ b/docs/user/embeddings.md @@ -22,7 +22,7 @@ Mark a Vector property with `@embed("source_text_property")`. At ingest, the eng ## CLI `omnigraph embed` (offline file pipeline) -Operates on **JSONL files** (not on a repo). Three modes (mutually exclusive): +Operates on **JSONL files** (not on a graph). Three modes (mutually exclusive): - (default) `fill_missing` — only embed rows whose target field is empty - `--reembed-all` — overwrite all diff --git a/docs/user/errors.md b/docs/user/errors.md index fd047eb..8373b0d 100644 --- a/docs/user/errors.md +++ b/docs/user/errors.md @@ -9,7 +9,7 @@ - `Manifest(ManifestError { kind: BadRequest|NotFound|Conflict|Internal, details: Option, … })` - `ManifestConflictDetails::ExpectedVersionMismatch { table_key, expected, actual }` — caller's `expected_table_versions` did not match the manifest's current latest non-tombstoned version (set by `OmniError::manifest_expected_version_mismatch`). - `ManifestConflictDetails::RowLevelCasContention` — Lance row-level CAS rejected the publish because a concurrent writer landed the same `object_id`. Retried internally by the publisher; only surfaces if the retry budget exhausts. - - **D₂ parse-time rejection** (MR-794): a single mutation query that mixes inserts/updates with deletes errors out *before any I/O* with kind `BadRequest`. Message: `mutation '' on the same query mixes inserts/updates and deletes; split into separate mutations: (1) inserts and updates, then (2) deletes`. See [docs/user/query-language.md](query-language.md) for the rule and [docs/dev/runs.md](../dev/runs.md) for the underlying staged-write rationale. + - **D₂ parse-time rejection** (MR-794): a single mutation query that mixes inserts/updates with deletes errors out *before any I/O* with kind `BadRequest`. Message: `mutation '' on the same query mixes inserts/updates and deletes; split into separate mutations: (1) inserts and updates, then (2) deletes`. See [docs/user/query-language.md](query-language.md) for the rule and [docs/dev/writes.md](../dev/writes.md) for the underlying staged-write rationale. - `MergeConflicts(Vec)` Compiler-side `NanoError` covers parse / catalog / type / storage / plan / execution / arrow / lance / IO / manifest / unique-constraint, each with structured spans (`SourceSpan { start, end }`) for ariadne-style diagnostics. diff --git a/docs/user/index.md b/docs/user/index.md index 45d8f01..1b93efa 100644 --- a/docs/user/index.md +++ b/docs/user/index.md @@ -18,11 +18,11 @@ of MRs, internal recovery mechanics, or contributor-only invariants. | Write queries and mutations | [query-language.md](query-language.md) | | Use embeddings | [embeddings.md](embeddings.md) | -## Operate A Repo +## Operate A Graph | Goal | Read | |---|---| -| Understand repo layout and URI support | [storage.md](storage.md) | +| Understand graph layout and URI support | [storage.md](storage.md) | | Work with branches, commits, and snapshots | [branches-commits.md](branches-commits.md) | | Coordinate multi-query workflows | [transactions.md](transactions.md) | | Read diffs and change feeds | [changes.md](changes.md) | diff --git a/docs/user/install.md b/docs/user/install.md index 725961e..4a11372 100644 --- a/docs/user/install.md +++ b/docs/user/install.md @@ -2,16 +2,29 @@ ## Quick Install +macOS / Linux: + ```bash curl -fsSL https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/install.sh | bash ``` +Windows PowerShell: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -Command "iwr -UseBasicParsing https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/install.ps1 | iex" +``` + By default the installer places: - `omnigraph` - `omnigraph-server` -in `~/.local/bin`. +in `~/.local/bin` on macOS / Linux, or: + +- `omnigraph.exe` +- `omnigraph-server.exe` + +in `%USERPROFILE%\.local\bin` on Windows. The default installer is binary-only. It downloads a published release asset, verifies the SHA256 checksum, and unpacks it. It does not build from source. @@ -39,6 +52,13 @@ Rolling edge binaries from `main`: curl -fsSL https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/install.sh | RELEASE_CHANNEL=edge bash ``` +Windows rolling edge binaries: + +```powershell +iwr -UseBasicParsing https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/install.ps1 -OutFile install.ps1 +powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -ReleaseChannel edge +``` + Install from source: ```bash @@ -53,12 +73,24 @@ Install to a different directory: curl -fsSL https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/install.sh | INSTALL_DIR="$HOME/bin" bash ``` +Windows: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -InstallDir "$env:USERPROFILE\bin" +``` + Install a specific tag: ```bash curl -fsSL https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/install.sh | VERSION=v0.1.0 bash ``` +Windows: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -Version v0.1.0 +``` + Build from a specific git ref: ```bash @@ -67,28 +99,53 @@ curl -fsSL https://raw.githubusercontent.com/ModernRelay/omnigraph/main/scripts/ ## Manual Source Build +macOS / Linux: + ```bash cargo build --release --locked -p omnigraph-cli -p omnigraph-server install -m 0755 target/release/omnigraph ~/.local/bin/omnigraph install -m 0755 target/release/omnigraph-server ~/.local/bin/omnigraph-server ``` +Windows: + +```powershell +cargo build --release --locked -p omnigraph-cli -p omnigraph-server +New-Item -ItemType Directory -Force "$env:USERPROFILE\.local\bin" | Out-Null +Copy-Item target\release\omnigraph.exe "$env:USERPROFILE\.local\bin\omnigraph.exe" +Copy-Item target\release\omnigraph-server.exe "$env:USERPROFILE\.local\bin\omnigraph-server.exe" +``` + ## Release Assets Tagged releases are expected to publish: - `omnigraph-linux-x86_64.tar.gz` -- `omnigraph-macos-x86_64.tar.gz` - `omnigraph-macos-arm64.tar.gz` +- `omnigraph-windows-x86_64.zip` -Each archive contains both binaries: +The macOS / Linux archives contain both binaries: - `omnigraph` - `omnigraph-server` +The Windows archive contains: + +- `omnigraph.exe` +- `omnigraph-server.exe` + ## Verify The Install +macOS / Linux: + ```bash omnigraph version omnigraph-server --help ``` + +Windows: + +```powershell +omnigraph.exe version +omnigraph-server.exe --help +``` diff --git a/docs/user/maintenance.md b/docs/user/maintenance.md index 08ae8da..3628fa0 100644 --- a/docs/user/maintenance.md +++ b/docs/user/maintenance.md @@ -7,16 +7,23 @@ - Lance `compact_files()` on every node + edge table on `main`. - Rewrites small fragments into fewer large ones; old fragments remain reachable via older manifests. - Bounded by `OMNIGRAPH_MAINTENANCE_CONCURRENCY` (default 8). -- Returns `[TableOptimizeStats { table_key, fragments_removed, fragments_added, committed }]`. +- Returns `[TableOptimizeStats { table_key, fragments_removed, fragments_added, committed, skipped }]`. +- **Blob tables are skipped.** A table that declares any `Blob` property is not compacted: it is reported with `skipped: Some(BlobColumnsUnsupportedByLance)` (and logged via `tracing::warn`) instead of compacted, and the rest of the sweep proceeds normally. The current Lance `compact_files` mis-decodes blob-v2 columns under its forced `BlobHandling::AllBinary` read; **reads and writes are unaffected** — only compaction is. This is gated by `LANCE_SUPPORTS_BLOB_COMPACTION` (`db/omnigraph/optimize.rs`) and removed when the upstream Lance fix lands (see [docs/dev/lance.md](../dev/lance.md)). Consequence: fragment count and deleted-row space on blob tables are not reclaimed until then; query results are never affected. ## `cleanup_all_tables(db, options)` — destructive - Lance `cleanup_old_versions()` per table. - Removes manifests (and their unique fragments) older than the retention policy. - `CleanupPolicyOptions { keep_versions: Option, older_than: Option }` — at least one is required. -- Returns `[TableCleanupStats { table_key, bytes_removed, old_versions_removed }]`. +- Returns `[TableCleanupStats { table_key, bytes_removed, old_versions_removed, error }]`. +- **Fault-isolated per table.** A single table's transient failure (version GC or + orphan reclaim) is recorded on that table's stats row (`error: Some(..)`, logged + via `tracing`) and never aborts the healthy tables — cleanup is the convergence + backstop, so it does as much as it can and converges on re-run. The CLI reports + any failed tables; rerun `cleanup` to retry them. - CLI guards with `--confirm`; without it, prints a preview line. - **Recovery floor:** `--keep < 3` may garbage-collect Lance versions that the open-time recovery sweep needs as a rollback target (the sweep restores to the branch's manifest-pinned table version, which is HEAD-1 in the typical Phase B → Phase C drift case). Default `--keep 10` is safe. +- **Orphaned-branch reconciliation:** before the version GC, cleanup runs `reconcile_orphaned_branches`, which `force_delete_branch`es any per-table or commit-graph Lance branch absent from the manifest branch list. These orphans arise when a `branch_delete` flips the manifest authority but a downstream best-effort reclaim does not complete (see [branches-commits.md](branches-commits.md)). The reconciler is authority-derived and idempotent (it no-ops once nothing is orphaned), runs regardless of the `keep_versions` / `older_than` values (those gate version GC only), and never reclaims `main` or system-branch forks. Reclaimed forks are logged via `tracing::info`. ## Tombstones diff --git a/docs/user/policy.md b/docs/user/policy.md index b121213..ec0d214 100644 --- a/docs/user/policy.md +++ b/docs/user/policy.md @@ -4,6 +4,8 @@ OmniGraph integrates AWS Cedar (`cedar-policy = 4.9`) for ABAC. ## Policy actions +Per-graph actions (bind to `Omnigraph::Graph::""`): + 1. `read` — query / snapshot / list branches & commits 2. `export` — NDJSON export 3. `change` — mutations @@ -12,6 +14,13 @@ OmniGraph integrates AWS Cedar (`cedar-policy = 4.9`) for ABAC. 6. `branch_delete` 7. `branch_merge` 8. `admin` — reserved for policy-management surfaces (hot reload, audit log, approvals). No call site today; see MR-724 for the reservation rationale. +9. `invoke_query` — gates invoking a server-side stored query (the `queries:` registry). Graph-scoped (like `admin`) — per-branch access is enforced by the inner `read` / `change` gate, so a rule that sets `branch_scope` on `invoke_query` is rejected. Coarse in this release: an `invoke_query` allow rule permits any stored query on the graph; a future, additive refinement adds an optional per-query-name scope without changing rules written against the coarse action. Enforced at `POST /queries/{name}` (see [server](server.md)). A stored *mutation* is double-gated: `invoke_query` to reach the tool, plus `change` for the write itself (the engine `_as` writers still enforce per the query body). + +Server-scoped action (v0.6.0+; binds to `Omnigraph::Server::"root"`): + +10. `graph_list` — `GET /graphs` registry enumeration (multi-graph mode) + +Server-scoped actions cannot use `branch_scope` or `target_branch_scope` — they operate on the registry, not on a graph's branches. A rule cannot mix server-scoped and per-graph actions; split into separate rules. (Runtime `graph_create` / `graph_delete` are reserved but not shipped in v0.6.0; operators add/remove graphs by editing `omnigraph.yaml` and restarting.) ## Scope kinds @@ -19,6 +28,50 @@ OmniGraph integrates AWS Cedar (`cedar-policy = 4.9`) for ABAC. - `target_branch_scope` — applied to destination (`schema_apply`, branch ops, run ops) - `protected_branches` — named list with special rules; rule scopes are `any | protected | unprotected` +## Per-graph vs. server-level policy (multi-graph mode) + +In multi mode (`omnigraph.yaml` with a non-empty `graphs:` map), policy files attach at two levels: + +```yaml +server: + policy: + file: ./server-policy.yaml # server-level: graph_list + +graphs: + alpha: + uri: s3://tenant-bucket/alpha + policy: + file: ./policies/alpha.yaml # per-graph: read, change, branch_*, schema_apply + beta: + uri: s3://tenant-bucket/beta + # no per-graph policy → no engine-layer Cedar enforcement on beta +``` + +**Config follows graph identity, not server mode.** A graph served by **name** +(`--target ` or `server.graph`) uses its own `graphs..policy.file`, +exactly as in multi-graph mode. Top-level `policy.file` applies only to an +**anonymous** graph — one served by a bare `` with no `graphs:` entry. +Serving a **named** graph (single- or multi-graph mode) while top-level +`policy.file` (or `queries:`) is populated **refuses boot**, naming the block, +since the top-level value would otherwise be silently shadowed by the per-graph +block. Move per-graph rules to `graphs..policy.file` and `graph_list` +rules to `server.policy.file`. + +Each graph's HTTP request flows through its own per-graph policy. The management endpoint (`GET /graphs`) flows through the server-level policy. When `server.policy.file` is unset, `GET /graphs` is denied in every runtime state, including `--unauthenticated`; with bearer tokens configured, it returns 403 after admission control because `graph_list` is not a `read`-equivalent action. The operator must explicitly authorize via `server-policy.yaml` to expose `/graphs`. + +Example server-level policy: + +```yaml +version: 1 +groups: + admins: [act-andrew] +rules: + - id: admins-can-list-graphs + allow: + actors: { group: admins } + actions: [graph_list] +``` + ## Configuration `omnigraph.yaml`: @@ -32,7 +85,7 @@ cli: actor: act-andrew # default actor for CLI direct-engine writes ``` -Each rule must use exactly one of `branch_scope` or `target_branch_scope`. +Each per-graph rule may use at most one of `branch_scope` or `target_branch_scope`. Server-scoped rules (`graph_list`) take neither — they have no branch context. `cli.actor` is the default actor identity for CLI direct-engine writes when `policy.file` is configured. Override per-invocation with `--as @@ -45,6 +98,10 @@ bearer token. ## CLI +Policy tooling resolves its graph like server single-mode policy: `cli.graph` +wins, otherwise `server.graph` is used, otherwise the top-level `policy.file` +is validated/tested/explained as the anonymous policy. + - `omnigraph policy validate` — parse + count actors, exit 1 on parse error. - `omnigraph policy test` — run cases in `policy.tests.yaml`, exit 1 on any expectation mismatch. - `omnigraph policy explain --actor … --action … [--branch …] [--target-branch …]` — show decision and matched rule. @@ -74,12 +131,13 @@ reaches `authorize_request()` without a matching policy permit. |---|---|---|---| | **Open** | no | no | Every request is permitted. Refuses to start unless `--unauthenticated` or `OMNIGRAPH_UNAUTHENTICATED=1` is set — the operator must explicitly opt in. | | **DefaultDeny** | yes | no | Every authenticated request for an action other than `read` is rejected with HTTP 403. Closes the "tokens but forgot the policy file" trap — an operator who sets up auth and forgot to point at a policy file used to ship the illusion of protection. | -| **PolicyEnabled** | any | yes | Every request is evaluated by Cedar against the configured policy. | +| **PolicyEnabled** | yes | yes | Authenticated requests that reach a configured policy engine are evaluated by Cedar. Server-scoped actions still require `server.policy.file`. | The classifier is `classify_server_runtime_state` in `crates/omnigraph-server/src/lib.rs`; it returns `Err` for the "no -tokens, no policy, no flag" cell so the server refuses to start instead -of silently shipping an open instance. Tests pin every cell of the +tokens, no policy, no flag" cell and for "policy file, no tokens" so the +server refuses to start instead of silently shipping an open instance or +a policy-protected server that can only 401. Tests pin every cell of the matrix and the State-2 deny path. Server-side, `authorize_request()` still runs at the HTTP boundary — diff --git a/docs/user/query-language.md b/docs/user/query-language.md index 94528af..6c7516f 100644 --- a/docs/user/query-language.md +++ b/docs/user/query-language.md @@ -70,7 +70,7 @@ A single mutation query must be **either insert/update-only or delete-only**. Mi > `mutation '' on the same query mixes inserts/updates and deletes; split into separate mutations: (1) inserts and updates, then (2) deletes. This restriction lifts when Lance exposes a two-phase delete API (tracked: MR-793 / Lance-upstream).` -Reason: under the staged-write rewire (MR-794), inserts and updates accumulate in memory and commit at end-of-query, while deletes still inline-commit (Lance 4.0.0 has no public two-phase delete). Mixing creates ordering hazards (same-row insert→delete becomes a no-op because the staged insert isn't visible to delete; cascading deletes of just-inserted edges break referential integrity by silent design). Until Lance exposes `DeleteJob::execute_uncommitted`, the parse-time rejection keeps both paths atomic and correct. See [docs/dev/runs.md](../dev/runs.md) and [docs/dev/invariants.md](../dev/invariants.md). +Reason: under the staged-write rewire (MR-794), inserts and updates accumulate in memory and commit at end-of-query, while deletes still inline-commit (Lance 4.0.0 has no public two-phase delete). Mixing creates ordering hazards (same-row insert→delete becomes a no-op because the staged insert isn't visible to delete; cascading deletes of just-inserted edges break referential integrity by silent design). Until Lance exposes `DeleteJob::execute_uncommitted`, the parse-time rejection keeps both paths atomic and correct. See [docs/dev/writes.md](../dev/writes.md) and [docs/dev/invariants.md](../dev/invariants.md). ## IR (Intermediate Representation) diff --git a/docs/user/server.md b/docs/user/server.md index 6904e99..67b5afe 100644 --- a/docs/user/server.md +++ b/docs/user/server.md @@ -1,26 +1,137 @@ # HTTP Server (`omnigraph-server`) -Axum 0.8 + tokio + utoipa-generated OpenAPI. Single repo per process; deploy multiple processes for multi-tenant. +Axum 0.8 + tokio + utoipa-generated OpenAPI. **Two modes** (v0.6.0+): single-graph (legacy) and multi-graph (MR-668). Mode is inferred from CLI args + config shape. + +## Modes + +### Single-graph mode (legacy) + +`omnigraph-server ` or `omnigraph-server --target --config omnigraph.yaml`. Routes are flat — `/snapshot`, `/read`, `/branches`, etc. + +**Config follows graph identity.** A bare `` is an *anonymous* graph and uses the **top-level** `policy.file` / `queries:`. A graph chosen by **name** (`--target` / `server.graph`) uses its own `graphs..{policy.file, queries}` — the same block multi-graph mode uses. ⚠️ *Changed from v0.6.0, which always used top-level config in single mode: a named-graph config that puts `policy`/`queries` at top-level now **refuses boot** and points you at `graphs..…` (move the block there). Bare-`` single mode is unchanged.* + +### Multi-graph mode (v0.6.0+) + +`omnigraph-server --config omnigraph.yaml` with a non-empty `graphs:` map and **no** single-mode selector (no `server.graph`, no ``, no `--target`). The server opens every configured graph in parallel at startup (bounded concurrency = 4, fail-fast on the first open error). Routes are nested under `/graphs/{graph_id}/...`. Bare flat paths return 404 in multi mode. + +Mode inference (four-rule matrix): + +1. CLI positional `` → single +2. CLI `--target ` → single +3. `server.graph` in config → single +4. `--config` + non-empty `graphs:` + no single-mode selector → **multi** +5. otherwise → error with migration hint + +### Stored-query validation at startup + +If a graph declares a `queries:` registry (see [cli-reference](cli-reference.md)), the server **loads and type-checks every stored query against that graph's live schema at startup** and **refuses to boot** if any query references a type or property the schema lacks — the same fail-loud posture as a malformed policy file, so schema drift surfaces at the deploy boundary rather than at invocation. Two MCP-exposed queries claiming the same tool name is likewise a boot error. Non-blocking advisories (e.g. an MCP-exposed query with a vector parameter an agent cannot supply) are logged. Validate offline before deploying with `omnigraph queries validate`. Discover the exposed queries as a typed tool catalog with `GET /queries`, and invoke one over HTTP with `POST /queries/{name}` (both below). ## Endpoint inventory +Per-graph endpoints — same body shape across modes; URLs differ: + +| Method | Single-mode path | Multi-mode path | Auth | Action | Handler | +|---|---|---|---|---|---| +| GET | `/healthz` | `/healthz` | none | — | `server_health` | +| GET | `/openapi.json` | `/openapi.json` | none | — | `server_openapi` (strips security if auth disabled; in multi mode emits cluster paths with `cluster_` operation-id prefix) | +| GET | `/snapshot?branch=` | `/graphs/{id}/snapshot?branch=` | bearer + `read` | snapshot of branch | `server_snapshot` | +| POST | `/query` | `/graphs/{id}/query` | bearer + `read` | inline read query (canonical; clean field names `query`/`name`; mutations → 400) | `server_query` | +| POST | `/read` | `/graphs/{id}/read` | bearer + `read` | **deprecated** alias of `/query` (legacy field names `query_source`/`query_name`, byte-stable response; carries `Deprecation: true` + `Link: ; rel="successor-version"`) | `server_read` | +| POST | `/export` | `/graphs/{id}/export` | bearer + `export` | NDJSON stream | `server_export` | +| POST | `/mutate` | `/graphs/{id}/mutate` | bearer + `change` | mutation (canonical; `query`/`name`; accepts legacy `query_source`/`query_name` as serde aliases) | `server_mutate` | +| POST | `/change` | `/graphs/{id}/change` | bearer + `change` | **deprecated** alias of `/mutate` (carries `Deprecation: true` + `Link: ; rel="successor-version"`) | `server_change` | +| GET | `/queries` | `/graphs/{id}/queries` | bearer + `read` | list the `mcp.expose` stored queries as a typed tool catalog | `server_list_queries` | +| POST | `/queries/{name}` | `/graphs/{id}/queries/{name}` | bearer + `invoke_query` (+ `change` for a stored mutation) | invoke a named query from the `queries:` registry; deny == 404 | `server_invoke_query` | +| GET | `/schema` | `/graphs/{id}/schema` | bearer + `read` | get current `.pg` source | `server_schema_get` | +| POST | `/schema/apply` | `/graphs/{id}/schema/apply` | bearer + `schema_apply` (target=`main`) | migrate | `server_schema_apply` | +| POST | `/ingest` | `/graphs/{id}/ingest` | bearer + `branch_create` (if new) + `change` | bulk load | `server_ingest` (32 MB body limit) | +| GET | `/branches` | `/graphs/{id}/branches` | bearer + `read` | list branches | `server_branch_list` | +| POST | `/branches` | `/graphs/{id}/branches` | bearer + `branch_create` | create | `server_branch_create` | +| DELETE | `/branches/{branch}` | `/graphs/{id}/branches/{branch}` | bearer + `branch_delete` | delete | `server_branch_delete` | +| POST | `/branches/merge` | `/graphs/{id}/branches/merge` | bearer + `branch_merge` | merge `source → target` | `server_branch_merge` | +| GET | `/commits?branch=` | `/graphs/{id}/commits?branch=` | bearer + `read` | list | `server_commit_list` | +| GET | `/commits/{commit_id}` | `/graphs/{id}/commits/{commit_id}` | bearer + `read` | show | `server_commit_show` | + +Server-level management endpoints (v0.6.0+): + | Method | Path | Auth | Action | Handler | |---|---|---|---|---| -| GET | `/healthz` | none | — | `server_health` | -| GET | `/openapi.json` | none | — | `server_openapi` (strips security if auth disabled) | -| GET | `/snapshot?branch=` | bearer + `read` | snapshot of branch | `server_snapshot` | -| POST | `/read` | bearer + `read` | run named query | `server_read` | -| POST | `/export` | bearer + `export` | NDJSON stream | `server_export` | -| POST | `/change` | bearer + `change` | mutation | `server_change` | -| GET | `/schema` | bearer + `read` | get current `.pg` source | `server_schema_get` | -| POST | `/schema/apply` | bearer + `schema_apply` (target=`main`) | migrate | `server_schema_apply` | -| POST | `/ingest` | bearer + `branch_create` (if new) + `change` | bulk load | `server_ingest` (32 MB body limit) | -| GET | `/branches` | bearer + `read` | list branches | `server_branch_list` | -| POST | `/branches` | bearer + `branch_create` | create | `server_branch_create` | -| DELETE | `/branches/{branch}` | bearer + `branch_delete` | delete | `server_branch_delete` | -| POST | `/branches/merge` | bearer + `branch_merge` | merge `source → target` | `server_branch_merge` | -| GET | `/commits?branch=` | bearer + `read` | list | `server_commit_list` | -| GET | `/commits/{commit_id}` | bearer + `read` | show | `server_commit_show` | +| GET | `/graphs` | bearer + `graph_list` on `Server::"root"` | list registered graphs | `server_graphs_list` (405 in single mode) | + +### Stored-query catalog (`GET /queries`) + +List the graph's **`mcp.expose`** stored queries as a typed tool catalog — enough for a client (e.g. an MCP server) to register each as a tool without fetching `.gq` source. Each entry: `{ name, tool_name, description, instruction, mutation, params }`, where each param is `{ name, kind, item_kind?, vector_dim?, nullable }`. `kind` is one of `string | bool | int | bigint | float | date | datetime | blob | vector | list` (decomposed so a consumer maps it with a closed `switch`, never re-parsing GQ type spelling). `bigint` (I64/U64), `date`, `datetime`, and `blob` are carried as JSON **strings** — a 64-bit integer loses precision as a JSON number, dates are ISO strings, and a blob is a URI string. + +- **Read-gated** (works in default-deny mode). The catalog is **graph-wide** (branch-independent; `read` is authorized against `main`). +- **`mcp.expose` defaults to `true`** — declaring a query in `queries:` lists it; set `mcp: { expose: false }` to keep it HTTP/service-callable but hidden from the catalog. +- **Not Cedar-filtered per query (yet).** A caller with `read` but not `invoke_query` can *list* a query they can't *invoke* (which would 404). Closing that gap is future per-query authorization; for now the catalog is a discovery surface and `invoke_query` remains the invocation gate. + +### Stored-query invocation (`POST /queries/{name}`) + +Invoke a curated, server-side stored query by **name** — the source comes from the graph's `queries:` registry, so the client never sends `.gq`. The request body itself is optional; omit it for no-param queries, or send `{ "params": { … }, "branch": "main", "snapshot": null }`, where every field is optional and `params` keys match the query's declared parameters. The response is the **read envelope** (`ReadOutput`) for a stored read or the **mutation envelope** (`ChangeOutput`) for a stored mutation — serialized untagged, so the wire shape is identical to `/query` / `/mutate`. + +- **Gate:** `invoke_query` (per-graph, graph-scoped) at the boundary. A stored *mutation* is **double-gated** — it also passes the engine's `change` gate, so an actor with `invoke_query` but not `change` gets `403`. +- **Deny == unknown, for callers without `invoke_query`:** for a caller lacking the grant, an `invoke_query` denial and an unknown query name return the **same `404`** (identical body), so the catalog can't be probed. A caller that *holds* `invoke_query` may still get the inner gate's `403` for an existing query it can't `read`/`change` (the double-gate, above) — so existence is visible to grant-holders by design. +- **Requires an explicit policy grant when auth is on.** In default-deny mode (bearer tokens but no `policy.file`), only `read` is permitted, so *every* `/queries/{name}` call returns `404` until an `invoke_query` rule is configured. +- A stored mutation cannot target a `snapshot` (`400`); a parameter type error is a structured `400` naming the parameter. + +## Adding and removing graphs (multi mode) + +Runtime add/remove via API is **not** exposed in v0.6.0 — neither +`POST /graphs` nor `DELETE /graphs/{id}` is implemented. Operators add +or remove graphs by stopping the server, editing the `graphs:` map in +`omnigraph.yaml`, then restarting. The server treats `omnigraph.yaml` +as operator-owned configuration and never writes it. + +A future release may introduce a managed registry (Lance-backed, +catalog-style: reserve → init → publish with recovery sidecars) and +re-expose runtime mutation on top of it. + +## Inline read queries (`POST /query`) + +`POST /query` is the read-only, agent-friendly twin of `POST /read`. The +request body uses clean field names that match the CLI `-e` flag and the GQ +`query` keyword: + +```json +{ + "query": "query find($n: String) { match { $p: Person { name: $n } } return { $p.name } }", + "name": "find", + "params": { "n": "Alice" }, + "branch": "main", + "snapshot": null +} +``` + +Response shape is identical to `/read` (`ReadOutput`). If the inline source +contains mutations (`insert` / `update` / `delete`), the request is rejected +with HTTP 400 and an error pointing the caller at `POST /mutate` — the +read-only contract is enforced at the URL. + +`POST /mutate` is the canonical mutation endpoint. It accepts the same clean +field names (`query`, `name`); the legacy field names `query_source` and +`query_name` continue to deserialize as serde aliases so existing clients keep +working without changes. + +## Deprecated names (`/read`, `/change`) + +`POST /read` and `POST /change` are kept for back-compat indefinitely — they +are byte-stable on the request side and otherwise behave identically to +`/query` / `/mutate`. They are flagged as deprecated through three independent +channels: + +- **OpenAPI**: the operations carry `deprecated: true` in `openapi.json`, so + every OpenAPI codegen (typescript-fetch, openapi-generator, oapi-codegen, + …) emits a `@deprecated` marker on the generated SDK method. +- **Response headers (RFC 9745)**: every response carries `Deprecation: true`. +- **Response headers (RFC 8288)**: every response carries a `Link` header + pointing at the canonical successor: + `Link: ; rel="successor-version"` for `/read`, and + `Link: ; rel="successor-version"` for `/change`. SDKs and HTTP + proxies can pick the successor up automatically. + +Migration is purely cosmetic on the client side — swap the URL path, leave +the request body and response handling alone. ## Streaming @@ -34,8 +145,8 @@ Uniform `ErrorOutput { error, code?, merge_conflicts[], manifest_conflict? }` wi caller's pre-write view of one table's manifest version was stale. `ManifestConflictOutput { table_key, expected, actual }` tells the client which table to refresh and retry. This is the conflict shape produced by -concurrent `/change` or `/ingest` calls landing the same `(table, branch)` -race. +concurrent `/mutate` (or its `/change` alias) or `/ingest` calls landing +the same `(table, branch)` race. HTTP status codes used: 200, 400, 401, 403, 404, 409, 429, 500. @@ -61,10 +172,11 @@ actors are unaffected. Cedar policy authorization runs **before** admission accounting so denied requests don't consume admission slots. -Today admission gates every mutating handler: `/change`, `/ingest`, -`/branches/{create,delete,merge}`, and `/schema/apply`. Read-only -endpoints (`/snapshot`, `/read`, `/export`, `/branches` GET, `/commits`, -`/schema` GET) are not admission-gated. +Today admission gates every mutating handler: `/mutate` (and its +deprecated alias `/change`), `/ingest`, `/branches/{create,delete,merge}`, +and `/schema/apply`. Read-only endpoints (`/snapshot`, `/query`, `/read`, +`/export`, `/branches` GET, `/commits`, `/schema` GET) are not +admission-gated. ## Body limits @@ -79,7 +191,10 @@ endpoints (`/snapshot`, `/read`, `/export`, `/branches` GET, `/commits`, 1. `OMNIGRAPH_SERVER_BEARER_TOKENS_AWS_SECRET` — AWS Secrets Manager (build with `--features aws`) 2. `OMNIGRAPH_SERVER_BEARER_TOKENS_FILE` or `OMNIGRAPH_SERVER_BEARER_TOKENS_JSON` — JSON `{actor_id: token, …}` 3. `OMNIGRAPH_SERVER_BEARER_TOKEN` — single legacy token, actor `default` -- If no tokens configured, server runs unauthenticated (local dev) and `/openapi.json` strips the security scheme. +- If no tokens are configured, startup refuses unless `--unauthenticated` or + `OMNIGRAPH_UNAUTHENTICATED=1` explicitly opts into open local-dev mode. A + policy file without tokens is also rejected at startup. In open mode + `/openapi.json` strips the security scheme. See [deployment.md](deployment.md) for token-source operational details. @@ -87,15 +202,16 @@ See [deployment.md](deployment.md) for token-source operational details. - `tower_http::TraceLayer::new_for_http()` - Policy decisions logged at INFO level with actor, action, branch, decision, matched rule -- Startup logs: token source name, repo URI, bind address +- Startup logs: token source name, graph URI, bind address - Graceful SIGINT shutdown ## Not implemented (by design or "TBD") - CORS — not configured; add `tower_http::cors` if needed. -- Rate limiting — per-actor admission control gates `/change`, `/ingest`, - `/branches/{create,delete,merge}`, `/schema/apply` (see "Per-actor +- Rate limiting — per-actor admission control gates `/mutate` (alias + `/change`), `/ingest`, `/branches/{create,delete,merge}`, + `/schema/apply` (see "Per-actor admission control" above). No global rate limiter is configured; add `tower_http::limit` if a graph-wide cap is needed. - Pagination — none (commits/branches return everything; export streams). -- Multi-tenant routing — one repo per process. +- Runtime graph add/remove — edit `omnigraph.yaml` and restart. diff --git a/docs/user/storage.md b/docs/user/storage.md index b284bc2..c22d4d6 100644 --- a/docs/user/storage.md +++ b/docs/user/storage.md @@ -7,7 +7,7 @@ Every node type and every edge type is its own Lance dataset: - **Columnar Arrow storage**: each property is a column; nullable per Arrow schema. - **Fragments**: data is partitioned into fragments; new writes create new fragments. - **Manifest versioning**: every commit produces a new dataset version; old versions remain readable. -- **Stable row IDs**: `enable_stable_row_ids: true` is set on every Lance dataset OmniGraph creates — node and edge data tables, `__manifest`, `_graph_commits.lance`, `_graph_commit_recoveries.lance`, and any future system tables. This is an architectural invariant: the flag is one-way at dataset create per Lance's row-id-lineage spec, so a future change that introduces a Lance dataset must preserve it. Consequences: `_row_created_at_version` and `_row_last_updated_at_version` are available on every dataset (load-bearing for change-feed validators); `CreateIndex × Rewrite` is not a retryable conflict, so indices survive `omnigraph optimize` without needing the Fragment Reuse Index; readers must use a Lance build that recognises the flag (our pinned 4.0.0 is fine). Pre-0.4.x repos created before this code path settled may have datasets without the flag and cannot be retrofitted in place — the supported path is dump-and-reload. The `stage_overwrite` rewrite path (used by `schema_apply`) preserves the flag through `Operation::Overwrite`; pinned by `stage_overwrite_preserves_stable_row_ids` in `crates/omnigraph/tests/staged_writes.rs`. +- **Stable row IDs**: `enable_stable_row_ids: true` is set on every Lance dataset OmniGraph creates — node and edge data tables, `__manifest`, `_graph_commits.lance`, `_graph_commit_recoveries.lance`, and any future system tables. This is an architectural invariant: the flag is one-way at dataset create per Lance's row-id-lineage spec, so a future change that introduces a Lance dataset must preserve it. Consequences: `_row_created_at_version` and `_row_last_updated_at_version` are available on every dataset (load-bearing for change-feed validators); `CreateIndex × Rewrite` is not a retryable conflict, so indices survive `omnigraph optimize` without needing the Fragment Reuse Index; readers must use a Lance build that recognises the flag (our pinned 4.0.0 is fine). Pre-0.4.x graphs created before this code path settled may have datasets without the flag and cannot be retrofitted in place — the supported path is dump-and-reload. The `stage_overwrite` rewrite path (used by `schema_apply`) preserves the flag through `Operation::Overwrite`; pinned by `stage_overwrite_preserves_stable_row_ids` in `crates/omnigraph/tests/staged_writes.rs`. - **Append / delete / `merge_insert`**: native Lance write modes. - **Per-dataset branches** (Lance native): copy-on-write at the dataset level. - **Object-store agnostic**: file://, s3://, gs://, az://, http (read-only via Lance) — OmniGraph wires file:// and s3:// (`storage.rs`). @@ -22,7 +22,7 @@ OmniGraph is **not** a single Lance dataset; it is a *graph* of datasets coordin - `edges/{fnv1a64-hex(edge_type_name)}` — one Lance dataset per edge type - `__manifest/` — the catalog of all sub-tables and their published versions - `_graph_commits.lance` / `_graph_commit_actors.lance` — the commit graph and its actor map - - (legacy `_graph_runs.lance` / `_graph_run_actors.lance` from pre-v0.4.0 repos are inert; the run state machine was removed in MR-771 and these files are cleaned up via MR-770's production sweep) + - (legacy `_graph_runs.lance` / `_graph_run_actors.lance` from pre-v0.4.0 graphs are inert; the run state machine was removed in MR-771 and these files are cleaned up via MR-770's production sweep) - **Manifest row schema** (`object_id, object_type, location, metadata, base_objects, table_key, table_version, table_branch, row_count`): - `object_type` ∈ `table | table_version | table_tombstone` - `table_key` ∈ `node: | edge:` @@ -36,7 +36,7 @@ OmniGraph is **not** a single Lance dataset; it is a *graph* of datasets coordin The on-disk shape of `__manifest` is reconciled with the binary via a single stamp + dispatcher. `INTERNAL_MANIFEST_SCHEMA_VERSION` declares the shape this binary writes; the on-disk stamp `omnigraph:internal_schema_version` lives in the manifest dataset's schema-level metadata (Lance `update_schema_metadata`). -- **`init_manifest_repo`** stamps the current version at creation, so newly initialized repos never need migration. +- **`init_manifest_graph`** stamps the current version at creation, so newly initialized graphs never need migration. - **Publisher open-for-write path** (`load_publish_state`) calls `migrate_internal_schema(&mut dataset)` before reading state. When the on-disk stamp matches the binary, this is a single metadata read with no writes; otherwise the dispatcher walks `match`-arm steps forward (1→2, 2→3, …) until the stamp matches, then proceeds with the publish. Reads stay side-effect-free. - **Forward-version protection**: a stamp *higher* than the binary's known version triggers a clear "upgrade omnigraph first" error. An old binary cannot clobber a newer schema by silently treating "unknown stamp" as "missing stamp". - **Idempotency**: each migration step is safe to re-run. A crash between two metadata updates inside a single step leaves the partial state; the next open re-runs the step and the second update lands. The dispatcher itself is a cheap stamp-read on the steady-state path. @@ -50,14 +50,14 @@ Adding a new on-disk shape change is one constant bump (`INTERNAL_MANIFEST_SCHEM ## On-disk layout -A repo on disk is a directory tree of Lance datasets. Each dataset follows the standard Lance layout (`_versions/`, `data/`, `_indices/`, `_refs/`); OmniGraph adds the multi-dataset coordination by keeping `__manifest/` alongside the per-type datasets. +A graph on disk is a directory tree of Lance datasets. Each dataset follows the standard Lance layout (`_versions/`, `data/`, `_indices/`, `_refs/`); OmniGraph adds the multi-dataset coordination by keeping `__manifest/` alongside the per-type datasets. ```mermaid flowchart TB classDef l1 fill:#fef3e8,stroke:#c46900,color:#000 classDef l2 fill:#e8f4fd,stroke:#1e6aa8,color:#000 - repo["repo URI
file:// or s3://bucket/prefix"]:::l2 + graph["graph URI
file:// or s3://bucket/prefix"]:::l2 manifest["__manifest/
L2 catalog of sub-tables"]:::l2 nodes["nodes/{fnv1a64-hex}/
one dataset per node type"]:::l2 @@ -66,12 +66,12 @@ flowchart TB recovery["__recovery/{ulid}.json
recovery sidecars (transient)"]:::l2 refs["_refs/branches/{name}.json
graph-level branches"]:::l2 - repo --> manifest - repo --> nodes - repo --> edges - repo --> cgraph - repo --> recovery - repo --> refs + graph --> manifest + graph --> nodes + graph --> edges + graph --> cgraph + graph --> recovery + graph --> refs subgraph dataset[Inside each Lance dataset — L1] ds_v["_versions/{n}.manifest
per-dataset versions"]:::l1 @@ -88,10 +88,10 @@ flowchart TB **What's where:** -- **Repo root** is one directory (or S3 prefix). Everything below is part of one OmniGraph repo. +- **Graph root** is one directory (or S3 prefix). Everything below is part of one OmniGraph graph. - **`__manifest/`** is a Lance dataset whose rows describe which sub-table version is published at which graph-branch. Reading a snapshot starts here. - **`nodes/`** and **`edges/`** are sibling directories holding one Lance dataset per declared type. Names are `fnv1a64-hex` of the type name to keep paths fixed-length and case-safe. -- **`_graph_commits.lance`** is an L2 dataset that records the graph-level commit DAG, with a paired `_graph_commit_actors.lance` for the actor map. (Pre-v0.4.0 repos also have inert `_graph_runs.lance` / `_graph_run_actors.lance` from the removed Run state machine; MR-770 sweeps these in production.) +- **`_graph_commits.lance`** is an L2 dataset that records the graph-level commit DAG, with a paired `_graph_commit_actors.lance` for the actor map. (Pre-v0.4.0 graphs also have inert `_graph_runs.lance` / `_graph_run_actors.lance` from the removed Run state machine; MR-770 sweeps these in production.) - **`_graph_commit_recoveries.lance`** — one row per recovery sweep action. Joined to `_graph_commits.lance` by `graph_commit_id`; the linked commit row carries `actor_id=omnigraph:recovery`. Operators correlate recoveries with the original mutations they rolled forward / back via this join. See `crates/omnigraph/src/db/recovery_audit.rs`. - **`__recovery/{ulid}.json`** — transient sidecar files written by the four migrated writers (`MutationStaging::finalize`, `schema_apply`, `branch_merge`, `ensure_indices`) before Phase B begins, deleted after Phase C succeeds. A sidecar persisting after process exit means the writer crashed in the Phase B → Phase C window; the next `Omnigraph::open` recovery sweep processes it. Steady-state directory is empty. See `crates/omnigraph/src/db/manifest/recovery.rs`. - **`_refs/branches/{name}.json`** is graph-level branch metadata — pointers from a branch name to the manifest version it heads. diff --git a/docs/user/transactions.md b/docs/user/transactions.md index c917b46..d6c79f4 100644 --- a/docs/user/transactions.md +++ b/docs/user/transactions.md @@ -48,7 +48,7 @@ query register_employee_with_team($name: String, $age: I32, $team: String) { ```bash omnigraph change --query ./mutations.gq --name register_employee_with_team \ - --params '{"name":"Alice","age":30,"team":"Acme"}' ./repo.omni + --params '{"name":"Alice","age":30,"team":"Acme"}' ./graph.omni ``` If the second statement fails (e.g. `Acme` doesn't exist), the publisher never publishes; `Alice` is not in the database. Atomic. @@ -57,10 +57,10 @@ If the second statement fails (e.g. `Acme` doesn't exist), the publisher never p ```bash # Query 1 -omnigraph change --query ./mutations.gq --name register_employee --params '{"name":"Alice","age":30}' ./repo.omni +omnigraph change --query ./mutations.gq --name register_employee --params '{"name":"Alice","age":30}' ./graph.omni # Query 2 — runs after Query 1 has already published -omnigraph change --query ./mutations.gq --name link_to_team --params '{"name":"Alice","team":"Acme"}' ./repo.omni +omnigraph change --query ./mutations.gq --name link_to_team --params '{"name":"Alice","team":"Acme"}' ./graph.omni ``` These are **two publishes** on `main`. If Query 2 fails, Query 1's effects are already visible. There is no `ROLLBACK` for Query 1. @@ -75,32 +75,32 @@ The pattern when you need to run multiple queries — possibly across multiple c ```bash # Fork a working branch from main. -omnigraph branch create --from main onboarding/2026-04-25 ./repo.omni +omnigraph branch create --from main onboarding/2026-04-25 ./graph.omni # Run any number of mutations on the branch — each one is its own publish on the branch. # Concurrent reads of `main` are unaffected. omnigraph change --branch onboarding/2026-04-25 \ --query ./mutations.gq --name register_employee \ - --params '{"name":"Alice","age":30}' ./repo.omni + --params '{"name":"Alice","age":30}' ./graph.omni omnigraph change --branch onboarding/2026-04-25 \ --query ./mutations.gq --name register_employee \ - --params '{"name":"Bob","age":25}' ./repo.omni + --params '{"name":"Bob","age":25}' ./graph.omni omnigraph change --branch onboarding/2026-04-25 \ --query ./mutations.gq --name link_to_team \ - --params '{"name":"Alice","team":"Acme"}' ./repo.omni + --params '{"name":"Alice","team":"Acme"}' ./graph.omni # Inspect the branch — read queries work just like on main. omnigraph read --branch onboarding/2026-04-25 \ - --query ./queries.gq --name list_employees ./repo.omni + --query ./queries.gq --name list_employees ./graph.omni # Happy with what's on the branch? Merge it. This is one atomic publish: # `main` flips to include every commit on the branch. -omnigraph branch merge onboarding/2026-04-25 --into main ./repo.omni +omnigraph branch merge onboarding/2026-04-25 --into main ./graph.omni # OR: not happy? Throw it away. `main` is untouched. -# omnigraph branch delete onboarding/2026-04-25 ./repo.omni +# omnigraph branch delete onboarding/2026-04-25 ./graph.omni ``` Properties: @@ -115,16 +115,16 @@ Two agents writing to the same graph independently: ```bash # Agent A -omnigraph branch create --from main agent-a/work ./repo.omni -omnigraph change --branch agent-a/work … ./repo.omni +omnigraph branch create --from main agent-a/work ./graph.omni +omnigraph change --branch agent-a/work … ./graph.omni # … many mutations … -omnigraph branch merge agent-a/work --into main ./repo.omni +omnigraph branch merge agent-a/work --into main ./graph.omni # Agent B (running concurrently) -omnigraph branch create --from main agent-b/work ./repo.omni -omnigraph change --branch agent-b/work … ./repo.omni +omnigraph branch create --from main agent-b/work ./graph.omni +omnigraph change --branch agent-b/work … ./graph.omni # … many mutations … -omnigraph branch merge agent-b/work --into main ./repo.omni +omnigraph branch merge agent-b/work --into main ./graph.omni ``` Each agent sees a consistent snapshot of `main` at the time it forked. The first merge to `main` lands as a fast-forward (or a no-op if no concurrent change). The second merge runs three-way: rows touched by both branches surface as `MergeConflict`s for the caller to resolve. @@ -138,7 +138,7 @@ This is the workflow MR-797 / agentic loops are designed around: **branches are | Single query fails mid-flight | Publisher never publishes; target unchanged | Read the error, decide whether to retry | | Concurrent writers race the same `(table, branch)` | Publisher CAS rejects the loser with `ManifestConflictDetails::ExpectedVersionMismatch` | Refresh handle, retry the query | | Branch with N successful mutations, then merge fails (three-way conflict) | Each individual mutation already committed on the branch; merge surfaces `MergeConflicts` | Inspect, decide whether to keep working on the branch, abandon it (`branch_delete`), or resolve and re-merge | -| Process crashes mid-branch-workflow | Each completed mutation on the branch is durable | Re-open the repo, continue where you left off | +| Process crashes mid-branch-workflow | Each completed mutation on the branch is durable | Re-open the graph, continue where you left off | ## When to use what @@ -156,7 +156,7 @@ This is the workflow MR-797 / agentic loops are designed around: **branches are - **Cross-query atomicity on `main` without a branch.** If you don't want to fork a branch, multiple queries on `main` publish independently. There is no implicit transaction. - **Long-running interactive transactions.** No `BEGIN` over a connection. Branches are the durable equivalent. -- **Cross-graph (cross-repo) transactions.** Each repo is its own atomicity domain. +- **Cross-graph transactions.** Each graph is its own atomicity domain. - **"Pessimistic" locks** that serialize writers before they reach the storage layer. Snapshot-MVCC + publisher CAS handles concurrency optimistically; the loser retries. ## See also @@ -164,5 +164,5 @@ This is the workflow MR-797 / agentic loops are designed around: **branches are - [`docs/user/branches-commits.md`](branches-commits.md) — branch and commit-graph mechanics. - [`docs/dev/merge.md`](../dev/merge.md) — three-way merge details and conflict kinds. - [`docs/user/query-language.md`](query-language.md) — `.gq` syntax for the multi-statement queries used above. -- [`docs/dev/runs.md`](../dev/runs.md) — the per-query commit pipeline that gives single-query atomicity. +- [`docs/dev/writes.md`](../dev/writes.md) — the per-query commit pipeline that gives single-query atomicity. - [`docs/dev/invariants.md`](../dev/invariants.md) — the architectural rule. diff --git a/og-cheet-sheet.md b/og-cheet-sheet.md index 8ae6f5c..2cb4d76 100644 --- a/og-cheet-sheet.md +++ b/og-cheet-sheet.md @@ -5,23 +5,27 @@ Use an explicit schema file: ```bash -omnigraph query lint --query ./queries.gq --schema ./schema.pg --json -omnigraph query check --query ./queries.gq --schema ./schema.pg +omnigraph lint --query ./queries.gq --schema ./schema.pg --json +omnigraph check --query ./queries.gq --schema ./schema.pg ``` Use a local or `s3://` repo target: ```bash -omnigraph query lint --query ./queries.gq ./repo.omni --json -omnigraph query check --query ./queries.gq s3://bucket/repo +omnigraph lint --query ./queries.gq ./repo.omni --json +omnigraph check --query ./queries.gq s3://bucket/repo ``` Use `omnigraph.yaml` target resolution: ```bash -omnigraph query lint --query ./queries.gq --target local --config ./omnigraph.yaml +omnigraph lint --query ./queries.gq --target local --config ./omnigraph.yaml ``` +> The previous `omnigraph query lint` / `omnigraph query check` spellings +> are kept as deprecated argv shims that print a one-line warning to +> stderr and rewrite to the canonical `omnigraph lint` / `omnigraph check`. + ## What It Checks - parses every query in the file diff --git a/openapi.json b/openapi.json index b0ed1f2..aced64d 100644 --- a/openapi.json +++ b/openapi.json @@ -7,7 +7,7 @@ "name": "MIT", "identifier": "MIT" }, - "version": "0.4.2" + "version": "0.6.1" }, "paths": { "/branches": { @@ -312,8 +312,8 @@ "tags": [ "mutations" ], - "summary": "Apply a GQ mutation to a branch.", - "description": "Writes to the named `branch` (defaults to `main`). Mutations are atomic\nper call and produce a new commit. Returns counts of nodes and edges\naffected. **Destructive**: on success the branch is updated; rejected\nmutations may still acquire locks briefly. Returns 409 on merge conflict.", + "summary": "**Deprecated** — use [`POST /mutate`](#tag/mutations/operation/mutate) instead.", + "description": "Apply a GQ mutation to a branch. Behavior is unchanged; the route is\nkept indefinitely for back-compat. New integrations should target\n`POST /mutate`, which has identical semantics and a name that pairs\ncleanly with `POST /query`. Responses from this route include\n`Deprecation: true` and `Link: ; rel=\"successor-version\"`\nheaders per RFC 9745 / RFC 8288 so SDKs and proxies can surface the\nsignal.", "operationId": "change", "requestBody": { "content": { @@ -327,7 +327,7 @@ }, "responses": { "200": { - "description": "Mutation results", + "description": "Mutation results (response includes `Deprecation: true` + `Link: ; rel=\"successor-version\"`)", "content": { "application/json": { "schema": { @@ -387,6 +387,7 @@ } } }, + "deprecated": true, "security": [ { "bearer_token": [] @@ -585,6 +586,63 @@ ] } }, + "/graphs": { + "get": { + "tags": [ + "management" + ], + "summary": "List every graph currently registered with this server (MR-668).", + "description": "Multi-graph mode only. In single mode, the route returns 405 — there's\nno registry to enumerate. Cedar-gated by the server-level policy via\nthe `graph_list` action against `Omnigraph::Server::\"root\"`.\n\nOrder: alphabetical by `graph_id` (server-sorted so clients see\ndeterministic output across requests).", + "operationId": "listGraphs", + "responses": { + "200": { + "description": "List of registered graphs", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GraphListResponse" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "405": { + "description": "Method not allowed (single-graph mode)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + } + }, + "security": [ + { + "bearer_token": [] + } + ] + } + }, "/healthz": { "get": { "tags": [ @@ -684,13 +742,338 @@ ] } }, + "/mutate": { + "post": { + "tags": [ + "mutations" + ], + "summary": "Apply a GQ mutation to a branch (canonical mutation endpoint).", + "description": "Writes to the named `branch` (defaults to `main`). Mutations are atomic\nper call and produce a new commit. Returns counts of nodes and edges\naffected. **Destructive**: on success the branch is updated; rejected\nmutations may still acquire locks briefly. Returns 409 on merge conflict.\n\nPairs with `POST /query` (read-only). The legacy `POST /change` route\nhas identical semantics and is kept as a deprecated alias.", + "operationId": "mutate", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangeRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Mutation results", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangeOutput" + } + } + } + }, + "400": { + "description": "Bad request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "409": { + "description": "Merge conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "429": { + "description": "Per-actor admission cap exceeded; honor `Retry-After` header", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + } + }, + "security": [ + { + "bearer_token": [] + } + ] + } + }, + "/queries": { + "get": { + "tags": [ + "queries" + ], + "summary": "List the graph's exposed stored queries as a typed tool catalog.", + "description": "Returns the `mcp.expose == true` subset of 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. 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": "list_queries", + "responses": { + "200": { + "description": "Stored-query catalog (the mcp.expose subset, with typed params)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/QueriesCatalogOutput" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + } + }, + "security": [ + { + "bearer_token": [] + } + ] + } + }, + "/queries/{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": "invoke_query", + "parameters": [ + { + "name": "name", + "in": "path", + "description": "Stored query name (the registry key)", + "required": true, + "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", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvokeStoredQueryResponse" + } + } + } + }, + "400": { + "description": "Bad request (param type error; snapshot on a stored mutation)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "403": { + "description": "Forbidden (the inner `change` gate for a stored mutation)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "404": { + "description": "Unknown stored query, or `invoke_query` denied — indistinguishable to a caller without the grant", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "409": { + "description": "Merge conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "429": { + "description": "Per-actor admission cap exceeded; honor `Retry-After` header", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "500": { + "description": "Policy evaluation error (a denial is reported as 404, not 500)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + } + }, + "security": [ + { + "bearer_token": [] + } + ] + } + }, + "/query": { + "post": { + "tags": [ + "queries" + ], + "summary": "Execute an inline read query (friendlier-named alternative to `POST /read`).", + "description": "Designed for ad-hoc exploration and AI-agent tool-use: short field\nnames (`query`, `name`) match the CLI `-e` flag and the GQ `query`\nkeyword. Mutations (`insert`/`update`/`delete`) are rejected with 400\n-- use `POST /mutate` (or its deprecated alias `POST /change`) for\nwrite queries. Otherwise behaves identically to `POST /read`: same\ntarget semantics (branch xor snapshot), same Cedar action (Read),\nsame response shape.", + "operationId": "query", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/QueryRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Query results", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadOutput" + } + } + } + }, + "400": { + "description": "Bad request - also returned when the query body contains mutations; use POST /mutate (or its deprecated alias POST /change) for write queries", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOutput" + } + } + } + } + }, + "security": [ + { + "bearer_token": [] + } + ] + } + }, "/read": { "post": { "tags": [ "queries" ], - "summary": "Execute a GQ read query.", - "description": "Runs the query in `query_source` against either a branch or a frozen\nsnapshot (mutually exclusive). When `query_source` defines multiple named\nqueries, pick one with `query_name`. `params` is a JSON object whose keys\nmatch the parameters declared by the query. Returns rows as a JSON array\nplus a `columns` list. Read-only.", + "summary": "**Deprecated** — use [`POST /query`](#tag/queries/operation/query) instead.", + "description": "Execute a GQ read query. Behavior is unchanged from prior releases; the\nroute is kept indefinitely for byte-stable back-compat. New integrations\nshould target `POST /query`, which has clean field names (`query` /\n`name`) and a 400-on-mutation guard. Responses from this route include\n`Deprecation: true` and `Link: ; rel=\"successor-version\"`\nheaders per RFC 9745 / RFC 8288 so SDKs and proxies can surface the\nsignal.", "operationId": "read", "requestBody": { "content": { @@ -704,7 +1087,7 @@ }, "responses": { "200": { - "description": "Query results", + "description": "Query results (response includes `Deprecation: true` + `Link: ; rel=\"successor-version\"`)", "content": { "application/json": { "schema": { @@ -744,6 +1127,7 @@ } } }, + "deprecated": true, "security": [ { "bearer_token": [] @@ -1103,7 +1487,7 @@ "ChangeRequest": { "type": "object", "required": [ - "query_source" + "query" ], "properties": { "branch": { @@ -1113,19 +1497,19 @@ ], "description": "Target branch. Defaults to `main`." }, - "params": { - "description": "JSON object whose keys match the mutation's declared parameters." - }, - "query_name": { + "name": { "type": [ "string", "null" ], - "description": "Name of the mutation to run when `query_source` declares multiple." + "description": "Name of the mutation to run when `query` declares multiple.\n\nAccepts the legacy field name `query_name` as a deserialization alias." }, - "query_source": { + "params": { + "description": "JSON object whose keys match the mutation's declared parameters." + }, + "query": { "type": "string", - "description": "GQ mutation source containing `insert`, `update`, or `delete` statements.\nMay declare multiple named mutations; pick one with `query_name`.", + "description": "GQ mutation source containing `insert`, `update`, or `delete` statements.\nMay declare multiple named mutations; pick one with `name`.\n\nAccepts the legacy field name `query_source` as a deserialization alias.", "example": "query insert_person($name: String, $age: I32) {\n insert Person { name: $name, age: $age }\n}" } } @@ -1199,6 +1583,7 @@ "forbidden", "bad_request", "not_found", + "method_not_allowed", "conflict", "too_many_requests", "internal" @@ -1268,6 +1653,37 @@ } } }, + "GraphInfo": { + "type": "object", + "description": "One entry in the response from `GET /graphs`. Cluster operators\nconsume this list to discover which graphs the server is currently\nserving. The shape is intentionally minimal — `graph_id` and `uri`\nare the only fields a routing client needs.", + "required": [ + "graph_id", + "uri" + ], + "properties": { + "graph_id": { + "type": "string" + }, + "uri": { + "type": "string" + } + } + }, + "GraphListResponse": { + "type": "object", + "description": "Response from `GET /graphs`. Lists every graph registered with the\nserver in alphabetical order by `graph_id` (sorted server-side so\nclients get deterministic output across requests).", + "required": [ + "graphs" + ], + "properties": { + "graphs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GraphInfo" + } + } + } + }, "HealthOutput": { "type": "object", "required": [ @@ -1383,6 +1799,40 @@ } } }, + "InvokeStoredQueryRequest": { + "type": "object", + "description": "Body for `POST /queries/{name}` — invokes the server-side stored query\nnamed in the path. The query source and name come from the registry,\nnever the body; only the runtime inputs are supplied here.", + "properties": { + "branch": { + "type": [ + "string", + "null" + ], + "description": "Branch to run against. Defaults to `main`; for a stored mutation the\nwrite targets this branch." + }, + "params": { + "description": "JSON object whose keys match the stored query's declared parameters." + }, + "snapshot": { + "type": [ + "string", + "null" + ], + "description": "Snapshot id to read from (read queries only — rejected for a stored\nmutation). Mutually exclusive with `branch`." + } + } + }, + "InvokeStoredQueryResponse": { + "oneOf": [ + { + "$ref": "#/components/schemas/ReadOutput" + }, + { + "$ref": "#/components/schemas/ChangeOutput" + } + ], + "description": "Response for `POST /queries/{name}`: the read envelope for a stored\nread, or the mutation envelope for a stored mutation. Serialized\n**untagged**, so the wire shape is exactly [`ReadOutput`] or\n[`ChangeOutput`] — classification follows the stored query, not a\nwrapper field." + }, "LoadMode": { "type": "string", "description": "Shadow enum for documenting [`LoadMode`] in the OpenAPI schema.", @@ -1453,6 +1903,158 @@ } } }, + "ParamDescriptor": { + "type": "object", + "description": "One declared parameter of a stored query, projected for the catalog.", + "required": [ + "name", + "kind", + "nullable" + ], + "properties": { + "item_kind": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ParamKind", + "description": "Element kind when `kind == list` (always a scalar — the grammar\nforbids lists of vectors or nested lists)." + } + ] + }, + "kind": { + "$ref": "#/components/schemas/ParamKind" + }, + "name": { + "type": "string" + }, + "nullable": { + "type": "boolean", + "description": "`false` → the caller must supply it; `true` → optional." + }, + "vector_dim": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "Dimension when `kind == vector`.", + "minimum": 0 + } + } + }, + "ParamKind": { + "type": "string", + "description": "The kind of a stored-query parameter, decomposed so a client (e.g. an\nMCP server) can build a typed input schema with a closed `match` and\nnever re-parse omnigraph's type spelling. `bigint`/`date`/`datetime`/\n`blob` are carried as JSON strings on the wire: a 64-bit integer past\n2^53 loses precision as a JSON number, and Date/DateTime are ISO\nstrings, Blob a blob-URI string.", + "enum": [ + "string", + "bool", + "int", + "bigint", + "float", + "date", + "datetime", + "blob", + "vector", + "list" + ] + }, + "QueriesCatalogOutput": { + "type": "object", + "description": "Response for `GET /queries`: the `mcp.expose` subset of a graph's\nstored-query registry, each with typed parameters.", + "required": [ + "queries" + ], + "properties": { + "queries": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QueryCatalogEntry" + } + } + } + }, + "QueryCatalogEntry": { + "type": "object", + "description": "One entry in the stored-query catalog (`GET /queries`).", + "required": [ + "name", + "tool_name", + "mutation", + "params" + ], + "properties": { + "description": { + "type": [ + "string", + "null" + ] + }, + "instruction": { + "type": [ + "string", + "null" + ] + }, + "mutation": { + "type": "boolean", + "description": "`true` for a stored mutation → an MCP read-only hint of `false`." + }, + "name": { + "type": "string", + "description": "Registry key / invoke path segment (`POST /queries/{name}`)." + }, + "params": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ParamDescriptor" + } + }, + "tool_name": { + "type": "string", + "description": "MCP tool id (the `tool_name` override, else `name`)." + } + } + }, + "QueryRequest": { + "type": "object", + "description": "Inline read-query request for `POST /query`.\n\nFriendlier-named alternative to [`ReadRequest`] for ad-hoc reads and\nAI-agent integration. Mutations are rejected with 400 — use `POST\n/mutate` (or its deprecated alias `POST /change`) for write queries.\nField names are deliberately short (`query`, `name`) to match the GQ\nkeyword and the CLI `-e` flag.", + "required": [ + "query" + ], + "properties": { + "branch": { + "type": [ + "string", + "null" + ], + "description": "Branch to read from. Mutually exclusive with `snapshot`. Defaults to `main`." + }, + "name": { + "type": [ + "string", + "null" + ], + "description": "Name of the query to run when `query` declares multiple. Optional when\nonly one query is declared." + }, + "params": { + "description": "JSON object whose keys match the query's declared parameters." + }, + "query": { + "type": "string", + "description": "GQ read-query source. May declare one or more named queries; pick one\nwith `name` when more than one is declared. Mutations\n(`insert`/`update`/`delete`) get 400 — use `POST /mutate` (or its\ndeprecated alias `POST /change`) instead.", + "example": "query get_person($name: String) {\n match {\n $p: Person { name: $name }\n }\n return { $p.name, $p.age }\n}" + }, + "snapshot": { + "type": [ + "string", + "null" + ], + "description": "Snapshot id to read from. Mutually exclusive with `branch`." + } + } + }, "ReadOutput": { "type": "object", "required": [ diff --git a/scripts/apply-branch-protection.sh b/scripts/apply-branch-protection.sh index 910d5b6..25e93ee 100755 --- a/scripts/apply-branch-protection.sh +++ b/scripts/apply-branch-protection.sh @@ -3,7 +3,7 @@ # # Requires: # - `gh` CLI authenticated. -# - Repo-admin or org-admin permissions on ModernRelay/omnigraph. +# - Repository-admin or org-admin permissions on ModernRelay/omnigraph. # # This script is idempotent: re-running applies whatever is currently # declared in .github/branch-protection.json. The JSON file is the diff --git a/scripts/check-agents-md.sh b/scripts/check-agents-md.sh index ebb4606..abc6469 100755 --- a/scripts/check-agents-md.sh +++ b/scripts/check-agents-md.sh @@ -34,7 +34,7 @@ PY canonical=() while IFS= read -r line; do canonical+=("$line") -done < <(find docs -type f -name '*.md' ! -path 'docs/releases/*' | sort) +done < <(find docs -type f -name '*.md' ! -path 'docs/releases/*' ! -path 'docs/internal/*' | sort) if [[ -d docs/releases ]]; then canonical+=("docs/releases/") fi diff --git a/scripts/install.ps1 b/scripts/install.ps1 new file mode 100644 index 0000000..3bfd0f1 --- /dev/null +++ b/scripts/install.ps1 @@ -0,0 +1,151 @@ +param( + [string]$RepoSlug = "ModernRelay/omnigraph", + [string]$InstallDir = "$env:USERPROFILE\.local\bin", + [ValidateSet("stable", "edge")] + [string]$ReleaseChannel = "stable", + [string]$Version = "" +) + +$ErrorActionPreference = "Stop" + +$assetName = "omnigraph-windows-x86_64.zip" +$assetStem = "omnigraph-windows-x86_64" +$workDir = Join-Path ([System.IO.Path]::GetTempPath()) ("omnigraph-install-" + [System.Guid]::NewGuid().ToString("N")) +$selectedChannel = "" + +function Write-Log { + param([string]$Message) + Write-Host "==> $Message" +} + +function Get-ReleaseBaseUrl { + param([string]$Channel) + + if ($Version -ne "") { + return "https://github.com/$RepoSlug/releases/download/$Version" + } + + if ($Channel -eq "stable") { + return "https://github.com/$RepoSlug/releases/latest/download" + } + + if ($Channel -eq "edge") { + return "https://github.com/$RepoSlug/releases/download/edge" + } + + throw "unsupported ReleaseChannel '$Channel' (expected stable or edge)" +} + +function Download-ReleaseFiles { + param( + [string]$BaseUrl, + [string]$ArchivePath, + [string]$ChecksumPath + ) + + try { + Invoke-WebRequest -UseBasicParsing -Uri "$BaseUrl/$assetName" -OutFile $ArchivePath + Invoke-WebRequest -UseBasicParsing -Uri "$BaseUrl/$assetStem.sha256" -OutFile $ChecksumPath + return $true + } catch { + return $false + } +} + +function Verify-Checksum { + param( + [string]$ArchivePath, + [string]$ChecksumPath + ) + + $checksumText = (Get-Content -Path $ChecksumPath -Raw).Trim() + $expected = ($checksumText -split "\s+")[0].ToLowerInvariant() + if ($expected -eq "") { + throw "checksum file did not contain a SHA256 digest" + } + + $actual = (Get-FileHash -Path $ArchivePath -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actual -ne $expected) { + throw "checksum verification failed for $assetName" + } +} + +function Install-FromDirectory { + param([string]$SourceDir) + + New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null + Copy-Item -Path (Join-Path $SourceDir "omnigraph.exe") -Destination (Join-Path $InstallDir "omnigraph.exe") -Force + Copy-Item -Path (Join-Path $SourceDir "omnigraph-server.exe") -Destination (Join-Path $InstallDir "omnigraph-server.exe") -Force +} + +function Install-FromRelease { + New-Item -ItemType Directory -Force -Path $workDir | Out-Null + + $archivePath = Join-Path $workDir $assetName + $checksumPath = Join-Path $workDir "$assetStem.sha256" + + if ($Version -ne "") { + $script:selectedChannel = $Version + $baseUrl = Get-ReleaseBaseUrl -Channel $ReleaseChannel + Write-Log "Downloading $assetName from $Version" + if (!(Download-ReleaseFiles -BaseUrl $baseUrl -ArchivePath $archivePath -ChecksumPath $checksumPath)) { + throw "no published binary found for $assetName at release $Version" + } + } else { + $script:selectedChannel = $ReleaseChannel + $baseUrl = Get-ReleaseBaseUrl -Channel $selectedChannel + Write-Log "Downloading $assetName from $selectedChannel" + if (!(Download-ReleaseFiles -BaseUrl $baseUrl -ArchivePath $archivePath -ChecksumPath $checksumPath)) { + if ($ReleaseChannel -ne "stable") { + throw "no published binary found for $assetName on channel $ReleaseChannel" + } + + Write-Log "Stable release binaries are not published yet; falling back to edge" + $script:selectedChannel = "edge" + $baseUrl = Get-ReleaseBaseUrl -Channel $selectedChannel + if (!(Download-ReleaseFiles -BaseUrl $baseUrl -ArchivePath $archivePath -ChecksumPath $checksumPath)) { + throw "no published binary found for $assetName on stable or edge; build from source" + } + } + } + + Verify-Checksum -ArchivePath $archivePath -ChecksumPath $checksumPath + + $extractDir = Join-Path $workDir "extract" + New-Item -ItemType Directory -Force -Path $extractDir | Out-Null + Expand-Archive -Path $archivePath -DestinationPath $extractDir -Force + Install-FromDirectory -SourceDir $extractDir +} + +function Print-Summary { + $omnigraphPath = Join-Path $InstallDir "omnigraph.exe" + $serverPath = Join-Path $InstallDir "omnigraph-server.exe" + + Write-Host "" + Write-Host "Installed:" + Write-Host " $omnigraphPath" + Write-Host " $serverPath" + Write-Host "" + Write-Host "Verify:" + Write-Host " $omnigraphPath version" + Write-Host " $serverPath --help" + Write-Host "" + + if ($selectedChannel -ne "") { + Write-Host "Installed from release channel: $selectedChannel" + } + + $pathParts = $env:Path -split [System.IO.Path]::PathSeparator + if ($pathParts -notcontains $InstallDir) { + Write-Host "Add $InstallDir to PATH if needed." + } +} + +try { + Install-FromRelease + Print-Summary +} finally { + if (Test-Path $workDir) { + Remove-Item -Path $workDir -Recurse -Force + } +} diff --git a/scripts/local-rustfs-bootstrap.sh b/scripts/local-rustfs-bootstrap.sh index a314ebd..c4fdcbe 100755 --- a/scripts/local-rustfs-bootstrap.sh +++ b/scripts/local-rustfs-bootstrap.sh @@ -6,7 +6,14 @@ SOURCE_REF="${SOURCE_REF:-main}" RELEASE_CHANNEL="${RELEASE_CHANNEL:-edge}" WORKDIR="${WORKDIR:-$PWD/.omnigraph-rustfs-demo}" RUSTFS_CONTAINER_NAME="${RUSTFS_CONTAINER_NAME:-omnigraph-rustfs-demo}" -RUSTFS_IMAGE="${RUSTFS_IMAGE:-rustfs/rustfs:latest}" +# Pinned to 1.0.0-beta.3 (2026-05-14) — the last known-good tag, matching CI +# (.github/workflows/ci.yml). `rustfs/rustfs:latest` (1.0.0-beta.4, 2026-05-21) +# added a credentials-policy check that refuses to start when the access/secret +# keys are values it considers "default" (rustfsadmin/rustfsadmin here). This +# script still works on beta.4+ because it passes +# RUSTFS_ALLOW_INSECURE_DEFAULT_CREDENTIALS=true below — so overriding +# RUSTFS_IMAGE to a newer tag is safe. +RUSTFS_IMAGE="${RUSTFS_IMAGE:-rustfs/rustfs:1.0.0-beta.3}" RUSTFS_DATA_DIR="${RUSTFS_DATA_DIR:-$WORKDIR/rustfs-data}" BUCKET="${BUCKET:-omnigraph-local}" PREFIX="${PREFIX:-repos/context}" @@ -74,9 +81,6 @@ platform_asset_name() { Linux/x86_64) printf 'omnigraph-linux-x86_64.tar.gz\n' ;; - Darwin/x86_64) - printf 'omnigraph-macos-x86_64.tar.gz\n' - ;; Darwin/arm64) printf 'omnigraph-macos-arm64.tar.gz\n' ;; @@ -268,6 +272,7 @@ start_rustfs() { -v "$RUSTFS_DATA_DIR:/data" \ -e RUSTFS_ACCESS_KEY="$AWS_ACCESS_KEY_ID" \ -e RUSTFS_SECRET_KEY="$AWS_SECRET_ACCESS_KEY" \ + -e RUSTFS_ALLOW_INSECURE_DEFAULT_CREDENTIALS=true \ "$RUSTFS_IMAGE" \ /data >/dev/null } @@ -291,7 +296,7 @@ ensure_bucket() { s3api create-bucket --bucket "$BUCKET" >/dev/null 2>&1 || true } -repo_prefix_has_objects() { +graph_prefix_has_objects() { local key_count key_count="$("$AWS_BIN" --endpoint-url "$AWS_ENDPOINT_URL_S3" \ s3api list-objects-v2 \ @@ -304,27 +309,27 @@ repo_prefix_has_objects() { [ -n "$key_count" ] && [ "$key_count" != "None" ] && [ "$key_count" != "0" ] } -reset_repo_prefix() { +reset_graph_prefix() { log "Removing existing objects under $REPO_URI" "$AWS_BIN" --endpoint-url "$AWS_ENDPOINT_URL_S3" \ s3 rm "s3://$BUCKET/$PREFIX" --recursive >/dev/null } -initialize_repo() { +initialize_graph() { if "$BIN_DIR/omnigraph" snapshot "$REPO_URI" --json >/dev/null 2>&1; then - log "Reusing existing repo at $REPO_URI" + log "Reusing existing graph at $REPO_URI" return fi - if repo_prefix_has_objects; then + if graph_prefix_has_objects; then if [ "$RESET_REPO" = "1" ]; then - reset_repo_prefix + reset_graph_prefix else - die "found existing objects under $REPO_URI but could not open an Omnigraph repo there. This usually means a previous bootstrap left a partially initialized prefix. Rerun with RESET_REPO=1 to delete that prefix and recreate it, or set PREFIX to a new value." + die "found existing objects under $REPO_URI but could not open an Omnigraph graph there. This usually means a previous bootstrap left a partially initialized prefix. Rerun with RESET_REPO=1 to delete that prefix and recreate it, or set PREFIX to a new value." fi fi - log "Initializing repo at $REPO_URI" + log "Initializing graph at $REPO_URI" "$BIN_DIR/omnigraph" init --schema "$FIXTURE_DIR/context.pg" "$REPO_URI" log "Loading context fixture into $REPO_URI" @@ -377,7 +382,7 @@ Omnigraph local RustFS demo is up. Server: $base_url -Repo URI: +Graph URI: $REPO_URI RustFS console: @@ -414,7 +419,7 @@ main() { start_rustfs wait_for_rustfs ensure_bucket - initialize_repo + initialize_graph start_server print_summary "$(wait_for_server)" } diff --git a/scripts/update-homebrew-formula.sh b/scripts/update-homebrew-formula.sh index 6b3984c..f2f0df9 100755 --- a/scripts/update-homebrew-formula.sh +++ b/scripts/update-homebrew-formula.sh @@ -6,7 +6,7 @@ usage() { Usage: update-homebrew-formula.sh [formula_path] Environment: - REPO_SLUG GitHub repo that owns the Omnigraph release + REPO_SLUG GitHub repository that owns the Omnigraph release default: ModernRelay/omnigraph EOF } @@ -64,20 +64,8 @@ cat >"$FORMULA_PATH" <