diff --git a/.dockerignore b/.dockerignore index 05ec59a..ab6a1f8 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,4 +2,3 @@ !Dockerfile !docker/entrypoint.sh !target/release/omnigraph-server -!target/release/omnigraph diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 3650f9e..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 -README.md @aaltshuler -AGENTS.md @aaltshuler -CLAUDE.md @aaltshuler -SECURITY.md @aaltshuler +crates/** @ragnorc +docs/** @ragnorc +README.md @ragnorc +AGENTS.md @ragnorc +CLAUDE.md @ragnorc +SECURITY.md @ragnorc diff --git a/.github/DISCUSSION_TEMPLATE/rfc.yml b/.github/DISCUSSION_TEMPLATE/rfc.yml deleted file mode 100644 index 2a63525..0000000 --- a/.github/DISCUSSION_TEMPLATE/rfc.yml +++ /dev/null @@ -1,34 +0,0 @@ -labels: ["rfc"] -body: - - type: markdown - attributes: - value: | - Use this to **incubate an RFC** β€” socialize a design and reach rough - consensus before writing the formal document. When it's ready, graduate - it into a pull request that adds `docs/rfcs/NNNN-title.md` - (see [docs/rfcs/README.md](../blob/main/docs/rfcs/README.md)); a - maintainer merging that PR is acceptance. - - For a plain feature request or open-ended idea, use the **Ideas** - category instead. For bugs, open an [Issue](../../issues/new/choose). - - type: textarea - id: problem - attributes: - label: Problem / motivation - description: What needs solving, and why is it worth the long-run cost? - validations: - required: true - - type: textarea - id: sketch - attributes: - label: Proposed direction (sketch) - description: A rough shape of the design. Detail comes later in the RFC document. - validations: - required: true - - type: textarea - id: invariants - attributes: - label: Invariants touched - description: Which items in docs/dev/invariants.md does this affect or risk? Any deny-list brush? - validations: - required: false diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 8e19465..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: Bug report -description: Report a reproducible problem or wrong behavior in OmniGraph. -title: "bug: " -labels: ["bug", "needs-triage"] -body: - - type: markdown - attributes: - value: | - Issues are for **reporting problems** β€” concrete, reproducible bugs. - For ideas, feature requests, or questions, please use - [Discussions](../../discussions) instead. - For a security vulnerability, follow [SECURITY.md](../../blob/main/SECURITY.md) β€” do **not** file it here. - - A maintainer will triage this; once labelled **`accepted`** it's open for a pull request - (see [GOVERNANCE.md](../../blob/main/GOVERNANCE.md)). - - type: textarea - id: what-happened - attributes: - label: What happened - description: What went wrong, and what you expected instead. - validations: - required: true - - type: textarea - id: repro - attributes: - label: Steps to reproduce - description: Minimal steps, commands, schema/query, or a failing snippet. - placeholder: | - 1. omnigraph init ... - 2. omnigraph ... - 3. observed: ... / expected: ... - validations: - required: true - - type: input - id: version - attributes: - label: Version - description: Output of `omnigraph --version` (or the engine/crate version) and how you installed it. - validations: - required: true - - type: input - id: environment - attributes: - label: Environment - description: OS, architecture, and storage backend (local FS / S3 / RustFS / MinIO). - validations: - required: false - - type: textarea - id: logs - attributes: - label: Logs / output - description: Relevant error text or logs. Will be rendered as code. - render: shell - validations: - required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 50720b8..0000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,13 +0,0 @@ -# Issues are for problem reports only. Disable blank issues so everything is -# routed: bugs through the form, everything else to Discussions / SECURITY.md. -blank_issues_enabled: false -contact_links: - - name: πŸ’‘ Idea, feature request, or RFC - url: https://github.com/ModernRelay/omnigraph/discussions - about: Propose features and designs in Discussions. RFCs graduate from there into a docs/rfcs/ pull request. - - name: ❓ Question or help - url: https://github.com/ModernRelay/omnigraph/discussions - about: Ask in Discussions β€” questions are not tracked as Issues. - - name: πŸ”’ Security vulnerability - url: https://github.com/ModernRelay/omnigraph/blob/main/SECURITY.md - about: Report security issues privately per SECURITY.md β€” never as a public Issue. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 2a548c7..0000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,29 +0,0 @@ - - -## What & why - - - -## Backing issue / RFC - - - -- [ ] Fixes an **accepted** issue: Closes # -- [ ] Implements / is an **accepted** RFC: -- [ ] **Trivial fast-lane** (typo / docs / dependency bump / comment / one-line CI) β€” no issue/RFC required - -## Checklist - -- [ ] Change is focused (one logical change) -- [ ] Tests added/updated for behavior changes (or N/A) -- [ ] Public docs updated if user-facing surface changed (or N/A) -- [ ] Reviewed against [docs/dev/invariants.md](../blob/main/docs/dev/invariants.md) β€” no Hard Invariant weakened, no deny-list item hit (or justified) - -## Notes for reviewers - - diff --git a/.github/branch-protection.json b/.github/branch-protection.json index c039e32..61b7d33 100644 --- a/.github/branch-protection.json +++ b/.github/branch-protection.json @@ -1,5 +1,5 @@ { - "_comment": "Branch protection policy for main. Applied via scripts/apply-branch-protection.sh. See docs/branch-protection.md for rationale. NOTE: bypass_pull_request_allowances.users must mirror the engineering owners in .github/codeowners-roles.yml β€” code owners merge their own PRs without a second review; non-owners still need a code-owner approval. (render-codeowners.py does NOT generate this list; keep it in sync by hand.)", + "_comment": "Branch protection policy for main. Applied via scripts/apply-branch-protection.sh. See docs/branch-protection.md for rationale.", "required_status_checks": { "strict": true, "contexts": [ @@ -7,8 +7,8 @@ "Check AGENTS.md Links", "Test Workspace", "Test omnigraph-server --features aws", - "CODEOWNERS matches source", - "CODEOWNERS not hand-edited" + "CODEOWNERS / drift", + "CODEOWNERS / noedit" ] }, "enforce_admins": false, @@ -17,12 +17,7 @@ "dismiss_stale_reviews": true, "require_code_owner_reviews": true, "required_approving_review_count": 1, - "require_last_push_approval": false, - "bypass_pull_request_allowances": { - "users": ["ragnorc", "aaltshuler"], - "teams": [], - "apps": [] - } + "require_last_push_approval": false }, "restrictions": null, "required_linear_history": true, diff --git a/.github/codeowners-roles.yml b/.github/codeowners-roles.yml index ed43c4a..c5e36a9 100644 --- a/.github/codeowners-roles.yml +++ b/.github/codeowners-roles.yml @@ -21,14 +21,14 @@ roles: All production code under crates/**. Engine, CLI, server, compiler. members: - - aaltshuler + - ragnorc docs: description: > Documentation under docs/**, plus repo-level docs (README.md, AGENTS.md, CLAUDE.md symlink, SECURITY.md). members: - - aaltshuler + - ragnorc # Path β†’ role mapping. GitHub CODEOWNERS uses "last match wins" # semantics β€” when multiple patterns match a file, only the last diff --git a/.github/scripts/render-codeowners.py b/.github/scripts/render-codeowners.py index 5e96545..f243d0c 100755 --- a/.github/scripts/render-codeowners.py +++ b/.github/scripts/render-codeowners.py @@ -1,14 +1,10 @@ #!/usr/bin/env python3 -"""Render .github/CODEOWNERS and the ownership tables in -docs/dev/codeowners.md from .github/codeowners-roles.yml. +"""Render .github/CODEOWNERS from .github/codeowners-roles.yml. -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. +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. Usage: python3 .github/scripts/render-codeowners.py @@ -20,7 +16,6 @@ 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 @@ -39,13 +34,6 @@ 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. @@ -87,62 +75,6 @@ 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}") @@ -195,9 +127,6 @@ 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 b2b18d8..5b7b7b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,9 +89,7 @@ jobs: crates/omnigraph/src/storage.rs) run_rustfs_ci=true ;; crates/omnigraph/src/db/manifest.rs|crates/omnigraph/src/db/manifest/*) run_rustfs_ci=true ;; crates/omnigraph/tests/s3_storage.rs|crates/omnigraph/tests/helpers/*) run_rustfs_ci=true ;; - crates/omnigraph-cluster/src/store.rs|crates/omnigraph-cluster/src/serve.rs) run_rustfs_ci=true ;; - crates/omnigraph-cluster/tests/s3_cluster.rs) run_rustfs_ci=true ;; - crates/omnigraph-server/tests/s3.rs|crates/omnigraph-server/tests/support/*) run_rustfs_ci=true ;; + crates/omnigraph-server/tests/server.rs) run_rustfs_ci=true ;; crates/omnigraph-cli/tests/system_local.rs) run_rustfs_ci=true ;; esac done @@ -129,13 +127,7 @@ jobs: name: Test Workspace needs: classify_changes runs-on: ubuntu-latest - # 75, not 45: a cold rust-cache (every Cargo.lock change) costs a full - # workspace + failpoints-feature build on a 2-core runner, which now - # exceeds 45 minutes on slow runner days. A timed-out run never SAVES - # its cache, so an undersized budget self-perpetuates: every retry - # starts cold and dies the same way (observed 2026-06-11, four runs). - # Warm-cache runs stay ~15 minutes; this is headroom, not a target. - timeout-minutes: 75 + timeout-minutes: 45 permissions: contents: write env: @@ -181,18 +173,15 @@ jobs: OMNIGRAPH_UPDATE_OPENAPI: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) && '1' || '' }} run: cargo test --workspace --locked - - name: Run failpoints feature tests + - name: Run failpoints feature test if: needs.classify_changes.outputs.run_full_ci == 'true' # Run after the workspace test so the build cache is warm β€” # enabling --features failpoints is just an incremental rebuild - # of the target crate + the small `fail` crate, not the full + # of omnigraph-engine + the small `fail` crate, not the full # dep tree (lance, datafusion). A separate job with its own # cache key would be a fresh ~20min build on first run; this - # is ~30s on a warm cache. The cluster feature does not enable - # omnigraph/failpoints, so each line rebuilds only its crate. - run: | - cargo test --locked -p omnigraph-engine --features failpoints --test failpoints - cargo test --locked -p omnigraph-cluster --features failpoints --test failpoints + # is ~30s on a warm cache. + run: cargo test --locked -p omnigraph-engine --features failpoints --test failpoints - name: Commit regenerated openapi.json to PR branch if: | @@ -272,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: @@ -314,12 +360,14 @@ jobs: . -> target - name: Start RustFS - # Pinned to 1.0.0-beta.8 (2026-06-10). beta.4+ refuses "default" - # credentials (rustfsadmin/rustfsadmin) unless - # RUSTFS_ALLOW_INSECURE_DEFAULT_CREDENTIALS=true is set β€” fine for - # an ephemeral CI container. The three S3 suites were validated - # against the beta.8 binary locally before this bump. Keep the pin - # explicit (never `latest`) so upgrades are deliberate. + # Pinned to 1.0.0-beta.3 (2026-05-14) β€” the last known-good tag. + # `rustfs/rustfs:latest` (1.0.0-beta.4, 2026-05-21) added a + # credentials-policy check that refuses to start when + # AWS_ACCESS_KEY_ID/SECRET_ACCESS_KEY are values it considers + # "default" (rustfsadmin/rustfsadmin in our case). Bumping to + # beta.4+ requires either rotating those creds to less-default + # values or setting RUSTFS_ALLOW_INSECURE_DEFAULT_CREDENTIALS=true + # β€” deliberate work, not an emergency. Pin first; upgrade later. run: | docker rm -f rustfs >/dev/null 2>&1 || true docker run -d \ @@ -328,8 +376,7 @@ jobs: -p 9001:9001 \ -e RUSTFS_ACCESS_KEY="${AWS_ACCESS_KEY_ID}" \ -e RUSTFS_SECRET_KEY="${AWS_SECRET_ACCESS_KEY}" \ - -e RUSTFS_ALLOW_INSECURE_DEFAULT_CREDENTIALS=true \ - rustfs/rustfs:1.0.0-beta.8 \ + rustfs/rustfs:1.0.0-beta.3 \ /data - name: Install AWS CLI @@ -353,14 +400,7 @@ jobs: run: cargo test --locked -p omnigraph-engine --test s3_storage -- --nocapture - name: Run RustFS server smoke - # No name filter: every test in the s3 target is bucket-gated, and a - # filter matching nothing passes vacuously (which silently ran zero - # tests here for a while β€” the old filter said s3_repo, the test - # said s3_graph). - run: cargo test --locked -p omnigraph-server --test s3 -- --nocapture - - - name: Run RustFS cluster e2e - run: cargo test --locked -p omnigraph-cluster --test s3_cluster -- --nocapture + run: cargo test --locked -p omnigraph-server --test server server_opens_s3_repo_directly_and_serves_snapshot_and_read -- --nocapture - name: Run RustFS CLI smoke run: cargo test --locked -p omnigraph-cli --test system_local local_cli_s3_end_to_end_init_load_read_flow -- --nocapture diff --git a/.github/workflows/codeowners.yml b/.github/workflows/codeowners.yml index 75b3515..19d5835 100644 --- a/.github/workflows/codeowners.yml +++ b/.github/workflows/codeowners.yml @@ -1,24 +1,19 @@ 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: -# `drift` auto-commits the regenerated artifacts back to same-repo PR -# branches, so it needs write access. +# Read-only; we never push from this workflow. permissions: - contents: write + contents: read 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 @@ -33,56 +28,19 @@ jobs: - name: Install PyYAML run: pip install pyyaml - - name: Re-render CODEOWNERS + ownership docs + - name: Re-render CODEOWNERS run: python3 .github/scripts/render-codeowners.py - # 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 }} + - name: Reject drift run: | - 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." + 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." echo "--- diff ---" - git --no-pager diff -- .github/CODEOWNERS docs/dev/codeowners.md + git --no-pager diff .github/CODEOWNERS exit 1 fi - echo "Generated artifacts are in sync with their source." + echo "CODEOWNERS is in sync with its source." noedit: name: CODEOWNERS not hand-edited @@ -94,8 +52,6 @@ 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/release.yml b/.github/workflows/release.yml index a265c40..3a66ff2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -121,30 +121,16 @@ 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. + # tree so `modernrelay/tap/omnigraph` resolves to it. 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 + brew audit --strict --online modernrelay/tap/omnigraph - name: Commit and push formula update if: env.HOMEBREW_TAP_SKIP != '1' diff --git a/AGENTS.md b/AGENTS.md index b335955..b876749 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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.6.2 -**Workspace crates:** `omnigraph-compiler`, `omnigraph` (engine), `omnigraph-policy`, `omnigraph-cluster`, `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 @@ -86,7 +86,6 @@ Full diagram and concurrency model: [docs/dev/architecture.md](docs/dev/architec | 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) | | `optimize` (compaction) and `cleanup` (version GC) | [docs/user/maintenance.md](docs/user/maintenance.md) | -| Cluster operator guide (deploy/manage clusters, approvals, recovery, serving) | [docs/user/cluster.md](docs/user/cluster.md) | | Cedar policy actions, scopes, CLI | [docs/user/policy.md](docs/user/policy.md) | | HTTP server endpoints, auth, error model, body limits | [docs/user/server.md](docs/user/server.md) | | CLI quick-start | [docs/user/cli.md](docs/user/cli.md) | @@ -200,8 +199,9 @@ omnigraph init --schema ./schema.pg s3://my-bucket/graph.omni # Bulk load omnigraph load --data ./seed.jsonl --mode overwrite s3://my-bucket/graph.omni -# Load a review batch onto its own branch (--from forks it if missing) -omnigraph load --branch review/2026-04-25 --from main --mode merge --data ./batch.jsonl s3://my-bucket/graph.omni +# Branch + ingest a review batch +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 \ @@ -214,12 +214,8 @@ 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/graph.omni -# Compact, preview any uncovered drift, then repair/GC after review +# Compact + GC (preview, then confirm) omnigraph optimize s3://my-bucket/graph.omni -omnigraph repair s3://my-bucket/graph.omni -omnigraph repair --confirm s3://my-bucket/graph.omni -# For suspicious/unverifiable drift only after deliberate review: -# omnigraph repair --force --confirm 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 @@ -240,9 +236,8 @@ omnigraph policy explain --actor act-alice --action change --branch main | Columnar storage on object store | βœ… Arrow/Lance | URI normalization, S3 env-var plumbing | | 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 five migrated writers (`MutationStaging::finalize`, `schema_apply`, `branch_merge`, `ensure_indices`, `optimize_all_tables`) 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` followed by a manifest publish of the restored version (so both directions converge to `manifest == HEAD` β€” no residual drift), 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 (`db.storage()`) exposing only `stage_*` + `commit_staged` + reads; the inline-commit residuals (`delete_where`, `create_vector_index`) are split onto a separate sealed `InlineCommitResidual` trait reached via `db.storage_inline_residual()` (MR-854), so the default surface cannot couple a write with a HEAD advance β€” Β§1 holds by construction. `delete_where` and `create_vector_index` stay inline 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)); `LoadMode::Overwrite` uses Lance `Overwrite` staged transactions. | -| Compaction (`compact_files`) | βœ… | `omnigraph optimize` orchestrates over all node/edge tables, bounded concurrency; **publishes each compacted table's new version to `__manifest`** (so the manifest tracks the Lance HEAD β€” required for reads to observe compaction and for schema apply / strict writes to pass their HEAD-vs-manifest precondition), under the per-`(table, main)` write queue with `SidecarKind::Optimize` recovery coverage; **refuses on an unrecovered graph** (errors if a `__recovery` sidecar is pending); **skips uncovered HEAD > manifest drift** with `DriftNeedsRepair` instead of interpreting it; **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) | -| Repair uncovered drift | β€” | `omnigraph repair` explicitly classifies uncovered table `HEAD > manifest` drift: verified maintenance drift (`ReserveFragments`/`Rewrite`) can be published with `--confirm`; suspicious or unverifiable drift requires `--force --confirm`. Sidecar-covered crash residuals still recover automatically on open. | +| 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; **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 | @@ -257,7 +252,7 @@ omnigraph policy explain --actor act-alice --action change --branch main | 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 | β€” | 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` β€” the deprecated `ingest_as` shims route through it β€” `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. | +| 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 | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2d77ef0..8d9c687 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,29 +1,10 @@ # Contributing -Thanks for your interest in OmniGraph. This page is the practical how-to; the -rules and decision authority behind it live in [GOVERNANCE.md](GOVERNANCE.md). +Small bug fixes and documentation improvements are welcome directly through pull +requests. -## Start in the right place - -| I want to… | Go to | Notes | -|---|---|---| -| **Report a bug** or wrong behavior | **[Open an Issue](../../issues/new/choose)** | Concrete and reproducible. A maintainer triages it; once labelled **`accepted`** it's open for a PR. | -| **Suggest a feature / share an idea / ask** | **[Start a Discussion](../../discussions)** | Ideas and questions live here, not in Issues. | -| **Propose a design / RFC** | **An RFC pull request** | Anyone can author one β€” see [docs/rfcs/README.md](docs/rfcs/README.md). A maintainer merging it is acceptance. | -| **Fix something / implement a change** | **A pull request** | Must link an `accepted` issue or an accepted RFC β€” unless it's trivial (below). | -| **Report a security vulnerability** | **[SECURITY.md](SECURITY.md)** | Do **not** open a public Issue. | - -### When can I just open a PR? -The **trivial fast-lane** β€” open directly, no prior issue/RFC needed: typo and -wording fixes, doc corrections, dependency bumps, comment fixes, obvious -one-line CI tweaks. Anything more substantial needs a backing `accepted` issue -or accepted RFC first, so the *why* is agreed before the *how* is reviewed. A PR -that turns out to be non-trivial will be redirected β€” that's about process, not -the merit of the change. - -> **Maintainers (ModernRelay team)** follow a separate internal process and are -> not bound by the intake rules above. Everyone is bound by review, CODEOWNERS, -> branch protection, and CI. +For larger changes, please open an issue or design discussion first so the +proposed direction is clear before implementation starts. ## Development @@ -68,11 +49,6 @@ CI runs both. ## Pull Requests -- **Link the backing issue or RFC** (`Closes #123`, or reference the RFC) β€” or - mark the PR as trivial per the fast-lane. -- Keep changes focused; one logical change per PR. -- Include tests for behavior changes when practical. -- Update public docs when the user-facing surface changes. - -New to the codebase? Read [AGENTS.md](AGENTS.md) β€” the architecture map and the -always-on invariants every change is reviewed against. +- keep changes focused +- include tests for behavior changes when practical +- update public docs when the user-facing surface changes diff --git a/Cargo.lock b/Cargo.lock index b1cf0ef..3223b9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4543,14 +4543,13 @@ dependencies = [ [[package]] name = "omnigraph-cli" -version = "0.6.2" +version = "0.6.1" dependencies = [ "assert_cmd", "clap", "color-eyre", "lance", "lance-index", - "omnigraph-cluster", "omnigraph-compiler", "omnigraph-engine", "omnigraph-policy", @@ -4564,27 +4563,9 @@ dependencies = [ "tokio", ] -[[package]] -name = "omnigraph-cluster" -version = "0.6.2" -dependencies = [ - "fail", - "omnigraph-compiler", - "omnigraph-engine", - "serde", - "serde_json", - "serde_yaml", - "sha2", - "tempfile", - "thiserror", - "time", - "tokio", - "ulid", -] - [[package]] name = "omnigraph-compiler" -version = "0.6.2" +version = "0.6.1" dependencies = [ "ahash", "arrow-array", @@ -4605,7 +4586,7 @@ dependencies = [ [[package]] name = "omnigraph-engine" -version = "0.6.2" +version = "0.6.1" dependencies = [ "arc-swap", "arrow-array", @@ -4630,13 +4611,11 @@ dependencies = [ "object_store 0.12.5", "omnigraph-compiler", "omnigraph-policy", - "proptest", "regex", "reqwest", "serde", "serde_json", "serial_test", - "sha2", "tempfile", "thiserror", "time", @@ -4648,7 +4627,7 @@ dependencies = [ [[package]] name = "omnigraph-policy" -version = "0.6.2" +version = "0.6.1" dependencies = [ "cedar-policy", "clap", @@ -4661,7 +4640,7 @@ dependencies = [ [[package]] name = "omnigraph-server" -version = "0.6.2" +version = "0.6.1" dependencies = [ "arc-swap", "async-trait", @@ -4674,7 +4653,6 @@ dependencies = [ "futures", "lance", "lance-index", - "omnigraph-cluster", "omnigraph-compiler", "omnigraph-engine", "omnigraph-policy", @@ -5147,25 +5125,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "proptest" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" -dependencies = [ - "bit-set", - "bit-vec", - "bitflags", - "num-traits", - "rand 0.9.2", - "rand_chacha 0.9.0", - "rand_xorshift", - "regex-syntax", - "rusty-fork", - "tempfile", - "unarray", -] - [[package]] name = "prost" version = "0.14.3" @@ -5227,12 +5186,6 @@ dependencies = [ "cc", ] -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - [[package]] name = "quick-xml" version = "0.37.5" @@ -5404,15 +5357,6 @@ dependencies = [ "rand 0.9.2", ] -[[package]] -name = "rand_xorshift" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" -dependencies = [ - "rand_core 0.9.5", -] - [[package]] name = "rand_xoshiro" version = "0.7.0" @@ -5812,18 +5756,6 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" -[[package]] -name = "rusty-fork" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" -dependencies = [ - "fnv", - "quick-error", - "tempfile", - "wait-timeout", -] - [[package]] name = "ryu" version = "1.0.23" @@ -6811,12 +6743,6 @@ dependencies = [ "web-time", ] -[[package]] -name = "unarray" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" - [[package]] name = "unicase" version = "2.9.0" diff --git a/Cargo.toml b/Cargo.toml index 17990ea..66bfc01 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,6 @@ members = [ "crates/omnigraph-compiler", "crates/omnigraph", "crates/omnigraph-cli", - "crates/omnigraph-cluster", "crates/omnigraph-policy", "crates/omnigraph-server", ] diff --git a/Dockerfile b/Dockerfile index ca22a93..e49a6c7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,13 +11,9 @@ RUN groupadd --system omnigraph \ && useradd --system --gid omnigraph --create-home --home-dir /var/lib/omnigraph omnigraph COPY target/release/omnigraph-server /usr/local/bin/omnigraph-server -# The CLI ships in the image so the cluster day-2 loop (cluster -# apply/approve/status, data loads by explicit URI) runs in-container via -# `docker exec` / ECS exec / `railway shell` β€” no omnigraph.yaml required. -COPY target/release/omnigraph /usr/local/bin/omnigraph COPY docker/entrypoint.sh /usr/local/bin/omnigraph-entrypoint -RUN chmod 0755 /usr/local/bin/omnigraph-server /usr/local/bin/omnigraph /usr/local/bin/omnigraph-entrypoint +RUN chmod 0755 /usr/local/bin/omnigraph-server /usr/local/bin/omnigraph-entrypoint ENV OMNIGRAPH_BIND=0.0.0.0:8080 diff --git a/GOVERNANCE.md b/GOVERNANCE.md deleted file mode 100644 index 5878f1f..0000000 --- a/GOVERNANCE.md +++ /dev/null @@ -1,106 +0,0 @@ -# Governance - -This document describes how **external contributions** to OmniGraph are -proposed, accepted, and merged. It exists so an outside contributor can answer, -without asking: *where does my report/idea/change go, who decides, and what has -to happen before code lands?* - -> **Scope.** This governs the public contribution surface β€” Issues, -> Discussions, RFCs, and pull requests from people outside the ModernRelay -> team. **Maintainers operate under a separate internal process** and are not -> bound by the intake gates below. Everyone, maintainer or not, is still bound -> by the universal gates: branch protection on `main` and CODEOWNERS review -> (see [docs/dev/branch-protection.md](docs/dev/branch-protection.md) and -> [docs/dev/codeowners.md](docs/dev/codeowners.md)). - -## Roles - -| Role | Who | Authority | -|---|---|---| -| **Maintainer** | The code owners in [`.github/CODEOWNERS`](.github/CODEOWNERS) (generated from [`.github/codeowners-roles.yml`](.github/codeowners-roles.yml)) | Validate issues, accept/reject RFCs, review and merge PRs, set direction. Final decision authority. | -| **Contributor** | Anyone else | Report problems (Issues), propose ideas (Discussions), author RFCs, and open pull requests. | - -Decision authority rests with the maintainers. CODEOWNERS is the single source -of truth for who that is; this document does not duplicate the list. - -## The three channels - -Each channel has one job. Using the right one is the first thing we ask of a -contribution. - -| Channel | Purpose | Not for | -|---|---|---| -| **[Issues](../../issues)** | **Report a problem** β€” a bug, a regression, a documented behavior that's wrong. Something concrete and reproducible. | Feature requests, ideas, questions, or design proposals (β†’ Discussions). | -| **[Discussions](../../discussions)** | **Propose and explore** β€” new ideas, feature requests, questions, and the incubation of RFCs. | Bug reports (β†’ Issues). | -| **Pull requests** | **Land a sanctioned change** β€” a fix for a *validated* issue, an *accepted* RFC, or a trivial change (see fast-lane). | Substantive change with no backing issue/RFC β€” it will be redirected. | - -## How a change becomes mergeable - -``` - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ bug ───────────┐ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€ idea / feature ────────┐ - β–Ό β”‚ β–Ό β”‚ - Issue (problem report) β”‚ Discussion (idea / RFC incubation) β”‚ - β”‚ β”‚ β”‚ β”‚ - maintainer triage β”‚ rough consensus β”‚ - β”‚ β”‚ β”‚ graduate β”‚ - β–Ό β”‚ β–Ό β”‚ - label: accepted ──────────┐ β”‚ RFC PR (docs/rfcs/NNNN-*.md) β”‚ - β”‚ β”‚ β”‚ β”‚ β”‚ - β”‚ β”‚ β”‚ maintainer review β”‚ - β–Ό β–Ό β”‚ β–Ό β”‚ - Pull request ◀──────────┴──────────│── merged == accepted β”‚ - (links the issue or the accepted RFC) β—€β”€β”€β”€β”€β”€β”€β”€β”˜ (implementation PRs reference it) β”‚ - β”‚ - review + CODEOWNERS + branch protection - β–Ό - merged -``` - -### Issues β†’ validated -A new issue starts unlabeled. A maintainer triages it and, if it's a real, -in-scope problem, applies the **`accepted`** label. **Only `accepted` issues are -open for a contributor PR.** This prevents the "I fixed an issue you hadn't -agreed was a problem" rejection. Want to fix something? Get the issue accepted -first, or pick one already labelled `accepted` / `help wanted`. - -### Discussions β†’ RFCs β†’ accepted -Ideas and feature requests start in **Discussions**. Anyone β€” including external -contributors β€” may then **author an RFC** by opening a pull request that adds -`docs/rfcs/NNNN-title.md` (see [docs/rfcs/README.md](docs/rfcs/README.md)). The -RFC is reviewed as code; **a maintainer merging it is the act of acceptance** -(it becomes the durable decision record). Implementation PRs then reference the -accepted RFC. - -Authoring an RFC is open to everyone; **accepting one is a maintainer -decision.** Maintainers may also decline an RFC, with rationale, by closing it. - -### Pull requests β†’ sanctioned -A contributor PR must do one of: -1. link a maintainer-**`accepted`** issue it fixes, or -2. be (or reference) an **accepted RFC**, or -3. qualify for the **trivial fast-lane**. - -**Trivial fast-lane** β€” these may be opened directly, no prior issue/RFC: -typo and wording fixes, documentation corrections, dependency bumps, comment -fixes, and obviously-correct one-line CI tweaks. When in doubt, open an Issue or -Discussion first; a PR that turns out to be non-trivial will be asked to. - -A substantive PR with no backing issue/RFC will be closed with a pointer to the -right channel β€” not as a judgment of the idea, but to keep design discussion -where it's reviewable. - -## What maintainers do *not* gate -Maintainers' own changes do not pass through the intake gates above β€” the team -runs a separate internal process. The universal gates (review, CODEOWNERS, -branch protection, CI) apply to everyone. Enforcement of the intake rules is, to -start, **by convention and review** (PR template + labels); an automated check -keyed to author association may be added later if volume warrants. - -## Code of conduct & security -- Conduct: [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). -- Security issues are **not** public Issues β€” see [SECURITY.md](SECURITY.md). - -## Changing this document -Governance changes the same way code does: a pull request, reviewed by -maintainers. This file describes the external surface; the internal maintainer -process is intentionally out of scope here. diff --git a/README.md b/README.md index a75a839..0f6ebea 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ 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, data loading, commits, and policy commands. +See [docs/user/cli.md](docs/user/cli.md) for schema apply, snapshots, ingest, commits, and policy commands. ## Clients @@ -132,7 +132,7 @@ 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 graph lifecycle (init/load), query/mutate, branch/commit/merge, schema/lint, snapshot/export, policy, and maintenance (optimize/cleanup) +- `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 901d69c..641068e 100644 --- a/crates/omnigraph-cli/Cargo.toml +++ b/crates/omnigraph-cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-cli" -version = "0.6.2" +version = "0.6.1" edition = "2024" description = "CLI for the Omnigraph graph database." license = "MIT" @@ -13,11 +13,10 @@ name = "omnigraph" path = "src/main.rs" [dependencies] -omnigraph = { package = "omnigraph-engine", path = "../omnigraph", version = "0.6.2" } -omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.2" } -omnigraph-cluster = { path = "../omnigraph-cluster", version = "0.6.2" } -omnigraph-policy = { path = "../omnigraph-policy", version = "0.6.2" } -omnigraph-server = { path = "../omnigraph-server", version = "0.6.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/cli.rs b/crates/omnigraph-cli/src/cli.rs deleted file mode 100644 index 7b976b4..0000000 --- a/crates/omnigraph-cli/src/cli.rs +++ /dev/null @@ -1,706 +0,0 @@ -//! The clap surface: every command, subcommand, and argument struct -//! (moved verbatim from main.rs in the modularization). - -use super::*; - -pub(crate) const DEFAULT_BEARER_TOKEN_ENV: &str = "OMNIGRAPH_BEARER_TOKEN"; - -#[derive(Debug, Parser)] -#[command(name = "omnigraph")] -#[command(about = "Omnigraph graph database CLI")] -#[command(version = env!("CARGO_PKG_VERSION"), disable_version_flag = true)] -pub(crate) struct Cli { - /// Actor identity for direct-engine writes (MR-722). Overrides - /// `cli.actor` from `omnigraph.yaml`. When the configured policy - /// is in effect, Cedar evaluates this actor against the requested - /// action and scope; with policy configured but neither this flag - /// nor `cli.actor` set, the engine-layer footgun guard fires and - /// the write is denied (no silent bypass). Has no effect on remote - /// HTTP writes β€” those resolve their actor server-side from the - /// bearer token. - #[arg(long = "as", global = true, value_name = "ACTOR")] - pub(crate) as_actor: Option, - - /// Target an operator-defined server by name (RFC-007): resolves to - /// its `url` from `servers:` in ~/.omnigraph/config.yaml. Exclusive - /// with a positional URI or `--target`. - #[arg(long, global = true, value_name = "NAME")] - pub(crate) server: Option, - - /// Graph id on a multi-graph `--server` (appends `/graphs/` to - /// the server url). Requires --server. - #[arg(long, global = true, value_name = "GRAPH_ID", requires = "server")] - pub(crate) graph: Option, - - #[command(subcommand)] - pub(crate) command: Command, -} - -#[derive(Debug, Subcommand)] -pub(crate) enum Command { - /// Print the CLI version - Version, - /// Store a bearer token for a named server in ~/.omnigraph/credentials - /// (0600). Token from --token or one line on stdin: - /// `echo $TOKEN | omnigraph login prod`. The keyed token applies to - /// requests whose URL matches the server's `url` in the operator - /// config's `servers:` map. - Login { - /// Server name (keys the credential; declare its url under - /// `servers:` in ~/.omnigraph/config.yaml) - name: String, - /// The token. Prefer piping via stdin over this flag (shell - /// history). - #[arg(long)] - token: Option, - #[arg(long)] - json: bool, - }, - /// Legacy-config tooling (RFC-008): split omnigraph.yaml into its - /// two destinations. - Config { - #[command(subcommand)] - command: ConfigCommand, - }, - /// Remove a named server's stored credential. Idempotent. - Logout { - name: String, - #[arg(long)] - json: bool, - }, - /// Generate, clean, or refresh explicit seed embeddings - Embed(EmbedArgs), - /// Initialize a new graph from a schema - Init { - #[arg(long)] - schema: PathBuf, - /// 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 graph (local or remote) - Load { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - data: PathBuf, - /// Target branch (defaults to main). Without --from it must exist. - #[arg(long)] - branch: Option, - /// Base branch to fork --branch from when it doesn't exist yet. - /// Without this flag a missing branch is an error, never a fork. - #[arg(long)] - from: Option, - /// How existing rows are handled: overwrite | append | merge. - /// Required β€” overwrite is destructive, so there is no default. - #[arg(long)] - mode: CliLoadMode, - #[arg(long)] - json: bool, - }, - /// Deprecated alias of `load --from ` (defaults: --mode merge, --from main) - Ingest { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - data: PathBuf, - #[arg(long)] - branch: Option, - #[arg(long)] - from: Option, - #[arg(long, default_value = "merge")] - mode: CliLoadMode, - #[arg(long)] - json: bool, - }, - /// Branch operations - Branch { - #[command(subcommand)] - command: BranchCommand, - }, - /// Schema planning operations - Schema { - #[command(subcommand)] - command: SchemaCommand, - }, - /// 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, - }, - /// Operate on the server-side stored-query registry (`queries:`). - Queries { - #[command(subcommand)] - command: QueriesCommand, - }, - /// Show graph snapshot - Snapshot { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - branch: Option, - #[arg(long)] - json: bool, - }, - /// Export a full graph snapshot as JSONL - Export { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - branch: Option, - #[arg(long, hide = true)] - jsonl: bool, - #[arg(long = "type")] - type_names: Vec, - #[arg(long = "table")] - table_keys: Vec, - }, - /// Commit history operations - Commit { - #[command(subcommand)] - command: CommitCommand, - }, - /// 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)] - legacy_uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long, conflicts_with_all = ["query", "query_string"])] - alias: Option, - #[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)] - params: ParamsArgs, - #[arg(long, conflicts_with = "snapshot")] - branch: Option, - #[arg(long, conflicts_with = "branch")] - snapshot: Option, - #[arg(long, conflicts_with = "json")] - format: Option, - #[arg(long, conflicts_with = "format")] - json: bool, - #[arg()] - alias_args: Vec, - }, - /// 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)] - legacy_uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long, conflicts_with_all = ["query", "query_string"])] - alias: Option, - #[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)] - params: ParamsArgs, - #[arg(long)] - branch: Option, - #[arg(long)] - json: bool, - #[arg()] - alias_args: Vec, - }, - /// Policy administration and diagnostics - Policy { - #[command(subcommand)] - command: PolicyCommand, - }, - /// Compact small Lance fragments in every table of the graph - Optimize { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - json: bool, - }, - /// Classify and explicitly repair manifest/head drift - Repair { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - /// Publish verified maintenance drift. Without this flag, repair only - /// previews what it would do. - #[arg(long)] - confirm: bool, - /// Also publish suspicious or unverifiable drift. Requires - /// `--confirm`; use only after operator review. - #[arg(long, requires = "confirm")] - force: bool, - #[arg(long)] - json: bool, - }, - /// Remove old Lance versions from every table of the graph (destructive) - Cleanup { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - /// Number of recent versions to keep per table. Either `--keep` or - /// `--older-than` (or both) must be set. - #[arg(long)] - keep: Option, - /// Only remove versions older than this duration. Accepts Go-style - /// durations: `7d`, `24h`, `90m`. At least one of --keep / --older-than. - #[arg(long)] - older_than: Option, - /// Required to actually run; without it, prints what would be removed - #[arg(long)] - confirm: bool, - #[arg(long)] - json: bool, - }, - /// Validate and plan read-only cluster configuration. - Cluster { - #[command(subcommand)] - command: ClusterCommand, - }, - /// Manage graphs on a multi-graph server (MR-668) - Graphs { - #[command(subcommand)] - command: GraphsCommand, - }, -} - -#[derive(Debug, Subcommand)] -pub(crate) enum ClusterCommand { - /// Validate cluster.yaml and referenced schemas, queries, and policy files. - Validate { - /// Cluster config directory containing cluster.yaml. - #[arg(long, default_value = ".")] - config: PathBuf, - /// Emit JSON instead of human text. - #[arg(long)] - json: bool, - }, - /// Produce a read-only plan by diffing cluster.yaml against __cluster/state.json. - Plan { - /// Cluster config directory containing cluster.yaml. - #[arg(long, default_value = ".")] - config: PathBuf, - /// Emit JSON instead of human text. - #[arg(long)] - json: bool, - }, - /// Apply the config-only (query/policy) subset of the plan to the local - /// cluster catalog. Graph/schema changes are deferred to a later stage. - Apply { - /// Cluster config directory containing cluster.yaml. - #[arg(long, default_value = ".")] - config: PathBuf, - /// Emit JSON instead of human text. - #[arg(long)] - json: bool, - }, - /// Record a digest-bound approval for a gated (irreversible) change, - /// e.g. a graph delete. Requires the global --as actor. - Approve { - /// Typed resource address of the gated change (e.g. graph.scratch). - resource: String, - /// Cluster config directory containing cluster.yaml. - #[arg(long, default_value = ".")] - config: PathBuf, - /// Emit JSON instead of human text. - #[arg(long)] - json: bool, - }, - /// Read the local JSON state ledger without scanning live graph resources. - Status { - /// Cluster config directory containing cluster.yaml. - #[arg(long, default_value = ".")] - config: PathBuf, - /// Emit JSON instead of human text. - #[arg(long)] - json: bool, - }, - /// Refresh existing local JSON state from declared graph observations. - Refresh { - /// Cluster config directory containing cluster.yaml. - #[arg(long, default_value = ".")] - config: PathBuf, - /// Emit JSON instead of human text. - #[arg(long)] - json: bool, - }, - /// Import initial local JSON state from declared graph observations. - Import { - /// Cluster config directory containing cluster.yaml. - #[arg(long, default_value = ".")] - config: PathBuf, - /// Emit JSON instead of human text. - #[arg(long)] - json: bool, - }, - /// Remove a held local JSON state lock after operator confirmation. - ForceUnlock { - /// Exact lock id from cluster status or a state_lock_held diagnostic. - lock_id: String, - /// Cluster config directory containing cluster.yaml. - #[arg(long, default_value = ".")] - config: PathBuf, - /// Emit JSON instead of human text. - #[arg(long)] - json: bool, - }, -} - -/// 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)] -pub(crate) 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)] -pub(crate) enum BranchCommand { - /// Create a new branch - Create { - /// Graph URI - #[arg(long)] - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - from: Option, - name: String, - #[arg(long)] - json: bool, - }, - /// List branches - List { - /// Graph URI - #[arg(long)] - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - json: bool, - }, - /// Delete a branch - Delete { - /// Graph URI - #[arg(long)] - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - name: String, - #[arg(long)] - json: bool, - }, - /// Merge a source branch into a target branch - Merge { - /// Graph URI - #[arg(long)] - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - source: String, - #[arg(long)] - into: Option, - #[arg(long)] - json: bool, - }, -} - -#[derive(Debug, Subcommand)] -pub(crate) enum SchemaCommand { - /// Plan a schema migration against the accepted persisted schema - Plan { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - schema: PathBuf, - #[arg(long)] - json: bool, - /// Show the plan as it would execute with `--allow-data-loss`. - /// Promotes every `DropMode::Soft` step to `DropMode::Hard` - /// so the plan output reflects the destructive intent. - #[arg(long, default_value_t = false)] - allow_data_loss: bool, - }, - /// Apply a supported schema migration - Apply { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - schema: PathBuf, - #[arg(long)] - json: bool, - /// Allow destructive (data-loss) schema changes. - /// - /// Without this flag, drops are "soft": the column or table - /// is removed from the current manifest version but prior - /// versions are retained, so `snapshot_at_version(pre_drop)` - /// can still read the dropped data until `omnigraph cleanup` - /// runs. With this flag, drops are "hard": `cleanup_old_versions` - /// runs on the affected datasets immediately after the apply, - /// making the prior data unreachable. - #[arg(long, default_value_t = false)] - allow_data_loss: bool, - }, - /// Show the current accepted schema source - #[command(alias = "get")] - Show { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - json: bool, - }, -} - -#[derive(Debug, Subcommand)] - -pub(crate) enum CommitCommand { - /// List graph commits - List { - /// Graph URI - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - #[arg(long)] - branch: Option, - #[arg(long)] - json: bool, - }, - /// Show a graph commit - Show { - /// Graph URI - #[arg(long)] - uri: Option, - #[arg(long)] - target: Option, - #[arg(long)] - config: Option, - commit_id: String, - #[arg(long)] - json: bool, - }, -} - -#[derive(Debug, Subcommand)] -pub(crate) enum PolicyCommand { - /// Validate policy YAML and compiled Cedar policy state - Validate { - #[arg(long)] - config: Option, - }, - /// Run declarative policy tests from policy.tests.yaml - Test { - #[arg(long)] - config: Option, - }, - /// Explain one policy decision locally - Explain { - #[arg(long)] - config: Option, - #[arg(long)] - actor: String, - #[arg(long)] - action: PolicyAction, - #[arg(long)] - branch: Option, - #[arg(long = "target-branch")] - target_branch: Option, - }, -} - -#[derive(Debug, Subcommand)] -pub(crate) 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)] -pub(crate) struct ParamsArgs { - #[arg(long, conflicts_with = "params_file")] - pub(crate) params: Option, - #[arg(long, conflicts_with = "params")] - pub(crate) params_file: Option, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, ValueEnum)] -#[serde(rename_all = "snake_case")] -pub(crate) enum CliLoadMode { - Overwrite, - Append, - Merge, -} - -impl From for LoadMode { - fn from(value: CliLoadMode) -> Self { - match value { - CliLoadMode::Overwrite => LoadMode::Overwrite, - CliLoadMode::Append => LoadMode::Append, - CliLoadMode::Merge => LoadMode::Merge, - } - } -} - -impl CliLoadMode { - pub(crate) fn as_str(self) -> &'static str { - match self { - CliLoadMode::Overwrite => "overwrite", - CliLoadMode::Append => "append", - CliLoadMode::Merge => "merge", - } - } -} - -#[derive(Debug, Subcommand)] -pub(crate) enum ConfigCommand { - /// Propose (and with --write, apply) the RFC-008 split of a legacy - /// omnigraph.yaml: team half -> a ready-to-review cluster.yaml, - /// personal half -> ~/.omnigraph/config.yaml (key-level merge, - /// existing entries always win). Touches nothing without --write. - Migrate { - /// Path to the legacy omnigraph.yaml (default: ./omnigraph.yaml) - #[arg(long)] - config: Option, - /// Apply the split instead of only printing it - #[arg(long)] - write: bool, - #[arg(long)] - json: bool, - }, -} diff --git a/crates/omnigraph-cli/src/helpers.rs b/crates/omnigraph-cli/src/helpers.rs deleted file mode 100644 index 67fb6ea..0000000 --- a/crates/omnigraph-cli/src/helpers.rs +++ /dev/null @@ -1,1187 +0,0 @@ -//! Resolution helpers: config/actor/graph/branch/query resolution, -//! remote HTTP, env/token handling, scaffolding (moved verbatim from -//! main.rs in the modularization). - -use super::*; -use crate::operator; - -pub(crate) fn ensure_local_graph_parent(uri: &str) -> Result<()> { - if !uri.contains("://") { - fs::create_dir_all(uri)?; - } - Ok(()) -} - -pub(crate) fn is_remote_uri(uri: &str) -> bool { - uri.starts_with("http://") || uri.starts_with("https://") -} - -pub(crate) fn remote_url(base: &str, path: &str) -> String { - format!("{}{}", base.trim_end_matches('/'), path) -} - -pub(crate) fn remote_branch_url(base: &str, branch: &str) -> Result { - let mut url = reqwest::Url::parse(&format!("{}/", base.trim_end_matches('/')))?; - url.path_segments_mut() - .map_err(|_| color_eyre::eyre::eyre!("invalid remote base url"))? - .extend(["branches", branch]); - Ok(url.to_string()) -} - -pub(crate) fn normalize_bearer_token(value: Option) -> Option { - value - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) -} - -pub(crate) fn bearer_token_from_env(var_name: &str) -> Option { - normalize_bearer_token(std::env::var(var_name).ok()) -} - -pub(crate) fn parse_env_assignment(line: &str) -> Option<(String, String)> { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - return None; - } - - let line = line.strip_prefix("export ").unwrap_or(line).trim(); - let (name, value) = line.split_once('=')?; - let name = name.trim(); - if name.is_empty() { - return None; - } - - let value = value.trim(); - let value = if value.len() >= 2 - && ((value.starts_with('"') && value.ends_with('"')) - || (value.starts_with('\'') && value.ends_with('\''))) - { - &value[1..value.len() - 1] - } else { - value - }; - - Some((name.to_string(), value.to_string())) -} - -pub(crate) fn bearer_token_from_env_file(path: &Path, var_name: &str) -> Result> { - if !path.exists() { - return Ok(None); - } - - for line in fs::read_to_string(path)?.lines() { - let Some((name, value)) = parse_env_assignment(line) else { - continue; - }; - if name == var_name { - return Ok(normalize_bearer_token(Some(value))); - } - } - - Ok(None) -} - -pub(crate) fn load_env_file_into_process(path: &Path) -> Result<()> { - if !path.exists() { - return Ok(()); - } - - for line in fs::read_to_string(path)?.lines() { - let Some((name, value)) = parse_env_assignment(line) else { - continue; - }; - if std::env::var_os(&name).is_none() { - unsafe { - std::env::set_var(name, value); - } - } - } - - Ok(()) -} - -pub(crate) fn load_cli_config(config_path: Option<&PathBuf>) -> Result { - let config = load_config(config_path)?; - if let Some(path) = config.resolve_auth_env_file() { - load_env_file_into_process(&path)?; - } - Ok(config) -} - -#[derive(Debug, Clone)] -pub(crate) struct ResolvedCliGraph { - pub(crate) uri: String, - pub(crate) selected: Option, - pub(crate) graph_id: String, - pub(crate) policy_file: Option, - pub(crate) is_remote: bool, -} - -impl ResolvedCliGraph { - pub(crate) fn selected(&self) -> Option<&str> { - self.selected.as_deref() - } -} - -pub(crate) struct ResolvedPolicyContext { - pub(crate) policy_file: PathBuf, - pub(crate) graph_id: String, -} - -pub(crate) 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, - }) -} - -pub(crate) fn resolve_policy_engine(context: &ResolvedPolicyContext) -> Result { - PolicyEngine::load_graph(&context.policy_file, &context.graph_id) -} - -pub(crate) 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) -} - -pub(crate) 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) - } -} - -/// THE actor chain (RFC-007 Β§D3) β€” every command that needs an identity -/// resolves through this one function (one path per concern): -/// `--as` > legacy `cli.actor` in omnigraph.yaml (RFC-008 window) > -/// `operator.actor` in ~/.omnigraph/config.yaml > none. -pub(crate) fn resolve_actor( - cli_as: Option<&str>, - legacy_config_actor: Option<&str>, -) -> Result> { - if let Some(actor) = cli_as { - return Ok(Some(actor.to_string())); - } - if let Some(actor) = legacy_config_actor { - return Ok(Some(actor.to_string())); - } - Ok(operator::load_operator_config()? - .actor() - .map(str::to_string)) -} - -pub(crate) fn resolve_cluster_actor(cli_as: Option<&str>) -> Result> { - if let Some(actor) = cli_as { - return Ok(Some(actor.to_string())); - } - let config = load_config(None).wrap_err( - "resolving the default actor from omnigraph.yaml (pass --as to skip this lookup)", - )?; - resolve_actor(None, config.cli.actor.as_deref()) -} - -pub(crate) fn resolve_cli_actor( - cli_as: Option<&str>, - config: &OmnigraphConfig, -) -> Result> { - resolve_actor(cli_as, config.cli.actor.as_deref()) -} - -pub(crate) fn resolve_policy_tests_path(context: &ResolvedPolicyContext) -> PathBuf { - context.policy_file.with_file_name("policy.tests.yaml") -} - -pub(crate) 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)?) - } -} - -pub(crate) fn resolve_remote_bearer_token( - config: &OmnigraphConfig, - explicit_uri: Option<&str>, - explicit_target: Option<&str>, -) -> Result> { - // The keyed hop (RFC-007 Β§D4, gh-host model): when the effective remote - // URL belongs to an operator-defined server, that server's keyed chain - // applies first β€” OMNIGRAPH_TOKEN_ env, then the 0600 credentials - // file. Ok(None) falls through to the legacy chain unchanged, and the - // keyed token is structurally scoped to its own server (Β§D5 rule 3): - // a URL matching no operator server never sees it. - if let Some(remote_url) = effective_remote_url(config, explicit_uri, explicit_target) { - let operator_config = operator::load_operator_config()?; - if let Some(server) = operator_config.find_server_for_url(&remote_url) { - if let Some(token) = operator::resolve_keyed_token(server)? { - return Ok(Some(token)); - } - } - } - - let scoped_env = - config.graph_bearer_token_env(explicit_uri, explicit_target, config.cli_graph_name()); - let mut env_names = Vec::new(); - if let Some(name) = scoped_env { - env_names.push(name.to_string()); - } - if env_names - .iter() - .all(|name| name != DEFAULT_BEARER_TOKEN_ENV) - { - env_names.push(DEFAULT_BEARER_TOKEN_ENV.to_string()); - } - - let env_file = config.resolve_auth_env_file(); - for env_name in env_names { - if let Some(token) = bearer_token_from_env(&env_name) { - return Ok(Some(token)); - } - if let Some(path) = env_file.as_ref() { - if let Some(token) = bearer_token_from_env_file(path, &env_name)? { - return Ok(Some(token)); - } - } - } - - Ok(None) -} - -/// `--server ` (RFC-007 PR 3): resolve an operator-defined server -/// name (+ optional `--graph` for multi-graph servers) to the effective -/// remote URI. The result feeds the ordinary `uri` slot, so graph -/// resolution and the keyed-token URL match work unchanged β€” the flag is -/// sugar for a URI the operator already owns. Unknown names fail loudly, -/// listing what IS defined. -pub(crate) fn resolve_server_flag( - server: Option<&str>, - graph: Option<&str>, -) -> Result> { - let Some(server) = server else { - return Ok(None); - }; - let operator_config = operator::load_operator_config()?; - let Some(entry) = operator_config.servers.get(server) else { - let known = operator_config - .servers - .keys() - .map(String::as_str) - .collect::>() - .join(", "); - color_eyre::eyre::bail!( - "unknown server '{server}' β€” servers defined in the operator config: [{known}] (add it under servers: in ~/.omnigraph/config.yaml)" - ); - }; - let base = entry.url.trim_end_matches('/'); - Ok(Some(match graph { - Some(graph) => format!("{base}/graphs/{graph}"), - None => base.to_string(), - })) -} - -/// Execute an OPERATOR alias (RFC-007 PR 3): a pure binding invoking a -/// stored query by name on a named server β€” POST {base}/queries/{name}. -/// Param precedence: --params > positional args > the alias's fixed -/// params. The keyed token applies via the ordinary URL match. -pub(crate) async fn execute_operator_alias( - client: &reqwest::Client, - config: &OmnigraphConfig, - alias_name: &str, - alias: &crate::operator::OperatorAlias, - alias_args: &[String], - explicit_params: Option, -) -> Result { - let uri = resolve_server_flag(Some(&alias.server), alias.graph.as_deref())? - .expect("server name is present"); - let bearer_token = resolve_remote_bearer_token(config, Some(&uri), None)?; - - let mut params = serde_json::Map::new(); - for (key, value) in &alias.params { - let Some(key) = key.as_str() else { - bail!("alias '{alias_name}': params keys must be strings"); - }; - params.insert(key.to_string(), serde_json::to_value(value)?); - } - if alias_args.len() > alias.args.len() { - bail!( - "alias '{alias_name}' takes {} positional arg(s) ({}), got {}", - alias.args.len(), - alias.args.join(", "), - alias_args.len() - ); - } - for (name, value) in alias.args.iter().zip(alias_args) { - params.insert(name.clone(), parse_alias_value(value)); - } - if let Some(Value::Object(explicit)) = explicit_params { - for (key, value) in explicit { - params.insert(key, value); - } - } - - let body = (!params.is_empty()).then(|| serde_json::json!({ "params": params })); - remote_json( - client, - Method::POST, - remote_url(&uri, &format!("/queries/{}", alias.query)), - body, - bearer_token.as_deref(), - ) - .await -} - -/// Apply `--server`/`--graph` to a command's uri/target slots: exclusive -/// with both (loud error, not silent precedence), no-op when absent. -pub(crate) fn apply_server_flag( - server: Option<&str>, - graph: Option<&str>, - uri: Option, - target: Option<&str>, -) -> Result> { - if server.is_none() { - return Ok(uri); - } - if uri.is_some() || target.is_some() { - color_eyre::eyre::bail!( - "--server is exclusive with a positional URI and --target β€” pick one way to address the graph" - ); - } - resolve_server_flag(server, graph) -} - -/// The remote base URL a token resolution is FOR β€” the same scoping -/// `graph_bearer_token_env` uses: an explicit http(s) `--uri` wins, else -/// the config-resolved target's uri (when remote). Local URIs β†’ None. -fn effective_remote_url( - config: &OmnigraphConfig, - explicit_uri: Option<&str>, - explicit_target: Option<&str>, -) -> Option { - if let Some(uri) = explicit_uri { - return is_remote_uri(uri).then(|| uri.to_string()); - } - let target = config.resolve_target_name(explicit_uri, explicit_target, config.cli_graph_name())?; - let uri = &config.graphs.get(target)?.uri; - is_remote_uri(uri).then(|| uri.clone()) -} - -pub(crate) fn build_http_client() -> Result { - Ok(reqwest::Client::new()) -} - -pub(crate) fn apply_bearer_token( - request: reqwest::RequestBuilder, - token: Option<&str>, -) -> reqwest::RequestBuilder { - if let Some(token) = token { - request.header(AUTHORIZATION, format!("Bearer {}", token)) - } else { - request - } -} - -pub(crate) async fn remote_json( - client: &reqwest::Client, - method: Method, - url: String, - body: Option, - bearer_token: Option<&str>, -) -> Result { - let request = apply_bearer_token(client.request(method, url), bearer_token); - let request = if let Some(body) = body { - request.json(&body) - } else { - request - }; - let response = request.send().await?; - let status = response.status(); - let text = response.text().await?; - if !status.is_success() { - if let Ok(error) = serde_json::from_str::(&text) { - bail!(error.error); - } - bail!("server returned {}: {}", status, text); - } - Ok(serde_json::from_str(&text)?) -} - -pub(crate) fn resolve_uri( - config: &OmnigraphConfig, - cli_uri: Option, - cli_target: Option<&str>, -) -> Result { - config.resolve_target_uri(cli_uri, cli_target, config.cli_graph_name()) -} - -pub(crate) 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, - }) -} - -pub(crate) 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) -} - -pub(crate) fn parse_duration_arg(s: &str) -> Result { - let s = s.trim(); - 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..], - ), - None => (s, ""), - }; - let n: u64 = num_part - .parse() - .map_err(|e| color_eyre::eyre::eyre!("invalid duration '{}': {}", s, e))?; - let secs = match unit { - "" | "s" => n, - "m" => n * 60, - "h" => n * 60 * 60, - "d" => n * 60 * 60 * 24, - "w" => n * 60 * 60 * 24 * 7, - _ => bail!("unknown duration unit '{}'. Supported: s, m, h, d, w", unit), - }; - Ok(std::time::Duration::from_secs(secs)) -} - -pub(crate) fn resolve_local_uri( - config: &OmnigraphConfig, - cli_uri: Option, - cli_target: Option<&str>, - operation: &str, -) -> Result { - Ok(resolve_local_graph(config, cli_uri, cli_target, operation)?.uri) -} - -pub(crate) fn resolve_branch( - config: &OmnigraphConfig, - cli_branch: Option, - alias_branch: Option, - default_branch: &str, -) -> String { - cli_branch - .or(alias_branch) - .or_else(|| config.cli.branch.clone()) - .unwrap_or_else(|| default_branch.to_string()) -} - -pub(crate) fn resolve_read_target( - config: &OmnigraphConfig, - cli_branch: Option, - cli_snapshot: Option, - alias_branch: Option, -) -> Result { - if cli_branch.is_some() && cli_snapshot.is_some() { - bail!("read target may specify branch or snapshot, not both"); - } - Ok(read_target_from_cli( - cli_branch - .or(alias_branch) - .or_else(|| config.cli.branch.clone()), - cli_snapshot, - )) -} - -pub(crate) fn resolve_query_path( - config: &OmnigraphConfig, - explicit_query: Option<&PathBuf>, - alias_query: Option<&str>, -) -> Result { - explicit_query - .map(PathBuf::from) - .or_else(|| alias_query.map(PathBuf::from)) - .ok_or_else(|| { - 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)) -} - -pub(crate) 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, - alias_query, - )?)?) -} - -pub(crate) fn parse_alias_value(value: &str) -> Value { - serde_json::from_str(value).unwrap_or_else(|_| Value::String(value.to_string())) -} - -pub(crate) fn merged_params_json( - alias_name: Option<&str>, - alias_arg_names: &[String], - alias_arg_values: &[String], - explicit: Option, -) -> Result> { - if alias_arg_values.len() > alias_arg_names.len() { - let alias = alias_name.unwrap_or(""); - bail!( - "alias '{}' expects at most {} args but got {}", - alias, - alias_arg_names.len(), - alias_arg_values.len() - ); - } - - let mut merged = serde_json::Map::new(); - for (arg_name, arg_value) in alias_arg_names.iter().zip(alias_arg_values.iter()) { - merged.insert(arg_name.clone(), parse_alias_value(arg_value)); - } - - match explicit { - Some(Value::Object(object)) => { - for (key, value) in object { - merged.insert(key, value); - } - } - Some(_) => bail!("params JSON must be an object"), - None => {} - } - - if merged.is_empty() { - Ok(None) - } else { - Ok(Some(Value::Object(merged))) - } -} - -/// The format cascade (RFC-007 Β§D3): `--json` > `--format` > alias format > -/// legacy `cli.output_format` (RFC-008 window) > operator `defaults.output` -/// > table. -pub(crate) fn resolve_read_format( - config: &OmnigraphConfig, - cli_format: Option, - json: bool, - alias_format: Option, -) -> ReadOutputFormat { - if json { - return ReadOutputFormat::Json; - } - cli_format - .or(alias_format) - .or(config.cli.output_format) - .or_else(|| { - operator::load_operator_config() - .ok() - .and_then(|operator| operator.output()) - }) - .unwrap_or_default() -} - -pub(crate) fn resolve_alias<'a>( - config: &'a OmnigraphConfig, - alias_name: Option<&'a str>, - expected: AliasCommand, -) -> Result> { - let Some(alias_name) = alias_name else { - return Ok(None); - }; - let alias = config.alias(alias_name)?; - if alias.command != expected { - bail!( - "alias '{}' is a {:?} alias, not a {:?} alias", - alias_name, - alias.command, - expected - ); - } - Ok(Some((alias_name, alias))) -} - -pub(crate) fn normalize_legacy_alias_uri( - uri: Option, - target_available: bool, - alias_name: Option<&str>, - mut alias_args: Vec, -) -> (Option, Vec) { - let Some(candidate) = uri else { - return (None, alias_args); - }; - - if alias_name.is_some() && target_available { - alias_args.insert(0, candidate); - return (None, alias_args); - } - - (Some(candidate), alias_args) -} - - -pub(crate) fn inferred_config_path(uri: &str) -> Result { - if uri.contains("://") { - return Ok(omnigraph_server::config::default_config_path()); - } - - let path = Path::new(uri); - let base = if path.is_absolute() { - path.parent() - .map(Path::to_path_buf) - .unwrap_or(std::env::current_dir()?) - } else { - std::env::current_dir()?.join(path.parent().unwrap_or_else(|| Path::new("."))) - }; - Ok(base.join(omnigraph_server::config::DEFAULT_CONFIG_FILE)) -} - -pub(crate) fn read_target_from_cli(branch: Option, snapshot: Option) -> ReadTarget { - if let Some(snapshot) = snapshot { - ReadTarget::snapshot(SnapshotId::new(snapshot)) - } else { - ReadTarget::branch(branch.unwrap_or_else(|| "main".to_string())) - } -} - -pub(crate) fn load_params_json(params: &ParamsArgs) -> Result> { - match (¶ms.params, ¶ms.params_file) { - (Some(inline), None) => Ok(Some(serde_json::from_str(inline)?)), - (None, Some(path)) => Ok(Some(serde_json::from_str(&fs::read_to_string(path)?)?)), - (None, None) => Ok(None), - (Some(_), Some(_)) => bail!("only one of --params or --params-file may be provided"), - } -} - -pub(crate) fn select_named_query( - query_source: &str, - requested_name: Option<&str>, -) -> Result<(String, Vec)> { - let parsed = parse_query(query_source)?; - let query = if let Some(name) = requested_name { - parsed - .queries - .into_iter() - .find(|query| query.name == name) - .ok_or_else(|| color_eyre::eyre::eyre!("query '{}' not found", name))? - } else if parsed.queries.len() == 1 { - parsed.queries.into_iter().next().unwrap() - } else { - bail!("query file contains multiple queries; pass --name"); - }; - - Ok((query.name, query.params)) -} - -pub(crate) fn query_params_from_json( - query_params: &[omnigraph_compiler::query::ast::Param], - params_json: Option<&Value>, -) -> Result { - json_params_to_param_map(params_json, query_params, JsonParamMode::Standard) - .map_err(|err| color_eyre::eyre::eyre!(err.to_string())) -} - -pub(crate) async fn execute_query_lint( - config: &OmnigraphConfig, - cli_uri: Option, - cli_target: Option<&str>, - schema_path: Option<&PathBuf>, - query_path: &PathBuf, -) -> Result { - let resolved_query_path = resolve_query_path(config, Some(query_path), None)?; - let query_source = fs::read_to_string(&resolved_query_path)?; - let query_path = resolved_query_path.to_string_lossy().into_owned(); - - if let Some(schema_path) = schema_path { - let schema_source = fs::read_to_string(schema_path)?; - let schema = - parse_schema(&schema_source).map_err(|err| color_eyre::eyre::eyre!(err.to_string()))?; - let catalog = - build_catalog(&schema).map_err(|err| color_eyre::eyre::eyre!(err.to_string()))?; - return Ok(lint_query_file( - &catalog, - &query_source, - query_path, - QueryLintSchemaSource::file(schema_path.to_string_lossy().into_owned()), - )); - } - - let has_graph_target = - cli_uri.is_some() || cli_target.is_some() || config.cli_graph_name().is_some(); - 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")?; - let db = Omnigraph::open(&uri).await?; - Ok(lint_query_file( - &db.catalog(), - &query_source, - query_path, - QueryLintSchemaSource::graph(uri), - )) -} - -pub(crate) 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)) -} - -pub(crate) 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 ") - ) - }) -} - -pub(crate) 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() -} - -pub(crate) 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], - ) -} - -pub(crate) 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(()) -} - -pub(crate) 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(()) -} - -pub(crate) 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(()) -} - -pub(crate) async fn execute_read( - uri: &str, - query_source: &str, - query_name: Option<&str>, - target: ReadTarget, - params_json: Option<&Value>, -) -> 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 = Omnigraph::open(uri).await?; - let result = db - .query(target.clone(), query_source, &selected_name, ¶ms) - .await?; - Ok(read_output(selected_name, &target, result)) -} - -pub(crate) async fn execute_read_remote( - client: &reqwest::Client, - uri: &str, - query_source: &str, - query_name: Option<&str>, - target: ReadTarget, - params_json: Option<&Value>, - bearer_token: Option<&str>, -) -> Result { - let (branch, snapshot) = match &target { - ReadTarget::Branch(branch) => (Some(branch.clone()), None), - ReadTarget::Snapshot(snapshot) => (None, Some(snapshot.as_str().to_string())), - }; - remote_json( - client, - Method::POST, - remote_url(uri, "/read"), - Some(serde_json::to_value(ReadRequest { - query_source: query_source.to_string(), - query_name: query_name.map(ToOwned::to_owned), - params: params_json.cloned(), - branch, - snapshot, - })?), - bearer_token, - ) - .await -} - -pub(crate) async fn execute_change( - graph: &ResolvedCliGraph, - query_source: &str, - query_name: Option<&str>, - branch: &str, - params_json: Option<&Value>, - config: &OmnigraphConfig, - cli_as_actor: Option<&str>, -) -> 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(graph).await?; - let actor = resolve_cli_actor(cli_as_actor, config)?; - let actor = actor.as_deref(); - let result = db - .mutate_as(branch, query_source, &selected_name, ¶ms, actor) - .await?; - Ok(ChangeOutput { - branch: branch.to_string(), - query_name: selected_name, - affected_nodes: result.affected_nodes, - affected_edges: result.affected_edges, - actor_id: actor.map(String::from), - }) -} - -pub(crate) 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 -} - -pub(crate) async fn execute_change_remote( - client: &reqwest::Client, - uri: &str, - query_source: &str, - query_name: Option<&str>, - branch: &str, - params_json: Option<&Value>, - bearer_token: Option<&str>, -) -> Result { - remote_json( - client, - Method::POST, - remote_url(uri, "/change"), - Some(legacy_change_request_body( - query_source, - query_name, - branch, - params_json, - )), - bearer_token, - ) - .await -} - -pub(crate) async fn execute_export_to_writer( - uri: &str, - branch: &str, - type_names: &[String], - table_keys: &[String], - writer: &mut W, -) -> Result<()> { - let db = Omnigraph::open(uri).await?; - db.export_jsonl_to_writer(branch, type_names, table_keys, writer) - .await?; - writer.flush()?; - Ok(()) -} - -pub(crate) async fn execute_export_remote_to_writer( - client: &reqwest::Client, - uri: &str, - branch: &str, - type_names: &[String], - table_keys: &[String], - bearer_token: Option<&str>, - writer: &mut W, -) -> Result<()> { - let request = apply_bearer_token( - client.request(Method::POST, remote_url(uri, "/export")), - bearer_token, - ) - .json(&ExportRequest { - branch: Some(branch.to_string()), - type_names: type_names.to_vec(), - table_keys: table_keys.to_vec(), - }); - let mut response = request.send().await?; - let status = response.status(); - if !status.is_success() { - let text = response.text().await?; - if let Ok(error) = serde_json::from_str::(&text) { - bail!(error.error); - } - bail!("server returned {}: {}", status, text); - } - - while let Some(chunk) = response.chunk().await? { - writer.write_all(&chunk)?; - } - writer.flush()?; - Ok(()) -} - -pub(crate) 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 -} diff --git a/crates/omnigraph-cli/src/main.rs b/crates/omnigraph-cli/src/main.rs index 8178e65..29b55c4 100644 --- a/crates/omnigraph-cli/src/main.rs +++ b/crates/omnigraph-cli/src/main.rs @@ -6,15 +6,10 @@ use std::path::PathBuf; use std::sync::Arc; use clap::{Arg, ArgAction, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; -use color_eyre::eyre::{Result, WrapErr, bail}; +use color_eyre::eyre::{Result, bail}; use omnigraph::db::{Omnigraph, ReadTarget, SnapshotId}; use omnigraph::loader::LoadMode; use omnigraph::storage::normalize_root_uri; -use omnigraph_cluster::{ - ApplyOptions, ApplyOutput, ApproveOutput, DiagnosticSeverity, ForceUnlockOutput, PlanOutput, StateSyncOutput, StatusOutput, - ValidateOutput, apply_config_dir_with_options, approve_config_dir, force_unlock_config_dir, import_config_dir, plan_config_dir, - refresh_config_dir, status_config_dir, validate_config_dir, -}; use omnigraph_compiler::query::parser::parse_query; use omnigraph_compiler::schema::parser::parse_schema; use omnigraph_compiler::{ @@ -42,19 +37,2157 @@ use serde::de::DeserializeOwned; use serde_json::Value; mod embed; -mod migrate; -mod operator; mod read_format; use embed::{EmbedArgs, EmbedOutput, execute_embed}; use read_format::{ReadRenderOptions, render_read}; -mod cli; -mod helpers; -mod output; -use cli::*; -use helpers::*; -use output::*; +const DEFAULT_BEARER_TOKEN_ENV: &str = "OMNIGRAPH_BEARER_TOKEN"; + +#[derive(Debug, Parser)] +#[command(name = "omnigraph")] +#[command(about = "Omnigraph graph database CLI")] +#[command(version = env!("CARGO_PKG_VERSION"), disable_version_flag = true)] +struct Cli { + /// Actor identity for direct-engine writes (MR-722). Overrides + /// `cli.actor` from `omnigraph.yaml`. When the configured policy + /// is in effect, Cedar evaluates this actor against the requested + /// action and scope; with policy configured but neither this flag + /// nor `cli.actor` set, the engine-layer footgun guard fires and + /// the write is denied (no silent bypass). Has no effect on remote + /// HTTP writes β€” those resolve their actor server-side from the + /// bearer token. + #[arg(long = "as", global = true, value_name = "ACTOR")] + as_actor: Option, + + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Print the CLI version + Version, + /// Generate, clean, or refresh explicit seed embeddings + Embed(EmbedArgs), + /// Initialize a new graph from a schema + Init { + #[arg(long)] + schema: PathBuf, + /// 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 graph + Load { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + data: PathBuf, + #[arg(long)] + branch: Option, + #[arg(long, default_value = "overwrite")] + mode: CliLoadMode, + #[arg(long)] + json: bool, + }, + /// Ingest data into a reviewable named branch + Ingest { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + data: PathBuf, + #[arg(long)] + branch: Option, + #[arg(long)] + from: Option, + #[arg(long, default_value = "merge")] + mode: CliLoadMode, + #[arg(long)] + json: bool, + }, + /// Branch operations + Branch { + #[command(subcommand)] + command: BranchCommand, + }, + /// Schema planning operations + Schema { + #[command(subcommand)] + command: SchemaCommand, + }, + /// 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, + }, + /// Operate on the server-side stored-query registry (`queries:`). + Queries { + #[command(subcommand)] + command: QueriesCommand, + }, + /// Show graph snapshot + Snapshot { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + branch: Option, + #[arg(long)] + json: bool, + }, + /// Export a full graph snapshot as JSONL + Export { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + branch: Option, + #[arg(long, hide = true)] + jsonl: bool, + #[arg(long = "type")] + type_names: Vec, + #[arg(long = "table")] + table_keys: Vec, + }, + /// Commit history operations + Commit { + #[command(subcommand)] + command: CommitCommand, + }, + /// 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)] + legacy_uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long, conflicts_with_all = ["query", "query_string"])] + alias: Option, + #[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)] + params: ParamsArgs, + #[arg(long, conflicts_with = "snapshot")] + branch: Option, + #[arg(long, conflicts_with = "branch")] + snapshot: Option, + #[arg(long, conflicts_with = "json")] + format: Option, + #[arg(long, conflicts_with = "format")] + json: bool, + #[arg()] + alias_args: Vec, + }, + /// 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)] + legacy_uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long, conflicts_with_all = ["query", "query_string"])] + alias: Option, + #[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)] + params: ParamsArgs, + #[arg(long)] + branch: Option, + #[arg(long)] + json: bool, + #[arg()] + alias_args: Vec, + }, + /// Policy administration and diagnostics + Policy { + #[command(subcommand)] + command: PolicyCommand, + }, + /// Compact small Lance fragments in every table of the graph + Optimize { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + json: bool, + }, + /// Remove old Lance versions from every table of the graph (destructive) + Cleanup { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + /// Number of recent versions to keep per table. Either `--keep` or + /// `--older-than` (or both) must be set. + #[arg(long)] + keep: Option, + /// Only remove versions older than this duration. Accepts Go-style + /// durations: `7d`, `24h`, `90m`. At least one of --keep / --older-than. + #[arg(long)] + older_than: Option, + /// Required to actually run; without it, prints what would be removed + #[arg(long)] + confirm: bool, + #[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 { + /// Graph URI + #[arg(long)] + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + from: Option, + name: String, + #[arg(long)] + json: bool, + }, + /// List branches + List { + /// Graph URI + #[arg(long)] + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + json: bool, + }, + /// Delete a branch + Delete { + /// Graph URI + #[arg(long)] + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + name: String, + #[arg(long)] + json: bool, + }, + /// Merge a source branch into a target branch + Merge { + /// Graph URI + #[arg(long)] + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + source: String, + #[arg(long)] + into: Option, + #[arg(long)] + json: bool, + }, +} + +#[derive(Debug, Subcommand)] +enum SchemaCommand { + /// Plan a schema migration against the accepted persisted schema + Plan { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + schema: PathBuf, + #[arg(long)] + json: bool, + /// Show the plan as it would execute with `--allow-data-loss`. + /// Promotes every `DropMode::Soft` step to `DropMode::Hard` + /// so the plan output reflects the destructive intent. + #[arg(long, default_value_t = false)] + allow_data_loss: bool, + }, + /// Apply a supported schema migration + Apply { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + schema: PathBuf, + #[arg(long)] + json: bool, + /// Allow destructive (data-loss) schema changes. + /// + /// Without this flag, drops are "soft": the column or table + /// is removed from the current manifest version but prior + /// versions are retained, so `snapshot_at_version(pre_drop)` + /// can still read the dropped data until `omnigraph cleanup` + /// runs. With this flag, drops are "hard": `cleanup_old_versions` + /// runs on the affected datasets immediately after the apply, + /// making the prior data unreachable. + #[arg(long, default_value_t = false)] + allow_data_loss: bool, + }, + /// Show the current accepted schema source + #[command(alias = "get")] + Show { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + json: bool, + }, +} + +#[derive(Debug, Subcommand)] + +enum CommitCommand { + /// List graph commits + List { + /// Graph URI + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + #[arg(long)] + branch: Option, + #[arg(long)] + json: bool, + }, + /// Show a graph commit + Show { + /// Graph URI + #[arg(long)] + uri: Option, + #[arg(long)] + target: Option, + #[arg(long)] + config: Option, + commit_id: String, + #[arg(long)] + json: bool, + }, +} + +#[derive(Debug, Subcommand)] +enum PolicyCommand { + /// Validate policy YAML and compiled Cedar policy state + Validate { + #[arg(long)] + config: Option, + }, + /// Run declarative policy tests from policy.tests.yaml + Test { + #[arg(long)] + config: Option, + }, + /// Explain one policy decision locally + Explain { + #[arg(long)] + config: Option, + #[arg(long)] + actor: String, + #[arg(long)] + action: PolicyAction, + #[arg(long)] + branch: Option, + #[arg(long = "target-branch")] + target_branch: Option, + }, +} + +#[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")] + params: Option, + #[arg(long, conflicts_with = "params")] + params_file: Option, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, ValueEnum)] +#[serde(rename_all = "snake_case")] +enum CliLoadMode { + Overwrite, + Append, + Merge, +} + +impl From for LoadMode { + fn from(value: CliLoadMode) -> Self { + match value { + CliLoadMode::Overwrite => LoadMode::Overwrite, + CliLoadMode::Append => LoadMode::Append, + CliLoadMode::Merge => LoadMode::Merge, + } + } +} + +impl CliLoadMode { + fn as_str(self) -> &'static str { + match self { + CliLoadMode::Overwrite => "overwrite", + CliLoadMode::Append => "append", + CliLoadMode::Merge => "merge", + } + } +} + +#[derive(Debug, Serialize)] +struct LoadOutput<'a> { + uri: &'a str, + branch: &'a str, + mode: &'a str, + nodes_loaded: usize, + edges_loaded: usize, + node_types_loaded: usize, + edge_types_loaded: usize, +} + +#[derive(Debug, Serialize)] +struct SchemaPlanOutput<'a> { + uri: &'a str, + supported: bool, + step_count: usize, + steps: &'a [SchemaMigrationStep], +} + +fn print_schema_apply_human(output: &SchemaApplyOutput) { + println!("schema apply for {}", output.uri); + println!("supported: {}", if output.supported { "yes" } else { "no" }); + println!("applied: {}", if output.applied { "yes" } else { "no" }); + println!("manifest_version: {}", output.manifest_version); + if output.steps.is_empty() { + println!("no schema changes"); + return; + } + for step in &output.steps { + println!("- {}", render_schema_plan_step(step)); + } +} + +fn query_kind_label(kind: QueryLintQueryKind) -> &'static str { + match kind { + QueryLintQueryKind::Read => "read", + QueryLintQueryKind::Mutation => "mutation", + } +} + +fn severity_label(severity: QueryLintSeverity) -> &'static str { + match severity { + QueryLintSeverity::Error => "ERROR", + QueryLintSeverity::Warning => "WARN ", + QueryLintSeverity::Info => "INFO ", + } +} + +fn print_query_lint_human(output: &QueryLintOutput) { + for result in &output.results { + match result.status { + QueryLintStatus::Ok => { + println!( + "OK query `{}` ({})", + result.name, + query_kind_label(result.kind) + ); + } + QueryLintStatus::Error => { + println!( + "ERROR query `{}`: {}", + result.name, + result.error.as_deref().unwrap_or("unknown error") + ); + } + } + + for warning in &result.warnings { + println!("WARN query `{}`: {}", result.name, warning); + } + } + + for finding in &output.findings { + println!("{} {}", severity_label(finding.severity), finding.message); + } + + println!( + "INFO Lint complete: {} queries processed ({} error(s), {} warning(s), {} info item(s))", + output.queries_processed, output.errors, output.warnings, output.infos + ); +} + +fn finish_query_lint(output: &QueryLintOutput, json: bool) -> Result<()> { + if json { + print_json(output)?; + } else { + print_query_lint_human(output); + } + + if output.status == QueryLintStatus::Error { + io::stdout().flush()?; + std::process::exit(1); + } + + Ok(()) +} + +fn ensure_local_graph_parent(uri: &str) -> Result<()> { + if !uri.contains("://") { + fs::create_dir_all(uri)?; + } + Ok(()) +} + +fn print_json(value: &T) -> Result<()> { + println!("{}", serde_json::to_string_pretty(value)?); + Ok(()) +} + +fn is_remote_uri(uri: &str) -> bool { + uri.starts_with("http://") || uri.starts_with("https://") +} + +fn remote_url(base: &str, path: &str) -> String { + format!("{}{}", base.trim_end_matches('/'), path) +} + +fn remote_branch_url(base: &str, branch: &str) -> Result { + let mut url = reqwest::Url::parse(&format!("{}/", base.trim_end_matches('/')))?; + url.path_segments_mut() + .map_err(|_| color_eyre::eyre::eyre!("invalid remote base url"))? + .extend(["branches", branch]); + Ok(url.to_string()) +} + +fn normalize_bearer_token(value: Option) -> Option { + value + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) +} + +fn bearer_token_from_env(var_name: &str) -> Option { + normalize_bearer_token(std::env::var(var_name).ok()) +} + +fn parse_env_assignment(line: &str) -> Option<(String, String)> { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + return None; + } + + let line = line.strip_prefix("export ").unwrap_or(line).trim(); + let (name, value) = line.split_once('=')?; + let name = name.trim(); + if name.is_empty() { + return None; + } + + let value = value.trim(); + let value = if value.len() >= 2 + && ((value.starts_with('"') && value.ends_with('"')) + || (value.starts_with('\'') && value.ends_with('\''))) + { + &value[1..value.len() - 1] + } else { + value + }; + + Some((name.to_string(), value.to_string())) +} + +fn bearer_token_from_env_file(path: &Path, var_name: &str) -> Result> { + if !path.exists() { + return Ok(None); + } + + for line in fs::read_to_string(path)?.lines() { + let Some((name, value)) = parse_env_assignment(line) else { + continue; + }; + if name == var_name { + return Ok(normalize_bearer_token(Some(value))); + } + } + + Ok(None) +} + +fn load_env_file_into_process(path: &Path) -> Result<()> { + if !path.exists() { + return Ok(()); + } + + for line in fs::read_to_string(path)?.lines() { + let Some((name, value)) = parse_env_assignment(line) else { + continue; + }; + if std::env::var_os(&name).is_none() { + unsafe { + std::env::set_var(name, value); + } + } + } + + Ok(()) +} + +fn load_cli_config(config_path: Option<&PathBuf>) -> Result { + let config = load_config(config_path)?; + if let Some(path) = config.resolve_auth_env_file() { + load_env_file_into_process(&path)?; + } + Ok(config) +} + +#[derive(Debug, Clone)] +struct ResolvedCliGraph { + uri: String, + selected: Option, + graph_id: String, + policy_file: Option, + is_remote: bool, +} + +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) + } +} + +/// Resolve the CLI's effective actor identity for engine-layer policy +/// (MR-722). Precedence: `--as ` (top-level flag) overrides +/// `cli.actor` from `omnigraph.yaml`; both unset returns `None`. When +/// 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> { + cli_as.or(config.cli.actor.as_deref()) +} + +fn resolve_policy_tests_path(context: &ResolvedPolicyContext) -> PathBuf { + context.policy_file.with_file_name("policy.tests.yaml") +} + +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)?) + } +} + +fn resolve_remote_bearer_token( + config: &OmnigraphConfig, + explicit_uri: Option<&str>, + explicit_target: Option<&str>, +) -> Result> { + let scoped_env = + config.graph_bearer_token_env(explicit_uri, explicit_target, config.cli_graph_name()); + let mut env_names = Vec::new(); + if let Some(name) = scoped_env { + env_names.push(name.to_string()); + } + if env_names + .iter() + .all(|name| name != DEFAULT_BEARER_TOKEN_ENV) + { + env_names.push(DEFAULT_BEARER_TOKEN_ENV.to_string()); + } + + let env_file = config.resolve_auth_env_file(); + for env_name in env_names { + if let Some(token) = bearer_token_from_env(&env_name) { + return Ok(Some(token)); + } + if let Some(path) = env_file.as_ref() { + if let Some(token) = bearer_token_from_env_file(path, &env_name)? { + return Ok(Some(token)); + } + } + } + + Ok(None) +} + +fn build_http_client() -> Result { + Ok(reqwest::Client::new()) +} + +fn apply_bearer_token( + request: reqwest::RequestBuilder, + token: Option<&str>, +) -> reqwest::RequestBuilder { + if let Some(token) = token { + request.header(AUTHORIZATION, format!("Bearer {}", token)) + } else { + request + } +} + +async fn remote_json( + client: &reqwest::Client, + method: Method, + url: String, + body: Option, + bearer_token: Option<&str>, +) -> Result { + let request = apply_bearer_token(client.request(method, url), bearer_token); + let request = if let Some(body) = body { + request.json(&body) + } else { + request + }; + let response = request.send().await?; + let status = response.status(); + let text = response.text().await?; + if !status.is_success() { + if let Ok(error) = serde_json::from_str::(&text) { + bail!(error.error); + } + bail!("server returned {}: {}", status, text); + } + Ok(serde_json::from_str(&text)?) +} + +fn resolve_uri( + config: &OmnigraphConfig, + cli_uri: Option, + cli_target: Option<&str>, +) -> Result { + 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 { + let s = s.trim(); + 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..], + ), + None => (s, ""), + }; + let n: u64 = num_part + .parse() + .map_err(|e| color_eyre::eyre::eyre!("invalid duration '{}': {}", s, e))?; + let secs = match unit { + "" | "s" => n, + "m" => n * 60, + "h" => n * 60 * 60, + "d" => n * 60 * 60 * 24, + "w" => n * 60 * 60 * 24 * 7, + _ => bail!("unknown duration unit '{}'. Supported: s, m, h, d, w", unit), + }; + Ok(std::time::Duration::from_secs(secs)) +} + +fn resolve_local_uri( + config: &OmnigraphConfig, + cli_uri: Option, + cli_target: Option<&str>, + operation: &str, +) -> Result { + Ok(resolve_local_graph(config, cli_uri, cli_target, operation)?.uri) +} + +fn resolve_branch( + config: &OmnigraphConfig, + cli_branch: Option, + alias_branch: Option, + default_branch: &str, +) -> String { + cli_branch + .or(alias_branch) + .or_else(|| config.cli.branch.clone()) + .unwrap_or_else(|| default_branch.to_string()) +} + +fn resolve_read_target( + config: &OmnigraphConfig, + cli_branch: Option, + cli_snapshot: Option, + alias_branch: Option, +) -> Result { + if cli_branch.is_some() && cli_snapshot.is_some() { + bail!("read target may specify branch or snapshot, not both"); + } + Ok(read_target_from_cli( + cli_branch + .or(alias_branch) + .or_else(|| config.cli.branch.clone()), + cli_snapshot, + )) +} + +fn resolve_query_path( + config: &OmnigraphConfig, + explicit_query: Option<&PathBuf>, + alias_query: Option<&str>, +) -> Result { + explicit_query + .map(PathBuf::from) + .or_else(|| alias_query.map(PathBuf::from)) + .ok_or_else(|| { + 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)) +} + +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, + alias_query, + )?)?) +} + +fn parse_alias_value(value: &str) -> Value { + serde_json::from_str(value).unwrap_or_else(|_| Value::String(value.to_string())) +} + +fn merged_params_json( + alias_name: Option<&str>, + alias_arg_names: &[String], + alias_arg_values: &[String], + explicit: Option, +) -> Result> { + if alias_arg_values.len() > alias_arg_names.len() { + let alias = alias_name.unwrap_or(""); + bail!( + "alias '{}' expects at most {} args but got {}", + alias, + alias_arg_names.len(), + alias_arg_values.len() + ); + } + + let mut merged = serde_json::Map::new(); + for (arg_name, arg_value) in alias_arg_names.iter().zip(alias_arg_values.iter()) { + merged.insert(arg_name.clone(), parse_alias_value(arg_value)); + } + + match explicit { + Some(Value::Object(object)) => { + for (key, value) in object { + merged.insert(key, value); + } + } + Some(_) => bail!("params JSON must be an object"), + None => {} + } + + if merged.is_empty() { + Ok(None) + } else { + Ok(Some(Value::Object(merged))) + } +} + +fn print_load_human( + uri: &str, + branch: &str, + mode: CliLoadMode, + nodes_loaded: usize, + edges_loaded: usize, + node_types_loaded: usize, + edge_types_loaded: usize, +) { + println!( + "loaded {} on branch {} with {}: {} nodes across {} node types, {} edges across {} edge types", + uri, + branch, + mode.as_str(), + nodes_loaded, + node_types_loaded, + edges_loaded, + edge_types_loaded + ); +} + +fn print_ingest_human(output: &IngestOutput) { + println!( + "ingested {} into branch {} from {} with {} ({})", + output.uri, + output.branch, + output.base_branch, + output.mode.as_str(), + if output.branch_created { + "branch created" + } else { + "branch exists" + } + ); + for table in &output.tables { + println!("{} rows_loaded={}", table.table_key, table.rows_loaded); + } + if let Some(actor_id) = &output.actor_id { + println!("actor_id: {}", actor_id); + } +} + +fn print_schema_plan_human(uri: &str, plan: &SchemaMigrationPlan) { + println!("schema plan for {}", uri); + println!("supported: {}", if plan.supported { "yes" } else { "no" }); + if plan.steps.is_empty() { + println!("no schema changes"); + return; + } + for step in &plan.steps { + println!("- {}", render_schema_plan_step(step)); + } +} + +fn render_schema_plan_step(step: &SchemaMigrationStep) -> String { + match step { + SchemaMigrationStep::AddType { type_kind, name } => { + format!("add {} type '{}'", schema_type_kind_label(*type_kind), name) + } + SchemaMigrationStep::RenameType { + type_kind, + from, + to, + } => format!( + "rename {} type '{}' -> '{}'", + schema_type_kind_label(*type_kind), + from, + to + ), + SchemaMigrationStep::AddProperty { + type_kind, + type_name, + property_name, + property_type, + } => format!( + "add property '{}.{}' ({}) on {} '{}'", + type_name, + property_name, + render_prop_type(property_type), + schema_type_kind_label(*type_kind), + type_name + ), + SchemaMigrationStep::RenameProperty { + type_kind, + type_name, + from, + to, + } => format!( + "rename property '{}.{}' -> '{}.{}' on {} '{}'", + type_name, + from, + type_name, + to, + schema_type_kind_label(*type_kind), + type_name + ), + SchemaMigrationStep::AddConstraint { + type_kind, + type_name, + constraint, + } => format!( + "add constraint {} on {} '{}'", + render_constraint(constraint), + schema_type_kind_label(*type_kind), + type_name + ), + SchemaMigrationStep::UpdateTypeMetadata { + type_kind, + name, + annotations, + } => format!( + "update metadata on {} '{}' ({})", + schema_type_kind_label(*type_kind), + name, + render_annotations(annotations) + ), + SchemaMigrationStep::UpdatePropertyMetadata { + type_kind, + type_name, + property_name, + annotations, + } => format!( + "update metadata on property '{}.{}' of {} '{}' ({})", + type_name, + property_name, + schema_type_kind_label(*type_kind), + type_name, + render_annotations(annotations) + ), + SchemaMigrationStep::DropType { + type_kind, + name, + mode, + } => format!( + "drop {} type '{}' ({} mode)", + schema_type_kind_label(*type_kind), + name, + drop_mode_label(*mode), + ), + SchemaMigrationStep::DropProperty { + type_kind, + type_name, + property_name, + mode, + } => format!( + "drop property '{}.{}' of {} '{}' ({} mode)", + type_name, + property_name, + schema_type_kind_label(*type_kind), + type_name, + drop_mode_label(*mode), + ), + 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. + // Reach the diagnostic via the `diagnostic()` helper so the + // CLI doesn't need to know how the lookup works. + match step.diagnostic() { + Some(diag) => format!( + "unsupported change on {} [{}, {}]: {}", + entity, + diag.code, + schema_lint_tier_label(diag.tier), + reason, + ), + None => format!("unsupported change on {}: {}", entity, reason), + } + } + } +} + +fn schema_type_kind_label(kind: omnigraph_compiler::SchemaTypeKind) -> &'static str { + match kind { + omnigraph_compiler::SchemaTypeKind::Interface => "interface", + omnigraph_compiler::SchemaTypeKind::Node => "node", + omnigraph_compiler::SchemaTypeKind::Edge => "edge", + } +} + +fn schema_lint_tier_label(tier: omnigraph_compiler::SafetyTier) -> &'static str { + match tier { + omnigraph_compiler::SafetyTier::Safe => "safe", + omnigraph_compiler::SafetyTier::Validated => "validated", + omnigraph_compiler::SafetyTier::Destructive => "destructive", + } +} + +fn drop_mode_label(mode: omnigraph_compiler::DropMode) -> &'static str { + match mode { + omnigraph_compiler::DropMode::Soft => "soft", + omnigraph_compiler::DropMode::Hard => "hard", + } +} + +fn render_prop_type(prop_type: &omnigraph_compiler::PropType) -> String { + let base = if let Some(values) = &prop_type.enum_values { + format!("Enum({})", values.join("|")) + } else { + prop_type.scalar.to_string() + }; + let base = if prop_type.list { + format!("[{}]", base) + } else { + base + }; + if prop_type.nullable { + format!("{}?", base) + } else { + base + } +} + +fn render_constraint(constraint: &omnigraph_compiler::schema::ast::Constraint) -> String { + match constraint { + omnigraph_compiler::schema::ast::Constraint::Key(columns) => { + format!("@key({})", columns.join(", ")) + } + omnigraph_compiler::schema::ast::Constraint::Unique(columns) => { + format!("@unique({})", columns.join(", ")) + } + omnigraph_compiler::schema::ast::Constraint::Index(columns) => { + format!("@index({})", columns.join(", ")) + } + omnigraph_compiler::schema::ast::Constraint::Range { property, min, max } => { + format!("@range({}, {:?}, {:?})", property, min, max) + } + omnigraph_compiler::schema::ast::Constraint::Check { property, pattern } => { + format!("@check({}, {:?})", property, pattern) + } + } +} + +fn render_annotations(annotations: &[omnigraph_compiler::schema::ast::Annotation]) -> String { + annotations + .iter() + .map(|annotation| match &annotation.value { + Some(value) => format!("@{}({})", annotation.name, value), + None => format!("@{}", annotation.name), + }) + .collect::>() + .join(", ") +} + +fn print_embed_human(output: &EmbedOutput) { + println!( + "embedded {} rows (selected {}, cleaned {}) from {} -> {} [{} {}d]", + output.embedded_rows, + output.selected_rows, + output.cleaned_rows, + output.input, + output.output, + output.mode, + output.dimension + ); +} + +fn print_snapshot_human(branch: &str, manifest_version: u64, entries: &[SnapshotTableOutput]) { + println!("branch: {}", branch); + println!("manifest_version: {}", manifest_version); + for entry in entries { + println!( + "{} v{} branch={} rows={}", + entry.table_key, + entry.table_version, + entry.table_branch.as_deref().unwrap_or("main"), + entry.row_count + ); + } +} + +fn print_read_output( + output: &ReadOutput, + format: ReadOutputFormat, + config: &OmnigraphConfig, +) -> Result<()> { + println!( + "{}", + render_read( + output, + format, + &ReadRenderOptions { + max_column_width: config.table_max_column_width(), + cell_layout: config.table_cell_layout(), + }, + )? + ); + Ok(()) +} + +fn print_change_human(output: &ChangeOutput) { + println!( + "changed {} via {}: {} nodes, {} edges", + output.branch, output.query_name, output.affected_nodes, output.affected_edges + ); + if let Some(actor_id) = &output.actor_id { + println!("actor_id: {}", actor_id); + } +} + +fn print_commit_list_human(commits: &[CommitOutput]) { + for commit in commits { + let branch = commit.manifest_branch.as_deref().unwrap_or("main"); + println!( + "{} branch={} version={}{}", + commit.graph_commit_id, + branch, + commit.manifest_version, + commit + .actor_id + .as_deref() + .map(|actor| format!(" actor={}", actor)) + .unwrap_or_default() + ); + } +} + +fn print_commit_human(commit: &CommitOutput) { + println!("graph_commit_id: {}", commit.graph_commit_id); + println!( + "manifest_branch: {}", + commit.manifest_branch.as_deref().unwrap_or("main") + ); + println!("manifest_version: {}", commit.manifest_version); + if let Some(parent_commit_id) = &commit.parent_commit_id { + println!("parent_commit_id: {}", parent_commit_id); + } + if let Some(merged_parent_commit_id) = &commit.merged_parent_commit_id { + println!("merged_parent_commit_id: {}", merged_parent_commit_id); + } + if let Some(actor_id) = &commit.actor_id { + println!("actor_id: {}", actor_id); + } + println!("created_at: {}", commit.created_at); +} + +fn print_policy_explain(decision: &PolicyDecision, actor_id: &str, request: &PolicyRequest) { + println!( + "decision: {}", + if decision.allowed { "allow" } else { "deny" } + ); + println!("actor: {}", actor_id); + println!("action: {}", request.action); + if let Some(branch) = &request.branch { + println!("branch: {}", branch); + } + if let Some(target_branch) = &request.target_branch { + println!("target_branch: {}", target_branch); + } + if let Some(rule_id) = &decision.matched_rule_id { + println!("matched_rule: {}", rule_id); + } + println!("message: {}", decision.message); +} + +fn resolve_read_format( + config: &OmnigraphConfig, + cli_format: Option, + json: bool, + alias_format: Option, +) -> ReadOutputFormat { + if json { + ReadOutputFormat::Json + } else { + cli_format + .or(alias_format) + .unwrap_or_else(|| config.cli_output_format()) + } +} + +fn resolve_alias<'a>( + config: &'a OmnigraphConfig, + alias_name: Option<&'a str>, + expected: AliasCommand, +) -> Result> { + let Some(alias_name) = alias_name else { + return Ok(None); + }; + let alias = config.alias(alias_name)?; + if alias.command != expected { + bail!( + "alias '{}' is a {:?} alias, not a {:?} alias", + alias_name, + alias.command, + expected + ); + } + Ok(Some((alias_name, alias))) +} + +fn normalize_legacy_alias_uri( + uri: Option, + target_available: bool, + alias_name: Option<&str>, + mut alias_args: Vec, +) -> (Option, Vec) { + let Some(candidate) = uri else { + return (None, alias_args); + }; + + if alias_name.is_some() && target_available { + alias_args.insert(0, candidate); + return (None, alias_args); + } + + (Some(candidate), alias_args) +} + +fn scaffold_config_if_missing(uri: &str) -> Result<()> { + let path = inferred_config_path(uri)?; + if path.exists() { + return Ok(()); + } + + fs::write( + path, + format!( + "\ +project: + name: Omnigraph Project + +graphs: + local: + uri: {} + # bearer_token_env: OMNIGRAPH_BEARER_TOKEN + +server: + graph: local + bind: 127.0.0.1:8080 + +cli: + graph: local + branch: main + output_format: table + table_max_column_width: 80 + table_cell_layout: truncate + +query: + roots: + - queries + - . + +aliases: + # owner: + # command: read + # query: context.gq + # name: decision_owner + # args: [slug] + # graph: local + # branch: main + # format: kv + # + # attach_trace: + # command: change + # query: mutations.gq + # name: attach_trace + # args: [decision_slug, trace_slug] + # graph: local + # branch: main + +# auth: +# env_file: ./.env.omni +# +# policy: +# file: ./policy.yaml +", + yaml_string(uri), + ), + )?; + Ok(()) +} + +fn yaml_string(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + +fn inferred_config_path(uri: &str) -> Result { + if uri.contains("://") { + return Ok(omnigraph_server::config::default_config_path()); + } + + let path = Path::new(uri); + let base = if path.is_absolute() { + path.parent() + .map(Path::to_path_buf) + .unwrap_or(std::env::current_dir()?) + } else { + std::env::current_dir()?.join(path.parent().unwrap_or_else(|| Path::new("."))) + }; + Ok(base.join(omnigraph_server::config::DEFAULT_CONFIG_FILE)) +} + +fn read_target_from_cli(branch: Option, snapshot: Option) -> ReadTarget { + if let Some(snapshot) = snapshot { + ReadTarget::snapshot(SnapshotId::new(snapshot)) + } else { + ReadTarget::branch(branch.unwrap_or_else(|| "main".to_string())) + } +} + +fn load_params_json(params: &ParamsArgs) -> Result> { + match (¶ms.params, ¶ms.params_file) { + (Some(inline), None) => Ok(Some(serde_json::from_str(inline)?)), + (None, Some(path)) => Ok(Some(serde_json::from_str(&fs::read_to_string(path)?)?)), + (None, None) => Ok(None), + (Some(_), Some(_)) => bail!("only one of --params or --params-file may be provided"), + } +} + +fn select_named_query( + query_source: &str, + requested_name: Option<&str>, +) -> Result<(String, Vec)> { + let parsed = parse_query(query_source)?; + let query = if let Some(name) = requested_name { + parsed + .queries + .into_iter() + .find(|query| query.name == name) + .ok_or_else(|| color_eyre::eyre::eyre!("query '{}' not found", name))? + } else if parsed.queries.len() == 1 { + parsed.queries.into_iter().next().unwrap() + } else { + bail!("query file contains multiple queries; pass --name"); + }; + + Ok((query.name, query.params)) +} + +fn query_params_from_json( + query_params: &[omnigraph_compiler::query::ast::Param], + params_json: Option<&Value>, +) -> Result { + json_params_to_param_map(params_json, query_params, JsonParamMode::Standard) + .map_err(|err| color_eyre::eyre::eyre!(err.to_string())) +} + +async fn execute_query_lint( + config: &OmnigraphConfig, + cli_uri: Option, + cli_target: Option<&str>, + schema_path: Option<&PathBuf>, + query_path: &PathBuf, +) -> Result { + let resolved_query_path = resolve_query_path(config, Some(query_path), None)?; + let query_source = fs::read_to_string(&resolved_query_path)?; + let query_path = resolved_query_path.to_string_lossy().into_owned(); + + if let Some(schema_path) = schema_path { + let schema_source = fs::read_to_string(schema_path)?; + let schema = + parse_schema(&schema_source).map_err(|err| color_eyre::eyre::eyre!(err.to_string()))?; + let catalog = + build_catalog(&schema).map_err(|err| color_eyre::eyre::eyre!(err.to_string()))?; + return Ok(lint_query_file( + &catalog, + &query_source, + query_path, + QueryLintSchemaSource::file(schema_path.to_string_lossy().into_owned()), + )); + } + + let has_graph_target = + cli_uri.is_some() || cli_target.is_some() || config.cli_graph_name().is_some(); + 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")?; + let db = Omnigraph::open(&uri).await?; + Ok(lint_query_file( + &db.catalog(), + &query_source, + query_path, + 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, + query_name: Option<&str>, + target: ReadTarget, + params_json: Option<&Value>, +) -> 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 = Omnigraph::open(uri).await?; + let result = db + .query(target.clone(), query_source, &selected_name, ¶ms) + .await?; + Ok(read_output(selected_name, &target, result)) +} + +async fn execute_read_remote( + client: &reqwest::Client, + uri: &str, + query_source: &str, + query_name: Option<&str>, + target: ReadTarget, + params_json: Option<&Value>, + bearer_token: Option<&str>, +) -> Result { + let (branch, snapshot) = match &target { + ReadTarget::Branch(branch) => (Some(branch.clone()), None), + ReadTarget::Snapshot(snapshot) => (None, Some(snapshot.as_str().to_string())), + }; + remote_json( + client, + Method::POST, + remote_url(uri, "/read"), + Some(serde_json::to_value(ReadRequest { + query_source: query_source.to_string(), + query_name: query_name.map(ToOwned::to_owned), + params: params_json.cloned(), + branch, + snapshot, + })?), + bearer_token, + ) + .await +} + +async fn execute_change( + graph: &ResolvedCliGraph, + query_source: &str, + query_name: Option<&str>, + branch: &str, + params_json: Option<&Value>, + config: &OmnigraphConfig, + cli_as_actor: Option<&str>, +) -> 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(graph).await?; + let actor = resolve_cli_actor(cli_as_actor, config); + let result = db + .mutate_as(branch, query_source, &selected_name, ¶ms, actor) + .await?; + Ok(ChangeOutput { + branch: branch.to_string(), + query_name: selected_name, + affected_nodes: result.affected_nodes, + affected_edges: result.affected_edges, + actor_id: actor.map(String::from), + }) +} + +/// 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, + query_source: &str, + query_name: Option<&str>, + branch: &str, + params_json: Option<&Value>, + bearer_token: Option<&str>, +) -> Result { + remote_json( + client, + Method::POST, + remote_url(uri, "/change"), + Some(legacy_change_request_body( + query_source, + query_name, + branch, + params_json, + )), + bearer_token, + ) + .await +} + +async fn execute_export_to_writer( + uri: &str, + branch: &str, + type_names: &[String], + table_keys: &[String], + writer: &mut W, +) -> Result<()> { + let db = Omnigraph::open(uri).await?; + db.export_jsonl_to_writer(branch, type_names, table_keys, writer) + .await?; + writer.flush()?; + Ok(()) +} + +async fn execute_export_remote_to_writer( + client: &reqwest::Client, + uri: &str, + branch: &str, + type_names: &[String], + table_keys: &[String], + bearer_token: Option<&str>, + writer: &mut W, +) -> Result<()> { + let request = apply_bearer_token( + client.request(Method::POST, remote_url(uri, "/export")), + bearer_token, + ) + .json(&ExportRequest { + branch: Some(branch.to_string()), + type_names: type_names.to_vec(), + table_keys: table_keys.to_vec(), + }); + let mut response = request.send().await?; + let status = response.status(); + if !status.is_success() { + let text = response.text().await?; + if let Ok(error) = serde_json::from_str::(&text) { + bail!(error.error); + } + bail!("server returned {}: {}", status, text); + } + + while let Some(chunk) = response.chunk().await? { + writer.write_all(&chunk)?; + } + writer.flush()?; + 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<()> { @@ -74,65 +2207,6 @@ async fn main() -> Result<()> { }; let http_client = build_http_client()?; match cli.command { - Command::Config { command } => match command { - ConfigCommand::Migrate { config, write, json } => { - let path = migrate::legacy_config_path(config.as_ref()); - if !path.exists() { - bail!( - "no legacy config at '{}' β€” nothing to migrate", - path.display() - ); - } - let legacy = load_config(Some(&path))?; - let report = migrate::build_report(&legacy, &path); - if write { - let legacy_dir = path - .parent() - .filter(|parent| !parent.as_os_str().is_empty()) - .unwrap_or(std::path::Path::new(".")) - .to_path_buf(); - let written = migrate::apply_report(&report, &legacy_dir)?; - if json { - print_json(&serde_json::json!({ - "report": report, - "written": written, - }))?; - } else { - print!("{}", migrate::render_report(&report)); - for line in written { - println!("wrote: {line}"); - } - } - } else if json { - print_json(&report)?; - } else { - print!("{}", migrate::render_report(&report)); - } - } - }, - Command::Login { name, token, json } => { - let token = match token { - Some(token) => token, - None => { - let mut line = String::new(); - std::io::stdin().read_line(&mut line)?; - line - } - }; - let Some(token) = normalize_bearer_token(Some(token)) else { - color_eyre::eyre::bail!( - "no token provided: pass --token or pipe it on stdin (echo $TOKEN | omnigraph login {name})" - ); - }; - let operator_config = crate::operator::load_operator_config()?; - let declared = operator_config.servers.contains_key(&name); - let path = crate::operator::write_credential(&name, &token)?; - finish_login(&name, &path, declared, json)?; - } - Command::Logout { name, json } => { - let path = crate::operator::remove_credential(&name)?; - finish_logout(&name, &path, json)?; - } Command::Version => { println!("omnigraph {}", env!("CARGO_PKG_VERSION")); } @@ -153,6 +2227,7 @@ async fn main() -> Result<()> { omnigraph::db::InitOptions { force }, ) .await?; + scaffold_config_if_missing(&uri)?; println!("initialized {}", uri); } Command::Load { @@ -161,63 +2236,39 @@ async fn main() -> Result<()> { config, data, branch, - from, mode, json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; - let bearer_token = - resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; - let graph = resolve_cli_graph(&config, uri, target.as_deref())?; + 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 payload = if graph.is_remote { - let data = fs::read_to_string(&data)?; - let output = remote_json::( - &http_client, - Method::POST, - remote_url(&uri, "/ingest"), - Some(serde_json::to_value(IngestRequest { - branch: Some(branch.clone()), - from: from.clone(), - mode: Some(mode.into()), - data, - })?), - bearer_token.as_deref(), - ) + 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) .await?; - load_output_from_tables(&uri, &branch, mode, &output) - } else { - let db = open_local_db_with_policy(&graph).await?; - let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config)?; - let actor = actor.as_deref(); - let result = db - .load_file_as( - &branch, - from.as_deref(), - &data.to_string_lossy(), - mode.into(), - actor, - ) - .await?; - LoadOutput { - uri: uri.clone(), - branch: branch.clone(), - mode: mode.as_str(), - base_branch: result.base_branch.clone(), - branch_created: result.branch_created, - nodes_loaded: result.nodes_loaded.values().sum(), - edges_loaded: result.edges_loaded.values().sum(), - node_types_loaded: result.nodes_loaded.len(), - edge_types_loaded: result.edges_loaded.len(), - } + let payload = LoadOutput { + uri: &uri, + branch: &branch, + mode: mode.as_str(), + nodes_loaded: result.nodes_loaded.values().sum(), + edges_loaded: result.edges_loaded.values().sum(), + node_types_loaded: result.nodes_loaded.len(), + edge_types_loaded: result.edges_loaded.len(), }; if json { print_json(&payload)?; } else { - print_load_human(&payload); + print_load_human( + &uri, + &branch, + mode, + payload.nodes_loaded, + payload.edges_loaded, + payload.node_types_loaded, + payload.edge_types_loaded, + ); } } Command::Ingest { @@ -230,14 +2281,7 @@ async fn main() -> Result<()> { mode, json, } => { - // stderr so `--json` consumers reading stdout are unaffected. - eprintln!( - "warning: `omnigraph ingest` is deprecated and will be removed in a future release; \ - use `omnigraph load --from --mode ` (ingest defaults: --from main --mode merge)" - ); let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let graph = resolve_cli_graph(&config, uri, target.as_deref())?; @@ -261,10 +2305,9 @@ async fn main() -> Result<()> { .await? } else { let db = open_local_db_with_policy(&graph).await?; - let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config)?; - let actor = actor.as_deref(); + let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); let result = db - .load_file_as( + .ingest_file_as( &branch, Some(&from), &data.to_string_lossy(), @@ -272,7 +2315,7 @@ async fn main() -> Result<()> { actor, ) .await?; - ingest_output(&uri, &result, mode.into(), None) + ingest_output(&uri, &result, None) }; if json { print_json(&payload)?; @@ -290,8 +2333,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let graph = resolve_cli_graph(&config, uri, target.as_deref())?; @@ -311,8 +2352,7 @@ async fn main() -> Result<()> { .await? } else { let db = open_local_db_with_policy(&graph).await?; - let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config)?; - let actor = actor.as_deref(); + let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); db.branch_create_from_as(ReadTarget::branch(&from), &name, actor) .await?; BranchCreateOutput { @@ -335,8 +2375,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let graph = resolve_cli_graph(&config, uri, target.as_deref())?; @@ -372,8 +2410,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let graph = resolve_cli_graph(&config, uri, target.as_deref())?; @@ -389,8 +2425,7 @@ async fn main() -> Result<()> { .await? } else { let db = open_local_db_with_policy(&graph).await?; - let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config)?; - let actor = actor.as_deref(); + let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); db.branch_delete_as(&name, actor).await?; BranchDeleteOutput { uri: uri.clone(), @@ -413,8 +2448,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let graph = resolve_cli_graph(&config, uri, target.as_deref())?; @@ -434,8 +2467,7 @@ async fn main() -> Result<()> { .await? } else { let db = open_local_db_with_policy(&graph).await?; - let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config)?; - let actor = actor.as_deref(); + let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config); let outcome = db.branch_merge_as(&source, &into, actor).await?; BranchMergeOutput { source: source.clone(), @@ -465,8 +2497,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let uri = resolve_uri(&config, uri, target.as_deref())?; @@ -506,8 +2536,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let uri = resolve_uri(&config, uri, target.as_deref())?; @@ -571,8 +2599,6 @@ async fn main() -> Result<()> { allow_data_loss, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let graph = resolve_cli_graph(&config, uri, target.as_deref())?; @@ -597,8 +2623,7 @@ async fn main() -> Result<()> { .await? } else { let db = open_local_db_with_policy(&graph).await?; - let actor = resolve_cli_actor(cli.as_actor.as_deref(), &config)?; - let actor = actor.as_deref(); + 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(); @@ -630,8 +2655,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let uri = resolve_uri(&config, uri, target.as_deref())?; @@ -696,8 +2719,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let uri = resolve_uri(&config, uri, target.as_deref())?; @@ -733,8 +2754,6 @@ async fn main() -> Result<()> { table_keys, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let uri = resolve_uri(&config, uri, target.as_deref())?; @@ -782,43 +2801,6 @@ async fn main() -> Result<()> { } let config = load_cli_config(config.as_ref())?; - // Operator aliases (RFC-007 PR 3): pure bindings to stored - // queries. A legacy file-alias with the same name wins during - // the RFC-008 window (with a warning); an alias name found - // only in the operator layer takes the invoke path here. - if let Some(alias_name) = alias.as_deref() { - let operator_config = crate::operator::load_operator_config()?; - if let Some(operator_alias) = operator_config.aliases.get(alias_name) { - if config.alias(alias_name).is_ok() { - eprintln!( - "warning: alias '{alias_name}' is defined in both omnigraph.yaml (legacy, wins during the deprecation window) and the operator config; the legacy definition applies" - ); - } else { - // The hidden legacy-uri positional swallows the first - // bare arg; an operator alias always knows its target, - // so reclaim it as the first positional param. - let (_, alias_args) = normalize_legacy_alias_uri( - legacy_uri.clone(), - true, - Some(alias_name), - alias_args.clone(), - ); - let output = execute_operator_alias( - &http_client, - &config, - alias_name, - operator_alias, - &alias_args, - load_params_json(¶ms)?, - ) - .await?; - let format = - resolve_read_format(&config, format, json, operator_alias.format); - print_read_output(&output, format, &config)?; - return Ok(()); - } - } - } let alias = resolve_alias(&config, alias.as_deref(), AliasCommand::Read)?; let alias_name = alias.as_ref().map(|(name, _)| *name); let alias_config = alias.as_ref().map(|(_, alias)| *alias); @@ -833,7 +2815,6 @@ async fn main() -> Result<()> { let target_name = target .as_deref() .or_else(|| alias_config.and_then(|alias| alias.graph.as_deref())); - let uri = apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target_name)?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target_name)?; let graph = resolve_cli_graph(&config, uri, target_name)?; let uri = graph.uri.clone(); @@ -920,7 +2901,6 @@ async fn main() -> Result<()> { let target_name = target .as_deref() .or_else(|| alias_config.and_then(|alias| alias.graph.as_deref())); - let uri = apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target_name)?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target_name)?; let graph = resolve_cli_graph(&config, uri, target_name)?; let uri = graph.uri.clone(); @@ -1032,8 +3012,6 @@ async fn main() -> Result<()> { "fragments_added": s.fragments_added, "committed": s.committed, "skipped": s.skipped.map(|r| r.as_str()), - "manifest_version": s.manifest_version, - "lance_head_version": s.lance_head_version, })).collect::>(), }); print_json(&value)?; @@ -1053,89 +3031,6 @@ async fn main() -> Result<()> { } } } - Command::Repair { - uri, - target, - config, - confirm, - force, - json, - } => { - let config = load_cli_config(config.as_ref())?; - let uri = resolve_uri(&config, uri, target.as_deref())?; - let db = Omnigraph::open(&uri).await?; - let stats = db - .repair(omnigraph::db::RepairOptions { confirm, force }) - .await?; - let refused_count = stats - .tables - .iter() - .filter(|s| matches!(s.action, omnigraph::db::RepairAction::Refused)) - .count(); - if json { - let value = serde_json::json!({ - "uri": uri, - "confirm": confirm, - "force": force, - "manifest_version": stats.manifest_version, - "tables": stats.tables.iter().map(|s| serde_json::json!({ - "table_key": s.table_key, - "manifest_version": s.manifest_version, - "lance_head_version": s.lance_head_version, - "classification": s.classification.as_str(), - "action": s.action.as_str(), - "operations": s.operations, - "error": s.error, - })).collect::>(), - }); - print_json(&value)?; - } else { - let mode = if confirm { "confirm" } else { "preview" }; - println!( - "repair {} β€” {} mode, {} tables", - uri, - mode, - stats.tables.len() - ); - for s in &stats.tables { - let drift = if s.manifest_version == s.lance_head_version { - format!("{}", s.manifest_version) - } else { - format!("{} β†’ {}", s.manifest_version, s.lance_head_version) - }; - let ops = if s.operations.is_empty() { - String::new() - } else { - format!(" [{}]", s.operations.join(", ")) - }; - let err = s - .error - .as_ref() - .map(|err| format!(" ({err})")) - .unwrap_or_default(); - println!( - " {:<40} {:<12} {:<22} {}{}{}", - s.table_key, - s.action.as_str(), - s.classification.as_str(), - drift, - ops, - err - ); - } - if !confirm { - println!("rerun with --confirm to publish verified maintenance drift"); - } - } - if refused_count > 0 { - bail!( - "repair refused {} suspicious or unverifiable table(s); review the preview \ - output and rerun with --force --confirm only if publishing that drift is \ - intentional", - refused_count - ); - } - } Command::Cleanup { uri, target, @@ -1216,58 +3111,6 @@ async fn main() -> Result<()> { } } } - Command::Cluster { command } => match command { - ClusterCommand::Validate { config, json } => { - let output = validate_config_dir(config); - finish_cluster_validate(&output, json)?; - } - ClusterCommand::Plan { config, json } => { - let output = plan_config_dir(config).await; - finish_cluster_plan(&output, json)?; - } - ClusterCommand::Apply { config, json } => { - // The actor attributes graph-moving operations (sidecars, - // audit entries, engine schema-apply commits). Cluster FACTS - // stay unlayered; the operator's identity resolves --as flag - // first, then the per-operator omnigraph.yaml `cli.actor`. - let actor = resolve_cluster_actor(cli.as_actor.as_deref())?; - let output = apply_config_dir_with_options(config, ApplyOptions { actor }).await; - finish_cluster_apply(&output, json)?; - } - ClusterCommand::Approve { - resource, - config, - json, - } => { - let Some(approver) = resolve_cluster_actor(cli.as_actor.as_deref())? else { - bail!( - "`cluster approve` requires an approver: pass the global --as flag or set `cli.actor` in your omnigraph.yaml β€” an approval without an approver is meaningless" - ); - }; - let output = approve_config_dir(config, &resource, &approver).await; - finish_cluster_approve(&output, json)?; - } - ClusterCommand::Status { config, json } => { - let output = status_config_dir(config).await; - finish_cluster_status(&output, json)?; - } - ClusterCommand::Refresh { config, json } => { - let output = refresh_config_dir(config).await; - finish_cluster_state_sync(&output, json)?; - } - ClusterCommand::Import { config, json } => { - let output = import_config_dir(config).await; - finish_cluster_state_sync(&output, json)?; - } - ClusterCommand::ForceUnlock { - lock_id, - config, - json, - } => { - let output = force_unlock_config_dir(config, lock_id).await; - finish_cluster_force_unlock(&output, json)?; - } - }, Command::Graphs { command } => match command { GraphsCommand::List { uri, @@ -1276,8 +3119,6 @@ async fn main() -> Result<()> { json, } => { let config = load_cli_config(config.as_ref())?; - let uri = - apply_server_flag(cli.server.as_deref(), cli.graph.as_deref(), uri, target.as_deref())?; let bearer_token = resolve_remote_bearer_token(&config, uri.as_deref(), target.as_deref())?; let uri = resolve_uri(&config, uri, target.as_deref())?; @@ -1309,7 +3150,418 @@ async fn main() -> Result<()> { Ok(()) } - #[cfg(test)] -#[path = "main_tests.rs"] -mod tests; +mod tests { + use std::fs; + + use super::{ + 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(); + let request = apply_bearer_token(client.get("http://example.com"), Some("demo-token")) + .build() + .unwrap(); + assert_eq!( + request + .headers() + .get(AUTHORIZATION) + .and_then(|value| value.to_str().ok()), + Some("Bearer demo-token") + ); + } + + #[test] + fn apply_bearer_token_leaves_request_unchanged_when_not_configured() { + let client = reqwest::Client::new(); + let request = apply_bearer_token(client.get("http://example.com"), None) + .build() + .unwrap(); + assert!(request.headers().get(AUTHORIZATION).is_none()); + } + + #[test] + fn normalize_bearer_token_trims_and_filters_blank_values() { + assert_eq!(normalize_bearer_token(None), None); + assert_eq!(normalize_bearer_token(Some(" ".to_string())), None); + assert_eq!( + normalize_bearer_token(Some(" demo-token ".to_string())).as_deref(), + Some("demo-token") + ); + } + + #[test] + fn parse_env_assignment_supports_plain_and_exported_values() { + assert_eq!( + parse_env_assignment("DEMO_TOKEN=demo-token"), + Some(("DEMO_TOKEN".to_string(), "demo-token".to_string())) + ); + assert_eq!( + parse_env_assignment("export DEMO_TOKEN=\"quoted-token\""), + Some(("DEMO_TOKEN".to_string(), "quoted-token".to_string())) + ); + assert_eq!(parse_env_assignment("# comment"), None); + assert_eq!(parse_env_assignment(" "), None); + } + + #[test] + fn bearer_token_from_env_file_reads_named_value() { + let temp = tempdir().unwrap(); + let env_file = temp.path().join(".env.omni"); + fs::write( + &env_file, + "FIRST=ignore\nexport DEMO_TOKEN=\" demo-token \"\n", + ) + .unwrap(); + + assert_eq!( + bearer_token_from_env_file(&env_file, "DEMO_TOKEN") + .unwrap() + .as_deref(), + Some("demo-token") + ); + assert_eq!( + bearer_token_from_env_file(&env_file, "MISSING").unwrap(), + None + ); + } + + #[test] + fn load_env_file_into_process_sets_missing_values_without_overriding_existing_ones() { + let temp = tempdir().unwrap(); + let env_file = temp.path().join(".env.omni"); + fs::write( + &env_file, + "AUTOLOAD_ONLY=from-file\nAUTOLOAD_PRESET=from-file\n", + ) + .unwrap(); + + let missing_key = "AUTOLOAD_ONLY"; + let preset_key = "AUTOLOAD_PRESET"; + let previous_missing = std::env::var_os(missing_key); + let previous_preset = std::env::var_os(preset_key); + + unsafe { + std::env::remove_var(missing_key); + std::env::set_var(preset_key, "from-env"); + } + + load_env_file_into_process(&env_file).unwrap(); + + assert_eq!(std::env::var(missing_key).unwrap(), "from-file"); + assert_eq!(std::env::var(preset_key).unwrap(), "from-env"); + + unsafe { + if let Some(value) = previous_missing { + std::env::set_var(missing_key, value); + } else { + std::env::remove_var(missing_key); + } + + if let Some(value) = previous_preset { + std::env::set_var(preset_key, value); + } else { + std::env::remove_var(preset_key); + } + } + } + + #[test] + fn resolve_remote_bearer_token_uses_scoped_env_file_with_global_fallback() { + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + r#" +graphs: + demo: + uri: https://example.com + bearer_token_env: DEMO_TOKEN +auth: + env_file: .env.omni +cli: + graph: demo +"#, + ) + .unwrap(); + fs::write( + temp.path().join(".env.omni"), + "DEMO_TOKEN=scoped-token\nOMNIGRAPH_BEARER_TOKEN=global-token\n", + ) + .unwrap(); + + let previous = std::env::var_os(DEFAULT_BEARER_TOKEN_ENV); + unsafe { + std::env::remove_var(DEFAULT_BEARER_TOKEN_ENV); + } + + let config_path = temp.path().join("omnigraph.yaml"); + let config = load_config(Some(&config_path)).unwrap(); + + assert_eq!( + resolve_remote_bearer_token(&config, None, Some("demo")) + .unwrap() + .as_deref(), + Some("scoped-token") + ); + assert_eq!( + resolve_remote_bearer_token(&config, Some("https://override.example.com"), None) + .unwrap() + .as_deref(), + Some("global-token") + ); + + unsafe { + if let Some(value) = previous { + std::env::set_var(DEFAULT_BEARER_TOKEN_ENV, value); + } else { + std::env::remove_var(DEFAULT_BEARER_TOKEN_ENV); + } + } + } + + #[test] + fn load_cli_config_autoloads_env_file_into_process() { + let temp = tempdir().unwrap(); + fs::write( + temp.path().join("omnigraph.yaml"), + r#" +auth: + env_file: .env.omni +graphs: + demo: + uri: s3://bucket/prefix +"#, + ) + .unwrap(); + fs::write( + temp.path().join(".env.omni"), + "AUTOLOAD_FROM_CONFIG=loaded\n", + ) + .unwrap(); + + let key = "AUTOLOAD_FROM_CONFIG"; + let previous = std::env::var_os(key); + unsafe { + std::env::remove_var(key); + } + + let config_path = temp.path().join("omnigraph.yaml"); + let config = load_cli_config(Some(&config_path)).unwrap(); + + assert_eq!( + config.resolve_target_uri(None, Some("demo"), None).unwrap(), + "s3://bucket/prefix" + ); + assert_eq!(std::env::var(key).unwrap(), "loaded"); + + unsafe { + if let Some(value) = previous { + std::env::set_var(key, value); + } else { + std::env::remove_var(key); + } + } + } + + #[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/src/main_tests.rs b/crates/omnigraph-cli/src/main_tests.rs deleted file mode 100644 index 8380c36..0000000 --- a/crates/omnigraph-cli/src/main_tests.rs +++ /dev/null @@ -1,427 +0,0 @@ -//! In-source test suite for the CLI binary (moved verbatim from -//! main.rs; `use super::*` resolves through the #[path] declaration). - - use std::fs; - - use super::{ - 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_cli_graph, resolve_policy_context, - 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(); - let request = apply_bearer_token(client.get("http://example.com"), Some("demo-token")) - .build() - .unwrap(); - assert_eq!( - request - .headers() - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()), - Some("Bearer demo-token") - ); - } - - #[test] - fn apply_bearer_token_leaves_request_unchanged_when_not_configured() { - let client = reqwest::Client::new(); - let request = apply_bearer_token(client.get("http://example.com"), None) - .build() - .unwrap(); - assert!(request.headers().get(AUTHORIZATION).is_none()); - } - - #[test] - fn normalize_bearer_token_trims_and_filters_blank_values() { - assert_eq!(normalize_bearer_token(None), None); - assert_eq!(normalize_bearer_token(Some(" ".to_string())), None); - assert_eq!( - normalize_bearer_token(Some(" demo-token ".to_string())).as_deref(), - Some("demo-token") - ); - } - - #[test] - fn parse_env_assignment_supports_plain_and_exported_values() { - assert_eq!( - parse_env_assignment("DEMO_TOKEN=demo-token"), - Some(("DEMO_TOKEN".to_string(), "demo-token".to_string())) - ); - assert_eq!( - parse_env_assignment("export DEMO_TOKEN=\"quoted-token\""), - Some(("DEMO_TOKEN".to_string(), "quoted-token".to_string())) - ); - assert_eq!(parse_env_assignment("# comment"), None); - assert_eq!(parse_env_assignment(" "), None); - } - - #[test] - fn bearer_token_from_env_file_reads_named_value() { - let temp = tempdir().unwrap(); - let env_file = temp.path().join(".env.omni"); - fs::write( - &env_file, - "FIRST=ignore\nexport DEMO_TOKEN=\" demo-token \"\n", - ) - .unwrap(); - - assert_eq!( - bearer_token_from_env_file(&env_file, "DEMO_TOKEN") - .unwrap() - .as_deref(), - Some("demo-token") - ); - assert_eq!( - bearer_token_from_env_file(&env_file, "MISSING").unwrap(), - None - ); - } - - #[test] - fn load_env_file_into_process_sets_missing_values_without_overriding_existing_ones() { - let temp = tempdir().unwrap(); - let env_file = temp.path().join(".env.omni"); - fs::write( - &env_file, - "AUTOLOAD_ONLY=from-file\nAUTOLOAD_PRESET=from-file\n", - ) - .unwrap(); - - let missing_key = "AUTOLOAD_ONLY"; - let preset_key = "AUTOLOAD_PRESET"; - let previous_missing = std::env::var_os(missing_key); - let previous_preset = std::env::var_os(preset_key); - - unsafe { - std::env::remove_var(missing_key); - std::env::set_var(preset_key, "from-env"); - } - - load_env_file_into_process(&env_file).unwrap(); - - assert_eq!(std::env::var(missing_key).unwrap(), "from-file"); - assert_eq!(std::env::var(preset_key).unwrap(), "from-env"); - - unsafe { - if let Some(value) = previous_missing { - std::env::set_var(missing_key, value); - } else { - std::env::remove_var(missing_key); - } - - if let Some(value) = previous_preset { - std::env::set_var(preset_key, value); - } else { - std::env::remove_var(preset_key); - } - } - } - - #[test] - fn resolve_remote_bearer_token_uses_scoped_env_file_with_global_fallback() { - let temp = tempdir().unwrap(); - fs::write( - temp.path().join("omnigraph.yaml"), - r#" -graphs: - demo: - uri: https://example.com - bearer_token_env: DEMO_TOKEN -auth: - env_file: .env.omni -cli: - graph: demo -"#, - ) - .unwrap(); - fs::write( - temp.path().join(".env.omni"), - "DEMO_TOKEN=scoped-token\nOMNIGRAPH_BEARER_TOKEN=global-token\n", - ) - .unwrap(); - - let previous = std::env::var_os(DEFAULT_BEARER_TOKEN_ENV); - let previous_home = std::env::var_os("OMNIGRAPH_HOME"); - unsafe { - std::env::remove_var(DEFAULT_BEARER_TOKEN_ENV); - // Hermetic: the keyed hop (RFC-007 PR 2) must not pick up a real - // ~/.omnigraph on the developer's machine β€” and with no operator - // servers defined, the legacy chain below must behave - // byte-identically to pre-PR-2 (tested-as-untouched). - std::env::set_var("OMNIGRAPH_HOME", temp.path().join("no-operator-config")); - } - - let config_path = temp.path().join("omnigraph.yaml"); - let config = load_config(Some(&config_path)).unwrap(); - - assert_eq!( - resolve_remote_bearer_token(&config, None, Some("demo")) - .unwrap() - .as_deref(), - Some("scoped-token") - ); - assert_eq!( - resolve_remote_bearer_token(&config, Some("https://override.example.com"), None) - .unwrap() - .as_deref(), - Some("global-token") - ); - - unsafe { - if let Some(value) = previous { - std::env::set_var(DEFAULT_BEARER_TOKEN_ENV, value); - } else { - std::env::remove_var(DEFAULT_BEARER_TOKEN_ENV); - } - if let Some(value) = previous_home { - std::env::set_var("OMNIGRAPH_HOME", value); - } else { - std::env::remove_var("OMNIGRAPH_HOME"); - } - } - } - - #[test] - fn load_cli_config_autoloads_env_file_into_process() { - let temp = tempdir().unwrap(); - fs::write( - temp.path().join("omnigraph.yaml"), - r#" -auth: - env_file: .env.omni -graphs: - demo: - uri: s3://bucket/prefix -"#, - ) - .unwrap(); - fs::write( - temp.path().join(".env.omni"), - "AUTOLOAD_FROM_CONFIG=loaded\n", - ) - .unwrap(); - - let key = "AUTOLOAD_FROM_CONFIG"; - let previous = std::env::var_os(key); - unsafe { - std::env::remove_var(key); - } - - let config_path = temp.path().join("omnigraph.yaml"); - let config = load_cli_config(Some(&config_path)).unwrap(); - - assert_eq!( - config.resolve_target_uri(None, Some("demo"), None).unwrap(), - "s3://bucket/prefix" - ); - assert_eq!(std::env::var(key).unwrap(), "loaded"); - - unsafe { - if let Some(value) = previous { - std::env::set_var(key, value); - } else { - std::env::remove_var(key); - } - } - } - - #[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/src/migrate.rs b/crates/omnigraph-cli/src/migrate.rs deleted file mode 100644 index 3891061..0000000 --- a/crates/omnigraph-cli/src/migrate.rs +++ /dev/null @@ -1,408 +0,0 @@ -//! `omnigraph config migrate` (RFC-008 stage 2): split a legacy -//! `omnigraph.yaml` into its two destinations β€” the team half as a -//! ready-to-review `cluster.yaml` proposal, the personal half merged into -//! `~/.omnigraph/config.yaml` β€” and name what's obsolete. The command is -//! the completeness test of RFC-008's migration map: any key it cannot -//! place is a bug in the RFC. -//! -//! Touches nothing without `--write`. Referenced `.gq`/policy files are -//! never moved; manual steps are printed instead. - -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; - -use color_eyre::Result; -use color_eyre::eyre::eyre; -use omnigraph_server::OmnigraphConfig; -use serde::Serialize; - -use crate::operator; - -#[derive(Debug, Serialize)] -pub(crate) struct MigrateReport { - pub(crate) source: String, - /// The ready-to-review cluster.yaml text (None when the legacy file - /// declares nothing team-shaped). - pub(crate) cluster_yaml: Option, - /// Operator keys to merge: dotted key -> YAML value text. - pub(crate) operator_merge: BTreeMap, - /// Keys with no destination, and why. - pub(crate) dropped: Vec, - /// Steps the command will not do for you. - pub(crate) manual_steps: Vec, -} - -#[derive(Debug, Serialize)] -pub(crate) struct DroppedKey { - pub(crate) key: String, - pub(crate) reason: String, -} - -/// Classify a parsed legacy config into the report. Pure β€” no I/O. -pub(crate) fn build_report(config: &OmnigraphConfig, source: &Path) -> MigrateReport { - let mut dropped = Vec::new(); - let mut manual_steps = Vec::new(); - let mut operator_merge: BTreeMap = BTreeMap::new(); - - // ---- personal half ---- - if let Some(actor) = &config.cli.actor { - operator_merge.insert("operator.actor".into(), actor.clone()); - } - if let Some(format) = config.cli.output_format { - operator_merge.insert( - "defaults.output".into(), - serde_yaml::to_string(&format).unwrap_or_default().trim().to_string(), - ); - } - if let Some(width) = config.cli.table_max_column_width { - operator_merge.insert("defaults.table_max_column_width".into(), width.to_string()); - } - if let Some(layout) = config.cli.table_cell_layout { - operator_merge.insert( - "defaults.table_cell_layout".into(), - serde_yaml::to_string(&layout).unwrap_or_default().trim().to_string(), - ); - } - if config.cli.graph.is_some() { - dropped.push(DroppedKey { - key: "cli.graph".into(), - reason: "no operator default-target yet β€” address graphs explicitly via --target/--server (RFC-002 locator territory)".into(), - }); - } - if config.cli.branch.is_some() { - dropped.push(DroppedKey { - key: "cli.branch".into(), - reason: "pass --branch explicitly".into(), - }); - } - - // Remote graphs with a token env become operator servers (the keyed - // chain replaces invented env-var names). - for (name, target) in &config.graphs { - if target.uri.starts_with("http://") || target.uri.starts_with("https://") { - operator_merge.insert(format!("servers.{name}.url"), target.uri.clone()); - if target.bearer_token_env.is_some() { - manual_steps.push(format!( - "store the '{name}' token in the keyed chain: echo $TOKEN | omnigraph login {name} (replaces bearer_token_env)" - )); - } - } - } - if config.auth.env_file.is_some() { - manual_steps.push( - "auth.env_file keeps working during the window; prefer `omnigraph login ` per server going forward".into(), - ); - } - - // Legacy aliases split: content -> catalog stored query, binding -> - // operator alias referencing the name. - for (name, alias) in &config.aliases { - let query_name = alias.name.clone().unwrap_or_else(|| name.clone()); - operator_merge.insert( - format!("aliases.{name}"), - format!( - "{{ server: TODO-server-name, graph: {}, query: {query_name}, args: [{}] }}", - alias.graph.as_deref().unwrap_or("TODO-graph-id"), - alias.args.join(", ") - ), - ); - manual_steps.push(format!( - "alias '{name}': move its query content ('{}') into the cluster checkout's queries/ so '{query_name}' becomes a catalog stored query", - alias.query - )); - } - - // ---- team half ---- - let has_team_content = !config.graphs.is_empty() - || !config.queries.is_empty() - || config.policy.file.is_some() - || config.server.policy.file.is_some(); - let cluster_yaml = has_team_content.then(|| { - let mut out = String::from("version: 1\n"); - if let Some(name) = &config.project.name { - out.push_str(&format!("metadata:\n name: {name}\n")); - } - out.push_str("# storage: s3://bucket/prefix # or omit: this folder is the root\n"); - if !config.graphs.is_empty() || !config.queries.is_empty() { - out.push_str("graphs:\n"); - } - // Single-graph top-level queries belong to a graph the legacy file - // never named; propose one. - if !config.queries.is_empty() && config.graphs.is_empty() { - out.push_str(" default: # TODO: pick the graph id\n schema: # TODO: path to this graph's .pg schema\n queries: queries/\n"); - } - for (name, target) in &config.graphs { - out.push_str(&format!(" {name}:\n")); - out.push_str(" schema: # TODO: path to this graph's .pg schema\n"); - if !target.queries.is_empty() { - out.push_str(" queries: queries/ # move the .gq files here\n"); - } - out.push_str(&format!( - " # legacy root: {} β€” the cluster manages graph roots under its storage; run `omnigraph cluster import` after reviewing\n", - target.uri - )); - } - let mut policies: Vec<(String, String, String)> = Vec::new(); - if let Some(file) = &config.policy.file { - policies.push(("default".into(), file.clone(), "graph. # TODO: bind".into())); - } - if let Some(file) = &config.server.policy.file { - policies.push(("server".into(), file.clone(), "cluster".into())); - } - for (name, target) in &config.graphs { - if let Some(file) = &target.policy.file { - policies.push((name.clone(), file.clone(), format!("graph.{name}"))); - } - } - if !policies.is_empty() { - out.push_str("policies:\n"); - for (name, file, binding) in policies { - out.push_str(&format!( - " {name}:\n file: {file}\n applies_to: [{binding}]\n" - )); - } - } - out - }); - - if !config.query.roots.is_empty() { - dropped.push(DroppedKey { - key: "query.roots".into(), - reason: "obsolete β€” cluster query discovery (queries: ) replaced it".into(), - }); - } - if config.server.bind.is_some() || config.server.graph.is_some() { - dropped.push(DroppedKey { - key: "server.bind / server.graph".into(), - reason: "deployment runtime β€” pass --bind / target flags or env".into(), - }); - } - if config.project.name.is_some() && cluster_yaml.is_none() { - dropped.push(DroppedKey { - key: "project.name".into(), - reason: "the cluster's metadata.name is the deployment label".into(), - }); - } - - MigrateReport { - source: source.display().to_string(), - cluster_yaml, - operator_merge, - dropped, - manual_steps, - } -} - -pub(crate) fn render_report(report: &MigrateReport) -> String { - let mut out = format!("migration plan for {}\n", report.source); - if let Some(cluster) = &report.cluster_yaml { - out.push_str("\n== team half -> cluster.yaml (ready to review) ==\n"); - out.push_str(cluster); - } - if !report.operator_merge.is_empty() { - out.push_str("\n== personal half -> ~/.omnigraph/config.yaml ==\n"); - for (key, value) in &report.operator_merge { - out.push_str(&format!(" {key}: {value}\n")); - } - } - if !report.dropped.is_empty() { - out.push_str("\n== no destination ==\n"); - for dropped in &report.dropped { - out.push_str(&format!(" {} β€” {}\n", dropped.key, dropped.reason)); - } - } - if !report.manual_steps.is_empty() { - out.push_str("\n== manual steps ==\n"); - for step in &report.manual_steps { - out.push_str(&format!(" - {step}\n")); - } - } - out.push_str("\n(nothing written; pass --write to apply the operator merge and emit cluster.yaml)\n"); - out -} - -/// `--write`: merge the personal half into the operator config (key-level, -/// existing entries always win; the prior file is backed up) and write the -/// team half to cluster.yaml in the legacy config's directory (or -/// cluster.yaml.proposed when one already exists). -pub(crate) fn apply_report(report: &MigrateReport, legacy_dir: &Path) -> Result> { - let mut written = Vec::new(); - - if !report.operator_merge.is_empty() { - let dir = operator::operator_dir() - .ok_or_else(|| eyre!("no home directory resolvable for the operator config"))?; - std::fs::create_dir_all(&dir)?; - let path = dir.join(operator::OPERATOR_CONFIG_FILE); - let existing_text = std::fs::read_to_string(&path).unwrap_or_default(); - let mut mapping: serde_yaml::Mapping = if existing_text.trim().is_empty() { - serde_yaml::Mapping::new() - } else { - serde_yaml::from_str(&existing_text) - .map_err(|err| eyre!("operator config '{}' does not parse: {err}", path.display()))? - }; - let mut merged_any = false; - for (dotted, value_text) in &report.operator_merge { - if merge_dotted_if_absent(&mut mapping, dotted, value_text)? { - merged_any = true; - } - } - if merged_any { - if !existing_text.is_empty() { - let backup = path.with_extension("yaml.bak"); - std::fs::write(&backup, &existing_text)?; - written.push(format!("backed up prior operator config to {}", backup.display())); - } - let rendered = serde_yaml::to_string(&mapping)?; - let tmp = path.with_extension(format!("yaml.tmp.{}", std::process::id())); - std::fs::write(&tmp, &rendered)?; - std::fs::rename(&tmp, &path)?; - written.push(format!("merged personal keys into {}", path.display())); - } else { - written.push("operator config already carries every personal key (nothing merged)".into()); - } - } - - if let Some(cluster) = &report.cluster_yaml { - let target = legacy_dir.join("cluster.yaml"); - let target = if target.exists() { - legacy_dir.join("cluster.yaml.proposed") - } else { - target - }; - std::fs::write(&target, cluster)?; - written.push(format!("wrote team-half proposal to {}", target.display())); - } - - Ok(written) -} - -/// Set `a.b.c` in the mapping only when absent; returns whether it wrote. -fn merge_dotted_if_absent( - mapping: &mut serde_yaml::Mapping, - dotted: &str, - value_text: &str, -) -> Result { - let value: serde_yaml::Value = - serde_yaml::from_str(value_text).unwrap_or(serde_yaml::Value::String(value_text.into())); - let parts: Vec<&str> = dotted.split('.').collect(); - let mut current = mapping; - for part in &parts[..parts.len() - 1] { - let key = serde_yaml::Value::String((*part).into()); - let entry = current - .entry(key) - .or_insert_with(|| serde_yaml::Value::Mapping(serde_yaml::Mapping::new())); - current = entry - .as_mapping_mut() - .ok_or_else(|| eyre!("operator config key '{dotted}' collides with a non-mapping"))?; - } - let leaf = serde_yaml::Value::String(parts[parts.len() - 1].into()); - if current.contains_key(&leaf) { - return Ok(false); - } - current.insert(leaf, value); - Ok(true) -} - -pub(crate) fn legacy_config_path(explicit: Option<&PathBuf>) -> PathBuf { - explicit.cloned().unwrap_or_else(|| PathBuf::from("omnigraph.yaml")) -} - -#[cfg(test)] -mod tests { - use super::*; - use omnigraph_server::config::load_config; - - fn full_legacy_fixture(dir: &Path) -> PathBuf { - let path = dir.join("omnigraph.yaml"); - std::fs::write( - &path, - r#" -project: { name: brain } -graphs: - prod: - uri: https://graph.example.com - bearer_token_env: PROD_TOKEN - policy: { file: ./prod.policy.yaml } - queries: - find: { file: ./find.gq } - local: - uri: /tmp/local.omni -server: { bind: "0.0.0.0:9999", policy: { file: ./server.policy.yaml } } -auth: { env_file: .env.omni } -cli: - graph: prod - branch: main - actor: act-me - output_format: json - table_max_column_width: 40 -query: { roots: ["."] } -aliases: - triage: { command: query, query: ./triage.gq, name: weekly_triage, args: [since], graph: prod } -policy: { file: ./top.policy.yaml } -queries: - top_q: { file: ./top.gq } -"#, - ) - .unwrap(); - path - } - - /// The RFC-008 completeness contract: every top-level key of the - /// legacy schema must appear in the report somewhere (team half, - /// operator merge, dropped, or manual steps). - #[test] - fn every_legacy_key_is_classified() { - let dir = tempfile::tempdir().unwrap(); - let path = full_legacy_fixture(dir.path()); - let config = load_config(Some(&path)).unwrap(); - let report = build_report(&config, &path); - let rendered = render_report(&report); - - let serialized = - serde_yaml::to_value(OmnigraphConfig::default()).expect("default serializes"); - for key in serialized.as_mapping().unwrap().keys() { - let key = key.as_str().unwrap(); - assert!( - rendered.contains(key) - || report.operator_merge.keys().any(|k| k.contains(key)) - || matches!(key, "graphs" | "queries" | "policy" | "project") - && report.cluster_yaml.is_some(), - "legacy key '{key}' is unclassified β€” fix the RFC-008 map: {rendered}" - ); - } - - // spot checks on each section - assert_eq!(report.operator_merge["operator.actor"], "act-me"); - assert_eq!(report.operator_merge["defaults.output"], "json"); - assert_eq!( - report.operator_merge["servers.prod.url"], - "https://graph.example.com" - ); - assert!(report.operator_merge["aliases.triage"].contains("query: weekly_triage")); - let cluster = report.cluster_yaml.as_deref().unwrap(); - assert!(cluster.contains("version: 1")); - assert!(cluster.contains("name: brain")); - assert!(cluster.contains(" prod:")); - assert!(cluster.contains("applies_to: [cluster]")); - assert!(cluster.contains("applies_to: [graph.prod]")); - assert!(report.dropped.iter().any(|d| d.key == "query.roots")); - assert!(report.dropped.iter().any(|d| d.key.contains("server.bind"))); - assert!( - report - .manual_steps - .iter() - .any(|s| s.contains("omnigraph login prod")) - ); - } - - #[test] - fn merge_dotted_never_clobbers_existing() { - let mut mapping: serde_yaml::Mapping = - serde_yaml::from_str("operator:\n actor: keep-me\n").unwrap(); - assert!(!merge_dotted_if_absent(&mut mapping, "operator.actor", "new").unwrap()); - assert!(merge_dotted_if_absent(&mut mapping, "defaults.output", "json").unwrap()); - let text = serde_yaml::to_string(&mapping).unwrap(); - assert!(text.contains("keep-me") && !text.contains("new")); - assert!(text.contains("output: json")); - } -} diff --git a/crates/omnigraph-cli/src/operator.rs b/crates/omnigraph-cli/src/operator.rs deleted file mode 100644 index fb8658d..0000000 --- a/crates/omnigraph-cli/src/operator.rs +++ /dev/null @@ -1,582 +0,0 @@ -//! The operator config surface (RFC-007): `~/.omnigraph/config.yaml` β€” who -//! the operator IS (identity, ergonomics), never what the system is (that's -//! cluster config) and never a project file (nothing here arrives with a -//! repo checkout). -//! -//! PR-1 scope: `operator.actor` + `defaults.output`. Unknown keys WARN and -//! are preserved-by-ignoring β€” a file written for a newer CLI (servers, -//! aliases, credentials keys from later slices) must load cleanly on this -//! one. Contrast with `cluster.yaml`, where unknown keys are fatal because -//! they change what a plan means. -//! -//! This module is CLI-only by design: the server never reads operator -//! config (server-side identity comes from bearer auth β€” invariant 11 -//! holds by construction). - -use std::collections::BTreeMap; -use std::env; -use std::path::{Path, PathBuf}; - -use color_eyre::Result; -use color_eyre::eyre::eyre; -use serde::Deserialize; - -use omnigraph_server::config::ReadOutputFormat; - -pub(crate) const OPERATOR_HOME_ENV: &str = "OMNIGRAPH_HOME"; -pub(crate) const OPERATOR_DIR: &str = ".omnigraph"; -pub(crate) const OPERATOR_CONFIG_FILE: &str = "config.yaml"; - -#[derive(Debug, Default, Deserialize)] -pub(crate) struct OperatorConfig { - #[serde(default)] - pub(crate) operator: OperatorIdentity, - #[serde(default)] - pub(crate) defaults: OperatorDefaults, - /// Operator-owned endpoint definitions (RFC-007 Β§D2/Β§D4): name β†’ url. - /// The name keys the credential chain; nothing a repo checkout supplies - /// can redefine an entry here. No tokens in this file, ever. - #[serde(default)] - pub(crate) servers: BTreeMap, - /// Personal alias bindings (RFC-007 PR 3); see OperatorAlias. - #[serde(default)] - pub(crate) aliases: BTreeMap, - /// Everything this CLI version doesn't know. Warned once at load, - /// otherwise ignored (forward compatibility within the operator layer). - #[serde(flatten)] - unknown: serde_yaml::Mapping, -} - -/// A personal alias: a pure BINDING to a stored query on a named server β€” -/// never content, never a file (RFC-007 Β§D2 "Aliases are bindings, not -/// content"). The stored query is the team's contract; the alias, its -/// defaults, and its name are the operator's. -#[derive(Debug, Deserialize)] -pub(crate) struct OperatorAlias { - /// Names an entry under `servers:`. - pub(crate) server: String, - /// Graph id for multi-graph servers (appends `/graphs/`). - pub(crate) graph: Option, - /// The STORED query's name on that server. - pub(crate) query: String, - /// Positional CLI args bind to these param names, in order. - #[serde(default)] - pub(crate) args: Vec, - /// Fixed default params; positionals and `--params` override per key. - #[serde(default)] - pub(crate) params: serde_yaml::Mapping, - pub(crate) format: Option, - #[serde(flatten)] - unknown: serde_yaml::Mapping, -} - -#[derive(Debug, Deserialize)] -pub(crate) struct OperatorServer { - pub(crate) url: String, - #[serde(flatten)] - unknown: serde_yaml::Mapping, -} - -#[derive(Debug, Default, Deserialize)] -pub(crate) struct OperatorIdentity { - /// Default actor for every `--as` cascade (CLI direct-engine writes and - /// cluster commands alike): `--as` > legacy config actor (RFC-008 - /// window) > this > none. - pub(crate) actor: Option, - #[serde(flatten)] - unknown: serde_yaml::Mapping, -} - -#[derive(Debug, Default, Deserialize)] -pub(crate) struct OperatorDefaults { - /// Default read output format, below every more-specific source. - pub(crate) output: Option, - /// Table rendering preferences (below the legacy cli.table_* keys - /// during the RFC-008 window). - pub(crate) table_max_column_width: Option, - pub(crate) table_cell_layout: Option, - #[serde(flatten)] - unknown: serde_yaml::Mapping, -} - -impl OperatorConfig { - pub(crate) fn actor(&self) -> Option<&str> { - self.operator.actor.as_deref() - } - - pub(crate) fn output(&self) -> Option { - self.defaults.output - } - - /// The gh-host model: which operator server (if any) does this request - /// URL belong to? Longest-prefix match after trailing-slash - /// normalization, so `url: http://h:8080` matches - /// `http://h:8080/graphs/spike` but never `http://h:8080-evil`. - pub(crate) fn find_server_for_url(&self, request_url: &str) -> Option<&str> { - let request = request_url.trim_end_matches('/'); - let mut best: Option<(&str, usize)> = None; - for (name, server) in &self.servers { - let base = server.url.trim_end_matches('/'); - let matches = request == base - || request - .strip_prefix(base) - .is_some_and(|rest| rest.starts_with('/')); - if matches && best.is_none_or(|(_, len)| base.len() > len) { - best = Some((name, base.len())); - } - } - best.map(|(name, _)| name) - } -} - -/// The operator dir: `$OMNIGRAPH_HOME` if set (tilde-expanded), else -/// `~/.omnigraph`. Returns None when no home directory is resolvable -/// (degenerate environments β€” the layer is simply absent). -pub(crate) fn operator_dir() -> Option { - if let Some(home_override) = env::var_os(OPERATOR_HOME_ENV) { - let raw = home_override.to_string_lossy().into_owned(); - return Some(expand_tilde(&raw)); - } - env::home_dir().map(|home| home.join(OPERATOR_DIR)) -} - -/// Load the operator layer. Absent file (or unresolvable home) is an empty -/// layer, never an error; a present-but-malformed file is a loud error (the -/// operator owns it and can fix it); unknown keys warn to stderr once. -pub(crate) fn load_operator_config() -> Result { - let Some(dir) = operator_dir() else { - return Ok(OperatorConfig::default()); - }; - load_operator_config_at(&dir.join(OPERATOR_CONFIG_FILE)) -} - -pub(crate) fn load_operator_config_at(path: &Path) -> Result { - let text = match std::fs::read_to_string(path) { - Ok(text) => text, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - return Ok(OperatorConfig::default()); - } - Err(err) => { - return Err(eyre!( - "could not read operator config '{}': {err}", - path.display() - )); - } - }; - let config: OperatorConfig = serde_yaml::from_str(&text).map_err(|err| { - eyre!( - "could not parse operator config '{}': {err}", - path.display() - ) - })?; - for warning in config.unknown_key_warnings() { - eprintln!("warning: {warning} in operator config '{}'", path.display()); - } - Ok(config) -} - -impl OperatorConfig { - fn unknown_key_warnings(&self) -> Vec { - let mut warnings = Vec::new(); - let mut collect = |mapping: &serde_yaml::Mapping, prefix: &str| { - for key in mapping.keys() { - if let Some(name) = key.as_str() { - warnings.push(format!( - "unknown key `{prefix}{name}` (newer CLI feature or typo); ignored" - )); - } - } - }; - collect(&self.unknown, ""); - collect(&self.operator.unknown, "operator."); - collect(&self.defaults.unknown, "defaults."); - for (name, server) in &self.servers { - collect(&server.unknown, &format!("servers.{name}.")); - } - for (name, alias) in &self.aliases { - collect(&alias.unknown, &format!("aliases.{name}.")); - } - warnings - } -} - -// ---- keyed credentials (RFC-007 Β§D4) ---- - -pub(crate) const CREDENTIALS_FILE: &str = "credentials"; -const TOKEN_ENV_PREFIX: &str = "OMNIGRAPH_TOKEN_"; - -pub(crate) fn credentials_path() -> Option { - operator_dir().map(|dir| dir.join(CREDENTIALS_FILE)) -} - -/// `intel-dev` β†’ `OMNIGRAPH_TOKEN_INTEL_DEV`. -pub(crate) fn token_env_name(server: &str) -> String { - let mut name = String::from(TOKEN_ENV_PREFIX); - for c in server.chars() { - name.push(match c { - '-' => '_', - other => other.to_ascii_uppercase(), - }); - } - name -} - -/// The keyed token chain for a named server (Β§D4 steps 1–2): -/// `OMNIGRAPH_TOKEN_` env β†’ `[]` in the credentials file. -/// `Ok(None)` means "no keyed token" β€” callers fall through to the legacy -/// chain; a present-but-unreadable/over-permissive credentials file is a -/// loud error, never a silent skip. -pub(crate) fn resolve_keyed_token(server: &str) -> Result> { - if let Ok(token) = env::var(token_env_name(server)) { - let token = token.trim(); - if !token.is_empty() { - return Ok(Some(token.to_string())); - } - } - let Some(path) = credentials_path() else { - return Ok(None); - }; - read_credential_at(&path, server) -} - -pub(crate) fn read_credential_at(path: &Path, server: &str) -> Result> { - let text = match std::fs::read_to_string(path) { - Ok(text) => text, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(err) => { - return Err(eyre!( - "could not read credentials file '{}': {err}", - path.display() - )); - } - }; - refuse_over_permissive(path)?; - let mut in_section = false; - for line in text.lines() { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { - in_section = section.trim() == server; - continue; - } - if in_section { - if let Some((key, value)) = line.split_once('=') { - if key.trim() == "token" { - let value = unquote(value.trim()); - if value.is_empty() { - return Ok(None); - } - return Ok(Some(value.to_string())); - } - } - } - } - Ok(None) -} - -/// Write (or rotate) one server's token, preserving every other section. -/// Temp file + rename (#139 finding 7), created 0600. -pub(crate) fn write_credential(server: &str, token: &str) -> Result { - let path = credentials_path() - .ok_or_else(|| eyre!("no home directory resolvable for the credentials file"))?; - rewrite_credentials_at(&path, server, Some(token))?; - Ok(path) -} - -/// Remove one server's section. Idempotent: absent file or section is fine. -pub(crate) fn remove_credential(server: &str) -> Result { - let path = credentials_path() - .ok_or_else(|| eyre!("no home directory resolvable for the credentials file"))?; - rewrite_credentials_at(&path, server, None)?; - Ok(path) -} - -pub(crate) fn rewrite_credentials_at( - path: &Path, - server: &str, - token: Option<&str>, -) -> Result<()> { - let existing = match std::fs::read_to_string(path) { - Ok(text) => { - refuse_over_permissive(path)?; - text - } - Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(), - Err(err) => { - return Err(eyre!( - "could not read credentials file '{}': {err}", - path.display() - )); - } - }; - - // Drop the target section (if present), keep everything else verbatim. - let mut out = String::new(); - let mut in_target = false; - for line in existing.lines() { - let trimmed = line.trim(); - if let Some(section) = trimmed.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { - in_target = section.trim() == server; - if in_target { - continue; - } - } - if !in_target { - out.push_str(line); - out.push('\n'); - } - } - if let Some(token) = token { - if !out.is_empty() && !out.ends_with("\n\n") { - out.push('\n'); - } - out.push_str(&format!("[{server}]\ntoken = {token}\n")); - } - - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - let tmp = path.with_extension(format!("tmp.{}", std::process::id())); - write_owner_only(&tmp, &out)?; - std::fs::rename(&tmp, path).map_err(|err| { - let _ = std::fs::remove_file(&tmp); - eyre!( - "could not move credentials file into place '{}': {err}", - path.display() - ) - })?; - Ok(()) -} - -#[cfg(unix)] -fn write_owner_only(path: &Path, content: &str) -> Result<()> { - use std::io::Write; - use std::os::unix::fs::OpenOptionsExt; - let mut file = std::fs::OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .mode(0o600) - .open(path)?; - file.write_all(content.as_bytes())?; - Ok(()) -} - -#[cfg(not(unix))] -fn write_owner_only(path: &Path, content: &str) -> Result<()> { - std::fs::write(path, content)?; - Ok(()) -} - -/// Secrets are operator-private: refuse a credentials file other accounts -/// can read (the chain errs loudly rather than using a leaked secret). -#[cfg(unix)] -fn refuse_over_permissive(path: &Path) -> Result<()> { - use std::os::unix::fs::PermissionsExt; - let mode = std::fs::metadata(path)?.permissions().mode(); - if mode & 0o077 != 0 { - return Err(eyre!( - "credentials file '{}' is group/world-accessible (mode {:o}); run `chmod 600 {}`", - path.display(), - mode & 0o777, - path.display() - )); - } - Ok(()) -} - -#[cfg(not(unix))] -fn refuse_over_permissive(_path: &Path) -> Result<()> { - Ok(()) -} - -fn unquote(value: &str) -> &str { - if value.len() >= 2 - && ((value.starts_with('"') && value.ends_with('"')) - || (value.starts_with('\'') && value.ends_with('\''))) - { - &value[1..value.len() - 1] - } else { - value - } -} - -/// Expand a leading `~` / `~/` to the home directory (PR #139 finding 9: -/// a literal `./~/…` path silently created a directory named `~`). -pub(crate) fn expand_tilde(raw: &str) -> PathBuf { - if raw == "~" { - return env::home_dir().unwrap_or_else(|| PathBuf::from(raw)); - } - if let Some(rest) = raw.strip_prefix("~/") { - if let Some(home) = env::home_dir() { - return home.join(rest); - } - } - PathBuf::from(raw) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - - #[test] - fn absent_file_is_an_empty_layer() { - let dir = tempfile::tempdir().unwrap(); - let config = load_operator_config_at(&dir.path().join("config.yaml")).unwrap(); - assert!(config.actor().is_none()); - assert!(config.output().is_none()); - } - - #[test] - fn parses_identity_and_defaults() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.yaml"); - fs::write( - &path, - "operator:\n actor: act-andrew\ndefaults:\n output: json\n", - ) - .unwrap(); - let config = load_operator_config_at(&path).unwrap(); - assert_eq!(config.actor(), Some("act-andrew")); - assert_eq!(config.output(), Some(ReadOutputFormat::Json)); - } - - #[test] - fn unknown_keys_warn_but_load() { - // A file written for a later slice (servers/aliases) must load - // cleanly today β€” warn-only forward compatibility. - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.yaml"); - fs::write( - &path, - "operator:\n actor: act-a\n color: green\nservers:\n prod:\n url: https://example.com\naliases: {}\n", - ) - .unwrap(); - let config = load_operator_config_at(&path).unwrap(); - assert_eq!(config.actor(), Some("act-a")); - let warnings = config.unknown_key_warnings(); - // `servers` (PR 2) and `aliases` (PR 3) are known keys now. - assert_eq!(warnings.len(), 1, "{warnings:?}"); - assert!(warnings.iter().any(|w| w.contains("`operator.color`"))); - assert_eq!(config.servers["prod"].url, "https://example.com"); - } - - #[test] - fn malformed_yaml_is_a_loud_error() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.yaml"); - fs::write(&path, "operator: [not, a, mapping\n").unwrap(); - let err = load_operator_config_at(&path).unwrap_err(); - assert!(err.to_string().contains("could not parse operator config")); - } - - #[test] - fn find_server_for_url_longest_prefix_no_substring_traps() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.yaml"); - fs::write( - &path, - "servers:\n dev:\n url: http://h:8080\n dev-spike:\n url: http://h:8080/graphs/spike\n", - ) - .unwrap(); - let config = load_operator_config_at(&path).unwrap(); - assert_eq!(config.find_server_for_url("http://h:8080"), Some("dev")); - assert_eq!( - config.find_server_for_url("http://h:8080/graphs/other"), - Some("dev") - ); - // longest prefix wins - assert_eq!( - config.find_server_for_url("http://h:8080/graphs/spike/queries/q"), - Some("dev-spike") - ); - // no substring trap: a different port/host must not match - assert_eq!(config.find_server_for_url("http://h:8080-evil/x"), None); - assert_eq!(config.find_server_for_url("http://other:9999"), None); - } - - #[test] - fn server_lookup_supports_targeting() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.yaml"); - fs::write( - &path, - "servers:\n intel-dev:\n url: http://127.0.0.1:8080/\n", - ) - .unwrap(); - let config = load_operator_config_at(&path).unwrap(); - // the --server resolution shape: bare url and graph-scoped url - let base = config.servers["intel-dev"].url.trim_end_matches('/'); - assert_eq!(base, "http://127.0.0.1:8080"); - assert_eq!( - format!("{base}/graphs/spike"), - "http://127.0.0.1:8080/graphs/spike" - ); - } - - #[test] - fn token_env_name_uppercases_and_underscores() { - assert_eq!(token_env_name("intel-dev"), "OMNIGRAPH_TOKEN_INTEL_DEV"); - assert_eq!(token_env_name("prod"), "OMNIGRAPH_TOKEN_PROD"); - } - - #[test] - fn credentials_roundtrip_rotate_remove_preserving_other_sections() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("credentials"); - - rewrite_credentials_at(&path, "prod", Some("tok-1")).unwrap(); - rewrite_credentials_at(&path, "dev", Some("tok-dev")).unwrap(); - assert_eq!( - read_credential_at(&path, "prod").unwrap().as_deref(), - Some("tok-1") - ); - - // rotate prod; dev preserved - rewrite_credentials_at(&path, "prod", Some("tok-2")).unwrap(); - assert_eq!( - read_credential_at(&path, "prod").unwrap().as_deref(), - Some("tok-2") - ); - assert_eq!( - read_credential_at(&path, "dev").unwrap().as_deref(), - Some("tok-dev") - ); - - // remove prod; dev preserved; removal is idempotent - rewrite_credentials_at(&path, "prod", None).unwrap(); - rewrite_credentials_at(&path, "prod", None).unwrap(); - assert_eq!(read_credential_at(&path, "prod").unwrap(), None); - assert_eq!( - read_credential_at(&path, "dev").unwrap().as_deref(), - Some("tok-dev") - ); - } - - #[cfg(unix)] - #[test] - fn credentials_written_0600_and_over_permissive_refused() { - use std::os::unix::fs::PermissionsExt; - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("credentials"); - rewrite_credentials_at(&path, "prod", Some("tok")).unwrap(); - let mode = fs::metadata(&path).unwrap().permissions().mode(); - assert_eq!(mode & 0o777, 0o600, "written {:o}", mode & 0o777); - - fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); - let err = read_credential_at(&path, "prod").unwrap_err(); - assert!(err.to_string().contains("chmod 600"), "{err}"); - } - - #[test] - fn expand_tilde_resolves_home_prefix() { - let home = env::home_dir().unwrap(); - assert_eq!(expand_tilde("~"), home); - assert_eq!(expand_tilde("~/x/y"), home.join("x/y")); - assert_eq!(expand_tilde("/abs/path"), PathBuf::from("/abs/path")); - assert_eq!(expand_tilde("rel/path"), PathBuf::from("rel/path")); - } -} diff --git a/crates/omnigraph-cli/src/output.rs b/crates/omnigraph-cli/src/output.rs deleted file mode 100644 index 964307b..0000000 --- a/crates/omnigraph-cli/src/output.rs +++ /dev/null @@ -1,890 +0,0 @@ -//! Human/JSON output formatting for every command (moved verbatim from -//! main.rs in the modularization). - -use super::*; - -#[derive(Debug, Serialize)] -pub(crate) struct LoadOutput { - pub(crate) uri: String, - pub(crate) branch: String, - pub(crate) mode: &'static str, - /// Present only when `--from` was given; echoes the requested base. - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) base_branch: Option, - pub(crate) branch_created: bool, - pub(crate) nodes_loaded: usize, - pub(crate) edges_loaded: usize, - pub(crate) node_types_loaded: usize, - pub(crate) edge_types_loaded: usize, -} - -pub(crate) fn load_output_from_tables( - uri: &str, - branch: &str, - mode: CliLoadMode, - output: &IngestOutput, -) -> LoadOutput { - let mut nodes_loaded = 0; - let mut edges_loaded = 0; - let mut node_types_loaded = 0; - let mut edge_types_loaded = 0; - for table in &output.tables { - if table.table_key.starts_with("node:") { - nodes_loaded += table.rows_loaded; - node_types_loaded += 1; - } else if table.table_key.starts_with("edge:") { - edges_loaded += table.rows_loaded; - edge_types_loaded += 1; - } - } - LoadOutput { - uri: uri.to_string(), - branch: branch.to_string(), - mode: mode.as_str(), - base_branch: output.base_branch.clone(), - branch_created: output.branch_created, - nodes_loaded, - edges_loaded, - node_types_loaded, - edge_types_loaded, - } -} - -#[derive(Debug, Serialize)] -pub(crate) struct SchemaPlanOutput<'a> { - pub(crate) uri: &'a str, - pub(crate) supported: bool, - pub(crate) step_count: usize, - pub(crate) steps: &'a [SchemaMigrationStep], -} - -pub(crate) fn print_schema_apply_human(output: &SchemaApplyOutput) { - println!("schema apply for {}", output.uri); - println!("supported: {}", if output.supported { "yes" } else { "no" }); - println!("applied: {}", if output.applied { "yes" } else { "no" }); - println!("manifest_version: {}", output.manifest_version); - if output.steps.is_empty() { - println!("no schema changes"); - return; - } - for step in &output.steps { - println!("- {}", render_schema_plan_step(step)); - } -} - -pub(crate) fn query_kind_label(kind: QueryLintQueryKind) -> &'static str { - match kind { - QueryLintQueryKind::Read => "read", - QueryLintQueryKind::Mutation => "mutation", - } -} - -pub(crate) fn severity_label(severity: QueryLintSeverity) -> &'static str { - match severity { - QueryLintSeverity::Error => "ERROR", - QueryLintSeverity::Warning => "WARN ", - QueryLintSeverity::Info => "INFO ", - } -} - -pub(crate) fn print_query_lint_human(output: &QueryLintOutput) { - for result in &output.results { - match result.status { - QueryLintStatus::Ok => { - println!( - "OK query `{}` ({})", - result.name, - query_kind_label(result.kind) - ); - } - QueryLintStatus::Error => { - println!( - "ERROR query `{}`: {}", - result.name, - result.error.as_deref().unwrap_or("unknown error") - ); - } - } - - for warning in &result.warnings { - println!("WARN query `{}`: {}", result.name, warning); - } - } - - for finding in &output.findings { - println!("{} {}", severity_label(finding.severity), finding.message); - } - - println!( - "INFO Lint complete: {} queries processed ({} error(s), {} warning(s), {} info item(s))", - output.queries_processed, output.errors, output.warnings, output.infos - ); -} - -pub(crate) fn finish_query_lint(output: &QueryLintOutput, json: bool) -> Result<()> { - if json { - print_json(output)?; - } else { - print_query_lint_human(output); - } - - if output.status == QueryLintStatus::Error { - io::stdout().flush()?; - std::process::exit(1); - } - - Ok(()) -} - -pub(crate) fn print_json(value: &T) -> Result<()> { - println!("{}", serde_json::to_string_pretty(value)?); - Ok(()) -} - -pub(crate) fn print_cluster_validate_human(output: &ValidateOutput) { - if output.ok { - println!( - "cluster config valid: {} resource(s), {} dependency edge(s)", - output.resources.len(), - output.dependencies.len() - ); - } else { - println!("cluster config invalid"); - } - print_cluster_diagnostics(&output.diagnostics); -} - -pub(crate) fn print_cluster_plan_human(output: &PlanOutput) { - if output.ok { - println!( - "cluster plan: {} change(s), {} approval gate(s)", - output.changes.len(), - output.approvals_required.len() - ); - for change in &output.changes { - let bindings = if change.binding_change { " [bindings]" } else { "" }; - println!(" {:?} {}{bindings}", change.operation, change.resource); - if let Some(migration) = &change.migration { - if !migration.supported { - println!(" migration UNSUPPORTED:"); - } - for step in &migration.steps { - println!( - " {}", - serde_json::to_string(step).unwrap_or_else(|_| format!("{step:?}")) - ); - } - } - } - if output.changes.is_empty() { - println!(" no changes"); - } - } else { - println!("cluster plan failed"); - } - print_cluster_diagnostics(&output.diagnostics); -} - -pub(crate) fn print_cluster_apply_human(output: &ApplyOutput) { - if output.ok { - println!( - "cluster apply: {} applied, {} deferred/blocked", - output.applied_count, output.deferred_count - ); - } else { - println!("cluster apply failed"); - } - // The change list prints on failure too: an operator debugging a partial - // apply (payload or state-write error) needs to see what was attempted. - print_cluster_apply_changes(&output.changes); - if output.ok { - let state = &output.state_observations; - println!( - " state: revision {}, converged: {}, written: {}", - state.state_revision, output.converged, output.state_written - ); - println!(" note: cluster-booted servers (--cluster) serve this on their next restart; omnigraph.yaml deployments are unaffected"); - } - print_cluster_diagnostics(&output.diagnostics); -} - -pub(crate) fn print_cluster_apply_changes(changes: &[omnigraph_cluster::PlanChange]) { - for change in changes { - let bindings = if change.binding_change { " [bindings]" } else { "" }; - match (&change.disposition, change.reason.as_deref()) { - (Some(disposition), Some(reason)) => println!( - " {:?} {}{bindings} [{disposition:?}: {reason}]", - change.operation, change.resource - ), - (Some(disposition), None) => println!( - " {:?} {}{bindings} [{disposition:?}]", - change.operation, change.resource - ), - _ => println!(" {:?} {}{bindings}", change.operation, change.resource), - } - } - if changes.is_empty() { - println!(" no changes"); - } -} - -pub(crate) fn print_cluster_status_human(output: &StatusOutput) { - if output.ok { - let state = &output.state_observations; - if state.state_found { - println!( - "cluster state: revision {}, {} resource(s)", - state.state_revision, state.resource_count - ); - if let Some(digest) = state.applied_config_digest.as_deref() { - println!(" applied config: {digest}"); - } - if state.locked { - println!(" lock: held{}", cluster_lock_summary(state)); - } else { - println!(" lock: not held"); - } - } else { - println!("cluster state missing"); - } - } else { - println!("cluster status failed"); - } - print_cluster_diagnostics(&output.diagnostics); -} - -pub(crate) fn print_cluster_state_sync_human(output: &StateSyncOutput) { - let operation = match output.operation { - omnigraph_cluster::StateSyncOperation::Refresh => "refresh", - omnigraph_cluster::StateSyncOperation::Import => "import", - }; - if output.ok { - let state = &output.state_observations; - println!( - "cluster {operation}: revision {}, {} resource(s)", - state.state_revision, state.resource_count - ); - if let Some(cas) = state.state_cas.as_deref() { - println!(" state_cas: {cas}"); - } - if state.locked { - println!(" lock: acquired{}", cluster_lock_summary(state)); - } else { - println!(" lock: not acquired"); - } - } else { - println!("cluster {operation} failed"); - } - print_cluster_diagnostics(&output.diagnostics); -} - -pub(crate) fn print_cluster_force_unlock_human(output: &ForceUnlockOutput) { - if output.ok { - if output.lock_removed { - println!( - "cluster force-unlock: removed lock{}", - cluster_lock_summary(&output.state_observations) - ); - } else { - println!("cluster force-unlock: no lock removed"); - } - } else { - println!("cluster force-unlock failed"); - if output.state_observations.locked { - println!( - " lock: held{}", - cluster_lock_summary(&output.state_observations) - ); - } - } - print_cluster_diagnostics(&output.diagnostics); -} - -pub(crate) fn cluster_lock_summary(state: &omnigraph_cluster::StateObservations) -> String { - let Some(lock_id) = state.lock_id.as_deref() else { - return String::new(); - }; - let mut parts = vec![format!("id={lock_id}")]; - if let Some(operation) = state.lock_operation.as_deref() { - parts.push(format!("operation={operation}")); - } - if let Some(pid) = state.lock_pid { - parts.push(format!("pid={pid}")); - } - if let Some(created_at) = state.lock_created_at.as_deref() { - parts.push(format!("created_at={created_at}")); - } - if let Some(age_seconds) = state.lock_age_seconds { - parts.push(format!("age_seconds={age_seconds}")); - } - format!(" ({})", parts.join(", ")) -} - -pub(crate) fn print_cluster_diagnostics(diagnostics: &[omnigraph_cluster::Diagnostic]) { - for diagnostic in diagnostics { - let label = match diagnostic.severity { - DiagnosticSeverity::Error => "ERROR", - DiagnosticSeverity::Warning => "WARN ", - }; - println!( - "{label} {} {}: {}", - diagnostic.code, diagnostic.path, diagnostic.message - ); - } -} - -pub(crate) fn finish_cluster_validate(output: &ValidateOutput, json: bool) -> Result<()> { - if json { - print_json(output)?; - } else { - print_cluster_validate_human(output); - } - if !output.ok { - io::stdout().flush()?; - std::process::exit(1); - } - Ok(()) -} - -pub(crate) fn finish_cluster_plan(output: &PlanOutput, json: bool) -> Result<()> { - if json { - print_json(output)?; - } else { - print_cluster_plan_human(output); - } - if !output.ok { - io::stdout().flush()?; - std::process::exit(1); - } - Ok(()) -} - -pub(crate) fn finish_cluster_apply(output: &ApplyOutput, json: bool) -> Result<()> { - if json { - print_json(output)?; - } else { - print_cluster_apply_human(output); - } - if !output.ok { - io::stdout().flush()?; - std::process::exit(1); - } - Ok(()) -} - -pub(crate) fn finish_cluster_approve(output: &ApproveOutput, json: bool) -> Result<()> { - if json { - print_json(output)?; - } else if output.ok { - println!( - "cluster approve: {} {} approved by {} (approval {})", - output - .operation - .as_ref() - .map(|operation| format!("{operation:?}").to_lowercase()) - .unwrap_or_default(), - output.resource.as_deref().unwrap_or("?"), - output.approved_by.as_deref().unwrap_or("?"), - output.approval_id.as_deref().unwrap_or("?"), - ); - print_cluster_diagnostics(&output.diagnostics); - } else { - println!("cluster approve failed"); - print_cluster_diagnostics(&output.diagnostics); - } - if !output.ok { - io::stdout().flush()?; - std::process::exit(1); - } - Ok(()) -} - -pub(crate) fn finish_cluster_status(output: &StatusOutput, json: bool) -> Result<()> { - if json { - print_json(output)?; - } else { - print_cluster_status_human(output); - } - if !output.ok { - io::stdout().flush()?; - std::process::exit(1); - } - Ok(()) -} - -pub(crate) fn finish_cluster_state_sync(output: &StateSyncOutput, json: bool) -> Result<()> { - if json { - print_json(output)?; - } else { - print_cluster_state_sync_human(output); - } - if !output.ok { - io::stdout().flush()?; - std::process::exit(1); - } - Ok(()) -} - -pub(crate) fn finish_cluster_force_unlock(output: &ForceUnlockOutput, json: bool) -> Result<()> { - if json { - print_json(output)?; - } else { - print_cluster_force_unlock_human(output); - } - if !output.ok { - io::stdout().flush()?; - std::process::exit(1); - } - Ok(()) -} - -pub(crate) fn print_load_human(payload: &LoadOutput) { - println!( - "loaded {} on branch {} with {}: {} nodes across {} node types, {} edges across {} edge types", - payload.uri, - payload.branch, - payload.mode, - payload.nodes_loaded, - payload.node_types_loaded, - payload.edges_loaded, - payload.edge_types_loaded - ); - if payload.branch_created { - if let Some(base) = &payload.base_branch { - println!("branch {} created from {}", payload.branch, base); - } - } -} - -pub(crate) fn print_ingest_human(output: &IngestOutput) { - println!( - "ingested {} into branch {} from {} with {} ({})", - output.uri, - output.branch, - output.base_branch.as_deref().unwrap_or("main"), - output.mode.as_str(), - if output.branch_created { - "branch created" - } else { - "branch exists" - } - ); - for table in &output.tables { - println!("{} rows_loaded={}", table.table_key, table.rows_loaded); - } - if let Some(actor_id) = &output.actor_id { - println!("actor_id: {}", actor_id); - } -} - -pub(crate) fn print_schema_plan_human(uri: &str, plan: &SchemaMigrationPlan) { - println!("schema plan for {}", uri); - println!("supported: {}", if plan.supported { "yes" } else { "no" }); - if plan.steps.is_empty() { - println!("no schema changes"); - return; - } - for step in &plan.steps { - println!("- {}", render_schema_plan_step(step)); - } -} - -pub(crate) fn render_schema_plan_step(step: &SchemaMigrationStep) -> String { - match step { - SchemaMigrationStep::AddType { type_kind, name } => { - format!("add {} type '{}'", schema_type_kind_label(*type_kind), name) - } - SchemaMigrationStep::RenameType { - type_kind, - from, - to, - } => format!( - "rename {} type '{}' -> '{}'", - schema_type_kind_label(*type_kind), - from, - to - ), - SchemaMigrationStep::AddProperty { - type_kind, - type_name, - property_name, - property_type, - } => format!( - "add property '{}.{}' ({}) on {} '{}'", - type_name, - property_name, - render_prop_type(property_type), - schema_type_kind_label(*type_kind), - type_name - ), - SchemaMigrationStep::RenameProperty { - type_kind, - type_name, - from, - to, - } => format!( - "rename property '{}.{}' -> '{}.{}' on {} '{}'", - type_name, - from, - type_name, - to, - schema_type_kind_label(*type_kind), - type_name - ), - SchemaMigrationStep::AddConstraint { - type_kind, - type_name, - constraint, - } => format!( - "add constraint {} on {} '{}'", - render_constraint(constraint), - schema_type_kind_label(*type_kind), - type_name - ), - SchemaMigrationStep::UpdateTypeMetadata { - type_kind, - name, - annotations, - } => format!( - "update metadata on {} '{}' ({})", - schema_type_kind_label(*type_kind), - name, - render_annotations(annotations) - ), - SchemaMigrationStep::UpdatePropertyMetadata { - type_kind, - type_name, - property_name, - annotations, - } => format!( - "update metadata on property '{}.{}' of {} '{}' ({})", - type_name, - property_name, - schema_type_kind_label(*type_kind), - type_name, - render_annotations(annotations) - ), - SchemaMigrationStep::DropType { - type_kind, - name, - mode, - } => format!( - "drop {} type '{}' ({} mode)", - schema_type_kind_label(*type_kind), - name, - drop_mode_label(*mode), - ), - SchemaMigrationStep::DropProperty { - type_kind, - type_name, - property_name, - mode, - } => format!( - "drop property '{}.{}' of {} '{}' ({} mode)", - type_name, - property_name, - schema_type_kind_label(*type_kind), - type_name, - drop_mode_label(*mode), - ), - 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. - // Reach the diagnostic via the `diagnostic()` helper so the - // CLI doesn't need to know how the lookup works. - match step.diagnostic() { - Some(diag) => format!( - "unsupported change on {} [{}, {}]: {}", - entity, - diag.code, - schema_lint_tier_label(diag.tier), - reason, - ), - None => format!("unsupported change on {}: {}", entity, reason), - } - } - } -} - -pub(crate) fn schema_type_kind_label(kind: omnigraph_compiler::SchemaTypeKind) -> &'static str { - match kind { - omnigraph_compiler::SchemaTypeKind::Interface => "interface", - omnigraph_compiler::SchemaTypeKind::Node => "node", - omnigraph_compiler::SchemaTypeKind::Edge => "edge", - } -} - -pub(crate) fn schema_lint_tier_label(tier: omnigraph_compiler::SafetyTier) -> &'static str { - match tier { - omnigraph_compiler::SafetyTier::Safe => "safe", - omnigraph_compiler::SafetyTier::Validated => "validated", - omnigraph_compiler::SafetyTier::Destructive => "destructive", - } -} - -pub(crate) fn drop_mode_label(mode: omnigraph_compiler::DropMode) -> &'static str { - match mode { - omnigraph_compiler::DropMode::Soft => "soft", - omnigraph_compiler::DropMode::Hard => "hard", - } -} - -pub(crate) fn render_prop_type(prop_type: &omnigraph_compiler::PropType) -> String { - let base = if let Some(values) = &prop_type.enum_values { - format!("Enum({})", values.join("|")) - } else { - prop_type.scalar.to_string() - }; - let base = if prop_type.list { - format!("[{}]", base) - } else { - base - }; - if prop_type.nullable { - format!("{}?", base) - } else { - base - } -} - -pub(crate) fn render_constraint(constraint: &omnigraph_compiler::schema::ast::Constraint) -> String { - match constraint { - omnigraph_compiler::schema::ast::Constraint::Key(columns) => { - format!("@key({})", columns.join(", ")) - } - omnigraph_compiler::schema::ast::Constraint::Unique(columns) => { - format!("@unique({})", columns.join(", ")) - } - omnigraph_compiler::schema::ast::Constraint::Index(columns) => { - format!("@index({})", columns.join(", ")) - } - omnigraph_compiler::schema::ast::Constraint::Range { property, min, max } => { - format!("@range({}, {:?}, {:?})", property, min, max) - } - omnigraph_compiler::schema::ast::Constraint::Check { property, pattern } => { - format!("@check({}, {:?})", property, pattern) - } - } -} - -pub(crate) fn render_annotations(annotations: &[omnigraph_compiler::schema::ast::Annotation]) -> String { - annotations - .iter() - .map(|annotation| match &annotation.value { - Some(value) => format!("@{}({})", annotation.name, value), - None => format!("@{}", annotation.name), - }) - .collect::>() - .join(", ") -} - -pub(crate) fn print_embed_human(output: &EmbedOutput) { - println!( - "embedded {} rows (selected {}, cleaned {}) from {} -> {} [{} {}d]", - output.embedded_rows, - output.selected_rows, - output.cleaned_rows, - output.input, - output.output, - output.mode, - output.dimension - ); -} - -pub(crate) fn print_snapshot_human(branch: &str, manifest_version: u64, entries: &[SnapshotTableOutput]) { - println!("branch: {}", branch); - println!("manifest_version: {}", manifest_version); - for entry in entries { - println!( - "{} v{} branch={} rows={}", - entry.table_key, - entry.table_version, - entry.table_branch.as_deref().unwrap_or("main"), - entry.row_count - ); - } -} - -pub(crate) fn print_read_output( - output: &ReadOutput, - format: ReadOutputFormat, - config: &OmnigraphConfig, -) -> Result<()> { - println!( - "{}", - render_read( - output, - format, - &resolve_table_render_options(config), - )? - ); - Ok(()) -} - -pub(crate) fn print_change_human(output: &ChangeOutput) { - println!( - "changed {} via {}: {} nodes, {} edges", - output.branch, output.query_name, output.affected_nodes, output.affected_edges - ); - if let Some(actor_id) = &output.actor_id { - println!("actor_id: {}", actor_id); - } -} - -pub(crate) fn print_commit_list_human(commits: &[CommitOutput]) { - for commit in commits { - let branch = commit.manifest_branch.as_deref().unwrap_or("main"); - println!( - "{} branch={} version={}{}", - commit.graph_commit_id, - branch, - commit.manifest_version, - commit - .actor_id - .as_deref() - .map(|actor| format!(" actor={}", actor)) - .unwrap_or_default() - ); - } -} - -pub(crate) fn print_commit_human(commit: &CommitOutput) { - println!("graph_commit_id: {}", commit.graph_commit_id); - println!( - "manifest_branch: {}", - commit.manifest_branch.as_deref().unwrap_or("main") - ); - println!("manifest_version: {}", commit.manifest_version); - if let Some(parent_commit_id) = &commit.parent_commit_id { - println!("parent_commit_id: {}", parent_commit_id); - } - if let Some(merged_parent_commit_id) = &commit.merged_parent_commit_id { - println!("merged_parent_commit_id: {}", merged_parent_commit_id); - } - if let Some(actor_id) = &commit.actor_id { - println!("actor_id: {}", actor_id); - } - println!("created_at: {}", commit.created_at); -} - -pub(crate) fn print_policy_explain(decision: &PolicyDecision, actor_id: &str, request: &PolicyRequest) { - println!( - "decision: {}", - if decision.allowed { "allow" } else { "deny" } - ); - println!("actor: {}", actor_id); - println!("action: {}", request.action); - if let Some(branch) = &request.branch { - println!("branch: {}", branch); - } - if let Some(target_branch) = &request.target_branch { - println!("target_branch: {}", target_branch); - } - if let Some(rule_id) = &decision.matched_rule_id { - println!("matched_rule: {}", rule_id); - } - println!("message: {}", decision.message); -} - -pub(crate) fn yaml_string(value: &str) -> String { - format!("'{}'", value.replace('\'', "''")) -} - -#[derive(serde::Serialize)] -pub(crate) struct QueriesIssue { - pub(crate) query: String, - pub(crate) message: String, -} - -#[derive(serde::Serialize)] -pub(crate) struct QueriesValidateOutput { - pub(crate) ok: bool, - pub(crate) breakages: Vec, - pub(crate) warnings: Vec, -} - -#[derive(serde::Serialize)] -pub(crate) struct QueriesParam { - pub(crate) name: String, - #[serde(rename = "type")] - pub(crate) type_name: String, - pub(crate) nullable: bool, -} - -#[derive(serde::Serialize)] -pub(crate) struct QueriesListItem { - pub(crate) name: String, - pub(crate) mcp_expose: bool, - pub(crate) tool_name: Option, - pub(crate) mutation: bool, - pub(crate) params: Vec, -} - -#[derive(serde::Serialize)] -pub(crate) struct QueriesListOutput { - pub(crate) queries: Vec, -} - -pub(crate) fn finish_login( - server: &str, - credentials_path: &std::path::Path, - declared: bool, - json: bool, -) -> Result<()> { - if json { - print_json(&serde_json::json!({ - "server": server, - "credentials_path": credentials_path.display().to_string(), - "declared": declared, - }))?; - } else { - println!( - "stored credential for '{server}' in {}", - credentials_path.display() - ); - } - if !declared { - eprintln!( - "note: '{server}' is not declared under servers: in the operator config; the token applies once you add `servers:\n {server}:\n url: ` to ~/.omnigraph/config.yaml" - ); - } - Ok(()) -} - -pub(crate) fn finish_logout( - server: &str, - credentials_path: &std::path::Path, - json: bool, -) -> Result<()> { - if json { - print_json(&serde_json::json!({ - "server": server, - "credentials_path": credentials_path.display().to_string(), - }))?; - } else { - println!( - "removed credential for '{server}' from {}", - credentials_path.display() - ); - } - Ok(()) -} - -/// Table prefs cascade (RFC-007/008): legacy cli.table_* (window) > -/// operator defaults.table_* > built-in. -pub(crate) fn resolve_table_render_options(config: &OmnigraphConfig) -> ReadRenderOptions { - let operator = crate::operator::load_operator_config().unwrap_or_default(); - ReadRenderOptions { - max_column_width: config - .cli - .table_max_column_width - .or(operator.defaults.table_max_column_width) - .unwrap_or(80), - cell_layout: config - .cli - .table_cell_layout - .or(operator.defaults.table_cell_layout) - .unwrap_or_default(), - } -} diff --git a/crates/omnigraph-cli/tests/cli_data.rs b/crates/omnigraph-cli/tests/cli.rs similarity index 54% rename from crates/omnigraph-cli/tests/cli_data.rs rename to crates/omnigraph-cli/tests/cli.rs index 203a7c2..9682d9a 100644 --- a/crates/omnigraph-cli/tests/cli_data.rs +++ b/crates/omnigraph-cli/tests/cli.rs @@ -1,8 +1,7 @@ -//! Data commands: load/read/change/branch/commit/export/snapshot/policy/embed/maintenance. -//! Moved verbatim from tests/cli.rs in the modularization. - use std::fs; +use lance::index::DatasetIndexExt; +use omnigraph::db::{Omnigraph, ReadTarget}; use serde_json::Value; use tempfile::tempdir; @@ -10,6 +9,85 @@ mod support; use support::*; +const POLICY_YAML: &str = r#" +version: 1 +groups: + team: [act-andrew, act-bruno] + admins: [act-andrew] +protected_branches: [main] +rules: + - id: team-read + allow: + actors: { group: team } + actions: [read] + branch_scope: any + - id: team-write + allow: + actors: { group: team } + actions: [change] + branch_scope: unprotected + - id: admins-promote + allow: + actors: { group: admins } + actions: [branch_merge] + target_branch_scope: protected +"#; + +const POLICY_TESTS_YAML: &str = r#" +version: 1 +cases: + - id: allow-feature-write + actor: act-andrew + action: change + branch: feature + expect: allow + - id: deny-main-write + actor: act-bruno + action: change + branch: main + expect: deny +"#; + +fn manifest_dataset_version(graph: &std::path::Path) -> u64 { + tokio::runtime::Runtime::new().unwrap().block_on(async { + Omnigraph::open(graph.to_string_lossy().as_ref()) + .await + .unwrap() + .snapshot_of(ReadTarget::branch("main")) + .await + .unwrap() + .version() + }) +} + +fn write_policy_config_fixture(root: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) { + let config = root.join("omnigraph.yaml"); + let policy = root.join("policy.yaml"); + fs::write( + &config, + r#" +project: + name: policy-test-graph +policy: + file: ./policy.yaml +"#, + ) + .unwrap(); + fs::write(&policy, POLICY_YAML).unwrap(); + fs::write(root.join("policy.tests.yaml"), POLICY_TESTS_YAML).unwrap(); + (config, policy) +} + +#[test] +fn version_command_prints_current_cli_version() { + let output = output_success(cli().arg("version")); + let stdout = stdout_string(&output); + + assert_eq!( + stdout.trim(), + format!("omnigraph {}", env!("CARGO_PKG_VERSION")) + ); +} #[test] fn short_version_flag_prints_current_cli_version() { @@ -143,80 +221,320 @@ fn embed_seed_preserves_non_entity_rows() { } #[test] -fn repair_json_reports_noop_on_clean_graph() { +fn init_creates_graph_successfully_on_missing_local_directory() { let temp = tempdir().unwrap(); let graph = graph_path(temp.path()); - init_graph(&graph); - load_fixture(&graph); + let schema = fixture("test.pg"); - let output = output_success(cli().arg("repair").arg("--json").arg(&graph)); + let output = output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&graph)); + let stdout = stdout_string(&output); + + assert!(stdout.contains("initialized")); + 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 graph = graph_path(temp.path()); + let schema_path = temp.path().join("next.pg"); + init_graph(&graph); + + let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( + " age: I32?\n}", + " age: I32?\n nickname: String?\n}", + ); + fs::write(&schema_path, next_schema).unwrap(); + + let output = output_success( + cli() + .arg("schema") + .arg("plan") + .arg("--schema") + .arg(&schema_path) + .arg("--json") + .arg(&graph), + ); let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(payload["confirm"], false); - assert_eq!(payload["force"], false); - assert_eq!(payload["manifest_version"], Value::Null); - let tables = payload["tables"].as_array().unwrap(); - assert_eq!(tables.len(), 4); - assert!(tables.iter().all(|table| { - table["classification"] == "no_drift" && table["action"] == "no_op" + assert_eq!(payload["supported"], true); + assert_eq!(payload["step_count"], 1); + assert_eq!(payload["steps"][0]["kind"], "add_property"); + assert_eq!(payload["steps"][0]["type_kind"], "node"); + assert_eq!(payload["steps"][0]["type_name"], "Person"); + assert_eq!(payload["steps"][0]["property_name"], "nickname"); +} + +#[test] +fn schema_plan_json_reports_unsupported_type_change() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = temp.path().join("breaking.pg"); + init_graph(&graph); + + let breaking_schema = fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("age: I32?", "age: I64?"); + fs::write(&schema_path, breaking_schema).unwrap(); + + let output = output_success( + cli() + .arg("schema") + .arg("plan") + .arg("--schema") + .arg(&schema_path) + .arg("--json") + .arg(&graph), + ); + let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); + + assert_eq!(payload["supported"], false); + assert!(payload["steps"].as_array().unwrap().iter().any(|step| { + step["kind"] == "unsupported_change" + && step["entity"] + .as_str() + .unwrap_or_default() + .contains("Person.age") })); } #[test] -fn repair_confirm_json_refuses_suspicious_drift_with_nonzero_exit_then_force_succeeds() { +fn schema_apply_json_applies_supported_migration() { let temp = tempdir().unwrap(); let graph = graph_path(temp.path()); + let schema_path = temp.path().join("next.pg"); init_graph(&graph); - load_fixture(&graph); - let graph_manifest_before = manifest_dataset_version(&graph); - let (table_manifest_before, table_head_before) = forge_person_delete_drift(&graph); - let refused = output_failure( + let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( + " age: I32?\n}", + " age: I32?\n nickname: String?\n}", + ); + fs::write(&schema_path, next_schema).unwrap(); + + let output = output_success( cli() - .arg("repair") - .arg("--confirm") + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) .arg("--json") .arg(&graph), ); - let refused_payload: Value = serde_json::from_slice(&refused.stdout).unwrap(); - assert_eq!(refused_payload["manifest_version"], Value::Null); - let person = refused_payload["tables"] - .as_array() + let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); + + assert_eq!(payload["supported"], true); + assert_eq!(payload["applied"], true); + assert_eq!(payload["step_count"], 1); + + let db = tokio::runtime::Runtime::new() .unwrap() - .iter() - .find(|table| table["table_key"] == "node:Person") + .block_on(Omnigraph::open(graph.to_string_lossy().as_ref())) .unwrap(); - assert_eq!(person["classification"], "suspicious"); - assert_eq!(person["action"], "refused"); assert!( - String::from_utf8_lossy(&refused.stderr).contains("repair refused"), - "stderr should explain the non-zero exit; got: {}", - String::from_utf8_lossy(&refused.stderr) + db.catalog().node_types["Person"] + .properties + .contains_key("nickname") ); - assert_eq!(manifest_dataset_version(&graph), graph_manifest_before); +} - let forced = output_success( +#[test] +fn schema_apply_human_reports_noop() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = fixture("test.pg"); + init_graph(&graph); + + let output = output_success( cli() - .arg("repair") - .arg("--force") - .arg("--confirm") + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) + .arg(&graph), + ); + let stdout = stdout_string(&output); + + assert!(stdout.contains("applied: no")); + assert!(stdout.contains("no schema changes")); +} + +#[test] +fn schema_apply_json_renames_type_and_updates_snapshot() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = temp.path().join("rename.pg"); + init_graph(&graph); + + let renamed_schema = fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("node Person {\n", "node Human @rename_from(\"Person\") {\n") + .replace("edge Knows: Person -> Person", "edge Knows: Human -> Human") + .replace( + "edge WorksAt: Person -> Company", + "edge WorksAt: Human -> Company", + ); + fs::write(&schema_path, renamed_schema).unwrap(); + + let output = output_success( + cli() + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) .arg("--json") .arg(&graph), ); - let forced_payload: Value = serde_json::from_slice(&forced.stdout).unwrap(); - let forced_manifest = forced_payload["manifest_version"].as_u64().unwrap(); - assert!(forced_manifest > graph_manifest_before); - let person = forced_payload["tables"] - .as_array() + let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(payload["applied"], true); + + let db = tokio::runtime::Runtime::new() .unwrap() - .iter() - .find(|table| table["table_key"] == "node:Person") + .block_on(Omnigraph::open(graph.to_string_lossy().as_ref())) .unwrap(); - assert_eq!(person["classification"], "suspicious"); - assert_eq!(person["action"], "forced"); - assert_eq!(person["manifest_version"], table_manifest_before); - assert_eq!(person["lance_head_version"], table_head_before); - assert_eq!(manifest_dataset_version(&graph), forced_manifest); + let snapshot = tokio::runtime::Runtime::new() + .unwrap() + .block_on(db.snapshot_of(ReadTarget::branch("main"))) + .unwrap(); + assert!(snapshot.entry("node:Human").is_some()); + assert!(snapshot.entry("node:Person").is_none()); +} + +#[test] +fn schema_apply_json_renames_property_and_updates_catalog() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = temp.path().join("rename-property.pg"); + init_graph(&graph); + + let renamed_schema = fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("age: I32?", "years: I32? @rename_from(\"age\")"); + fs::write(&schema_path, renamed_schema).unwrap(); + + let output = output_success( + cli() + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) + .arg("--json") + .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(graph.to_string_lossy().as_ref())) + .unwrap(); + let person = &db.catalog().node_types["Person"]; + assert!(person.properties.contains_key("years")); + assert!(!person.properties.contains_key("age")); +} + +#[test] +fn schema_apply_json_adds_index_for_existing_property() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = temp.path().join("index.pg"); + init_graph(&graph); + + let before_index_count = tokio::runtime::Runtime::new().unwrap().block_on(async { + let db = Omnigraph::open(graph.to_string_lossy().as_ref()) + .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() + }); + + let indexed_schema = fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("name: String @key", "name: String @key @index"); + fs::write(&schema_path, indexed_schema).unwrap(); + + let output = output_success( + cli() + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) + .arg("--json") + .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(graph.to_string_lossy().as_ref()) + .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() + }); + assert!(after_index_count > before_index_count); +} + +#[test] +fn schema_apply_rejects_unsupported_plan() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = temp.path().join("breaking.pg"); + init_graph(&graph); + + let breaking_schema = fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("age: I32?", "age: I64?"); + fs::write(&schema_path, breaking_schema).unwrap(); + + let output = output_failure( + cli() + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) + .arg(&graph), + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("changing property type")); +} + +#[test] +fn schema_apply_rejects_when_non_main_branch_exists() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = temp.path().join("next.pg"); + init_graph(&graph); + output_success( + cli() + .arg("branch") + .arg("create") + .arg("--from") + .arg("main") + .arg("--uri") + .arg(&graph) + .arg("feature"), + ); + + let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( + " age: I32?\n}", + " age: I32?\n nickname: String?\n}", + ); + fs::write(&schema_path, next_schema).unwrap(); + + let output = output_failure( + cli() + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) + .arg(&graph), + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("schema apply requires a graph with only main")); } #[test] @@ -266,6 +584,57 @@ query update_policy($slug: String, $name: String) { ); } +#[test] +fn query_check_alias_matches_lint_output() { + 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 lint_output = output_success( + cli() + .arg("query") + .arg("lint") + .arg("--query") + .arg(&query_path) + .arg("--schema") + .arg(&schema_path) + .arg("--json"), + ); + let check_output = output_success( + cli() + .arg("query") + .arg("check") + .arg("--query") + .arg(&query_path) + .arg("--schema") + .arg(&schema_path) + .arg("--json"), + ); + + 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 lint_top_level_matches_deprecated_query_lint_output() { let temp = tempdir().unwrap(); @@ -345,6 +714,12 @@ query list_people() { ); } +/// 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(); @@ -410,6 +785,10 @@ query list_people() { ); } +/// `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 @@ -419,7 +798,8 @@ fn deprecated_read_and_change_subcommands_emit_warnings() { 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`"), + stderr.contains("`omnigraph read` is deprecated") + && stderr.contains("`omnigraph query`"), "expected `omnigraph read` deprecation warning; got: {stderr}" ); @@ -669,8 +1049,6 @@ fn load_json_outputs_summary_for_main_branch() { let output = output_success( cli() .arg("load") - .arg("--mode") - .arg("overwrite") .arg("--data") .arg(&data) .arg("--json") @@ -958,6 +1336,135 @@ fn read_can_resolve_uri_from_config() { assert_eq!(payload["row_count"], 1); } +#[test] +fn read_alias_from_yaml_config_runs_with_kv_output() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let config = temp.path().join("omnigraph.yaml"); + let query = temp.path().join("aliases.gq"); + init_graph(&graph); + load_fixture(&graph); + write_query_file( + &query, + &std::fs::read_to_string(fixture("test.gq")).unwrap(), + ); + write_config( + &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(&graph) + ), + ); + + let output = output_success( + cli() + .arg("read") + .arg("--config") + .arg(&config) + .arg("--alias") + .arg("owner") + .arg("Alice"), + ); + let stdout = stdout_string(&output); + + assert!(stdout.contains("row 1")); + assert!(stdout.contains("p.name: Alice")); +} + +#[test] +fn read_alias_uses_alias_target_without_cli_default_and_accepts_url_like_arg() { + let temp = tempdir().unwrap(); + 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_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(&graph)); + write_query_file( + &query, + &std::fs::read_to_string(fixture("test.gq")).unwrap(), + ); + write_config( + &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", + graph.to_string_lossy() + ), + ); + + let output = output_success( + cli() + .arg("read") + .arg("--config") + .arg(&config) + .arg("--alias") + .arg("owner") + .arg("https://example.com"), + ); + let stdout = stdout_string(&output); + + assert!(stdout.contains("row 1")); + assert!(stdout.contains("p.name: https://example.com")); +} + +#[test] +fn change_alias_from_yaml_config_persists_changes() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let config = temp.path().join("omnigraph.yaml"); + let query = temp.path().join("mutations.gq"); + init_graph(&graph); + load_fixture(&graph); + write_query_file( + &query, + r#" +query insert_person($name: String, $age: I32) { + insert Person { name: $name, age: $age } +} +"#, + ); + write_config( + &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(&graph) + ), + ); + + let output = output_success( + cli() + .arg("change") + .arg("--config") + .arg(&config) + .arg("--alias") + .arg("add_person") + .arg("Eve") + .arg("29") + .arg("--json"), + ); + let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(payload["affected_nodes"], 1); + + let verify = output_success( + cli() + .arg("read") + .arg(&graph) + .arg("--query") + .arg(fixture("test.gq")) + .arg("--name") + .arg("get_person") + .arg("--params") + .arg(r#"{"name":"Eve"}"#) + .arg("--json"), + ); + let verify_payload: Value = serde_json::from_slice(&verify.stdout).unwrap(); + assert_eq!(verify_payload["row_count"], 1); +} + #[test] fn read_csv_format_outputs_header_and_row_values() { let temp = tempdir().unwrap(); @@ -984,52 +1491,6 @@ fn read_csv_format_outputs_header_and_row_values() { assert!(stdout.contains("Alice")); } -/// RFC-007 PR 1: the format cascade's operator hop β€” `defaults.output` in -/// ~/.omnigraph/config.yaml applies when nothing more specific is given, -/// and `--format` still wins over it. -#[test] -fn read_uses_operator_default_output_format() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - init_graph(&graph); - load_fixture(&graph); - let operator_home = tempdir().unwrap(); - fs::write( - operator_home.path().join("config.yaml"), - "defaults:\n output: csv\n", - ) - .unwrap(); - - let read = |extra: &[&str]| { - let mut command = cli(); - command - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("read") - .arg(&graph) - .arg("--query") - .arg(fixture("test.gq")) - .arg("--name") - .arg("get_person") - .arg("--params") - .arg(r#"{"name":"Alice"}"#); - for arg in extra { - command.arg(arg); - } - stdout_string(&output_success(&mut command)) - }; - - let stdout = read(&[]); - assert!( - stdout.lines().next().unwrap().contains("p.name") && stdout.contains("Alice"), - "operator defaults.output: csv applies with no --format: {stdout}" - ); - let stdout = read(&["--format", "jsonl"]); - assert!( - stdout.starts_with('{'), - "--format wins over the operator default: {stdout}" - ); -} - #[test] fn read_jsonl_format_outputs_metadata_header_first() { let temp = tempdir().unwrap(); @@ -1521,6 +1982,68 @@ fn snapshot_json_returns_manifest_version_and_tables() { assert!(payload["tables"].as_array().unwrap().len() >= 4); } +fn write_seed_fixture(root: &std::path::Path) -> std::path::PathBuf { + fs::create_dir_all(root.join("data")).unwrap(); + fs::create_dir_all(root.join("build")).unwrap(); + let raw_seed = root.join("data/seed.jsonl"); + let seed = root.join("seed.yaml"); + + fs::write( + &raw_seed, + concat!( + "{\"type\":\"Decision\",\"data\":{\"slug\":\"dec-alpha\",\"intent\":\"Alpha ship\"}}\n", + "{\"type\":\"Decision\",\"data\":{\"slug\":\"dec-beta\",\"intent\":\"Beta ship\",\"embedding\":[0.1,0.2]}}\n" + ), + ) + .unwrap(); + + fs::write( + &seed, + concat!( + "graph:\n", + " slug: mr-context-graph\n", + "sources:\n", + " raw_seed: ./data/seed.jsonl\n", + "artifacts:\n", + " embedded_seed: ./build/seed.embedded.jsonl\n", + "embeddings:\n", + " model: gemini-embedding-2-preview\n", + " dimension: 4\n", + " types:\n", + " Decision:\n", + " target: embedding\n", + " fields: [slug, intent]\n" + ), + ) + .unwrap(); + + seed +} + +fn write_seed_fixture_with_edge(root: &std::path::Path) -> std::path::PathBuf { + let seed = write_seed_fixture(root); + let raw_seed = root.join("data/seed.jsonl"); + fs::write( + &raw_seed, + concat!( + "{\"type\":\"Decision\",\"data\":{\"slug\":\"dec-alpha\",\"intent\":\"Alpha ship\"}}\n", + "{\"type\":\"Decision\",\"data\":{\"slug\":\"dec-beta\",\"intent\":\"Beta ship\",\"embedding\":[0.1,0.2]}}\n", + "{\"edge\":\"Triggered\",\"from\":\"sig-alpha\",\"to\":\"dec-alpha\"}\n" + ), + ) + .unwrap(); + seed +} + +fn read_embedded_rows(path: std::path::PathBuf) -> Vec { + fs::read_to_string(path) + .unwrap() + .lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| serde_json::from_str(line).unwrap()) + .collect() +} + #[test] fn snapshot_can_resolve_uri_from_config() { let temp = tempdir().unwrap(); @@ -1624,8 +2147,6 @@ fn cli_fails_for_missing_schema_or_data_file() { let load_output = output_failure( cli() .arg("load") - .arg("--mode") - .arg("overwrite") .arg("--data") .arg(&missing_data) .arg(&graph), @@ -1675,3 +2196,475 @@ fn cli_fails_for_invalid_merge_requests() { .contains("distinct source and target") ); } + +// `omnigraph run list/show/publish/abort` subcommands removed +// alongside the run state machine. Direct-to-target writes leave nothing +// for these CLIs to manage. Audit history is now visible via +// `omnigraph commit list` reading the commit graph. + +// ─── MR-694 PR B: --allow-data-loss flag end-to-end ────────────────────── +// +// The schema-lint chassis v1.2 (PR #100) shipped the `--allow-data-loss` +// flag at the CLI layer; the SDK suite verifies promotion to Hard mode +// via `apply_schema_with_options(.., SchemaApplyOptions { allow_data_loss })`. +// These CLI tests close the integration gap so a future change that +// drops the flag wiring in `main.rs` turns red. + +#[test] +fn schema_apply_allow_data_loss_flag_promotes_drops_to_hard() { + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = temp.path().join("drop-age.pg"); + init_graph(&graph); + + // Drop the nullable `age` column. + let next_schema = fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace(" age: I32?\n", ""); + fs::write(&schema_path, next_schema).unwrap(); + + let output = output_success( + cli() + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) + .arg("--allow-data-loss") + .arg("--json") + .arg(&graph), + ); + let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(payload["applied"], true); + + let drop_step = payload["steps"] + .as_array() + .unwrap() + .iter() + .find(|s| s["kind"] == "drop_property") + .expect("plan should include a drop_property step"); + assert_eq!( + drop_step["mode"], "hard", + "--allow-data-loss should promote Soft β†’ Hard; full step: {drop_step}", + ); +} + +#[test] +fn schema_apply_without_allow_data_loss_keeps_soft_drops() { + // Symmetric to the above: same schema change without the flag β†’ + // drops stay Soft. Pins default semantics against accidental Hard + // promotion if a future refactor changes the option threading. + let temp = tempdir().unwrap(); + let graph = graph_path(temp.path()); + let schema_path = temp.path().join("drop-age-soft.pg"); + init_graph(&graph); + + let next_schema = fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace(" age: I32?\n", ""); + fs::write(&schema_path, next_schema).unwrap(); + + let output = output_success( + cli() + .arg("schema") + .arg("apply") + .arg("--schema") + .arg(&schema_path) + .arg("--json") + .arg(&graph), + ); + let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(payload["applied"], true); + + let drop_step = payload["steps"] + .as_array() + .unwrap() + .iter() + .find(|s| s["kind"] == "drop_property") + .expect("plan should include a drop_property step"); + assert_eq!( + drop_step["mode"], "soft", + "no flag should leave drops Soft; full step: {drop_step}", + ); +} + +#[test] +fn schema_plan_parity_cli_and_sdk() { + // Same .pg through `Omnigraph::plan_schema_with_options` (SDK) and + // `omnigraph schema plan --json` (CLI). Asserts the steps array is + // byte-identical after JSON round-trip. HTTP doesn't expose a + // separate /schema/plan route β€” that side of parity is covered by + // the HTTP soft/hard drop tests, which exercise apply with + // identical fixtures. + let temp = tempdir().unwrap(); + 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}", + " age: I32?\n nickname: String?\n}", + ); + fs::write(&schema_path, &next_schema).unwrap(); + + // CLI side. + let cli_output = output_success( + cli() + .arg("schema") + .arg("plan") + .arg("--schema") + .arg(&schema_path) + .arg("--json") + .arg(&graph), + ); + let cli_payload: Value = serde_json::from_slice(&cli_output.stdout).unwrap(); + + // SDK side: open graph, call plan_schema. + let plan = tokio::runtime::Runtime::new().unwrap().block_on(async { + let db = Omnigraph::open(graph.to_string_lossy().as_ref()) + .await + .unwrap(); + db.plan_schema(&next_schema).await.unwrap() + }); + let sdk_steps = serde_json::to_value(&plan.steps).unwrap(); + + assert_eq!( + cli_payload["steps"], sdk_steps, + "CLI plan steps must match SDK plan steps for identical input", + ); + 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/cli_cluster.rs b/crates/omnigraph-cli/tests/cli_cluster.rs deleted file mode 100644 index 3b2eed3..0000000 --- a/crates/omnigraph-cli/tests/cli_cluster.rs +++ /dev/null @@ -1,952 +0,0 @@ -//! Cluster command surface: validate/plan/apply/approve/status/sync/force-unlock. -//! Moved verbatim from tests/cli.rs in the modularization. - -use std::fs; - -use tempfile::tempdir; - -mod support; - -use support::*; - - -#[test] -fn cluster_validate_config_success() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - - let output = output_success( - cli() - .arg("cluster") - .arg("validate") - .arg("--config") - .arg(temp.path()), - ); - let stdout = stdout_string(&output); - assert!(stdout.contains("cluster config valid"), "{stdout}"); -} - -#[test] -fn cluster_validate_json_is_stable() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("validate") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert!(json["resource_digests"]["graph.knowledge"].is_string()); - assert!(json["resource_digests"]["query.knowledge.find_person"].is_string()); - assert_eq!(json["dependencies"][0]["from"], "policy.base"); - assert_eq!(json["dependencies"][0]["to"], "graph.knowledge"); -} - -#[test] -fn cluster_plan_json_reads_inferred_local_state() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - let state_dir = temp.path().join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#" -{ - "version": 1, - "applied_revision": { - "config_digest": "old", - "resources": { - "graph.knowledge": { "digest": "old-graph" }, - "policy.old": { "digest": "old-policy" } - } - } -} -"#, - ) - .unwrap(); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("plan") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert_eq!(json["state_observations"]["state_found"], true); - assert!( - json["changes"] - .as_array() - .unwrap() - .iter() - .any(|change| change["resource"] == "policy.old" && change["operation"] == "delete"), - "plan should read state and delete stale resources: {json}" - ); -} - -#[test] -fn cluster_status_json_reports_missing_state() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("status") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert_eq!(json["state_observations"]["state_found"], false); - assert!( - json["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_missing"), - "missing state should be a warning diagnostic: {json}" - ); -} - -#[test] -fn cluster_status_json_reports_lock_metadata() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - write_cluster_lock(temp.path(), "held-lock", "refresh"); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("status") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert_eq!(json["state_observations"]["locked"], true); - assert_eq!(json["state_observations"]["lock_id"], "held-lock"); - assert_eq!(json["state_observations"]["lock_operation"], "refresh"); - assert_eq!(json["state_observations"]["lock_pid"], 123); - assert_eq!( - json["state_observations"]["lock_created_at"], - "1970-01-01T00:00:00Z" - ); - assert!(json["state_observations"]["lock_age_seconds"].is_number()); -} - -#[test] -fn cluster_status_json_reports_extended_state() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - let state_dir = temp.path().join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#" -{ - "version": 1, - "state_revision": 5, - "applied_revision": { - "config_digest": "applied", - "resources": { - "graph.knowledge": { "digest": "graph-digest" } - } - }, - "resource_statuses": { - "graph.knowledge": { "status": "applied", "conditions": ["healthy"] } - }, - "approval_records": {}, - "recovery_records": {}, - "observations": {} -} -"#, - ) - .unwrap(); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("status") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert_eq!(json["state_observations"]["state_revision"], 5); - assert!( - json["state_observations"]["state_cas"] - .as_str() - .unwrap() - .starts_with("sha256:") - ); - assert_eq!(json["resource_digests"]["graph.knowledge"], "graph-digest"); - assert_eq!( - json["resource_statuses"]["graph.knowledge"]["status"], - "applied" - ); -} - -#[test] -fn cluster_plan_json_includes_state_cas_revision_and_lock_observation() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - let state_dir = temp.path().join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#" -{ - "version": 1, - "state_revision": 9, - "applied_revision": { - "config_digest": "old", - "resources": { - "graph.knowledge": { "digest": "old-graph" } - } - } -} -"#, - ) - .unwrap(); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("plan") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert_eq!(json["state_observations"]["state_revision"], 9); - assert!( - json["state_observations"]["state_cas"] - .as_str() - .unwrap() - .starts_with("sha256:") - ); - assert_eq!(json["state_observations"]["locked"], false); - assert_eq!(json["state_observations"]["lock_acquired"], true); - assert!(json["state_observations"]["acquired_lock_id"].is_string()); - assert!(!state_dir.join("lock.json").exists()); -} - -#[test] -fn cluster_plan_locked_state_exits_nonzero() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - write_cluster_lock(temp.path(), "held-lock", "plan"); - - let output = output_failure( - cli() - .arg("cluster") - .arg("plan") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - ); - let json = parse_stdout_json(&output); - assert_eq!(json["ok"], false); - assert_eq!(json["state_observations"]["locked"], true); - assert_eq!(json["state_observations"]["lock_acquired"], false); - assert_eq!(json["state_observations"]["lock_id"], "held-lock"); - assert_eq!(json["state_observations"]["lock_operation"], "plan"); - assert_eq!(json["state_observations"]["lock_pid"], 123); - assert_eq!( - json["state_observations"]["lock_created_at"], - "1970-01-01T00:00:00Z" - ); - assert!(json["state_observations"]["lock_age_seconds"].is_number()); - assert!( - json["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_lock_held" - && diagnostic["message"] - .as_str() - .unwrap() - .contains("force-unlock held-lock")), - "locked state should produce a useful diagnostic: {json}" - ); -} - -#[test] -fn cluster_force_unlock_json_removes_lock() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - write_cluster_lock(temp.path(), "held-lock", "plan"); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("force-unlock") - .arg("held-lock") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert_eq!(json["lock_removed"], true); - assert_eq!(json["state_observations"]["lock_id"], "held-lock"); - assert_eq!(json["state_observations"]["lock_operation"], "plan"); - assert!(!temp.path().join("__cluster/lock.json").exists()); -} - -#[test] -fn cluster_force_unlock_wrong_id_exits_nonzero() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - write_cluster_lock(temp.path(), "held-lock", "plan"); - - let json = parse_stdout_json(&output_failure( - cli() - .arg("cluster") - .arg("force-unlock") - .arg("other-lock") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], false); - assert_eq!(json["lock_removed"], false); - assert!( - json["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_lock_id_mismatch") - ); - assert!(temp.path().join("__cluster/lock.json").exists()); -} - -#[test] -fn cluster_locked_plan_then_force_unlock_then_plan_succeeds() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - write_cluster_lock(temp.path(), "held-lock", "plan"); - - let locked = parse_stdout_json(&output_failure( - cli() - .arg("cluster") - .arg("plan") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(locked["ok"], false); - assert_eq!(locked["state_observations"]["lock_id"], "held-lock"); - - let unlocked = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("force-unlock") - .arg("held-lock") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(unlocked["lock_removed"], true); - - let planned = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("plan") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(planned["ok"], true); -} - -#[test] -fn cluster_import_json_bootstraps_missing_state() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - init_cluster_derived_graph(temp.path()); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("import") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert_eq!(json["operation"], "import"); - assert_eq!(json["state_observations"]["state_revision"], 1); - assert!( - json["state_observations"]["state_cas"] - .as_str() - .unwrap() - .starts_with("sha256:") - ); - assert_eq!(json["state_observations"]["locked"], false); - assert_eq!(json["state_observations"]["lock_acquired"], true); - assert!(json["state_observations"]["acquired_lock_id"].is_string()); - assert!(json["observations"]["graph.knowledge"]["manifest_version"].is_number()); - assert_eq!( - json["resource_statuses"]["graph.knowledge"]["status"], - "applied" - ); - assert!(temp.path().join("__cluster/state.json").exists()); - assert!(!temp.path().join("__cluster/lock.json").exists()); -} - -#[test] -fn cluster_refresh_json_updates_revision_cas_and_removes_lock() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - init_cluster_derived_graph(temp.path()); - let state_dir = temp.path().join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#" -{ - "version": 1, - "state_revision": 2, - "applied_revision": { "resources": {} } -} -"#, - ) - .unwrap(); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("refresh") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true); - assert_eq!(json["operation"], "refresh"); - assert_eq!(json["state_observations"]["state_revision"], 3); - assert!( - json["state_observations"]["state_cas"] - .as_str() - .unwrap() - .starts_with("sha256:") - ); - assert_eq!(json["state_observations"]["locked"], false); - assert_eq!(json["state_observations"]["lock_acquired"], true); - assert!(json["state_observations"]["acquired_lock_id"].is_string()); - assert!(!state_dir.join("lock.json").exists()); -} - -#[test] -fn cluster_refresh_missing_state_exits_nonzero() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - - let output = output_failure( - cli() - .arg("cluster") - .arg("refresh") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - ); - let json = parse_stdout_json(&output); - assert_eq!(json["ok"], false); - assert!( - json["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_missing"), - "missing state should produce a useful diagnostic: {json}" - ); -} - -#[test] -fn cluster_import_existing_state_exits_nonzero() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - let state_dir = temp.path().join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"applied_revision":{"resources":{}}}"#, - ) - .unwrap(); - - let output = output_failure( - cli() - .arg("cluster") - .arg("import") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - ); - let json = parse_stdout_json(&output); - assert_eq!(json["ok"], false); - assert!( - json["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_already_exists"), - "existing state should produce a useful diagnostic: {json}" - ); -} - -#[test] -fn cluster_refresh_and_import_locked_state_exit_nonzero() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - let state_dir = temp.path().join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"applied_revision":{"resources":{}}}"#, - ) - .unwrap(); - fs::write( - state_dir.join("lock.json"), - r#"{"version":1,"lock_id":"held-lock","operation":"refresh","created_at":"2026-06-08T00:00:00Z","pid":123}"#, - ) - .unwrap(); - - let refresh = parse_stdout_json(&output_failure( - cli() - .arg("cluster") - .arg("refresh") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(refresh["state_observations"]["locked"], true); - assert_eq!(refresh["state_observations"]["lock_id"], "held-lock"); - assert_eq!(refresh["state_observations"]["lock_acquired"], false); - assert!( - refresh["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_lock_held") - ); - - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - let state_dir = temp.path().join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("lock.json"), - r#"{"version":1,"lock_id":"held-lock","operation":"import","created_at":"2026-06-08T00:00:00Z","pid":123}"#, - ) - .unwrap(); - - let imported = parse_stdout_json(&output_failure( - cli() - .arg("cluster") - .arg("import") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(imported["state_observations"]["locked"], true); - assert_eq!(imported["state_observations"]["lock_id"], "held-lock"); - assert_eq!(imported["state_observations"]["lock_acquired"], false); - assert!( - imported["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_lock_held") - ); -} - -#[test] -fn cluster_validate_invalid_config_exits_nonzero() { - let temp = tempdir().unwrap(); - fs::write( - temp.path().join("cluster.yaml"), - "version: 1\ngraphs: {}\npipelines: {}\n", - ) - .unwrap(); - - let output = output_failure( - cli() - .arg("cluster") - .arg("validate") - .arg("--config") - .arg(temp.path()), - ); - let stdout = stdout_string(&output); - assert!(stdout.contains("future_phase_field"), "{stdout}"); -} - -#[test] -fn cluster_apply_json_applies_query_and_policy() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - let validate = write_cluster_applyable_state(temp.path()); - - let json = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("apply") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(json["ok"], true, "{json}"); - assert_eq!(json["applied_count"], 2, "{json}"); - assert_eq!(json["converged"], true, "{json}"); - assert_eq!(json["state_written"], true, "{json}"); - assert_eq!( - json["resource_statuses"]["query.knowledge.find_person"]["status"], - "applied" - ); - - let query_digest = validate["resource_digests"]["query.knowledge.find_person"] - .as_str() - .unwrap(); - let payload = temp - .path() - .join("__cluster/resources/query/knowledge/find_person") - .join(format!("{query_digest}.gq")); - assert!(payload.exists(), "missing payload {}", payload.display()); - - let state: serde_json::Value = serde_json::from_str( - &fs::read_to_string(temp.path().join("__cluster/state.json")).unwrap(), - ) - .unwrap(); - assert_eq!(state["state_revision"], 2); - assert_eq!( - state["applied_revision"]["resources"]["query.knowledge.find_person"]["digest"], - *query_digest - ); -} - -#[test] -fn cluster_apply_missing_state_exits_nonzero() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - - let output = output_failure( - cli() - .arg("cluster") - .arg("apply") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - ); - let json = parse_stdout_json(&output); - assert_eq!(json["ok"], false); - assert!( - json["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_missing"), - "{json}" - ); - assert!(!temp.path().join("__cluster/resources").exists()); -} - -#[test] -fn cluster_apply_locked_exits_nonzero() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - write_cluster_applyable_state(temp.path()); - write_cluster_lock(temp.path(), "held-lock", "plan"); - - let output = output_failure( - cli() - .arg("cluster") - .arg("apply") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - ); - let json = parse_stdout_json(&output); - assert_eq!(json["ok"], false); - assert!( - json["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "state_lock_held"), - "{json}" - ); - assert!(temp.path().join("__cluster/lock.json").exists()); - assert!(!temp.path().join("__cluster/resources").exists()); -} - -#[test] -fn cluster_apply_uses_cli_actor_from_local_config() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - fs::write( - temp.path().join("omnigraph.yaml"), - "cli:\n actor: act-local\n", - ) - .unwrap(); - // Phase 1: import once (setup, not under test). - let output = cli() - .current_dir(temp.path()) - .arg("cluster") - .arg("import") - .arg("--config") - .arg(temp.path()) - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - - // Phase 2: apply alone, capturing the echoed actor (idempotent re-runs). - let apply = |extra: &[&str]| { - let mut command = cli(); - command.current_dir(temp.path()); - for arg in extra { - command.arg(arg); - } - let output = command - .arg("cluster") - .arg("apply") - .arg("--config") - .arg(temp.path()) - .arg("--json") - .output() - .unwrap(); - let json: serde_json::Value = - serde_json::from_str(String::from_utf8_lossy(&output.stdout).trim()).unwrap(); - json["actor"].clone() - }; - assert_eq!(apply(&[]), "act-local", "cli.actor is the no-flag default"); - assert_eq!(apply(&["--as", "andrew"]), "andrew", "--as overrides cli.actor"); -} - -/// RFC-007 PR 1: the operator layer joins the actor chain β€” -/// `--as` > legacy `cli.actor` (RFC-008 window) > `operator.actor` > none. -#[test] -fn cluster_apply_uses_operator_actor_from_omnigraph_home() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - let operator_home = tempdir().unwrap(); - fs::write( - operator_home.path().join("config.yaml"), - "operator:\n actor: act-operator\n", - ) - .unwrap(); - - let output = cli() - .current_dir(temp.path()) - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("cluster") - .arg("import") - .arg("--config") - .arg(temp.path()) - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - - let apply = |extra: &[&str]| { - let mut command = cli(); - command - .current_dir(temp.path()) - .env("OMNIGRAPH_HOME", operator_home.path()); - for arg in extra { - command.arg(arg); - } - let output = command - .arg("cluster") - .arg("apply") - .arg("--config") - .arg(temp.path()) - .arg("--json") - .output() - .unwrap(); - let json: serde_json::Value = - serde_json::from_str(String::from_utf8_lossy(&output.stdout).trim()).unwrap(); - json["actor"].clone() - }; - - // No --as, no omnigraph.yaml: the operator identity applies. - assert_eq!( - apply(&[]), - "act-operator", - "operator.actor is the no-flag, no-legacy-config default" - ); - // --as still wins over everything. - assert_eq!(apply(&["--as", "andrew"]), "andrew"); - - // A legacy cli.actor (RFC-008 window) outranks the operator layer. - fs::write( - temp.path().join("omnigraph.yaml"), - "cli:\n actor: act-legacy\n", - ) - .unwrap(); - assert_eq!( - apply(&[]), - "act-legacy", - "legacy cli.actor wins over operator.actor during the deprecation window" - ); -} - -#[test] -fn cluster_approve_uses_cli_actor_fallback() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - fs::write( - temp.path().join("omnigraph.yaml"), - "cli:\n actor: act-local\n", - ) - .unwrap(); - // Converge, then remove the graph so a gated delete is pending. - for command in ["import", "apply"] { - let output = cli() - .current_dir(temp.path()) - .arg("cluster") - .arg(command) - .arg("--config") - .arg(temp.path()) - .output() - .unwrap(); - assert!(output.status.success(), "cluster {command} failed"); - } - fs::write(temp.path().join("cluster.yaml"), "version: 1\ngraphs: {}\n").unwrap(); - - let output = cli() - .current_dir(temp.path()) - .arg("cluster") - .arg("approve") - .arg("graph.knowledge") - .arg("--config") - .arg(temp.path()) - .arg("--json") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - let json: serde_json::Value = - serde_json::from_str(String::from_utf8_lossy(&output.stdout).trim()).unwrap(); - assert_eq!(json["approved_by"], "act-local"); - - // With neither flag nor config: refused with the actionable message. - let bare = tempdir().unwrap(); - write_cluster_config_fixture(bare.path()); - let output = output_failure( - cli() - .current_dir(bare.path()) - .arg("cluster") - .arg("approve") - .arg("graph.knowledge") - .arg("--config") - .arg(bare.path()), - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("--as"), "{stderr}"); - assert!(stderr.contains("cli.actor"), "{stderr}"); -} - -#[test] -fn cluster_commands_ignore_malformed_local_config() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - fs::write(temp.path().join("omnigraph.yaml"), "{{{{ not yaml").unwrap(); - - for command in ["validate", "plan", "status"] { - let output = cli() - .current_dir(temp.path()) - .arg("cluster") - .arg(command) - .arg("--config") - .arg(temp.path()) - .arg("--json") - .output() - .unwrap(); - assert!( - output.status.success() || command == "plan", // plan warns state-missing pre-import; still must not config-error - "cluster {command} affected by malformed omnigraph.yaml: {output:?}" - ); - assert!( - !String::from_utf8_lossy(&output.stderr).contains("omnigraph.yaml"), - "cluster {command} touched omnigraph.yaml" - ); - } - // import + apply with an explicit --as: the config is never loaded. - for (command, args) in [("import", vec![]), ("apply", vec!["--as", "andrew"])] { - let mut invocation = cli(); - invocation.current_dir(temp.path()); - for arg in &args { - invocation.arg(arg); - } - let output = invocation - .arg("cluster") - .arg(command) - .arg("--config") - .arg(temp.path()) - .output() - .unwrap(); - assert!( - output.status.success(), - "cluster {command} affected by malformed omnigraph.yaml: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - // Only the no-flag actor lookup is allowed to fail, and loudly. - let output = output_failure( - cli() - .current_dir(temp.path()) - .arg("cluster") - .arg("apply") - .arg("--config") - .arg(temp.path()), - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("omnigraph.yaml") && stderr.contains("--as"), - "the actor-default config read must fail loudly and actionably: {stderr}" - ); -} - -#[test] -fn cluster_commands_ignore_conflicting_local_config() { - let baseline = tempdir().unwrap(); - write_cluster_config_fixture(baseline.path()); - let with_config = tempdir().unwrap(); - write_cluster_config_fixture(with_config.path()); - fs::write( - with_config.path().join("omnigraph.yaml"), - r#" -server: - bind: 0.0.0.0:9999 -graphs: - phantom: - uri: ./phantom.omni -"#, - ) - .unwrap(); - - let validate = |dir: &std::path::Path| { - let output = cli() - .current_dir(dir) - .arg("cluster") - .arg("validate") - .arg("--config") - .arg(dir) - .arg("--json") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - serde_json::from_str::(String::from_utf8_lossy(&output.stdout).trim()) - .unwrap() - }; - let (a, b) = (validate(baseline.path()), validate(with_config.path())); - // Compare the path-free invariants (paths embed each tempdir). - for key in ["ok", "diagnostics", "resource_digests", "dependencies"] { - assert_eq!(a[key], b[key], "conflicting omnigraph.yaml leaked into cluster validate ({key})"); - } - let leaked = b.to_string(); - assert!(!leaked.contains("phantom") && !leaked.contains("9999"), "{leaked}"); -} - diff --git a/crates/omnigraph-cli/tests/cli_cluster_e2e.rs b/crates/omnigraph-cli/tests/cli_cluster_e2e.rs deleted file mode 100644 index 36b476a..0000000 --- a/crates/omnigraph-cli/tests/cli_cluster_e2e.rs +++ /dev/null @@ -1,621 +0,0 @@ -//! Cluster lifecycle compositions over the spawned binary (recovery, drift, convergence). -//! Moved verbatim from tests/cli.rs in the modularization. - -use std::fs; - -use tempfile::tempdir; - -mod support; - -use support::*; - - -#[test] -fn cluster_e2e_lifecycle_import_apply_status_refresh_converges() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - init_cluster_derived_graph(temp.path()); - - let import = cluster_json(temp.path(), "import"); - assert_eq!(import["ok"], true, "{import}"); - assert_eq!(import["state_observations"]["state_revision"], 1); - - let plan = cluster_json(temp.path(), "plan"); - let changes = plan["changes"].as_array().unwrap(); - assert_eq!(changes.len(), 3, "{plan}"); - let disposition_of = |resource: &str| { - changes - .iter() - .find(|change| change["resource"] == resource) - .unwrap_or_else(|| panic!("missing change for {resource}: {plan}"))["disposition"] - .clone() - }; - assert_eq!(disposition_of("graph.knowledge"), "derived"); - assert_eq!(disposition_of("query.knowledge.find_person"), "applied"); - assert_eq!(disposition_of("policy.base"), "applied"); - - let apply = cluster_json(temp.path(), "apply"); - assert_eq!(apply["ok"], true, "{apply}"); - assert_eq!(apply["applied_count"], 2, "{apply}"); - assert_eq!(apply["converged"], true, "{apply}"); - - let status = cluster_json(temp.path(), "status"); - assert_eq!( - status["resource_statuses"]["query.knowledge.find_person"]["status"], - "applied" - ); - assert_eq!(status["resource_statuses"]["policy.base"]["status"], "applied"); - assert!( - status["state_observations"]["applied_config_digest"].is_string(), - "converged apply must record the applied config digest: {status}" - ); - - // Refresh re-observes the live graph; it must not undo apply's work. - let refresh = cluster_json(temp.path(), "refresh"); - assert_eq!(refresh["ok"], true, "{refresh}"); - let replan = cluster_json(temp.path(), "plan"); - assert!( - replan["changes"].as_array().unwrap().is_empty(), - "refresh after a converged apply must not re-open the plan: {replan}" - ); - - // A query edit round-trips: plan update -> apply -> converged again. - fs::write( - temp.path().join("people.gq"), - r#" -query find_person($name: String) { - match { $p: Person { name: $name } } - return { $p.name } -} -"#, - ) - .unwrap(); - let apply_edit = cluster_json(temp.path(), "apply"); - assert_eq!(apply_edit["applied_count"], 1, "{apply_edit}"); - assert_eq!(apply_edit["converged"], true, "{apply_edit}"); - - let final_apply = cluster_json(temp.path(), "apply"); - assert_eq!(final_apply["state_written"], false, "{final_apply}"); - assert!(final_apply["changes"].as_array().unwrap().is_empty()); -} - -#[test] -fn cluster_e2e_schema_change_applied_by_cluster() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - init_cluster_derived_graph(temp.path()); - let import = cluster_json(temp.path(), "import"); - assert_eq!(import["ok"], true, "{import}"); - let apply = cluster_json(temp.path(), "apply"); - assert_eq!(apply["converged"], true, "{apply}"); - - // Additive schema change: Stage 4B applies it from the cluster β€” no - // manual schema apply, no refresh round-trip. - fs::write( - temp.path().join("people.pg"), - r#" -node Person { - name: String @key - age: I32? - bio: String? -} -"#, - ) - .unwrap(); - - // Plan previews the real migration steps (RFC-004 Β§D7). - let plan = cluster_json(temp.path(), "plan"); - let schema_change = change_for(&plan, "schema.knowledge"); - assert_eq!(schema_change["disposition"], "applied", "{plan}"); - let migration = &schema_change["migration"]; - assert_eq!(migration["supported"], true, "{plan}"); - assert!( - migration["steps"] - .as_array() - .unwrap() - .iter() - .any(|step| step["kind"] == "add_property"), - "{plan}" - ); - - let evolve = cluster_json(temp.path(), "apply"); - assert_eq!(evolve["ok"], true, "{evolve}"); - assert_eq!(evolve["converged"], true, "{evolve}"); - assert_eq!(change_for(&evolve, "schema.knowledge")["disposition"], "applied"); - - // The live graph carries the new schema; the plan is empty. - let schema_show = output_success( - cli() - .arg("schema") - .arg("show") - .arg(temp.path().join("graphs/knowledge.omni")), - ); - assert!(stdout_string(&schema_show).contains("bio"), "live schema updated"); - let replan = cluster_json(temp.path(), "plan"); - assert!( - replan["changes"].as_array().unwrap().is_empty(), - "one cluster apply converges a schema change: {replan}" - ); -} - -#[test] -fn cluster_e2e_force_unlock_unblocks_apply() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - write_cluster_applyable_state(temp.path()); - write_cluster_lock(temp.path(), "stuck-lock", "apply"); - - let refused = parse_stdout_json(&output_failure( - cli() - .arg("cluster") - .arg("apply") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(refused["ok"], false); - - let unlocked = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("force-unlock") - .arg("stuck-lock") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(unlocked["lock_removed"], true, "{unlocked}"); - - let retried = cluster_json(temp.path(), "apply"); - assert_eq!(retried["ok"], true, "{retried}"); - assert_eq!(retried["converged"], true, "{retried}"); -} - -#[test] -fn cluster_e2e_lost_state_reimport_recovers_catalog() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - init_cluster_derived_graph(temp.path()); - let import = cluster_json(temp.path(), "import"); - assert_eq!(import["ok"], true, "{import}"); - let apply = cluster_json(temp.path(), "apply"); - assert_eq!(apply["converged"], true, "{apply}"); - - let query_digest = change_for(&apply, "query.knowledge.find_person")["after_digest"] - .as_str() - .unwrap() - .to_string(); - let blob = temp - .path() - .join("__cluster/resources/query/knowledge/find_person") - .join(format!("{query_digest}.gq")); - let blob_content = fs::read_to_string(&blob).unwrap(); - - // Disaster: the state ledger is lost. - fs::remove_file(temp.path().join("__cluster/state.json")).unwrap(); - - let reimport = cluster_json(temp.path(), "import"); - assert_eq!(reimport["ok"], true, "{reimport}"); - assert_eq!(reimport["state_observations"]["state_revision"], 1); - // Import observes graph/schema only; query/policy digests are not invented. - assert!( - reimport["resource_digests"] - .get("query.knowledge.find_person") - .is_none(), - "{reimport}" - ); - - let plan = cluster_json(temp.path(), "plan"); - assert_eq!( - change_for(&plan, "query.knowledge.find_person")["disposition"], - "applied" - ); - assert_eq!(change_for(&plan, "policy.base")["disposition"], "applied"); - - let reapply = cluster_json(temp.path(), "apply"); - assert_eq!(reapply["ok"], true, "{reapply}"); - assert_eq!(reapply["converged"], true, "{reapply}"); - assert!( - reapply["state_observations"]["applied_config_digest"].is_string(), - "{reapply}" - ); - // The catalog blob was reused, not rewritten with different content. - assert_eq!(fs::read_to_string(&blob).unwrap(), blob_content); - - let replan = cluster_json(temp.path(), "plan"); - assert!(replan["changes"].as_array().unwrap().is_empty(), "{replan}"); -} - -#[test] -fn cluster_e2e_out_of_band_schema_drift_then_apply_converges_it() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - init_cluster_derived_graph(temp.path()); - let import = cluster_json(temp.path(), "import"); - assert_eq!(import["ok"], true, "{import}"); - let apply = cluster_json(temp.path(), "apply"); - assert_eq!(apply["converged"], true, "{apply}"); - - // Out-of-band: the live graph evolves, cluster.yaml stays put. - fs::write( - temp.path().join("people_v2.pg"), - r#" -node Person { - name: String @key - age: I32? - bio: String? -} -"#, - ) - .unwrap(); - output_success( - cli() - .arg("schema") - .arg("apply") - .arg(temp.path().join("graphs/knowledge.omni")) - .arg("--schema") - .arg(temp.path().join("people_v2.pg")) - .arg("--json"), - ); - - // Drift is visible... - let refresh = cluster_json(temp.path(), "refresh"); - assert_eq!( - refresh["resource_statuses"]["schema.knowledge"]["status"], - "drifted" - ); - // ...the plan proposes converging back to desired, with a migration - // preview (a soft drop of the out-of-band field)... - let plan = cluster_json(temp.path(), "plan"); - let schema_change = change_for(&plan, "schema.knowledge"); - assert_eq!(schema_change["disposition"], "applied", "{plan}"); - assert!( - schema_change["migration"]["steps"] - .as_array() - .unwrap() - .iter() - .any(|step| step["kind"] == "drop_property" && step["mode"] == "soft"), - "{plan}" - ); - // ...and apply converges the live schema back (axiom 8: drift correction - // is gated like any change; a soft migration is the recoverable tier). - let converge = cluster_json(temp.path(), "apply"); - assert_eq!(converge["ok"], true, "{converge}"); - assert_eq!(converge["converged"], true, "{converge}"); - let schema_show = output_success( - cli() - .arg("schema") - .arg("show") - .arg(temp.path().join("graphs/knowledge.omni")), - ); - assert!( - !stdout_string(&schema_show).contains("bio"), - "out-of-band field soft-dropped back to desired" - ); - let replan = cluster_json(temp.path(), "plan"); - assert!(replan["changes"].as_array().unwrap().is_empty(), "{replan}"); -} - -#[test] -fn cluster_e2e_graph_root_destruction_drifts_then_apply_recreates_empty_graph() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - init_cluster_derived_graph(temp.path()); - let import = cluster_json(temp.path(), "import"); - assert_eq!(import["ok"], true, "{import}"); - let apply = cluster_json(temp.path(), "apply"); - assert_eq!(apply["converged"], true, "{apply}"); - let query_digest = change_for(&apply, "query.knowledge.find_person")["after_digest"] - .as_str() - .unwrap() - .to_string(); - - fs::remove_dir_all(temp.path().join("graphs/knowledge.omni")).unwrap(); - - // Missing root is drift, not an error. - let refresh = cluster_json(temp.path(), "refresh"); - assert_eq!(refresh["ok"], true, "{refresh}"); - assert_eq!( - refresh["resource_statuses"]["graph.knowledge"]["status"], - "drifted" - ); - assert!( - refresh["resource_statuses"]["graph.knowledge"]["conditions"] - .as_array() - .unwrap() - .iter() - .any(|condition| condition == "graph_missing"), - "{refresh}" - ); - // Graph/schema digests removed; query/policy digests preserved. - assert!(refresh["resource_digests"].get("graph.knowledge").is_none()); - assert!(refresh["resource_digests"].get("schema.knowledge").is_none()); - assert!( - refresh["resource_digests"] - .get("query.knowledge.find_person") - .is_some(), - "{refresh}" - ); - - let plan = cluster_json(temp.path(), "plan"); - assert_eq!(change_for(&plan, "graph.knowledge")["operation"], "create"); - // Stage 4A: the re-create is executable and the plan says so β€” nothing - // hidden about converging a destroyed root back to an EMPTY graph (the - // data was already lost; this is declarative convergence, RFC-004 Β§D1). - assert_eq!(change_for(&plan, "graph.knowledge")["disposition"], "applied"); - assert_eq!(change_for(&plan, "schema.knowledge")["disposition"], "applied"); - // Converged-then-destroyed: query/policy are already in state at the - // desired digests, so they are not changes at all. - assert_eq!(plan["changes"].as_array().unwrap().len(), 2, "{plan}"); - - let recreate = cluster_json(temp.path(), "apply"); - assert_eq!(recreate["ok"], true, "{recreate}"); - assert_eq!(recreate["converged"], true, "{recreate}"); - // The empty graph is back on disk; catalog state survived throughout. - assert!(temp.path().join("graphs/knowledge.omni").exists()); - let state: serde_json::Value = serde_json::from_str( - &fs::read_to_string(temp.path().join("__cluster/state.json")).unwrap(), - ) - .unwrap(); - assert_eq!( - state["applied_revision"]["resources"]["query.knowledge.find_person"]["digest"], - query_digest - ); - assert!( - temp.path() - .join("__cluster/resources/query/knowledge/find_person") - .join(format!("{query_digest}.gq")) - .exists() - ); -} - -#[test] -fn cluster_e2e_multi_graph_mixed_dispositions_then_approve_and_converge() { - let temp = tempdir().unwrap(); - write_multi_graph_cluster_fixture(temp.path()); - // No manual init: Stage 4A creates both graphs. - - let import = cluster_json(temp.path(), "import"); - assert_eq!(import["ok"], true, "{import}"); - - let apply = cluster_json(temp.path(), "apply"); - assert_eq!(apply["ok"], true, "{apply}"); - assert_eq!(apply["converged"], true, "{apply}"); - assert_eq!(change_for(&apply, "graph.knowledge")["disposition"], "applied"); - assert_eq!( - change_for(&apply, "graph.engineering")["disposition"], - "applied" - ); - assert_eq!( - change_for(&apply, "query.engineering.find_service")["disposition"], - "applied" - ); - // The graph-spanning and cluster-scoped policies ride the same run. - assert_eq!(change_for(&apply, "policy.shared")["disposition"], "applied"); - assert_eq!( - change_for(&apply, "policy.cluster_wide")["disposition"], - "applied" - ); - assert!(temp.path().join("graphs/knowledge.omni").exists()); - assert!(temp.path().join("graphs/engineering.omni").exists()); - - // Mixed run: a graph REMOVAL (4C territory β€” deferred) gates its query - // delete (blocked), while a knowledge query update is independent - // (applied) and re-derives its composite. All four dispositions at once. - fs::write( - temp.path().join("cluster.yaml"), - r#" -version: 1 -metadata: - name: company-brain -state: - backend: cluster - lock: true -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -policies: - shared: - file: ./shared.policy.yaml - applies_to: [knowledge] - cluster_wide: - file: ./cluster_wide.policy.yaml - applies_to: [cluster] -"#, - ) - .unwrap(); - fs::write( - temp.path().join("people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n", - ) - .unwrap(); - - let mixed = cluster_json(temp.path(), "apply"); - assert_eq!(mixed["ok"], true, "{mixed}"); - assert_eq!(mixed["converged"], false, "{mixed}"); - // Stage 4C: deletes are gated on a digest-bound approval, one gate per - // subtree (the graph-level approval carries schema + queries). - assert_eq!( - change_for(&mixed, "graph.engineering")["disposition"], - "blocked" - ); - assert_eq!( - change_for(&mixed, "graph.engineering")["reason"], - "approval_required" - ); - assert_eq!( - change_for(&mixed, "schema.engineering")["reason"], - "approval_required" - ); - assert_eq!( - change_for(&mixed, "query.engineering.find_service")["reason"], - "approval_required" - ); - let gate_plan = cluster_json(temp.path(), "plan"); - let gates = gate_plan["approvals_required"].as_array().unwrap(); - assert_eq!(gates.len(), 1, "{gate_plan}"); - assert_eq!(gates[0]["resource"], "graph.engineering"); - assert_eq!(gates[0]["satisfied"], false); - assert_eq!( - change_for(&mixed, "query.knowledge.find_person")["disposition"], - "applied" - ); - // 5A: policy.shared's applies_to narrowed with an unchanged file digest - // β€” now a first-class binding change, applied in the same run. - assert_eq!(change_for(&mixed, "policy.shared")["binding_change"], true); - assert_eq!(change_for(&mixed, "policy.shared")["disposition"], "applied"); - assert_eq!( - change_for(&mixed, "graph.knowledge")["disposition"], - "derived" - ); - // Deterministic ordering: changes sorted by resource address. - let order: Vec<&str> = mixed["changes"] - .as_array() - .unwrap() - .iter() - .map(|change| change["resource"].as_str().unwrap()) - .collect(); - let mut sorted = order.clone(); - sorted.sort_unstable(); - assert_eq!(order, sorted, "{mixed}"); - // The conclusion: an apply without approval stays blocked; the approved - // delete converges the cluster, tombstoning the removed graph. - let still_blocked = cluster_json(temp.path(), "apply"); - assert_eq!(still_blocked["converged"], false, "{still_blocked}"); - - let approve = parse_stdout_json(&output_success( - cli() - .arg("--as") - .arg("andrew") - .arg("cluster") - .arg("approve") - .arg("graph.engineering") - .arg("--config") - .arg(temp.path()) - .arg("--json"), - )); - assert_eq!(approve["ok"], true, "{approve}"); - assert_eq!(approve["approved_by"], "andrew"); - - let converge = cluster_json(temp.path(), "apply"); - assert_eq!(converge["ok"], true, "{converge}"); - assert_eq!(converge["converged"], true, "{converge}"); - assert!(!temp.path().join("graphs/engineering.omni").exists()); - - let status = cluster_json(temp.path(), "status"); - assert_eq!(status["observations"]["graph.engineering"]["kind"], "tombstone"); - let final_plan = cluster_json(temp.path(), "plan"); - assert!( - final_plan["changes"].as_array().unwrap().is_empty(), - "{final_plan}" - ); -} - -#[test] -fn cluster_e2e_approve_requires_actor() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - - let output = output_failure( - cli() - .arg("cluster") - .arg("approve") - .arg("graph.knowledge") - .arg("--config") - .arg(temp.path()), - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("--as"), "{stderr}"); -} - -#[test] -fn cluster_e2e_declared_graph_created_by_apply() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - - let import = cluster_json(temp.path(), "import"); - assert_eq!(import["ok"], true, "{import}"); - - let apply = cluster_json(temp.path(), "apply"); - assert_eq!(apply["ok"], true, "{apply}"); - assert_eq!(apply["converged"], true, "{apply}"); - assert_eq!(change_for(&apply, "graph.knowledge")["disposition"], "applied"); - assert!(temp.path().join("graphs/knowledge.omni").exists()); - - // The created graph is a real graph: the per-graph CLI can open it. - let snapshot = output_success( - cli() - .arg("snapshot") - .arg(temp.path().join("graphs/knowledge.omni")), - ); - assert!(!stdout_string(&snapshot).is_empty()); - - let plan = cluster_json(temp.path(), "plan"); - assert!(plan["changes"].as_array().unwrap().is_empty(), "{plan}"); - let status = cluster_json(temp.path(), "status"); - assert_eq!( - status["resource_statuses"]["graph.knowledge"]["status"], - "applied" - ); -} - -#[test] -fn cluster_e2e_payload_drift_self_heals() { - let temp = tempdir().unwrap(); - write_cluster_config_fixture(temp.path()); - init_cluster_derived_graph(temp.path()); - let import = cluster_json(temp.path(), "import"); - assert_eq!(import["ok"], true, "{import}"); - let apply = cluster_json(temp.path(), "apply"); - assert_eq!(apply["converged"], true, "{apply}"); - - let query_digest = change_for(&apply, "query.knowledge.find_person")["after_digest"] - .as_str() - .unwrap() - .to_string(); - let blob = temp - .path() - .join("__cluster/resources/query/knowledge/find_person") - .join(format!("{query_digest}.gq")); - fs::remove_file(&blob).unwrap(); - - let status = cluster_json(temp.path(), "status"); - assert_eq!(status["ok"], true, "{status}"); - assert!( - status["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| diagnostic["code"] == "catalog_payload_missing"), - "{status}" - ); - - let refresh = cluster_json(temp.path(), "refresh"); - assert_eq!(refresh["ok"], true, "{refresh}"); - assert_eq!( - refresh["resource_statuses"]["query.knowledge.find_person"]["status"], - "drifted" - ); - - let heal = cluster_json(temp.path(), "apply"); - assert_eq!(heal["ok"], true, "{heal}"); - assert_eq!(heal["converged"], true, "{heal}"); - assert!(blob.exists(), "blob republished"); - - let clean = cluster_json(temp.path(), "status"); - assert!( - !clean["diagnostics"] - .as_array() - .unwrap() - .iter() - .any(|diagnostic| { - diagnostic["code"] - .as_str() - .is_some_and(|code| code.starts_with("catalog_payload")) - }), - "{clean}" - ); -} diff --git a/crates/omnigraph-cli/tests/cli_queries.rs b/crates/omnigraph-cli/tests/cli_queries.rs deleted file mode 100644 index 8a1e553..0000000 --- a/crates/omnigraph-cli/tests/cli_queries.rs +++ /dev/null @@ -1,535 +0,0 @@ -//! Stored-query commands and alias resolution. -//! Moved verbatim from tests/cli.rs in the modularization. - - -use serde_json::Value; -use tempfile::tempdir; - -mod support; - -use support::*; - - -#[test] -fn query_check_alias_matches_lint_output() { - 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 lint_output = output_success( - cli() - .arg("query") - .arg("lint") - .arg("--query") - .arg(&query_path) - .arg("--schema") - .arg(&schema_path) - .arg("--json"), - ); - let check_output = output_success( - cli() - .arg("query") - .arg("check") - .arg("--query") - .arg(&query_path) - .arg("--schema") - .arg(&schema_path) - .arg("--json"), - ); - - assert_eq!(stdout_string(&lint_output), stdout_string(&check_output)); -} - -#[test] -fn read_alias_from_yaml_config_runs_with_kv_output() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let config = temp.path().join("omnigraph.yaml"); - let query = temp.path().join("aliases.gq"); - init_graph(&graph); - load_fixture(&graph); - write_query_file( - &query, - &std::fs::read_to_string(fixture("test.gq")).unwrap(), - ); - write_config( - &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(&graph) - ), - ); - - let output = output_success( - cli() - .arg("read") - .arg("--config") - .arg(&config) - .arg("--alias") - .arg("owner") - .arg("Alice"), - ); - let stdout = stdout_string(&output); - - assert!(stdout.contains("row 1")); - assert!(stdout.contains("p.name: Alice")); -} - -#[test] -fn read_alias_uses_alias_target_without_cli_default_and_accepts_url_like_arg() { - let temp = tempdir().unwrap(); - 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_graph(&graph); - write_jsonl( - &data, - r#"{"type":"Person","data":{"name":"https://example.com","age":30}}"#, - ); - output_success( - cli() - .arg("load") - .arg("--mode") - .arg("overwrite") - .arg("--data") - .arg(&data) - .arg(&graph), - ); - write_query_file( - &query, - &std::fs::read_to_string(fixture("test.gq")).unwrap(), - ); - write_config( - &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", - graph.to_string_lossy() - ), - ); - - let output = output_success( - cli() - .arg("read") - .arg("--config") - .arg(&config) - .arg("--alias") - .arg("owner") - .arg("https://example.com"), - ); - let stdout = stdout_string(&output); - - assert!(stdout.contains("row 1")); - assert!(stdout.contains("p.name: https://example.com")); -} - -#[test] -fn change_alias_from_yaml_config_persists_changes() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let config = temp.path().join("omnigraph.yaml"); - let query = temp.path().join("mutations.gq"); - init_graph(&graph); - load_fixture(&graph); - write_query_file( - &query, - r#" -query insert_person($name: String, $age: I32) { - insert Person { name: $name, age: $age } -} -"#, - ); - write_config( - &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(&graph) - ), - ); - - let output = output_success( - cli() - .arg("change") - .arg("--config") - .arg(&config) - .arg("--alias") - .arg("add_person") - .arg("Eve") - .arg("29") - .arg("--json"), - ); - let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(payload["affected_nodes"], 1); - - let verify = output_success( - cli() - .arg("read") - .arg(&graph) - .arg("--query") - .arg(fixture("test.gq")) - .arg("--name") - .arg("get_person") - .arg("--params") - .arg(r#"{"name":"Eve"}"#) - .arg("--json"), - ); - let verify_payload: Value = serde_json::from_slice(&verify.stdout).unwrap(); - assert_eq!(verify_payload["row_count"], 1); -} - -#[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/cli_schema_config.rs b/crates/omnigraph-cli/tests/cli_schema_config.rs deleted file mode 100644 index 710c856..0000000 --- a/crates/omnigraph-cli/tests/cli_schema_config.rs +++ /dev/null @@ -1,648 +0,0 @@ -//! init/config scaffolding, schema plan/apply, graphs listing, version. -//! Moved verbatim from tests/cli.rs in the modularization. - -use std::fs; - -use lance::index::DatasetIndexExt; -use omnigraph::db::{Omnigraph, ReadTarget}; -use serde_json::Value; -use tempfile::tempdir; - -mod support; - -use support::*; - - -#[test] -fn version_command_prints_current_cli_version() { - let output = output_success(cli().arg("version")); - let stdout = stdout_string(&output); - - assert_eq!( - stdout.trim(), - format!("omnigraph {}", env!("CARGO_PKG_VERSION")) - ); -} - -#[test] -fn init_creates_graph_successfully_on_missing_local_directory() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema = fixture("test.pg"); - - let output = output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&graph)); - let stdout = stdout_string(&output); - - assert!(stdout.contains("initialized")); - assert!(graph.join("_schema.pg").exists()); - assert!(graph.join("__manifest").exists()); - // RFC-008 stage 3: init no longer scaffolds the legacy config file. - assert!(!temp.path().join("omnigraph.yaml").exists()); -} - -#[test] -fn schema_plan_json_reports_supported_additive_change() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("next.pg"); - init_graph(&graph); - - let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ); - fs::write(&schema_path, next_schema).unwrap(); - - let output = output_success( - cli() - .arg("schema") - .arg("plan") - .arg("--schema") - .arg(&schema_path) - .arg("--json") - .arg(&graph), - ); - let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); - - assert_eq!(payload["supported"], true); - assert_eq!(payload["step_count"], 1); - assert_eq!(payload["steps"][0]["kind"], "add_property"); - assert_eq!(payload["steps"][0]["type_kind"], "node"); - assert_eq!(payload["steps"][0]["type_name"], "Person"); - assert_eq!(payload["steps"][0]["property_name"], "nickname"); -} - -#[test] -fn schema_plan_json_reports_unsupported_type_change() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("breaking.pg"); - init_graph(&graph); - - let breaking_schema = fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("age: I32?", "age: I64?"); - fs::write(&schema_path, breaking_schema).unwrap(); - - let output = output_success( - cli() - .arg("schema") - .arg("plan") - .arg("--schema") - .arg(&schema_path) - .arg("--json") - .arg(&graph), - ); - let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); - - assert_eq!(payload["supported"], false); - assert!(payload["steps"].as_array().unwrap().iter().any(|step| { - step["kind"] == "unsupported_change" - && step["entity"] - .as_str() - .unwrap_or_default() - .contains("Person.age") - })); -} - -#[test] -fn schema_apply_json_applies_supported_migration() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("next.pg"); - init_graph(&graph); - - let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ); - fs::write(&schema_path, next_schema).unwrap(); - - let output = output_success( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg("--json") - .arg(&graph), - ); - let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); - - assert_eq!(payload["supported"], true); - assert_eq!(payload["applied"], true); - assert_eq!(payload["step_count"], 1); - - let db = tokio::runtime::Runtime::new() - .unwrap() - .block_on(Omnigraph::open(graph.to_string_lossy().as_ref())) - .unwrap(); - assert!( - db.catalog().node_types["Person"] - .properties - .contains_key("nickname") - ); -} - -#[test] -fn schema_apply_human_reports_noop() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = fixture("test.pg"); - init_graph(&graph); - - let output = output_success( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg(&graph), - ); - let stdout = stdout_string(&output); - - assert!(stdout.contains("applied: no")); - assert!(stdout.contains("no schema changes")); -} - -#[test] -fn schema_apply_json_renames_type_and_updates_snapshot() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("rename.pg"); - init_graph(&graph); - - let renamed_schema = fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("node Person {\n", "node Human @rename_from(\"Person\") {\n") - .replace("edge Knows: Person -> Person", "edge Knows: Human -> Human") - .replace( - "edge WorksAt: Person -> Company", - "edge WorksAt: Human -> Company", - ); - fs::write(&schema_path, renamed_schema).unwrap(); - - let output = output_success( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg("--json") - .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(graph.to_string_lossy().as_ref())) - .unwrap(); - let snapshot = tokio::runtime::Runtime::new() - .unwrap() - .block_on(db.snapshot_of(ReadTarget::branch("main"))) - .unwrap(); - assert!(snapshot.entry("node:Human").is_some()); - assert!(snapshot.entry("node:Person").is_none()); -} - -#[test] -fn schema_apply_json_renames_property_and_updates_catalog() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("rename-property.pg"); - init_graph(&graph); - - let renamed_schema = fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("age: I32?", "years: I32? @rename_from(\"age\")"); - fs::write(&schema_path, renamed_schema).unwrap(); - - let output = output_success( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg("--json") - .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(graph.to_string_lossy().as_ref())) - .unwrap(); - let person = &db.catalog().node_types["Person"]; - assert!(person.properties.contains_key("years")); - assert!(!person.properties.contains_key("age")); -} - -#[test] -fn schema_apply_json_adds_index_for_existing_property() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("index.pg"); - init_graph(&graph); - - let before_index_count = tokio::runtime::Runtime::new().unwrap().block_on(async { - let db = Omnigraph::open(graph.to_string_lossy().as_ref()) - .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() - }); - - let indexed_schema = fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("name: String @key", "name: String @key @index"); - fs::write(&schema_path, indexed_schema).unwrap(); - - let output = output_success( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg("--json") - .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(graph.to_string_lossy().as_ref()) - .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() - }); - assert!(after_index_count > before_index_count); -} - -#[test] -fn schema_apply_rejects_unsupported_plan() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("breaking.pg"); - init_graph(&graph); - - let breaking_schema = fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("age: I32?", "age: I64?"); - fs::write(&schema_path, breaking_schema).unwrap(); - - let output = output_failure( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg(&graph), - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("changing property type")); -} - -#[test] -fn schema_apply_rejects_when_non_main_branch_exists() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("next.pg"); - init_graph(&graph); - output_success( - cli() - .arg("branch") - .arg("create") - .arg("--from") - .arg("main") - .arg("--uri") - .arg(&graph) - .arg("feature"), - ); - - let next_schema = fs::read_to_string(fixture("test.pg")).unwrap().replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ); - fs::write(&schema_path, next_schema).unwrap(); - - let output = output_failure( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg(&graph), - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("schema apply requires a graph with only main")); -} - -#[test] -fn schema_apply_allow_data_loss_flag_promotes_drops_to_hard() { - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("drop-age.pg"); - init_graph(&graph); - - // Drop the nullable `age` column. - let next_schema = fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace(" age: I32?\n", ""); - fs::write(&schema_path, next_schema).unwrap(); - - let output = output_success( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg("--allow-data-loss") - .arg("--json") - .arg(&graph), - ); - let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(payload["applied"], true); - - let drop_step = payload["steps"] - .as_array() - .unwrap() - .iter() - .find(|s| s["kind"] == "drop_property") - .expect("plan should include a drop_property step"); - assert_eq!( - drop_step["mode"], "hard", - "--allow-data-loss should promote Soft β†’ Hard; full step: {drop_step}", - ); -} - -#[test] -fn schema_apply_without_allow_data_loss_keeps_soft_drops() { - // Symmetric to the above: same schema change without the flag β†’ - // drops stay Soft. Pins default semantics against accidental Hard - // promotion if a future refactor changes the option threading. - let temp = tempdir().unwrap(); - let graph = graph_path(temp.path()); - let schema_path = temp.path().join("drop-age-soft.pg"); - init_graph(&graph); - - let next_schema = fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace(" age: I32?\n", ""); - fs::write(&schema_path, next_schema).unwrap(); - - let output = output_success( - cli() - .arg("schema") - .arg("apply") - .arg("--schema") - .arg(&schema_path) - .arg("--json") - .arg(&graph), - ); - let payload: Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(payload["applied"], true); - - let drop_step = payload["steps"] - .as_array() - .unwrap() - .iter() - .find(|s| s["kind"] == "drop_property") - .expect("plan should include a drop_property step"); - assert_eq!( - drop_step["mode"], "soft", - "no flag should leave drops Soft; full step: {drop_step}", - ); -} - -#[test] -fn schema_plan_parity_cli_and_sdk() { - // Same .pg through `Omnigraph::plan_schema_with_options` (SDK) and - // `omnigraph schema plan --json` (CLI). Asserts the steps array is - // byte-identical after JSON round-trip. HTTP doesn't expose a - // separate /schema/plan route β€” that side of parity is covered by - // the HTTP soft/hard drop tests, which exercise apply with - // identical fixtures. - let temp = tempdir().unwrap(); - 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}", - " age: I32?\n nickname: String?\n}", - ); - fs::write(&schema_path, &next_schema).unwrap(); - - // CLI side. - let cli_output = output_success( - cli() - .arg("schema") - .arg("plan") - .arg("--schema") - .arg(&schema_path) - .arg("--json") - .arg(&graph), - ); - let cli_payload: Value = serde_json::from_slice(&cli_output.stdout).unwrap(); - - // SDK side: open graph, call plan_schema. - let plan = tokio::runtime::Runtime::new().unwrap().block_on(async { - let db = Omnigraph::open(graph.to_string_lossy().as_ref()) - .await - .unwrap(); - db.plan_schema(&next_schema).await.unwrap() - }); - let sdk_steps = serde_json::to_value(&plan.steps).unwrap(); - - assert_eq!( - cli_payload["steps"], sdk_steps, - "CLI plan steps must match SDK plan steps for identical input", - ); - assert_eq!(cli_payload["supported"], plan.supported); -} - -#[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}" - ); -} - -#[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}" - ); -} - -/// RFC-008 stage 1: loading a legacy omnigraph.yaml emits the per-key -/// deprecation block (the migration map applied to THIS file), suppressible -/// via OMNIGRAPH_SUPPRESS_YAML_DEPRECATION. -#[test] -fn legacy_config_load_warns_per_key_and_suppression_silences() { - let temp = tempdir().unwrap(); - fs::write( - temp.path().join("omnigraph.yaml"), - "cli:\n actor: act-x\ngraphs:\n g:\n uri: /tmp/never-opened\n", - ) - .unwrap(); - - // `graphs list --json` loads the config and exits without touching the - // graph URI. - let output = cli() - .current_dir(temp.path()) - .arg("graphs") - .arg("list") - .arg("--json") - .output() - .unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("deprecated (RFC-008)") && stderr.contains("`cli.actor` -> `operator.actor`"), - "{stderr}" - ); - assert!(stderr.contains("config migrate"), "{stderr}"); - - let output = cli() - .current_dir(temp.path()) - .env("OMNIGRAPH_SUPPRESS_YAML_DEPRECATION", "1") - .arg("graphs") - .arg("list") - .arg("--json") - .output() - .unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(!stderr.contains("deprecated (RFC-008)"), "{stderr}"); -} - -/// RFC-008 stage 2: `config migrate` proposes the split read-only, applies -/// it with --write (operator merge never clobbers; cluster.yaml emitted), -/// and a second --write is idempotent. -#[test] -fn config_migrate_splits_legacy_config() { - let temp = tempdir().unwrap(); - fs::write( - temp.path().join("omnigraph.yaml"), - "graphs:\n prod:\n uri: https://graph.example.com\n bearer_token_env: PROD_TOKEN\ncli:\n actor: act-me\n output_format: json\npolicy:\n file: ./top.policy.yaml\n", - ) - .unwrap(); - let operator_home = tempfile::tempdir().unwrap(); - fs::write( - operator_home.path().join("config.yaml"), - "operator:\n actor: act-existing\n", - ) - .unwrap(); - - // Read-only proposal: names both halves, writes nothing. - let output = cli() - .current_dir(temp.path()) - .env("OMNIGRAPH_HOME", operator_home.path()) - .env("OMNIGRAPH_SUPPRESS_YAML_DEPRECATION", "1") - .arg("config") - .arg("migrate") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("team half -> cluster.yaml"), "{stdout}"); - assert!(stdout.contains("operator.actor: act-me"), "{stdout}"); - assert!(stdout.contains("omnigraph login prod"), "{stdout}"); - assert!(!temp.path().join("cluster.yaml").exists()); - - // --write: cluster.yaml lands; the existing operator actor is KEPT. - let output = cli() - .current_dir(temp.path()) - .env("OMNIGRAPH_HOME", operator_home.path()) - .env("OMNIGRAPH_SUPPRESS_YAML_DEPRECATION", "1") - .arg("config") - .arg("migrate") - .arg("--write") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - let cluster = fs::read_to_string(temp.path().join("cluster.yaml")).unwrap(); - assert!(cluster.contains("version: 1") && cluster.contains(" prod:"), "{cluster}"); - let operator_text = - fs::read_to_string(operator_home.path().join("config.yaml")).unwrap(); - assert!(operator_text.contains("act-existing"), "{operator_text}"); - assert!(!operator_text.contains("act-me"), "existing keys win: {operator_text}"); - assert!(operator_text.contains("output: json"), "{operator_text}"); - assert!( - operator_text.contains("url: https://graph.example.com"), - "{operator_text}" - ); - - // Second --write: cluster.yaml exists -> proposal file, no clobber. - let output = cli() - .current_dir(temp.path()) - .env("OMNIGRAPH_HOME", operator_home.path()) - .env("OMNIGRAPH_SUPPRESS_YAML_DEPRECATION", "1") - .arg("config") - .arg("migrate") - .arg("--write") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - assert!(temp.path().join("cluster.yaml.proposed").exists()); -} - -/// RFC-008 stage 4: OMNIGRAPH_NO_LEGACY_CONFIG refuses a present legacy -/// file (pointing at config migrate) but changes nothing on migrated -/// setups with no file. -#[test] -fn strict_mode_refuses_legacy_file_but_not_its_absence() { - let temp = tempdir().unwrap(); - fs::write(temp.path().join("omnigraph.yaml"), "cli:\n actor: a\n").unwrap(); - let output = cli() - .current_dir(temp.path()) - .env("OMNIGRAPH_NO_LEGACY_CONFIG", "1") - .arg("graphs") - .arg("list") - .arg("--json") - .output() - .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("OMNIGRAPH_NO_LEGACY_CONFIG") && stderr.contains("config migrate"), - "{stderr}" - ); - - // Migrated setup (no file): strict mode is a no-op β€” a config-loading - // command that tolerates empty defaults succeeds. - let clean = tempdir().unwrap(); - let output = cli() - .current_dir(clean.path()) - .env("OMNIGRAPH_NO_LEGACY_CONFIG", "1") - .arg("queries") - .arg("list") - .arg("--json") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); -} diff --git a/crates/omnigraph-cli/tests/support/mod.rs b/crates/omnigraph-cli/tests/support/mod.rs index b11e94d..b62d861 100644 --- a/crates/omnigraph-cli/tests/support/mod.rs +++ b/crates/omnigraph-cli/tests/support/mod.rs @@ -12,24 +12,12 @@ use reqwest::blocking::Client; use serde_json::Value; use tempfile::{TempDir, tempdir}; -/// Hermetic default: point OMNIGRAPH_HOME at a path that exists on no -/// machine, so spawned binaries never read the developer's real -/// ~/.omnigraph/ (an absent operator config is an empty layer). Tests -/// exercising the operator layer override the var explicitly. -pub const HERMETIC_OPERATOR_HOME: &str = "/nonexistent/omnigraph-test-home"; - pub fn cli() -> Command { - let mut command = Command::cargo_bin("omnigraph").unwrap(); - command.env("OMNIGRAPH_HOME", HERMETIC_OPERATOR_HOME); - command.env_remove("OMNIGRAPH_CONFIG"); - command + Command::cargo_bin("omnigraph").unwrap() } pub fn cli_process() -> StdCommand { - let mut command = StdCommand::new(assert_cmd::cargo::cargo_bin("omnigraph")); - command.env("OMNIGRAPH_HOME", HERMETIC_OPERATOR_HOME); - command.env_remove("OMNIGRAPH_CONFIG"); - command + StdCommand::new(assert_cmd::cargo::cargo_bin("omnigraph")) } fn server_process() -> StdCommand { @@ -105,15 +93,7 @@ pub fn init_graph(graph: &Path) { pub fn load_fixture(graph: &Path) { let data = fixture("test.jsonl"); - output_success( - cli() - .arg("load") - .arg("--mode") - .arg("overwrite") - .arg("--data") - .arg(&data) - .arg(graph), - ); + output_success(cli().arg("load").arg("--data").arg(&data).arg(graph)); } pub fn write_jsonl(path: &Path, rows: &str) { @@ -232,42 +212,6 @@ pub fn spawn_server_with_config(config: &Path) -> TestServer { spawn_server_process(command) } -pub fn spawn_server_with_cluster(cluster_dir: &Path) -> TestServer { - let mut command = server_process(); - command.arg("--cluster").arg(cluster_dir).arg("--unauthenticated"); - spawn_server_process(command) -} - -/// Cluster boot with the server process's cwd set explicitly β€” used to prove -/// rule 0 never touches the cwd omnigraph.yaml search. -pub fn spawn_server_with_cluster_in(cluster_dir: &Path, cwd: &Path) -> TestServer { - let mut command = server_process(); - command - .arg("--cluster") - .arg(cluster_dir) - .arg("--unauthenticated") - .current_dir(cwd); - spawn_server_process(command) -} - -pub fn spawn_server_with_cluster_env(cluster_dir: &Path, envs: &[(&str, &str)]) -> TestServer { - let mut command = server_process(); - command.arg("--cluster").arg(cluster_dir); - for (name, value) in envs { - command.env(name, value); - } - spawn_server_process(command) -} - -pub fn spawn_server_with_env(graph: &Path, envs: &[(&str, &str)]) -> TestServer { - let mut command = server_process(); - command.arg(graph); - for (name, value) in envs { - command.env(name, value); - } - spawn_server_process(command) -} - pub fn spawn_server_with_config_env(config: &Path, envs: &[(&str, &str)]) -> TestServer { let mut command = server_process(); command.arg("--config").arg(config); @@ -338,353 +282,3 @@ impl SystemGraph { spawn_server_with_config_env(config, envs) } } - -// ---- helpers moved from the monolithic tests/cli.rs ---- -#[allow(unused_imports)] -use lance::Dataset; -#[allow(unused_imports)] -use lance::index::DatasetIndexExt; -#[allow(unused_imports)] -use omnigraph::db::{Omnigraph, ReadTarget}; - -pub const POLICY_YAML: &str = r#" -version: 1 -groups: - team: [act-andrew, act-bruno] - admins: [act-andrew] -protected_branches: [main] -rules: - - id: team-read - allow: - actors: { group: team } - actions: [read] - branch_scope: any - - id: team-write - allow: - actors: { group: team } - actions: [change] - branch_scope: unprotected - - id: admins-promote - allow: - actors: { group: admins } - actions: [branch_merge] - target_branch_scope: protected -"#; - -pub const POLICY_TESTS_YAML: &str = r#" -version: 1 -cases: - - id: allow-feature-write - actor: act-andrew - action: change - branch: feature - expect: allow - - id: deny-main-write - actor: act-bruno - action: change - branch: main - expect: deny -"#; - -pub fn manifest_dataset_version(graph: &std::path::Path) -> u64 { - tokio::runtime::Runtime::new().unwrap().block_on(async { - Omnigraph::open(graph.to_string_lossy().as_ref()) - .await - .unwrap() - .snapshot_of(ReadTarget::branch("main")) - .await - .unwrap() - .version() - }) -} - -pub fn forge_person_delete_drift(graph: &std::path::Path) -> (u64, u64) { - tokio::runtime::Runtime::new().unwrap().block_on(async { - let uri = graph.to_string_lossy(); - let db = Omnigraph::open(uri.as_ref()).await.unwrap(); - let snap = db - .snapshot_of(ReadTarget::branch("main")) - .await - .unwrap(); - let entry = snap.entry("node:Person").unwrap(); - let full_path = format!("{}/{}", uri.trim_end_matches('/'), entry.table_path); - let mut ds = Dataset::open(&full_path).await.unwrap(); - let deleted = ds.delete("name = 'Alice'").await.unwrap(); - assert_eq!(deleted.num_deleted_rows, 1); - let head = deleted.new_dataset.version().version; - assert!(head > entry.table_version); - (entry.table_version, head) - }) -} - -pub fn write_policy_config_fixture(root: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) { - let config = root.join("omnigraph.yaml"); - let policy = root.join("policy.yaml"); - fs::write( - &config, - r#" -project: - name: policy-test-graph -policy: - file: ./policy.yaml -"#, - ) - .unwrap(); - fs::write(&policy, POLICY_YAML).unwrap(); - fs::write(root.join("policy.tests.yaml"), POLICY_TESTS_YAML).unwrap(); - (config, policy) -} - -pub fn write_cluster_config_fixture(root: &std::path::Path) { - fs::write( - root.join("people.pg"), - r#" -node Person { - name: String @key - age: I32? -} -"#, - ) - .unwrap(); - fs::write( - root.join("people.gq"), - r#" -query find_person($name: String) { - match { $p: Person { name: $name } } - return { $p.name, $p.age } -} -"#, - ) - .unwrap(); - fs::write(root.join("base.policy.yaml"), "rules: []\n").unwrap(); - fs::write( - root.join("cluster.yaml"), - r#" -version: 1 -metadata: - name: company-brain -state: - backend: cluster - lock: true -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -policies: - base: - file: ./base.policy.yaml - applies_to: [knowledge] -"#, - ) - .unwrap(); -} - -pub fn init_cluster_derived_graph(root: &std::path::Path) { - init_named_cluster_graph(root, "knowledge", "people.pg"); -} - -pub fn init_named_cluster_graph(root: &std::path::Path, graph_id: &str, schema_file: &str) { - let graph_dir = root.join("graphs"); - fs::create_dir_all(&graph_dir).unwrap(); - output_success( - cli() - .arg("init") - .arg("--schema") - .arg(root.join(schema_file)) - .arg(graph_dir.join(format!("{graph_id}.omni"))), - ); -} - -pub fn write_cluster_lock(root: &std::path::Path, lock_id: &str, operation: &str) { - let state_dir = root.join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("lock.json"), - format!( - r#"{{"version":1,"lock_id":"{lock_id}","operation":"{operation}","created_at":"1970-01-01T00:00:00Z","pid":123}}"# - ), - ) - .unwrap(); -} - -pub fn write_cluster_applyable_state(root: &std::path::Path) -> serde_json::Value { - let validate = parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg("validate") - .arg("--config") - .arg(root) - .arg("--json"), - )); - let schema_digest = validate["resource_digests"]["schema.knowledge"] - .as_str() - .unwrap() - .to_string(); - let state_dir = root.join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - format!( - r#"{{ - "version": 1, - "state_revision": 1, - "applied_revision": {{ - "resources": {{ - "graph.knowledge": {{ "digest": "seed" }}, - "schema.knowledge": {{ "digest": "{schema_digest}" }} - }} - }} -}} -"# - ), - ) - .unwrap(); - validate -} - -pub fn cluster_json(root: &std::path::Path, command: &str) -> serde_json::Value { - parse_stdout_json(&output_success( - cli() - .arg("cluster") - .arg(command) - .arg("--config") - .arg(root) - .arg("--json"), - )) -} - -pub fn write_multi_graph_cluster_fixture(root: &std::path::Path) { - write_cluster_config_fixture(root); - fs::write( - root.join("services.pg"), - r#" -node Service { - name: String @key -} -"#, - ) - .unwrap(); - fs::write( - root.join("services.gq"), - r#" -query find_service($name: String) { - match { $s: Service { name: $name } } - return { $s.name } -} -"#, - ) - .unwrap(); - fs::write(root.join("cluster_wide.policy.yaml"), "rules: []\n").unwrap(); - fs::write(root.join("shared.policy.yaml"), "rules: []\n").unwrap(); - fs::write( - root.join("cluster.yaml"), - r#" -version: 1 -metadata: - name: company-brain -state: - backend: cluster - lock: true -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq - engineering: - schema: ./services.pg - queries: - find_service: - file: ./services.gq -policies: - shared: - file: ./shared.policy.yaml - applies_to: [knowledge, engineering] - cluster_wide: - file: ./cluster_wide.policy.yaml - applies_to: [cluster] -"#, - ) - .unwrap(); -} - -pub fn change_for<'j>(json: &'j serde_json::Value, resource: &str) -> &'j serde_json::Value { - json["changes"] - .as_array() - .unwrap() - .iter() - .find(|change| change["resource"] == resource) - .unwrap_or_else(|| panic!("missing change for {resource}: {json}")) -} - -pub fn write_seed_fixture(root: &std::path::Path) -> std::path::PathBuf { - fs::create_dir_all(root.join("data")).unwrap(); - fs::create_dir_all(root.join("build")).unwrap(); - let raw_seed = root.join("data/seed.jsonl"); - let seed = root.join("seed.yaml"); - - fs::write( - &raw_seed, - concat!( - "{\"type\":\"Decision\",\"data\":{\"slug\":\"dec-alpha\",\"intent\":\"Alpha ship\"}}\n", - "{\"type\":\"Decision\",\"data\":{\"slug\":\"dec-beta\",\"intent\":\"Beta ship\",\"embedding\":[0.1,0.2]}}\n" - ), - ) - .unwrap(); - - fs::write( - &seed, - concat!( - "graph:\n", - " slug: mr-context-graph\n", - "sources:\n", - " raw_seed: ./data/seed.jsonl\n", - "artifacts:\n", - " embedded_seed: ./build/seed.embedded.jsonl\n", - "embeddings:\n", - " model: gemini-embedding-2-preview\n", - " dimension: 4\n", - " types:\n", - " Decision:\n", - " target: embedding\n", - " fields: [slug, intent]\n" - ), - ) - .unwrap(); - - seed -} - -pub fn write_seed_fixture_with_edge(root: &std::path::Path) -> std::path::PathBuf { - let seed = write_seed_fixture(root); - let raw_seed = root.join("data/seed.jsonl"); - fs::write( - &raw_seed, - concat!( - "{\"type\":\"Decision\",\"data\":{\"slug\":\"dec-alpha\",\"intent\":\"Alpha ship\"}}\n", - "{\"type\":\"Decision\",\"data\":{\"slug\":\"dec-beta\",\"intent\":\"Beta ship\",\"embedding\":[0.1,0.2]}}\n", - "{\"edge\":\"Triggered\",\"from\":\"sig-alpha\",\"to\":\"dec-alpha\"}\n" - ), - ) - .unwrap(); - seed -} - -pub fn read_embedded_rows(path: std::path::PathBuf) -> Vec { - fs::read_to_string(path) - .unwrap() - .lines() - .filter(|line| !line.trim().is_empty()) - .map(|line| serde_json::from_str(line).unwrap()) - .collect() -} - -pub 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('\'', "''") - ) -} diff --git a/crates/omnigraph-cli/tests/system_local.rs b/crates/omnigraph-cli/tests/system_local.rs index 28ed7a3..4fc3e9a 100644 --- a/crates/omnigraph-cli/tests/system_local.rs +++ b/crates/omnigraph-cli/tests/system_local.rs @@ -221,8 +221,6 @@ fn local_cli_end_to_end_init_load_read_change_read_flow() { output_success( cli() .arg("load") - .arg("--mode") - .arg("overwrite") .arg("--data") .arg(fixture("test.jsonl")) .arg(graph.path()), @@ -399,7 +397,7 @@ fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { {"type":"Person","data":{"name":"Bob","age":26}}"#, ); - let ingest_output = output_success( + let ingest_payload = parse_stdout_json(&output_success( cli() .arg("ingest") .arg("--data") @@ -408,13 +406,7 @@ fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { .arg("feature-ingest") .arg(graph.path()) .arg("--json"), - ); - // The deprecation warning goes to stderr so --json stdout stays clean. - assert!( - String::from_utf8_lossy(&ingest_output.stderr).contains("deprecated"), - "ingest must warn about its deprecation on stderr" - ); - let ingest_payload = parse_stdout_json(&ingest_output); + )); assert_eq!(ingest_payload["branch"], "feature-ingest"); assert_eq!(ingest_payload["base_branch"], "main"); assert_eq!(ingest_payload["branch_created"], true); @@ -467,88 +459,6 @@ fn local_cli_ingest_creates_review_branch_and_keeps_it_readable() { assert_eq!(bob["rows"][0]["p.age"], 26); } -/// The unified `load` subsumes ingest: `--from` opts into fork-if-missing, -/// while without it a missing branch is an error β€” never an implicit fork. -#[test] -fn local_cli_load_from_forks_branch_and_missing_branch_errors_without_from() { - let graph = SystemGraph::loaded(); - let extra = graph.write_jsonl( - "system-local-load-from.jsonl", - r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#, - ); - - // Without --from, a missing branch must fail and create nothing. - let failure = output_failure( - cli() - .arg("load") - .arg("--mode") - .arg("merge") - .arg("--data") - .arg(&extra) - .arg("--branch") - .arg("feature-load") - .arg(graph.path()), - ); - assert!( - String::from_utf8_lossy(&failure.stderr).contains("feature-load"), - "error should name the missing branch" - ); - - // With --from, the branch is forked and the load lands on it. - let payload = parse_stdout_json(&output_success( - cli() - .arg("load") - .arg("--mode") - .arg("merge") - .arg("--data") - .arg(&extra) - .arg("--branch") - .arg("feature-load") - .arg("--from") - .arg("main") - .arg(graph.path()) - .arg("--json"), - )); - assert_eq!(payload["branch"], "feature-load"); - assert_eq!(payload["base_branch"], "main"); - assert_eq!(payload["branch_created"], true); - assert_eq!(payload["mode"], "merge"); - assert_eq!(payload["nodes_loaded"], 1); - - let snapshot = parse_stdout_json(&output_success( - cli() - .arg("snapshot") - .arg(graph.path()) - .arg("--branch") - .arg("feature-load") - .arg("--json"), - )); - assert_eq!(snapshot["branch"], "feature-load"); -} - -/// `--mode` is required: overwrite is destructive, so the unified `load` -/// has no implicit default. -#[test] -fn local_cli_load_requires_mode_flag() { - let graph = SystemGraph::loaded(); - let extra = graph.write_jsonl( - "system-local-load-no-mode.jsonl", - r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#, - ); - - let failure = output_failure( - cli() - .arg("load") - .arg("--data") - .arg(&extra) - .arg(graph.path()), - ); - assert!( - String::from_utf8_lossy(&failure.stderr).contains("--mode"), - "clap should demand the missing --mode flag" - ); -} - #[test] fn local_cli_export_round_trips_full_branch_graph() { let graph = SystemGraph::loaded(); @@ -602,8 +512,6 @@ fn local_cli_export_round_trips_full_branch_graph() { output_success( cli() .arg("load") - .arg("--mode") - .arg("overwrite") .arg("--data") .arg(&export_path) .arg(&imported_graph), @@ -687,12 +595,8 @@ policy: {{}} ), ); - // current_dir matters: `init` scaffolds an omnigraph.yaml into its cwd, - // and without this it pollutes the crate dir, breaking unrelated tests - // (anything resolving a graph target from the cwd config). output_success( cli() - .current_dir(query_root) .arg("init") .arg("--schema") .arg(fixture("test.pg")) @@ -700,10 +604,7 @@ policy: {{}} ); output_success( cli() - .current_dir(query_root) .arg("load") - .arg("--mode") - .arg("overwrite") .arg("--data") .arg(fixture("test.jsonl")) .arg(&graph_uri), @@ -961,15 +862,7 @@ query get_task($slug: String) { ); output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&graph)); - output_success( - cli() - .arg("load") - .arg("--mode") - .arg("overwrite") - .arg("--data") - .arg(&data) - .arg(&graph), - ); + output_success(cli().arg("load").arg("--data").arg(&data).arg(&graph)); let filtered = parse_stdout_json(&output_success( cli() @@ -1099,15 +992,7 @@ query vector_search($q: String) { ); output_success(cli().arg("init").arg("--schema").arg(&schema).arg(&graph)); - output_success( - cli() - .arg("load") - .arg("--mode") - .arg("overwrite") - .arg("--data") - .arg(&data) - .arg(&graph), - ); + output_success(cli().arg("load").arg("--data").arg(&data).arg(&graph)); let result = parse_stdout_json(&output_success( cli() @@ -1331,8 +1216,6 @@ fn local_cli_load_enforces_engine_layer_policy() { .arg("--as") .arg("act-bruno") .arg("load") - .arg("--mode") - .arg("overwrite") .arg("--config") .arg(&config) .arg("--data") @@ -1351,8 +1234,6 @@ fn local_cli_load_enforces_engine_layer_policy() { .arg("--as") .arg("act-ragnor") .arg("load") - .arg("--mode") - .arg("overwrite") .arg("--config") .arg(&config) .arg("--data") @@ -1752,796 +1633,3 @@ fn local_cli_actor_flag_overrides_config_actor() { "expected 'denied' when --as overrides config to bruno, got: {stderr}" ); } - -/// Phase 5 (RFC-005): "applied means serving" β€” converge a cluster with the -/// CLI, boot the real omnigraph-server binary with --cluster, and serve the -/// applied stored query over HTTP with zero omnigraph.yaml involvement. -#[test] -fn local_cluster_apply_then_server_boots_from_cluster_state() { - let temp = tempfile::tempdir().unwrap(); - std::fs::write( - temp.path().join("people.pg"), - "\nnode Person {\n name: String @key\n}\n", - ) - .unwrap(); - std::fs::write( - temp.path().join("people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n", - ) - .unwrap(); - std::fs::write( - temp.path().join("cluster.yaml"), - r#" -version: 1 -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -"#, - ) - .unwrap(); - for command in ["import", "apply"] { - let output = cli() - .arg("cluster") - .arg(command) - .arg("--config") - .arg(temp.path()) - .arg("--json") - .output() - .unwrap(); - assert!(output.status.success(), "cluster {command} failed"); - } - // Seed a row through the graph plane so the stored query has data. - let data = temp.path().join("seed.jsonl"); - std::fs::write(&data, "{\"type\":\"Person\",\"data\":{\"name\":\"Ada\"}}\n").unwrap(); - let output = cli() - .arg("load") - .arg("--mode") - .arg("overwrite") - .arg("--data") - .arg(&data) - .arg(temp.path().join("graphs/knowledge.omni")) - .output() - .unwrap(); - assert!(output.status.success(), "graph load failed"); - - let server = spawn_server_with_cluster(temp.path()); - let client = reqwest::blocking::Client::new(); - let queries: serde_json::Value = client - .get(format!("{}/graphs/knowledge/queries", server.base_url)) - .send() - .unwrap() - .json() - .unwrap(); - assert!( - queries["queries"] - .as_array() - .unwrap() - .iter() - .any(|q| q["name"] == "find_person"), - "{queries}" - ); - let response = client - .post(format!( - "{}/graphs/knowledge/queries/find_person", - server.base_url - )) - .json(&serde_json::json!({"params": {"name": "Ada"}})) - .send() - .unwrap(); - assert!(response.status().is_success(), "{:?}", response.status()); - let body: serde_json::Value = response.json().unwrap(); - assert!(body.to_string().contains("Ada"), "{body}"); -} - -// ---- Comprehensive full-cycle cluster e2e (Phases 1-5 composed) ---- - -/// Run a `cluster` subcommand and return its JSON output. Deliberately does -/// NOT assert a zero exit code: blocked/unconverged runs (e.g. an `apply` -/// awaiting an approval) exit non-zero by contract while still emitting the -/// structured output the caller asserts on (`ok`/`converged`/dispositions). -/// Commands where failure is never expected must assert on those fields -/// (every call here checks `ok` or `converged`) or use `cli()` directly with -/// `status.success()`. -fn cluster_cli(dir: &std::path::Path, args: &[&str]) -> serde_json::Value { - let mut command = cli(); - command.arg("cluster"); - for arg in args { - command.arg(arg); - } - let output = command - .arg("--config") - .arg(dir) - .arg("--json") - .output() - .unwrap(); - let stdout = String::from_utf8_lossy(&output.stdout); - serde_json::from_str(stdout.trim()).unwrap_or_else(|err| { - panic!( - "cluster {args:?} produced unparseable output ({err}): stdout={stdout} stderr={}", - String::from_utf8_lossy(&output.stderr) - ) - }) -} - -fn write_two_graph_cluster(dir: &std::path::Path) { - std::fs::write( - dir.join("people.pg"), - "\nnode Person {\n name: String @key\n}\n", - ) - .unwrap(); - std::fs::write( - dir.join("services.pg"), - "\nnode Service {\n name: String @key\n}\n", - ) - .unwrap(); - std::fs::write( - dir.join("people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n", - ) - .unwrap(); - std::fs::write( - dir.join("services.gq"), - "\nquery find_service($name: String) {\n match { $s: Service { name: $name } }\n return { $s.name }\n}\n", - ) - .unwrap(); - std::fs::write( - dir.join("cluster.yaml"), - r#" -version: 1 -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq - engineering: - schema: ./services.pg - queries: - find_service: - file: ./services.gq -"#, - ) - .unwrap(); -} - -fn seed_graph(dir: &std::path::Path, graph: &str, row: &str) { - let data = dir.join(format!("{graph}-seed.jsonl")); - std::fs::write(&data, row).unwrap(); - let output = cli() - .arg("load") - .arg("--mode") - .arg("overwrite") - .arg("--data") - .arg(&data) - .arg(dir.join(format!("graphs/{graph}.omni"))) - .output() - .unwrap(); - assert!( - output.status.success(), - "seed {graph} failed: {}", - String::from_utf8_lossy(&output.stderr) - ); -} - -fn invoke_query( - client: &Client, - base_url: &str, - graph: &str, - query: &str, - params: serde_json::Value, -) -> (u16, serde_json::Value) { - let response = client - .post(format!("{base_url}/graphs/{graph}/queries/{query}")) - .json(&serde_json::json!({ "params": params })) - .send() - .unwrap(); - let status = response.status().as_u16(); - let body = response.json().unwrap_or(serde_json::Value::Null); - (status, body) -} - -/// Opt-out for the comprehensive system e2es below. They need no external -/// services β€” only the workspace-built `omnigraph`/`omnigraph-server` -/// binaries (cargo provides them via `CARGO_BIN_EXE_*`), ephemeral localhost -/// ports, and local-FS temp dirs β€” but they spawn real server processes and -/// run multi-stage lifecycles, so constrained sandboxes can suppress them: -/// `OMNIGRAPH_SKIP_SYSTEM_E2E=1 cargo test ...` (same skip-with-message -/// pattern as the S3 tests' `OMNIGRAPH_S3_TEST_BUCKET` gate). -fn skip_system_e2e(test_name: &str) -> bool { - if std::env::var("OMNIGRAPH_SKIP_SYSTEM_E2E").is_ok_and(|v| !v.is_empty() && v != "0") { - eprintln!("skipping {test_name}: OMNIGRAPH_SKIP_SYSTEM_E2E is set"); - return true; - } - false -} - -/// The whole control-plane story in one test: declare two graphs β†’ converge -/// (apply creates them) β†’ serve β†’ evolve schema+query in one apply β†’ restart -/// serves the new shape β†’ out-of-band drift converged back β†’ approved graph -/// delete β†’ restart serves the survivor only β†’ plan empty. -#[test] -fn local_cluster_full_lifecycle_declare_serve_evolve_delete() { - if skip_system_e2e("local_cluster_full_lifecycle_declare_serve_evolve_delete") { - return; - } - let temp = tempfile::tempdir().unwrap(); - let dir = temp.path(); - write_two_graph_cluster(dir); - - // Phase 1-2: declare + record. - assert_eq!(cluster_cli(dir, &["import"])["ok"], true); - // Phase 3-4: one apply creates both graphs and publishes the catalog. - let converge = cluster_cli(dir, &["apply"]); - assert_eq!(converge["converged"], true, "{converge}"); - seed_graph(dir, "knowledge", "{\"type\":\"Person\",\"data\":{\"name\":\"Ada\"}}\n"); - seed_graph(dir, "engineering", "{\"type\":\"Service\",\"data\":{\"name\":\"billing\"}}\n"); - - // Phase 5: serve the applied revision. - let client = Client::new(); - { - let server = spawn_server_with_cluster(dir); - let (status, body) = invoke_query( - &client, - &server.base_url, - "knowledge", - "find_person", - serde_json::json!({"name": "Ada"}), - ); - assert_eq!(status, 200, "{body}"); - assert_eq!(body["rows"][0]["p.name"], "Ada", "{body}"); - let (status, body) = invoke_query( - &client, - &server.base_url, - "engineering", - "find_service", - serde_json::json!({"name": "billing"}), - ); - assert_eq!(status, 200, "{body}"); - assert_eq!(body["rows"][0]["s.name"], "billing", "{body}"); - } - - // Evolve: schema gains a field, the query returns it β€” one apply, with - // the migration previewed in plan. - std::fs::write( - dir.join("people.pg"), - "\nnode Person {\n name: String @key\n bio: String?\n}\n", - ) - .unwrap(); - std::fs::write( - dir.join("people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name, $p.bio }\n}\n", - ) - .unwrap(); - let plan = cluster_cli(dir, &["plan"]); - let schema_change = plan["changes"] - .as_array() - .unwrap() - .iter() - .find(|change| change["resource"] == "schema.knowledge") - .unwrap(); - assert_eq!(schema_change["migration"]["supported"], true, "{plan}"); - let evolve = cluster_cli(dir, &["apply"]); - assert_eq!(evolve["converged"], true, "{evolve}"); - - // Restart: the server serves the evolved shape. - { - let server = spawn_server_with_cluster(dir); - let (status, body) = invoke_query( - &client, - &server.base_url, - "knowledge", - "find_person", - serde_json::json!({"name": "Ada"}), - ); - assert_eq!(status, 200, "{body}"); - assert!( - body["columns"] - .as_array() - .unwrap() - .iter() - .any(|column| column == "p.bio"), - "evolved query must project the new field: {body}" - ); - } - - // Out-of-band drift: the live graph evolves behind the cluster's back; - // refresh observes it, apply converges it back to the declared schema. - std::fs::write( - dir.join("rogue.pg"), - "\nnode Person {\n name: String @key\n bio: String?\n rogue: String?\n}\n", - ) - .unwrap(); - let output = cli() - .arg("schema") - .arg("apply") - .arg(dir.join("graphs/knowledge.omni")) - .arg("--schema") - .arg(dir.join("rogue.pg")) - .arg("--json") - .output() - .unwrap(); - assert!(output.status.success(), "out-of-band schema apply failed"); - let refresh = cluster_cli(dir, &["refresh"]); - assert_eq!( - refresh["resource_statuses"]["schema.knowledge"]["status"], - "drifted", - "{refresh}" - ); - let heal = cluster_cli(dir, &["apply"]); - assert_eq!(heal["converged"], true, "{heal}"); - let schema_show = cli() - .arg("schema") - .arg("show") - .arg(dir.join("graphs/knowledge.omni")) - .output() - .unwrap(); - assert!( - schema_show.status.success(), - "schema show failed: {}", - String::from_utf8_lossy(&schema_show.stderr) - ); - let shown = String::from_utf8_lossy(&schema_show.stdout); - assert!(shown.contains("Person"), "schema show produced no schema: {shown}"); - assert!( - !shown.contains("rogue"), - "drift must be soft-dropped back to the declared schema: {shown}" - ); - - // Retire engineering: gated delete, then the server serves the survivor. - std::fs::write( - dir.join("cluster.yaml"), - r#" -version: 1 -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -"#, - ) - .unwrap(); - let blocked = cluster_cli(dir, &["apply"]); - assert_eq!(blocked["converged"], false, "{blocked}"); - let approve_output = cli() - .arg("--as") - .arg("andrew") - .arg("cluster") - .arg("approve") - .arg("graph.engineering") - .arg("--config") - .arg(dir) - .arg("--json") - .output() - .unwrap(); - assert!(approve_output.status.success(), "approve failed"); - let delete = cluster_cli(dir, &["apply"]); - assert_eq!(delete["converged"], true, "{delete}"); - assert!(!dir.join("graphs/engineering.omni").exists()); - - { - let server = spawn_server_with_cluster(dir); - let (status, body) = invoke_query( - &client, - &server.base_url, - "knowledge", - "find_person", - serde_json::json!({"name": "Ada"}), - ); - assert_eq!(status, 200, "{body}"); - let response = client - .post(format!( - "{}/graphs/engineering/queries/find_service", - server.base_url - )) - .json(&serde_json::json!({"params": {"name": "billing"}})) - .send() - .unwrap(); - assert_eq!( - response.status().as_u16(), - 404, - "a deleted graph must vanish from the serving surface" - ); - } - - // The story ends converged: nothing left to do. - let final_plan = cluster_cli(dir, &["plan"]); - assert!( - final_plan["changes"].as_array().unwrap().is_empty(), - "{final_plan}" - ); -} - -/// Applied policy bundles gate serving per their bindings: the cluster-bound -/// bundle owns the management surface (graph_list), the graph-bound bundle -/// owns query invocation β€” enforced over HTTP with bearer-resolved actors. -#[test] -fn local_cluster_serving_enforces_applied_policy_bindings() { - if skip_system_e2e("local_cluster_serving_enforces_applied_policy_bindings") { - return; - } - let temp = tempfile::tempdir().unwrap(); - let dir = temp.path(); - std::fs::write( - dir.join("people.pg"), - "\nnode Person {\n name: String @key\n}\n", - ) - .unwrap(); - std::fs::write( - dir.join("people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n", - ) - .unwrap(); - std::fs::write( - dir.join("graph.policy.yaml"), - r#" -version: 1 -groups: - readers: ["act-reader"] -protected_branches: [main] -rules: - - id: allow-invoke - allow: - actors: { group: readers } - actions: [invoke_query] - - id: allow-read - allow: - actors: { group: readers } - actions: [read] - branch_scope: any -"#, - ) - .unwrap(); - std::fs::write( - dir.join("server.policy.yaml"), - r#" -version: 1 -kind: server -groups: - admins: ["act-admin"] -rules: - - id: allow-list - allow: - actors: { group: admins } - actions: [graph_list] -"#, - ) - .unwrap(); - std::fs::write( - dir.join("cluster.yaml"), - r#" -version: 1 -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -policies: - graph_rules: - file: ./graph.policy.yaml - applies_to: [knowledge] - server_rules: - file: ./server.policy.yaml - applies_to: [cluster] -"#, - ) - .unwrap(); - assert_eq!(cluster_cli(dir, &["import"])["ok"], true); - let converge = cluster_cli(dir, &["apply"]); - assert_eq!(converge["converged"], true, "{converge}"); - seed_graph(dir, "knowledge", "{\"type\":\"Person\",\"data\":{\"name\":\"Ada\"}}\n"); - - let server = spawn_server_with_cluster_env( - dir, - &[( - "OMNIGRAPH_SERVER_BEARER_TOKENS_JSON", - r#"{"act-admin":"admin-token","act-reader":"reader-token"}"#, - )], - ); - let client = Client::new(); - let get_graphs = |token: Option<&str>| { - let mut request = client.get(format!("{}/graphs", server.base_url)); - if let Some(token) = token { - request = request.bearer_auth(token); - } - request.send().unwrap().status().as_u16() - }; - // Management surface: cluster-bound bundle, admins only. - assert_eq!(get_graphs(Some("admin-token")), 200); - assert_eq!(get_graphs(Some("reader-token")), 403); - assert_eq!(get_graphs(None), 401); - - // Query invocation: graph-bound bundle, readers only. - let invoke = |token: &str| { - client - .post(format!( - "{}/graphs/knowledge/queries/find_person", - server.base_url - )) - .bearer_auth(token) - .json(&serde_json::json!({"params": {"name": "Ada"}})) - .send() - .unwrap() - }; - let response = invoke("reader-token"); - assert_eq!(response.status().as_u16(), 200); - let body: serde_json::Value = response.json().unwrap(); - assert_eq!(body["rows"][0]["p.name"], "Ada", "{body}"); - // Denied invocation is deliberately 404, indistinguishable from an - // unknown query β€” the server's anti-probing contract. - assert_eq!(invoke("admin-token").status().as_u16(), 404); -} - -/// Rule 0 (axiom 15): a --cluster server never reads omnigraph.yaml β€” not -/// even the implicit cwd search. A MALFORMED config in the process cwd must -/// not affect boot or serving. -#[test] -fn cluster_server_boot_ignores_local_config_in_cwd() { - let cluster = tempfile::tempdir().unwrap(); - std::fs::write( - cluster.path().join("people.pg"), - "\nnode Person {\n name: String @key\n}\n", - ) - .unwrap(); - std::fs::write( - cluster.path().join("cluster.yaml"), - "version: 1\ngraphs:\n knowledge:\n schema: ./people.pg\n", - ) - .unwrap(); - for command in ["import", "apply"] { - let output = cli() - .arg("cluster") - .arg(command) - .arg("--config") - .arg(cluster.path()) - .output() - .unwrap(); - assert!(output.status.success(), "cluster {command} failed"); - } - let cwd = tempfile::tempdir().unwrap(); - std::fs::write(cwd.path().join("omnigraph.yaml"), "{{{{ not yaml").unwrap(); - - let server = spawn_server_with_cluster_in(cluster.path(), cwd.path()); - let response = reqwest::blocking::get(format!("{}/healthz", server.base_url)).unwrap(); - assert!(response.status().is_success()); -} - -/// RFC-007 PR 2: keyed credentials end to end β€” `login` stores a 0600 -/// credential, the URL-matched server's token chain authenticates remote -/// reads (env > file), a non-matching URL never sees the token (Β§D5 rule -/// 3), and `logout` revokes. -#[test] -fn local_cli_keyed_credentials_authenticate_url_matched_server() { - let graph = SystemGraph::loaded(); - let server = spawn_server_with_env( - graph.path(), - &[("OMNIGRAPH_SERVER_BEARER_TOKEN", "secret-tok")], - ); - let operator_home = tempfile::tempdir().unwrap(); - let write_server_url = |url: &str| { - fs::write( - operator_home.path().join("config.yaml"), - format!("servers:\n test-srv:\n url: {url}\n"), - ) - .unwrap(); - }; - write_server_url(&server.base_url); - - let remote_read = |envs: &[(&str, &str)]| { - let mut command = cli(); - command.env("OMNIGRAPH_HOME", operator_home.path()); - for (name, value) in envs { - command.env(name, value); - } - command - .arg("read") - .arg(&server.base_url) - .arg("--query") - .arg(fixture("test.gq")) - .arg("--name") - .arg("get_person") - .arg("--params") - .arg(r#"{"name":"Alice"}"#) - .arg("--json") - .output() - .unwrap() - }; - - // No credential anywhere: the server refuses. - let output = remote_read(&[]); - assert!(!output.status.success(), "{output:?}"); - - // login with a WRONG token (via stdin, the documented pipe flow). - let output = cli() - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("login") - .arg("test-srv") - .write_stdin("wrong-tok\n") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - let output = remote_read(&[]); - assert!(!output.status.success(), "wrong token must not authenticate"); - - // Re-login rotates to the right token (via --token); 0600 on disk. - let output = cli() - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("login") - .arg("test-srv") - .arg("--token") - .arg("secret-tok") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - let credentials = operator_home.path().join("credentials"); - let text = fs::read_to_string(&credentials).unwrap(); - assert!(text.contains("[test-srv]"), "{text}"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = fs::metadata(&credentials).unwrap().permissions().mode(); - assert_eq!(mode & 0o777, 0o600, "{:o}", mode & 0o777); - } - let output = remote_read(&[]); - assert!( - output.status.success(), - "keyed credential must authenticate the URL-matched server: {output:?}" - ); - let payload: serde_json::Value = - serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(payload["rows"][0]["p.name"], "Alice"); - - // OMNIGRAPH_TOKEN_ env outranks the credentials file. - let output = remote_read(&[("OMNIGRAPH_TOKEN_TEST_SRV", "env-wrong")]); - assert!( - !output.status.success(), - "keyed env token must outrank the credentials file" - ); - - // Β§D5 rule 3: a URL matching no operator server never sees the token. - write_server_url("http://127.0.0.1:1"); - let output = remote_read(&[]); - assert!( - !output.status.success(), - "token keyed to another url must not be sent here" - ); - write_server_url(&server.base_url); - - // logout revokes; idempotent. - for _ in 0..2 { - let output = cli() - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("logout") - .arg("test-srv") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - } - let output = remote_read(&[]); - assert!(!output.status.success(), "logout must revoke access"); -} - -/// RFC-007 PR 3: --server targeting and operator aliases (pure bindings to -/// stored queries) end to end, with the keyed credential from PR 2. -#[test] -fn local_cli_operator_alias_and_server_flag_invoke_stored_query() { - let graph = SystemGraph::loaded(); - graph.write_query( - "stored-find-person.gq", - "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.name } }", - ); - // invoke_query is policy-gated (anti-probing 404 without the grant), - // so the server gets a per-graph bundle granting it to the operator. - graph.write_file( - "graph.policy.yaml", - "version: 1\ngroups:\n ops: [\"act-op\"]\nprotected_branches: [main]\nrules:\n - id: allow-invoke\n allow:\n actors: { group: ops }\n actions: [invoke_query]\n - id: allow-read\n allow:\n actors: { group: ops }\n actions: [read]\n branch_scope: any\n", - ); - let config = graph.write_config( - "omnigraph-server.yaml", - &format!( - "graphs:\n local:\n uri: {}\n policy:\n file: ./graph.policy.yaml\n queries:\n find_person:\n file: ./stored-find-person.gq\n", - yaml_string(&graph.path().to_string_lossy()) - ), - ); - let server = spawn_server_with_config_env( - &config, - &[( - "OMNIGRAPH_SERVER_BEARER_TOKENS_JSON", - r#"{"act-op":"srv-tok"}"#, - )], - ); - - let operator_home = tempfile::tempdir().unwrap(); - fs::write( - operator_home.path().join("config.yaml"), - format!( - "servers:\n dev:\n url: {}\naliases:\n who:\n server: dev\n graph: local\n query: find_person\n args: [name]\n", - server.base_url - ), - ) - .unwrap(); - fs::write( - operator_home.path().join("credentials"), - "[dev]\ntoken = srv-tok\n", - ) - .unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions( - operator_home.path().join("credentials"), - fs::Permissions::from_mode(0o600), - ) - .unwrap(); - } - - // The operator alias: name + positional arg, nothing else β€” server, - // graph, stored query, and token all resolve from the operator layer. - let output = cli() - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("query") - .arg("--alias") - .arg("who") - .arg("Alice") - .arg("--json") - .output() - .unwrap(); - assert!( - output.status.success(), - "operator alias must invoke the stored query: {output:?}" - ); - let payload: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(payload["rows"][0]["p.name"], "Alice", "{payload}"); - - // --server/--graph: the same stored query via explicit targeting. - let output = cli() - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("query") - .arg("--server") - .arg("dev") - .arg("--graph") - .arg("local") - .arg("--query-string") - .arg("query q($name: String) { match { $p: Person { name: $name } } return { $p.name } }") - .arg("--params") - .arg(r#"{"name":"Alice"}"#) - .arg("--json") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - - // Unknown --server errors listing what IS defined. - let output = cli() - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("query") - .arg("--server") - .arg("nope") - .arg("--query-string") - .arg("query q() { match { $p: Person } return { $p.name } }") - .output() - .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("unknown server 'nope'") && stderr.contains("dev"), "{stderr}"); - - // --server is exclusive with a positional URI. - let output = cli() - .env("OMNIGRAPH_HOME", operator_home.path()) - .arg("query") - .arg(&server.base_url) - .arg("--server") - .arg("dev") - .arg("--query-string") - .arg("query q() { match { $p: Person } return { $p.name } }") - .output() - .unwrap(); - assert!(!output.status.success()); - assert!( - String::from_utf8_lossy(&output.stderr).contains("exclusive"), - "{output:?}" - ); -} diff --git a/crates/omnigraph-cli/tests/system_remote.rs b/crates/omnigraph-cli/tests/system_remote.rs index 95a53e7..45bf502 100644 --- a/crates/omnigraph-cli/tests/system_remote.rs +++ b/crates/omnigraph-cli/tests/system_remote.rs @@ -652,8 +652,6 @@ query add_friend($from: String, $to: String) { output_success( cli() .arg("load") - .arg("--mode") - .arg("overwrite") .arg("--data") .arg(&export_path) .arg(&imported_graph), @@ -757,71 +755,6 @@ fn remote_ingest_creates_review_branch_and_keeps_it_readable() { assert_eq!(zoe["rows"][0]["p.name"], "Zoe"); } -/// The unified `load` works against remote graphs through the server's -/// `/ingest` endpoint: without `--from` a missing branch is a hard error -/// (no implicit fork), with `--from` it forks like ingest did. -#[test] -#[ignore = "requires loopback socket permissions in sandboxed runners"] -fn remote_load_round_trips_and_requires_from_for_new_branches() { - let graph = SystemGraph::loaded(); - let server = graph.spawn_server(); - let config = graph.write_config("omnigraph.yaml", &remote_yaml_config(&server.base_url)); - let extra = graph.write_jsonl( - "system-remote-load.jsonl", - r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#, - ); - - // Missing branch without --from: refused remotely, nothing created. - let failure = output_failure( - cli() - .arg("load") - .arg("--config") - .arg(&config) - .arg("--mode") - .arg("merge") - .arg("--data") - .arg(&extra) - .arg("--branch") - .arg("feature-load"), - ); - assert!( - String::from_utf8_lossy(&failure.stderr).contains("feature-load"), - "error should name the missing branch" - ); - - // With --from, the remote load forks and lands the rows. - let payload = parse_stdout_json(&output_success( - cli() - .arg("load") - .arg("--config") - .arg(&config) - .arg("--mode") - .arg("merge") - .arg("--data") - .arg(&extra) - .arg("--branch") - .arg("feature-load") - .arg("--from") - .arg("main") - .arg("--json"), - )); - assert_eq!(payload["branch"], "feature-load"); - assert_eq!(payload["base_branch"], "main"); - assert_eq!(payload["branch_created"], true); - assert_eq!(payload["nodes_loaded"], 1); - - let snapshot = parse_stdout_json(&output_success( - cli() - .arg("snapshot") - .arg("--config") - .arg(&config) - .arg("--branch") - .arg("feature-load") - .arg("--json"), - )); - assert_eq!(snapshot["branch"], "feature-load"); -} - #[test] #[ignore = "requires loopback socket permissions in sandboxed runners"] fn remote_ingest_reuses_existing_branch_and_merges_updates() { diff --git a/crates/omnigraph-cluster/Cargo.toml b/crates/omnigraph-cluster/Cargo.toml deleted file mode 100644 index 973de6d..0000000 --- a/crates/omnigraph-cluster/Cargo.toml +++ /dev/null @@ -1,34 +0,0 @@ -[package] -name = "omnigraph-cluster" -version = "0.6.2" -edition = "2024" -description = "Cluster configuration validation, planning, and config-only apply for Omnigraph." -license = "MIT" -repository = "https://github.com/ModernRelay/omnigraph" -homepage = "https://github.com/ModernRelay/omnigraph" -documentation = "https://docs.rs/omnigraph-cluster" - -[features] -# Fault-injection hooks for the apply protocol (crash-mid-apply, CAS-race -# tests). Deliberately does NOT enable omnigraph/failpoints. -failpoints = ["dep:fail", "fail/failpoints"] - -[dependencies] -omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.2" } -omnigraph = { package = "omnigraph-engine", path = "../omnigraph", version = "0.6.2" } -fail = { workspace = true, optional = true } -serde = { workspace = true } -serde_json = { workspace = true } -serde_yaml = { workspace = true } -sha2 = { workspace = true } -thiserror = { workspace = true } -time = { workspace = true } -# Runtime handle only β€” best-effort async lock release in -# StateLockGuard::drop on object-store backends (cluster commands always -# run inside the caller's tokio runtime). -tokio = { workspace = true } -ulid = { workspace = true } - -[dev-dependencies] -tempfile = { workspace = true } -tokio = { workspace = true } diff --git a/crates/omnigraph-cluster/src/config.rs b/crates/omnigraph-cluster/src/config.rs deleted file mode 100644 index acc954d..0000000 --- a/crates/omnigraph-cluster/src/config.rs +++ /dev/null @@ -1,907 +0,0 @@ -//! Declared-configuration loading: cluster.yaml parsing, query -//! discovery, source digesting, validation (moved verbatim from lib.rs -//! in the modularization). Reads the operator's WORKING TREE β€” stored -//! state never lives here (see store.rs). - -use super::*; - -/// How a graph declares its stored queries. Terraform-style: the `.gq` -/// files ARE the declaration β€” point at them (or a directory) and every -/// `query ` they contain is discovered. The explicit name->file map -/// remains for fine-grained control. -#[derive(Debug, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum QueriesDecl { - /// `queries: ./queries/` β€” a directory (top-level `*.gq`, sorted) or a - /// single `.gq` file; every declaration inside is registered. - Discover(PathBuf), - /// `queries: [./queries/, ./extra.gq]` β€” several directories/files. - DiscoverMany(Vec), - /// `queries: { name: { file: ... } }` β€” explicit registry. - Explicit(BTreeMap), -} - -impl Default for QueriesDecl { - fn default() -> Self { - QueriesDecl::Explicit(BTreeMap::new()) - } -} - -/// Expand a graph's query declaration into the canonical name->file map. -/// Discovery reads and parses each `.gq`; unreadable or unparseable files -/// and duplicate query names are loud validation errors β€” a declaration the -/// tool cannot enumerate is broken, not partially usable. -pub(crate) fn resolve_query_decls( - config_dir: &Path, - graph_id: &str, - decl: &QueriesDecl, - diagnostics: &mut Vec, -) -> (BTreeMap, BTreeMap) { - let paths: Vec = match decl { - QueriesDecl::Explicit(map) => { - return ( - map.iter() - .map(|(name, config)| { - (name.clone(), QueryConfig { file: config.file.clone() }) - }) - .collect(), - BTreeMap::new(), - ); - } - QueriesDecl::Discover(path) => vec![path.clone()], - QueriesDecl::DiscoverMany(paths) => paths.clone(), - }; - - let mut files: Vec<(PathBuf, PathBuf)> = Vec::new(); // (declared-relative, resolved) - for declared in &paths { - let resolved = resolve_config_path(config_dir, declared); - if resolved.is_dir() { - let mut entries: Vec = match fs::read_dir(&resolved) { - Ok(read) => read - .flatten() - .map(|entry| entry.path()) - .filter(|path| path.extension().is_some_and(|ext| ext == "gq")) - .collect(), - Err(err) => { - diagnostics.push(Diagnostic::error( - "query_dir_unreadable", - format!("graphs.{graph_id}.queries"), - format!("could not list query directory '{}': {err}", resolved.display()), - )); - continue; - } - }; - entries.sort(); - if entries.is_empty() { - diagnostics.push(Diagnostic::warning( - "query_dir_empty", - format!("graphs.{graph_id}.queries"), - format!("query directory '{}' contains no .gq files", resolved.display()), - )); - } - for path in entries { - let relative = declared.join(path.file_name().expect("dir entries have names")); - files.push((relative, path)); - } - } else { - files.push((declared.clone(), resolved)); - } - } - - let mut registry: BTreeMap = BTreeMap::new(); - let mut origin: BTreeMap = BTreeMap::new(); - // Content read once at discovery and handed to the caller β€” the per-query - // digest/typecheck pass reuses it instead of re-reading (no N+1 reads, no - // window for the file to change between enumeration and validation). - let mut contents: BTreeMap = BTreeMap::new(); - for (declared, resolved) in files { - let source = match fs::read_to_string(&resolved) { - Ok(source) => source, - Err(err) => { - diagnostics.push(Diagnostic::error( - "query_file_missing", - format!("graphs.{graph_id}.queries"), - format!("could not read query file '{}': {err}", resolved.display()), - )); - continue; - } - }; - let parsed = match parse_query(&source) { - Ok(parsed) => parsed, - Err(err) => { - diagnostics.push(Diagnostic::error( - "query_parse_error", - format!("graphs.{graph_id}.queries"), - format!("'{}' does not parse: {err}", resolved.display()), - )); - continue; - } - }; - for query_decl in &parsed.queries { - let name = query_decl.name.clone(); - if let Some(previous) = origin.get(&name) { - diagnostics.push(Diagnostic::error( - "duplicate_query_name", - format!("graphs.{graph_id}.queries.{name}"), - format!( - "query '{name}' is declared in both '{}' and '{}'", - previous.display(), - declared.display() - ), - )); - continue; - } - origin.insert(name.clone(), declared.clone()); - registry.insert(name, QueryConfig { file: declared.clone() }); - } - contents.insert(declared, source); - } - (registry, contents) -} - -pub(crate) fn parse_cluster_config(config_dir: &Path) -> ParsedConfig { - let config_dir = config_dir.to_path_buf(); - let config_file = config_dir.join(CLUSTER_CONFIG_FILE); - let mut diagnostics = Vec::new(); - - if !config_dir.is_dir() { - diagnostics.push(Diagnostic::error( - "config_dir_not_found", - display_path(&config_dir), - "`--config` must point at a directory containing cluster.yaml", - )); - return ParsedConfig { - raw: None, - diagnostics, - config_dir, - config_file, - }; - } - - let text = match fs::read_to_string(&config_file) { - Ok(text) => text, - Err(err) => { - diagnostics.push(Diagnostic::error( - "cluster_config_read_error", - CLUSTER_CONFIG_FILE, - format!("could not read cluster.yaml: {err}"), - )); - return ParsedConfig { - raw: None, - diagnostics, - config_dir, - config_file, - }; - } - }; - - diagnostics.extend(duplicate_key_diagnostics(&text)); - diagnostics.extend(future_field_diagnostics(&text)); - if has_errors(&diagnostics) { - return ParsedConfig { - raw: None, - diagnostics, - config_dir, - config_file, - }; - } - - let raw = match serde_yaml::from_str::(&text) { - Ok(raw) => Some(raw), - Err(err) => { - diagnostics.push(Diagnostic::error( - "invalid_cluster_yaml", - CLUSTER_CONFIG_FILE, - format!("could not parse cluster.yaml: {err}"), - )); - None - } - }; - - ParsedConfig { - raw, - diagnostics, - config_dir, - config_file, - } -} - -pub(crate) fn validate_cluster_header( - raw: &RawClusterConfig, - diagnostics: &mut Vec, -) -> ClusterSettings { - if raw.version != 1 { - diagnostics.push(Diagnostic::error( - "unsupported_cluster_config_version", - "version", - format!( - "unsupported cluster config version {}; this build supports version 1", - raw.version - ), - )); - } - if let Some(name) = raw.metadata.name.as_deref() { - if name.trim().is_empty() { - diagnostics.push(Diagnostic::error( - "empty_metadata_name", - "metadata.name", - "metadata.name must not be empty when provided", - )); - } - } - if let Some(backend) = raw.state.backend.as_deref() { - if backend != "cluster" { - diagnostics.push(Diagnostic::error( - "unsupported_state_backend", - "state.backend", - "Stage 2C supports only omitted state.backend or `cluster`", - )); - } - } - - if let Some(storage) = raw.storage.as_deref() { - let trimmed = storage.trim(); - if trimmed.is_empty() { - diagnostics.push(Diagnostic::error( - "invalid_storage_root", - "storage", - "storage must be a non-empty URI (e.g. s3://bucket/prefix) when provided", - )); - } else if let Some(rest) = trimmed.strip_prefix("s3://") { - if rest.trim_start_matches('/').is_empty() { - diagnostics.push(Diagnostic::error( - "invalid_storage_root", - "storage", - "storage s3:// URI must name a bucket", - )); - } - } - } - - ClusterSettings { - state_lock: raw.state.lock.unwrap_or(true), - storage_root: raw - .storage - .as_deref() - .map(str::trim) - .filter(|storage| !storage.is_empty()) - .map(|storage| storage.trim_end_matches('/').to_string()), - } -} - - - -pub(crate) fn state_resource_digests(state: &ClusterState) -> BTreeMap { - state - .applied_revision - .resources - .iter() - .map(|(address, resource)| (address.clone(), resource.digest.clone())) - .collect() -} - -pub(crate) fn initial_import_state(desired: &DesiredCluster) -> ClusterState { - ClusterState { - version: 1, - state_revision: 0, - applied_revision: AppliedRevisionState { - config_digest: Some(desired.config_digest.clone()), - resources: BTreeMap::new(), - }, - resource_statuses: BTreeMap::new(), - approval_records: BTreeMap::new(), - recovery_records: BTreeMap::new(), - observations: BTreeMap::new(), - } -} - - -pub(crate) async fn observe_declared_graphs( - desired: &DesiredCluster, - backend: &ClusterStore, - state: &mut ClusterState, -) -> usize { - let mut graph_error_count = 0; - for graph in &desired.graphs { - let graph_address = graph_address(&graph.id); - let schema_address = schema_address(&graph.id); - let graph_uri = backend.graph_root(&graph.id); - let observed_at = now_rfc3339(); - - if !backend.graph_root_exists(&graph_uri).await { - state.applied_revision.resources.remove(&graph_address); - state.applied_revision.resources.remove(&schema_address); - state.observations.insert( - graph_address.clone(), - graph_observation_json(GraphObservationJson { - address: &graph_address, - graph_uri: &graph_uri, - observed_at: &observed_at, - exists: false, - manifest_version: None, - schema_digest: None, - desired_schema_digest: &graph.schema_digest, - schema_matches_desired: Some(false), - error: Some("derived graph root is missing"), - }), - ); - set_resource_status( - state, - &graph_address, - ResourceLifecycleStatus::Drifted, - "graph_missing", - "derived graph root is missing", - ); - set_resource_status( - state, - &schema_address, - ResourceLifecycleStatus::Drifted, - "graph_missing", - "derived graph root is missing", - ); - continue; - } - - match observe_live_graph(&graph_uri).await { - Ok(observation) => { - let schema_matches = observation.schema_digest == graph.schema_digest; - state.applied_revision.resources.insert( - schema_address.clone(), - StateResource { - digest: observation.schema_digest.clone(), - applies_to: None, - }, - ); - let query_digests = state_query_digests_for_graph(state, &graph.id); - let graph_digest_value = graph_digest( - &graph.id, - Some(&observation.schema_digest), - Some(&query_digests), - ); - state.applied_revision.resources.insert( - graph_address.clone(), - StateResource { - digest: graph_digest_value, - applies_to: None, - }, - ); - state.observations.insert( - graph_address.clone(), - graph_observation_json(GraphObservationJson { - address: &graph_address, - graph_uri: &graph_uri, - observed_at: &observed_at, - exists: true, - manifest_version: Some(observation.manifest_version), - schema_digest: Some(observation.schema_digest.as_str()), - desired_schema_digest: &graph.schema_digest, - schema_matches_desired: Some(schema_matches), - error: None, - }), - ); - if schema_matches { - set_resource_status_applied(state, &graph_address); - set_resource_status_applied(state, &schema_address); - } else { - set_resource_status( - state, - &graph_address, - ResourceLifecycleStatus::Drifted, - "schema_mismatch", - "live schema digest differs from desired schema digest", - ); - set_resource_status( - state, - &schema_address, - ResourceLifecycleStatus::Drifted, - "schema_mismatch", - "live schema digest differs from desired schema digest", - ); - } - } - Err(error) => { - graph_error_count += 1; - state.observations.insert( - graph_address.clone(), - graph_observation_json(GraphObservationJson { - address: &graph_address, - graph_uri: &graph_uri, - observed_at: &observed_at, - exists: true, - manifest_version: None, - schema_digest: None, - desired_schema_digest: &graph.schema_digest, - schema_matches_desired: None, - error: Some(error.as_str()), - }), - ); - set_resource_status( - state, - &graph_address, - ResourceLifecycleStatus::Error, - "graph_observation_error", - error.as_str(), - ); - set_resource_status( - state, - &schema_address, - ResourceLifecycleStatus::Error, - "graph_observation_error", - error.as_str(), - ); - } - } - } - graph_error_count -} - -/// RFC-004 Β§D7: the data-aware preview β€” the engine's migration plan for a -/// desired schema against the live graph, computed read-only (no lock). -pub(crate) async fn preview_schema_migration( - graph_uri: &str, - schema_path: &str, -) -> Result { - let source = fs::read_to_string(schema_path).map_err(|err| err.to_string())?; - let db = Omnigraph::open_read_only(graph_uri) - .await - .map_err(|err| err.to_string())?; - let preview = db - .preview_schema_apply_with_options(&source, SchemaApplyOptions::default()) - .await - .map_err(|err| err.to_string())?; - Ok(preview.plan) -} - -struct LiveGraphObservation { - manifest_version: u64, - schema_digest: String, -} - -pub(crate) async fn observe_live_graph(graph_uri: &str) -> Result { - let db = Omnigraph::open_read_only(graph_uri) - .await - .map_err(|err| err.to_string())?; - let snapshot = db - .snapshot_of(ReadTarget::branch("main")) - .await - .map_err(|err| err.to_string())?; - let schema_source = db.schema_source(); - Ok(LiveGraphObservation { - manifest_version: snapshot.version(), - schema_digest: sha256_hex(schema_source.as_bytes()), - }) -} - -struct GraphObservationJson<'a> { - address: &'a str, - graph_uri: &'a str, - observed_at: &'a str, - exists: bool, - manifest_version: Option, - schema_digest: Option<&'a str>, - desired_schema_digest: &'a str, - schema_matches_desired: Option, - error: Option<&'a str>, -} - -pub(crate) fn graph_observation_json(observation: GraphObservationJson<'_>) -> serde_json::Value { - json!({ - "kind": "graph", - "address": observation.address, - "graph_uri": observation.graph_uri, - "observed_at": observation.observed_at, - "exists": observation.exists, - "manifest_version": observation.manifest_version, - "schema_digest": observation.schema_digest, - "desired_schema_digest": observation.desired_schema_digest, - "schema_matches_desired": observation.schema_matches_desired, - "error": observation.error, - }) -} - - -pub(crate) fn load_desired(config_dir: &Path) -> LoadOutcome { - let parsed = parse_cluster_config(config_dir); - let config_dir = parsed.config_dir; - let config_file = parsed.config_file; - let mut diagnostics = parsed.diagnostics; - let Some(raw) = parsed.raw else { - return LoadOutcome { - desired: None, - diagnostics, - config_dir, - config_file, - }; - }; - let settings = validate_cluster_header(&raw, &mut diagnostics); - - let mut resources = BTreeMap::new(); - let mut dependencies = BTreeSet::new(); - let mut graph_query_digests: BTreeMap> = BTreeMap::new(); - let mut graph_schema_digests: BTreeMap = BTreeMap::new(); - - for (graph_id, graph) in &raw.graphs { - validate_id( - "graph id", - &format!("graphs.{graph_id}"), - graph_id, - &mut diagnostics, - ); - let graph_address = graph_address(graph_id); - let schema_address = schema_address(graph_id); - dependencies.insert(Dependency { - from: schema_address.clone(), - to: graph_address.clone(), - }); - - let schema_path = resolve_config_path(&config_dir, &graph.schema); - let schema_source = match fs::read_to_string(&schema_path) { - Ok(source) => { - let digest = sha256_hex(source.as_bytes()); - graph_schema_digests.insert(graph_id.clone(), digest.clone()); - resources.insert( - schema_address.clone(), - ResourceSummary { - address: schema_address.clone(), - kind: "schema".to_string(), - digest, - path: Some(display_path(&schema_path)), - }, - ); - Some(source) - } - Err(err) => { - diagnostics.push(Diagnostic::error( - "schema_file_missing", - format!("graphs.{graph_id}.schema"), - format!( - "could not read schema file '{}': {err}", - schema_path.display() - ), - )); - None - } - }; - - let catalog = schema_source.and_then(|source| match parse_schema(&source) { - Ok(schema) => match build_catalog(&schema) { - Ok(catalog) => Some(catalog), - Err(err) => { - diagnostics.push(Diagnostic::error( - "schema_catalog_error", - format!("graphs.{graph_id}.schema"), - err.to_string(), - )); - None - } - }, - Err(err) => { - diagnostics.push(Diagnostic::error( - "schema_parse_error", - format!("graphs.{graph_id}.schema"), - err.to_string(), - )); - None - } - }); - - let (graph_queries, query_contents) = - resolve_query_decls(&config_dir, graph_id, &graph.queries, &mut diagnostics); - for (query_name, query) in &graph_queries { - validate_id( - "query name", - &format!("graphs.{graph_id}.queries.{query_name}"), - query_name, - &mut diagnostics, - ); - let query_address = query_address(graph_id, query_name); - dependencies.insert(Dependency { - from: query_address.clone(), - to: graph_address.clone(), - }); - dependencies.insert(Dependency { - from: query_address.clone(), - to: schema_address.clone(), - }); - - let query_path = resolve_config_path(&config_dir, &query.file); - let source = match query_contents.get(&query.file) { - Some(cached) => Ok(cached.clone()), - None => fs::read_to_string(&query_path), - }; - match source { - Ok(source) => { - let digest = sha256_hex(source.as_bytes()); - graph_query_digests - .entry(graph_id.clone()) - .or_default() - .insert(query_name.clone(), digest.clone()); - resources.insert( - query_address.clone(), - ResourceSummary { - address: query_address, - kind: "query".to_string(), - digest, - path: Some(display_path(&query_path)), - }, - ); - validate_query_source( - graph_id, - query_name, - &source, - catalog.as_ref(), - &mut diagnostics, - ); - } - Err(err) => diagnostics.push(Diagnostic::error( - "query_file_missing", - format!("graphs.{graph_id}.queries.{query_name}.file"), - format!( - "could not read query file '{}': {err}", - query_path.display() - ), - )), - } - } - } - - for graph_id in raw.graphs.keys() { - let digest = graph_digest( - graph_id, - graph_schema_digests.get(graph_id), - graph_query_digests.get(graph_id), - ); - resources.insert( - graph_address(graph_id), - ResourceSummary { - address: graph_address(graph_id), - kind: "graph".to_string(), - digest, - path: None, - }, - ); - } - - let mut policy_bindings: BTreeMap> = BTreeMap::new(); - for (policy_name, policy) in &raw.policies { - validate_id( - "policy name", - &format!("policies.{policy_name}"), - policy_name, - &mut diagnostics, - ); - if policy.applies_to.is_empty() { - diagnostics.push(Diagnostic::error( - "policy_missing_applies_to", - format!("policies.{policy_name}.applies_to"), - "policy.applies_to must name `cluster` or at least one graph", - )); - } - - let policy_address = policy_address(policy_name); - let mut normalized_bindings: Vec = Vec::new(); - for (idx, target) in policy.applies_to.iter().enumerate() { - match normalize_policy_target(target) { - PolicyTarget::Cluster => { - normalized_bindings.push("cluster".to_string()); - } - PolicyTarget::Graph(graph_id) => { - normalized_bindings.push(graph_address(&graph_id)); - if raw.graphs.contains_key(&graph_id) { - dependencies.insert(Dependency { - from: policy_address.clone(), - to: graph_address(&graph_id), - }); - } else { - diagnostics.push(Diagnostic::error( - "dangling_graph_reference", - format!("policies.{policy_name}.applies_to[{idx}]"), - format!( - "policy references graph `{graph_id}`, but no graph with that id is declared" - ), - )); - } - } - PolicyTarget::WrongKind(kind) => diagnostics.push(Diagnostic::error( - "wrong_kind_reference", - format!("policies.{policy_name}.applies_to[{idx}]"), - format!("policy applies_to expects graph refs or `cluster`, got `{kind}`"), - )), - } - } - - normalized_bindings.sort(); - normalized_bindings.dedup(); - policy_bindings.insert(policy_address.clone(), normalized_bindings); - - let policy_path = resolve_config_path(&config_dir, &policy.file); - match fs::read(&policy_path) { - Ok(bytes) => { - resources.insert( - policy_address.clone(), - ResourceSummary { - address: policy_address, - kind: "policy".to_string(), - digest: sha256_hex(&bytes), - path: Some(display_path(&policy_path)), - }, - ); - } - Err(err) => diagnostics.push(Diagnostic::error( - "policy_file_missing", - format!("policies.{policy_name}.file"), - format!( - "could not read policy file '{}': {err}", - policy_path.display() - ), - )), - } - } - - let mut resource_digests = BTreeMap::new(); - let mut resource_list = Vec::new(); - for (address, resource) in resources { - resource_digests.insert(address, resource.digest.clone()); - resource_list.push(resource); - } - let dependencies: Vec<_> = dependencies.into_iter().collect(); - let graphs = raw - .graphs - .keys() - .map(|graph_id| DesiredGraph { - id: graph_id.clone(), - schema_digest: graph_schema_digests - .get(graph_id) - .cloned() - .unwrap_or_default(), - }) - .collect(); - let config_digest = desired_config_digest(&raw, &resource_digests); - - LoadOutcome { - desired: Some(DesiredCluster { - config_dir: config_dir.clone(), - config_digest, - storage_root: settings.storage_root.clone(), - state_lock: settings.state_lock, - graphs, - resource_digests, - resources: resource_list, - dependencies, - policy_bindings, - }), - diagnostics, - config_dir, - config_file, - } -} - -pub(crate) fn validate_query_source( - graph_id: &str, - query_name: &str, - source: &str, - catalog: Option<&omnigraph_compiler::catalog::Catalog>, - diagnostics: &mut Vec, -) { - let path = format!("graphs.{graph_id}.queries.{query_name}"); - match parse_query(source) { - Ok(query_file) => { - let Some(query_decl) = query_file.queries.iter().find(|q| q.name == query_name) else { - diagnostics.push(Diagnostic::error( - "query_key_mismatch", - path, - format!("no `query {query_name}` declaration found in the referenced .gq file"), - )); - return; - }; - if let Some(catalog) = catalog { - if let Err(err) = typecheck_query_decl(catalog, query_decl) { - diagnostics.push(Diagnostic::error( - "query_typecheck_error", - format!("graphs.{graph_id}.queries.{query_name}"), - err.to_string(), - )); - } - } else { - diagnostics.push(Diagnostic::warning( - "query_typecheck_skipped", - format!("graphs.{graph_id}.queries.{query_name}"), - "query parsed, but type-check was skipped because the graph schema is invalid", - )); - } - } - Err(err) => diagnostics.push(Diagnostic::error( - "query_parse_error", - path, - err.to_string(), - )), - } -} - -pub(crate) fn future_field_diagnostics(text: &str) -> Vec { - let Ok(value) = serde_yaml::from_str::(text) else { - return Vec::new(); - }; - let Some(mapping) = value.as_mapping() else { - return Vec::new(); - }; - let future_fields = [ - "apply", - "env_file", - "providers", - "pipelines", - "embeddings", - "ui", - "aliases", - "bindings", - ]; - mapping - .keys() - .filter_map(|key| key.as_str()) - .filter(|key| future_fields.contains(key)) - .map(|key| { - Diagnostic::error( - "future_phase_field", - key, - format!("`{key}` is reserved for a later cluster-control phase"), - ) - }) - .collect() -} - -pub(crate) fn validate_id(kind: &str, path: &str, value: &str, diagnostics: &mut Vec) { - let mut chars = value.chars(); - let valid = chars - .next() - .is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_') - && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-'); - if !valid { - diagnostics.push(Diagnostic::error( - "invalid_resource_id", - path, - format!("{kind} `{value}` must start with a letter or `_` and contain only ASCII letters, digits, `_`, or `-`"), - )); - } -} - -enum PolicyTarget { - Cluster, - Graph(String), - WrongKind(String), -} - -pub(crate) fn normalize_policy_target(value: &str) -> PolicyTarget { - if value == "cluster" { - PolicyTarget::Cluster - } else if let Some(graph_id) = value.strip_prefix("graph.") { - PolicyTarget::Graph(graph_id.to_string()) - } else if value.contains('.') { - PolicyTarget::WrongKind(value.to_string()) - } else { - PolicyTarget::Graph(value.to_string()) - } -} - -pub(crate) fn graph_address(graph_id: &str) -> String { - format!("graph.{graph_id}") -} - -pub(crate) fn schema_address(graph_id: &str) -> String { - format!("schema.{graph_id}") -} - -pub(crate) fn query_address(graph_id: &str, query_name: &str) -> String { - format!("query.{graph_id}.{query_name}") -} - -pub(crate) fn policy_address(policy_name: &str) -> String { - format!("policy.{policy_name}") -} - -pub(crate) fn resolve_config_path(config_dir: &Path, path: &Path) -> PathBuf { - if path.is_absolute() { - path.to_path_buf() - } else { - config_dir.join(path) - } -} diff --git a/crates/omnigraph-cluster/src/diff.rs b/crates/omnigraph-cluster/src/diff.rs deleted file mode 100644 index 593b2fa..0000000 --- a/crates/omnigraph-cluster/src/diff.rs +++ /dev/null @@ -1,420 +0,0 @@ -//! Plan/apply classification: resource diffing, dispositions, approval -//! gating, demotion (moved verbatim from lib.rs in the modularization). - -use super::*; - -pub(crate) fn diff_resources( - prior: &BTreeMap, - desired: &BTreeMap, -) -> Vec { - let mut changes = Vec::new(); - for (address, after) in desired { - match prior.get(address) { - None => changes.push(PlanChange { - resource: address.clone(), - operation: PlanOperation::Create, - before_digest: None, - after_digest: Some(after.clone()), - disposition: None, - reason: None, - binding_change: false, - migration: None, - }), - Some(before) if before != after => changes.push(PlanChange { - resource: address.clone(), - operation: PlanOperation::Update, - before_digest: Some(before.clone()), - after_digest: Some(after.clone()), - disposition: None, - reason: None, - binding_change: false, - migration: None, - }), - Some(_) => {} - } - } - for (address, before) in prior { - if !desired.contains_key(address) { - changes.push(PlanChange { - resource: address.clone(), - operation: PlanOperation::Delete, - before_digest: Some(before.clone()), - after_digest: None, - disposition: None, - reason: None, - binding_change: false, - migration: None, - }); - } - } - changes.sort_by(|a, b| a.resource.cmp(&b.resource)); - changes -} - -/// Binding-only policy changes: the file digest is unchanged (so -/// `diff_resources` saw nothing) but the applied `applies_to` differs from -/// the desired bindings β€” including the pre-5A case where the state entry -/// has no bindings recorded yet. These are first-class plan changes: without -/// this pass a binding edit would silently rot or silently converge. -pub(crate) fn append_policy_binding_changes( - changes: &mut Vec, - prior_state: Option<&ClusterState>, - desired: &DesiredCluster, -) { - let Some(state) = prior_state else { - return; // no state: everything is already a Create carrying bindings - }; - for (address, desired_bindings) in &desired.policy_bindings { - if changes.iter().any(|change| &change.resource == address) { - continue; // content change already covers it - } - let Some(entry) = state.applied_revision.resources.get(address) else { - continue; // not applied yet: the Create covers it - }; - if entry.applies_to.as_ref() == Some(desired_bindings) { - continue; - } - changes.push(PlanChange { - resource: address.clone(), - operation: PlanOperation::Update, - before_digest: Some(entry.digest.clone()), - after_digest: Some(entry.digest.clone()), - disposition: None, - reason: None, - binding_change: true, - migration: None, - }); - } - changes.sort_by(|a, b| a.resource.cmp(&b.resource)); -} - -pub(crate) fn compute_blast_radius( - changes: &[PlanChange], - dependencies: &[Dependency], -) -> Vec { - changes - .iter() - .filter_map(|change| { - let affected: Vec<_> = dependencies - .iter() - .filter_map(|dep| (dep.to == change.resource).then_some(dep.from.clone())) - .collect(); - (!affected.is_empty()).then(|| BlastRadius { - resource: change.resource.clone(), - affected, - }) - }) - .collect() -} - -pub(crate) fn compute_approvals( - changes: &[PlanChange], - approved: &BTreeSet, -) -> Vec { - // One gate per subtree: the graph. delete carries its schema and - // queries, so a schema delete whose graph is also deleted is not listed. - let graph_deletes: BTreeSet = changes - .iter() - .filter(|change| change.operation == PlanOperation::Delete) - .filter_map(|change| change.resource.strip_prefix("graph.").map(str::to_string)) - .collect(); - changes - .iter() - .filter_map(|change| { - if change.operation != PlanOperation::Delete { - return None; - } - let gated = match resource_kind(&change.resource) { - ResourceKind::Graph(_) => true, - ResourceKind::Schema(graph) => !graph_deletes.contains(&graph), - _ => false, - }; - gated.then(|| ApprovalRequirement { - resource: change.resource.clone(), - reason: "delete may remove deployed graph or schema definition".to_string(), - satisfied: approved.contains(&change.resource), - }) - }) - .collect() -} - -/// Resources with a valid (digest-matching, unconsumed) pending approval. -/// Near-misses β€” an artifact for the same resource whose bound digests no -/// longer match β€” warn as `approval_stale` and never authorize anything. -pub(crate) fn approved_resources( - artifacts: &[(String, ApprovalArtifact)], - changes: &[PlanChange], - config_digest: &str, - diagnostics: &mut Vec, -) -> BTreeSet { - let mut approved = BTreeSet::new(); - for change in changes { - let candidates: Vec<&ApprovalArtifact> = artifacts - .iter() - .map(|(_, artifact)| artifact) - .filter(|artifact| artifact.consumed_at.is_none() && artifact.resource == change.resource) - .collect(); - if candidates.is_empty() { - continue; - } - let matched = candidates.iter().any(|artifact| { - artifact.bound_config_digest == config_digest - && artifact.bound_before_digest == change.before_digest - && artifact.bound_after_digest == change.after_digest - }); - if matched { - approved.insert(change.resource.clone()); - } else { - diagnostics.push(Diagnostic::warning( - "approval_stale", - change.resource.clone(), - "an approval artifact exists but its bound digests no longer match the plan; re-run `cluster approve`", - )); - } - } - approved -} - -#[derive(Debug, PartialEq, Eq)] -pub(crate) enum ResourceKind { - Graph(String), - Schema(String), - Query { graph: String, name: String }, - Policy(String), - Unknown, -} - -pub(crate) fn resource_kind(address: &str) -> ResourceKind { - if let Some(graph) = address.strip_prefix("graph.") { - ResourceKind::Graph(graph.to_string()) - } else if let Some(graph) = address.strip_prefix("schema.") { - ResourceKind::Schema(graph.to_string()) - } else if let Some(rest) = address.strip_prefix("query.") { - match rest.split_once('.') { - Some((graph, name)) => ResourceKind::Query { - graph: graph.to_string(), - name: name.to_string(), - }, - None => ResourceKind::Unknown, - } - } else if let Some(name) = address.strip_prefix("policy.") { - ResourceKind::Policy(name.to_string()) - } else { - ResourceKind::Unknown - } -} - -/// Classify every planned change with the disposition config-only apply gives -/// it. Stage 3A executes only query/policy catalog writes; graph/schema -/// movement is a later phase, and `graph.` composite updates whose schema -/// component is unchanged converge automatically once query digests land. -pub(crate) fn classify_changes( - changes: &mut [PlanChange], - dependencies: &[Dependency], - pending_recovery: &BTreeSet, - approved: &BTreeSet, -) { - let mut schema_creates = BTreeSet::new(); - let mut schema_pending = BTreeSet::new(); - let mut graph_creates = BTreeSet::new(); - let mut graph_deletes = BTreeSet::new(); - for change in changes.iter() { - match resource_kind(&change.resource) { - ResourceKind::Schema(graph) => match change.operation { - PlanOperation::Create => { - schema_creates.insert(graph); - } - // Schema updates execute in-run before catalog writes (4B) - // and no longer block dependents; deletes (4C) still do. - PlanOperation::Update => {} - PlanOperation::Delete => { - schema_pending.insert(graph); - } - }, - ResourceKind::Graph(graph) => match change.operation { - PlanOperation::Create => { - graph_creates.insert(graph); - } - PlanOperation::Delete => { - graph_deletes.insert(graph); - } - PlanOperation::Update => {} - }, - _ => {} - } - } - // A schema Create is satisfied by its paired graph create (the init - // carries the schema); a standalone schema Create stays pending. - for graph in &schema_creates { - if !graph_creates.contains(graph) { - schema_pending.insert(graph.clone()); - } - } - // Subtree deletes ride the approved graph delete. - let rides_approved_delete = |graph: &str| { - graph_deletes.contains(graph) - && approved.contains(&graph_address(graph)) - && !pending_recovery.contains(graph) - }; - - for change in changes.iter_mut() { - let (disposition, reason) = match resource_kind(&change.resource) { - ResourceKind::Schema(graph) => match change.operation { - PlanOperation::Create - if graph_creates.contains(&graph) - && !pending_recovery.contains(&graph) => - { - // Applied with the graph create β€” the init carries it. - (ApplyDisposition::Applied, None) - } - PlanOperation::Update if !pending_recovery.contains(&graph) => { - // Stage 4B: schema updates execute via the engine's - // schema apply (soft drops only; allow_data_loss is 4C). - (ApplyDisposition::Applied, None) - } - PlanOperation::Create | PlanOperation::Update => { - (ApplyDisposition::Blocked, Some("cluster_recovery_pending")) - } - PlanOperation::Delete if graph_deletes.contains(&graph) => { - if rides_approved_delete(&graph) { - (ApplyDisposition::Applied, None) - } else if pending_recovery.contains(&graph) { - (ApplyDisposition::Blocked, Some("cluster_recovery_pending")) - } else { - (ApplyDisposition::Blocked, Some("approval_required")) - } - } - _ => (ApplyDisposition::Deferred, Some("apply_unsupported_kind")), - }, - ResourceKind::Graph(graph) => match change.operation { - PlanOperation::Create => { - if pending_recovery.contains(&graph) { - (ApplyDisposition::Blocked, Some("cluster_recovery_pending")) - } else { - (ApplyDisposition::Applied, None) - } - } - PlanOperation::Update if !schema_pending.contains(&graph) => { - (ApplyDisposition::Derived, None) - } - // Stage 4C: an approved graph delete executes (the - // irreversible tier β€” gated by a digest-bound artifact). - PlanOperation::Delete => { - if pending_recovery.contains(&graph) { - (ApplyDisposition::Blocked, Some("cluster_recovery_pending")) - } else if rides_approved_delete(&graph) { - (ApplyDisposition::Applied, None) - } else { - (ApplyDisposition::Blocked, Some("approval_required")) - } - } - _ => (ApplyDisposition::Deferred, Some("apply_unsupported_kind")), - }, - ResourceKind::Query { graph, .. } => match change.operation { - PlanOperation::Delete => { - if rides_approved_delete(&graph) { - // Tombstoned with the approved graph delete. - (ApplyDisposition::Applied, None) - } else if graph_deletes.contains(&graph) { - (ApplyDisposition::Blocked, Some("approval_required")) - } else { - (ApplyDisposition::Applied, None) - } - } - PlanOperation::Create | PlanOperation::Update => { - if pending_recovery.contains(&graph) { - (ApplyDisposition::Blocked, Some("cluster_recovery_pending")) - } else if schema_pending.contains(&graph) { - ( - ApplyDisposition::Blocked, - Some("dependency_not_applied"), - ) - } else { - // A graph create in the same plan no longer blocks: - // creates execute first in the same apply run. - (ApplyDisposition::Applied, None) - } - } - }, - ResourceKind::Policy(_) => match change.operation { - PlanOperation::Delete => (ApplyDisposition::Applied, None), - PlanOperation::Create | PlanOperation::Update => { - let blocked_pending = dependencies.iter().any(|dep| { - dep.from == change.resource - && dep - .to - .strip_prefix("graph.") - .is_some_and(|graph| pending_recovery.contains(graph)) - }); - if blocked_pending { - (ApplyDisposition::Blocked, Some("cluster_recovery_pending")) - } else { - (ApplyDisposition::Applied, None) - } - } - }, - ResourceKind::Unknown => { - (ApplyDisposition::Deferred, Some("apply_unsupported_kind")) - } - }; - change.disposition = Some(disposition); - change.reason = reason.map(str::to_string); - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum FailedGraphOrigin { - GraphCreate, - SchemaApply, - GraphDelete, -} - -/// After a graph-moving operation fails mid-run, every change that depended -/// on that graph flips from Applied to Blocked so the output and the -/// persisted statuses tell the truth about what this run actually executed. -/// The originating change carries the failure code; dependents carry -/// `dependency_not_applied`. -pub(crate) fn demote_dependents_of_failed_graphs( - changes: &mut [PlanChange], - failed: &BTreeMap, - dependencies: &[Dependency], -) { - for change in changes.iter_mut() { - if change.disposition != Some(ApplyDisposition::Applied) { - continue; - } - let demote_reason = match resource_kind(&change.resource) { - ResourceKind::Graph(graph) => match failed.get(&graph) { - Some(FailedGraphOrigin::GraphCreate) => Some("graph_create_failed"), - Some(FailedGraphOrigin::GraphDelete) => Some("graph_delete_failed"), - Some(FailedGraphOrigin::SchemaApply) => Some("dependency_not_applied"), - None => None, - }, - ResourceKind::Schema(graph) => match failed.get(&graph) { - Some(FailedGraphOrigin::SchemaApply) => Some("schema_apply_failed"), - Some(FailedGraphOrigin::GraphCreate) | Some(FailedGraphOrigin::GraphDelete) => { - Some("dependency_not_applied") - } - None => None, - }, - ResourceKind::Query { graph, .. } if failed.contains_key(&graph) => { - Some("dependency_not_applied") - } - ResourceKind::Policy(_) => { - let blocked = dependencies.iter().any(|dep| { - dep.from == change.resource - && dep - .to - .strip_prefix("graph.") - .is_some_and(|graph| failed.contains_key(graph)) - }); - blocked.then_some("dependency_not_applied") - } - _ => None, - }; - if let Some(reason) = demote_reason { - change.disposition = Some(ApplyDisposition::Blocked); - change.reason = Some(reason.to_string()); - } - } -} diff --git a/crates/omnigraph-cluster/src/failpoints.rs b/crates/omnigraph-cluster/src/failpoints.rs deleted file mode 100644 index f1799d7..0000000 --- a/crates/omnigraph-cluster/src/failpoints.rs +++ /dev/null @@ -1,56 +0,0 @@ -//! Fault-injection hooks for the cluster apply protocol, mirroring the -//! engine's `omnigraph::failpoints` pattern. With the `failpoints` feature -//! off, every call site compiles to `Ok(())`. - -use crate::Diagnostic; - -pub(crate) fn maybe_fail(_name: &str) -> Result<(), Diagnostic> { - #[cfg(feature = "failpoints")] - { - let name = _name; - fail::fail_point!(name, |_| { - return Err(Diagnostic::error( - "injected_failpoint", - name, - format!("injected failpoint triggered: {name}"), - )); - }); - } - Ok(()) -} - -#[cfg(feature = "failpoints")] -pub struct ScopedFailPoint { - name: String, -} - -#[cfg(feature = "failpoints")] -impl ScopedFailPoint { - pub fn new(name: &str, action: &str) -> Self { - fail::cfg(name, action).expect("configure failpoint"); - Self { - name: name.to_string(), - } - } - - /// Register a callback failpoint with the same Drop-based cleanup as - /// `new`. Without the guard, a panic while the point is active would - /// leak the callback into the process-global registry and fire it under - /// later tests in the same binary. - pub fn with_callback(name: &str, callback: F) -> Self - where - F: Fn() + Send + Sync + 'static, - { - fail::cfg_callback(name, callback).expect("configure callback failpoint"); - Self { - name: name.to_string(), - } - } -} - -#[cfg(feature = "failpoints")] -impl Drop for ScopedFailPoint { - fn drop(&mut self) { - fail::remove(&self.name); - } -} diff --git a/crates/omnigraph-cluster/src/lib.rs b/crates/omnigraph-cluster/src/lib.rs deleted file mode 100644 index 1422dad..0000000 --- a/crates/omnigraph-cluster/src/lib.rs +++ /dev/null @@ -1,1936 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet}; -use std::fs::{self, OpenOptions}; -use std::io::{ErrorKind, Write}; -use std::path::{Path, PathBuf}; -use std::process; - -use omnigraph::db::{Omnigraph, ReadTarget, SchemaApplyOptions}; -use omnigraph_compiler::SchemaMigrationPlan; -use omnigraph_compiler::build_catalog; -use omnigraph_compiler::query::parser::parse_query; -use omnigraph_compiler::query::typecheck::typecheck_query_decl; -use omnigraph_compiler::schema::parser::parse_schema; -use serde::{Deserialize, Serialize}; -use serde_json::json; -use sha2::{Digest, Sha256}; -use time::OffsetDateTime; -use time::format_description::well_known::Rfc3339; -use ulid::Ulid; - -pub mod failpoints; - -mod config; -mod types; -mod diff; -mod serve; -mod sweep; -mod store; -use store::{ClusterStore, StateLockGuard, StateSnapshot}; -pub use types::*; -use types::*; -pub use serve::{ServingGraph, ServingPolicy, ServingQuery, ServingSnapshot, read_serving_snapshot, read_serving_snapshot_from_storage}; -use config::{QueriesDecl, observe_declared_graphs, validate_cluster_header, future_field_diagnostics, initial_import_state, observe_live_graph, preview_schema_migration, state_resource_digests, graph_address, policy_address, query_address, schema_address, load_desired, normalize_policy_target, parse_cluster_config, resolve_config_path, resolve_query_decls, validate_id, validate_query_source}; -use diff::{FailedGraphOrigin, ResourceKind, append_policy_binding_changes, approved_resources, classify_changes, compute_approvals, compute_blast_radius, demote_dependents_of_failed_graphs, diff_resources, resource_kind}; -use sweep::{mark_approvals_consumed, record_approval_consumed, sweep_recovery_sidecars, tombstone_graph_subtree, warn_pending_recovery_sidecars}; - -pub const CLUSTER_CONFIG_FILE: &str = "cluster.yaml"; -pub const CLUSTER_GRAPHS_DIR: &str = "graphs"; -pub const CLUSTER_STATE_DIR: &str = "__cluster"; -pub const CLUSTER_STATE_FILE: &str = "__cluster/state.json"; -pub const CLUSTER_LOCK_FILE: &str = "__cluster/lock.json"; -pub const CLUSTER_RESOURCES_DIR: &str = "__cluster/resources"; -pub const CLUSTER_RECOVERIES_DIR: &str = "__cluster/recoveries"; -pub const CLUSTER_APPROVALS_DIR: &str = "__cluster/approvals"; - -/// The store for a load outcome: the declared `storage:` root when present, -/// the config directory itself otherwise. A bad root is a loud error. -fn store_for( - config_dir: &Path, - storage_root: Option<&str>, -) -> Result { - match storage_root { - Some(root) => ClusterStore::for_storage_root(root), - None => Ok(ClusterStore::for_config_dir(config_dir)), - } -} - -pub fn validate_config_dir(config_dir: impl AsRef) -> ValidateOutput { - let outcome = load_desired(config_dir.as_ref()); - let (resource_digests, resources, dependencies) = match outcome.desired { - Some(desired) => ( - desired.resource_digests, - desired.resources, - desired.dependencies, - ), - None => (BTreeMap::new(), Vec::new(), Vec::new()), - }; - let ok = !has_errors(&outcome.diagnostics); - - ValidateOutput { - ok, - config_dir: display_path(&outcome.config_dir), - config_file: display_path(&outcome.config_file), - resource_digests, - resources, - dependencies, - diagnostics: outcome.diagnostics, - } -} - -pub async fn plan_config_dir(config_dir: impl AsRef) -> PlanOutput { - let outcome = load_desired(config_dir.as_ref()); - let mut diagnostics = outcome.diagnostics; - let storage_root = outcome - .desired - .as_ref() - .and_then(|desired| desired.storage_root.clone()); - let backend = match store_for(&outcome.config_dir, storage_root.as_deref()) { - Ok(backend) => backend, - Err(diagnostic) => { - diagnostics.push(diagnostic); - ClusterStore::for_config_dir(&outcome.config_dir) - } - }; - let mut observations = backend.observations(); - - let Some(desired) = outcome.desired else { - return PlanOutput { - ok: false, - config_dir: display_path(&outcome.config_dir), - desired_revision: DesiredRevision { - config_digest: None, - }, - resource_digests: BTreeMap::new(), - dependencies: Vec::new(), - state_observations: observations, - changes: Vec::new(), - blast_radius: Vec::new(), - approvals_required: Vec::new(), - diagnostics, - }; - }; - - if has_errors(&diagnostics) { - return PlanOutput { - ok: false, - config_dir: display_path(&desired.config_dir), - desired_revision: DesiredRevision { - config_digest: Some(desired.config_digest), - }, - resource_digests: desired.resource_digests, - dependencies: desired.dependencies, - state_observations: observations, - changes: Vec::new(), - blast_radius: Vec::new(), - approvals_required: Vec::new(), - diagnostics, - }; - } - - let _lock_guard = if desired.state_lock { - match backend.acquire_lock("plan", &mut observations).await { - Ok(guard) => Some(guard), - Err(diagnostic) => { - diagnostics.push(diagnostic); - None - } - } - } else { - diagnostics.push(Diagnostic::warning( - "state_lock_disabled", - "state.lock", - "state.lock is false; plan read state without acquiring the cluster state lock", - )); - None - }; - - // Plan is read-only: pending sidecars are reported, never acted on - // (RFC-004 open question 3 keeps read-only commands warn-only). - warn_pending_recovery_sidecars(&desired.config_dir, &mut diagnostics); - - let mut prior_resources = BTreeMap::new(); - let mut prior_state: Option = None; - if !has_errors(&diagnostics) { - match backend.read_state(&mut observations).await { - Ok(snapshot) => { - if let Some(state) = snapshot.state { - prior_resources = state_resource_digests(&state); - prior_state = Some(state); - } - } - Err(diagnostic) => diagnostics.push(diagnostic), - } - } - - let mut changes = if has_errors(&diagnostics) { - Vec::new() - } else { - diff_resources(&prior_resources, &desired.resource_digests) - }; - if !has_errors(&diagnostics) { - append_policy_binding_changes(&mut changes, prior_state.as_ref(), &desired); - } - // Plan previews dispositions without sweeping; a pending recovery is - // surfaced as the cluster_recovery_pending warning above instead. - let artifacts = backend.list_approval_artifacts(&mut diagnostics).await; - let approved = approved_resources( - &artifacts, - &changes, - &desired.config_digest, - &mut diagnostics, - ); - classify_changes(&mut changes, &desired.dependencies, &BTreeSet::new(), &approved); - - // Embed real migration steps for schema updates so plan is a data-aware - // preview; failures degrade to the digest diff with a warning. - for change in &mut changes { - if change.operation != PlanOperation::Update { - continue; - } - let ResourceKind::Schema(graph_id) = resource_kind(&change.resource) else { - continue; - }; - let graph_uri = backend.graph_root(&graph_id); - let source_path = desired - .resources - .iter() - .find(|resource| resource.address == change.resource) - .and_then(|resource| resource.path.clone()); - let preview = match source_path { - Some(path) => preview_schema_migration(&graph_uri, &path).await, - None => Err("no schema source recorded".to_string()), - }; - match preview { - Ok(migration) => change.migration = Some(migration), - Err(err) => diagnostics.push(Diagnostic::warning( - "schema_preview_unavailable", - change.resource.clone(), - format!("could not preview the schema migration: {err}"), - )), - } - } - let blast_radius = compute_blast_radius(&changes, &desired.dependencies); - let approvals_required = compute_approvals(&changes, &approved); - let ok = !has_errors(&diagnostics); - - PlanOutput { - ok, - config_dir: display_path(&desired.config_dir), - desired_revision: DesiredRevision { - config_digest: Some(desired.config_digest), - }, - resource_digests: desired.resource_digests, - dependencies: desired.dependencies, - state_observations: observations, - changes, - blast_radius, - approvals_required, - diagnostics, - } -} - -/// Config-only `cluster apply` (Stage 3A): execute the query/policy subset of -/// the plan against the local cluster catalog. The plan is recomputed under -/// the state lock, so freshness is structural; the state CAS inside -/// `write_state` is the second fence. Graph/schema changes are never executed -/// here β€” they are deferred to the graph-lifecycle phase and reported loudly. -/// -/// Payloads are content-addressed and written BEFORE the state CAS because -/// state is the publish point: a failure after payload writes leaves inert -/// digest-named blobs and no success acknowledgement; re-running apply is the -/// repair. -/// Options for `cluster apply`. `actor` attributes graph-moving operations -/// (recorded in sidecars and audit entries, threaded to the engine's -/// `apply_schema_as` so Cedar enforcement fires wherever a policy checker is -/// installed). -#[derive(Debug, Clone, Default)] -pub struct ApplyOptions { - pub actor: Option, -} - -pub async fn apply_config_dir(config_dir: impl AsRef) -> ApplyOutput { - apply_config_dir_with_options(config_dir, ApplyOptions::default()).await -} - -pub async fn apply_config_dir_with_options( - config_dir: impl AsRef, - options: ApplyOptions, -) -> ApplyOutput { - let outcome = load_desired(config_dir.as_ref()); - let mut diagnostics = outcome.diagnostics; - let storage_root = outcome - .desired - .as_ref() - .and_then(|desired| desired.storage_root.clone()); - let backend = match store_for(&outcome.config_dir, storage_root.as_deref()) { - Ok(backend) => backend, - Err(diagnostic) => { - diagnostics.push(diagnostic); - ClusterStore::for_config_dir(&outcome.config_dir) - } - }; - let mut observations = backend.observations(); - - let actor_for_output = options.actor.clone(); - let early_return = |config_dir: String, - config_digest: Option, - observations: StateObservations, - changes: Vec, - resource_statuses: BTreeMap, - diagnostics: Vec| { - ApplyOutput { - ok: !has_errors(&diagnostics), - config_dir, - actor: actor_for_output.clone(), - desired_revision: DesiredRevision { - config_digest, - }, - state_observations: observations, - changes, - applied_count: 0, - deferred_count: 0, - converged: false, - state_written: false, - resource_statuses, - diagnostics, - } - }; - - let Some(desired) = outcome.desired else { - return early_return( - display_path(&outcome.config_dir), - None, - observations, - Vec::new(), - BTreeMap::new(), - diagnostics, - ); - }; - - if has_errors(&diagnostics) { - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - Vec::new(), - BTreeMap::new(), - diagnostics, - ); - } - - // Named guard: the lock must be held until the state outcome is recorded. - let _lock_guard = if desired.state_lock { - match backend.acquire_lock("apply", &mut observations).await { - Ok(guard) => Some(guard), - Err(diagnostic) => { - diagnostics.push(diagnostic); - None - } - } - } else { - diagnostics.push(Diagnostic::warning( - "state_lock_disabled", - "state.lock", - "state.lock is false; apply wrote state without acquiring the cluster state lock", - )); - None - }; - - if has_errors(&diagnostics) { - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - Vec::new(), - BTreeMap::new(), - diagnostics, - ); - } - - let snapshot = match backend.read_state(&mut observations).await { - Ok(snapshot) => snapshot, - Err(diagnostic) => { - diagnostics.push(diagnostic); - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - Vec::new(), - BTreeMap::new(), - diagnostics, - ); - } - }; - let expected_cas = snapshot.state_cas; - let Some(mut state) = snapshot.state else { - diagnostics.push(Diagnostic::error( - "state_missing", - CLUSTER_STATE_FILE, - "apply requires an existing state.json; run `cluster import` to bootstrap state", - )); - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - Vec::new(), - BTreeMap::new(), - diagnostics, - ); - }; - - // Snapshot the as-read state BEFORE the sweep so sweep mutations count as - // changes for the final dirty check and get persisted by the state CAS. - let before_value = - serde_json::to_value(&state).expect("cluster state must serialize deterministically"); - let sweep = sweep_recovery_sidecars(&backend, &mut state, &mut diagnostics).await; - - let prior_resources = state_resource_digests(&state); - let mut changes = diff_resources(&prior_resources, &desired.resource_digests); - append_policy_binding_changes(&mut changes, Some(&state), &desired); - let approval_artifacts = backend.list_approval_artifacts(&mut diagnostics).await; - let approved = approved_resources( - &approval_artifacts, - &changes, - &desired.config_digest, - &mut diagnostics, - ); - classify_changes( - &mut changes, - &desired.dependencies, - &sweep.pending_graphs, - &approved, - ); - - // Defensive invariant: nothing the approval gate covers may be executable - // WITHOUT a matching approval. Gated changes with a valid artifact are the - // sanctioned exception (stage 4C). - let approvals = compute_approvals(&changes, &approved); - let approval_violation = changes.iter().any(|change| { - change.disposition == Some(ApplyDisposition::Applied) - && approvals - .iter() - .any(|approval| approval.resource == change.resource && !approval.satisfied) - }); - if approval_violation { - diagnostics.push(Diagnostic::error( - "apply_approval_invariant_violation", - "changes", - "an executable change requires approval; refusing to apply", - )); - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - changes, - state.resource_statuses, - diagnostics, - ); - } - - // Graph creates execute first (RFC-004 Β§D5), sequentially, sidecar-fenced: - // sidecar written before the init, rewritten with the post-init manifest - // version, deleted only after the final state CAS lands. A failure stops - // further graph-moving work and demotes that graph's dependents. - let source_paths: BTreeMap<&str, &str> = desired - .resources - .iter() - .filter_map(|resource| { - resource - .path - .as_deref() - .map(|path| (resource.address.as_str(), path)) - }) - .collect(); - let graph_creates_to_run: Vec = changes - .iter() - .filter(|change| { - change.disposition == Some(ApplyDisposition::Applied) - && change.operation == PlanOperation::Create - && matches!(resource_kind(&change.resource), ResourceKind::Graph(_)) - }) - .filter_map(|change| change.resource.strip_prefix("graph.").map(str::to_string)) - .collect(); - let mut completed_op_sidecars: Vec = Vec::new(); - let mut failed_graphs: BTreeMap = BTreeMap::new(); - let mut graph_moving_aborted = false; - for graph_id in &graph_creates_to_run { - if graph_moving_aborted { - // A prior create failed: stop graph-moving work (loud partials). - diagnostics.push(Diagnostic::warning( - "graph_create_skipped", - graph_address(graph_id), - "skipped after an earlier graph create failed in this run", - )); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphCreate); - continue; - } - let Some(desired_graph) = desired.graphs.iter().find(|graph| &graph.id == graph_id) - else { - continue; - }; - let graph_uri = backend.graph_root(graph_id); - let mut sidecar = RecoverySidecar { - schema_version: 1, - operation_id: Ulid::new().to_string(), - started_at: now_rfc3339(), - actor: options.actor.clone(), - kind: RecoverySidecarKind::GraphCreate, - graph_id: graph_id.clone(), - graph_uri: graph_uri.clone(), - observed_manifest_version: None, - expected_manifest_version: None, - desired_schema_digest: desired_graph.schema_digest.clone(), - state_cas_base: expected_cas.clone(), - approval_id: None, - }; - let sidecar_path = match backend.write_recovery_sidecar(&sidecar).await { - Ok(path) => path, - Err(diagnostic) => { - diagnostics.push(diagnostic); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphCreate); - graph_moving_aborted = true; - continue; - } - }; - if let Err(diagnostic) = failpoints::maybe_fail("cluster_apply.before_graph_create") { - // Simulated crash before the init: the sidecar stays for the - // sweep (row 1: root absent -> intent removed next run). - diagnostics.push(diagnostic); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphCreate); - graph_moving_aborted = true; - continue; - } - // Re-read + re-verify the schema source under the lock β€” the same - // TOCTOU posture as write_resource_payload. - let schema_source = source_paths - .get(schema_address(graph_id).as_str()) - .ok_or_else(|| { - Diagnostic::error( - "graph_create_failed", - graph_address(graph_id), - "no schema source recorded for graph", - ) - }) - .and_then(|path| { - fs::read_to_string(Path::new(path)).map_err(|err| { - Diagnostic::error( - "graph_create_failed", - graph_address(graph_id), - format!("could not read schema source '{path}': {err}"), - ) - }) - }) - .and_then(|source| { - if sha256_hex(source.as_bytes()) == desired_graph.schema_digest { - Ok(source) - } else { - Err(Diagnostic::error( - "resource_content_changed", - schema_address(graph_id), - "schema source changed while apply was running; re-run `cluster apply`", - )) - } - }); - let schema_source = match schema_source { - Ok(source) => source, - Err(diagnostic) => { - diagnostics.push(diagnostic); - backend.delete_object(&sidecar_path).await; // nothing moved - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphCreate); - graph_moving_aborted = true; - continue; - } - }; - match Omnigraph::init(&graph_uri, &schema_source).await { - Ok(_) => {} - Err(err) => { - diagnostics.push(Diagnostic::error( - "graph_create_failed", - graph_address(graph_id), - format!("could not initialize graph at '{graph_uri}': {err}"), - )); - // The sidecar stays: the sweep classifies whether the failed - // init left a partial root (row 5) or nothing (row 1). - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphCreate); - graph_moving_aborted = true; - continue; - } - } - // Record the post-init pin in the sidecar (best effort β€” a failure - // here leaves expected = null and the sweep classifies by digest). - if let Ok(db) = Omnigraph::open_read_only(&graph_uri).await { - if let Ok(snapshot) = db.snapshot_of(ReadTarget::branch("main")).await { - sidecar.expected_manifest_version = Some(snapshot.version()); - if let Err(diagnostic) = backend.write_recovery_sidecar(&sidecar).await { - diagnostics.push(diagnostic); - } - } - } - // Crash point: the graph exists, the cluster state does not record it - // yet. A failure here must acknowledge nothing; the next run's sweep - // rolls the ledger forward (row 4). - if let Err(diagnostic) = failpoints::maybe_fail("cluster_apply.after_graph_create") { - diagnostics.push(diagnostic); - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - changes, - state.resource_statuses, - diagnostics, - ); - } - completed_op_sidecars.push(sidecar_path); - } - - // Schema applies execute next (RFC-004 Β§D5): the first cluster operation - // that moves an EXISTING graph manifest, sidecar-fenced the same way. - let schema_updates_to_run: Vec = changes - .iter() - .filter(|change| { - change.disposition == Some(ApplyDisposition::Applied) - && change.operation == PlanOperation::Update - && matches!(resource_kind(&change.resource), ResourceKind::Schema(_)) - }) - .filter_map(|change| change.resource.strip_prefix("schema.").map(str::to_string)) - .collect(); - for graph_id in &schema_updates_to_run { - if graph_moving_aborted { - diagnostics.push(Diagnostic::warning( - "schema_apply_skipped", - schema_address(graph_id), - "skipped after an earlier graph-moving operation failed in this run", - )); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::SchemaApply); - continue; - } - let Some(desired_graph) = desired.graphs.iter().find(|graph| &graph.id == graph_id) - else { - continue; - }; - let graph_uri = backend.graph_root(graph_id); - // Read-write open: the engine's own recovery sweep runs here, which - // is exactly what we want before moving its manifest. - let db = match Omnigraph::open(&graph_uri).await { - Ok(db) => db, - Err(err) => { - diagnostics.push(Diagnostic::error( - "schema_apply_failed", - schema_address(graph_id), - format!("could not open graph at '{graph_uri}': {err}"), - )); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::SchemaApply); - graph_moving_aborted = true; - continue; - } - }; - let observed_manifest_version = match db.snapshot_of(ReadTarget::branch("main")).await { - Ok(snapshot) => Some(snapshot.version()), - Err(_) => None, - }; - let mut sidecar = RecoverySidecar { - schema_version: 1, - operation_id: Ulid::new().to_string(), - started_at: now_rfc3339(), - actor: options.actor.clone(), - kind: RecoverySidecarKind::SchemaApply, - graph_id: graph_id.clone(), - graph_uri: graph_uri.clone(), - observed_manifest_version, - expected_manifest_version: None, - desired_schema_digest: desired_graph.schema_digest.clone(), - state_cas_base: expected_cas.clone(), - approval_id: None, - }; - let sidecar_path = match backend.write_recovery_sidecar(&sidecar).await { - Ok(path) => path, - Err(diagnostic) => { - diagnostics.push(diagnostic); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::SchemaApply); - graph_moving_aborted = true; - continue; - } - }; - if let Err(diagnostic) = failpoints::maybe_fail("cluster_apply.before_schema_apply") { - // Simulated crash before the engine call: the sidecar stays; the - // sweep retires it next run (ledger still consistent with live). - diagnostics.push(diagnostic); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::SchemaApply); - graph_moving_aborted = true; - continue; - } - // Re-read + digest-verify the desired schema source under the lock. - let schema_source = source_paths - .get(schema_address(graph_id).as_str()) - .ok_or_else(|| { - Diagnostic::error( - "schema_apply_failed", - schema_address(graph_id), - "no schema source recorded for graph", - ) - }) - .and_then(|path| { - fs::read_to_string(Path::new(path)).map_err(|err| { - Diagnostic::error( - "schema_apply_failed", - schema_address(graph_id), - format!("could not read schema source '{path}': {err}"), - ) - }) - }) - .and_then(|source| { - if sha256_hex(source.as_bytes()) == desired_graph.schema_digest { - Ok(source) - } else { - Err(Diagnostic::error( - "resource_content_changed", - schema_address(graph_id), - "schema source changed while apply was running; re-run `cluster apply`", - )) - } - }); - let schema_source = match schema_source { - Ok(source) => source, - Err(diagnostic) => { - diagnostics.push(diagnostic); - backend.delete_object(&sidecar_path).await; // nothing moved - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::SchemaApply); - graph_moving_aborted = true; - continue; - } - }; - // Soft drops only: allow_data_loss stays false until the approval - // artifacts of stage 4C exist (RFC-004 Β§D4). - match db - .apply_schema_as( - &schema_source, - SchemaApplyOptions::default(), - options.actor.as_deref(), - ) - .await - { - Ok(result) => { - sidecar.expected_manifest_version = Some(result.manifest_version); - if let Err(diagnostic) = backend.write_recovery_sidecar(&sidecar).await { - diagnostics.push(diagnostic); - } - } - Err(err) => { - diagnostics.push(Diagnostic::error( - "schema_apply_failed", - schema_address(graph_id), - format!("schema apply failed on '{graph_uri}': {err}"), - )); - // Sidecar stays; the sweep retires it (live digest unchanged - // == ledger consistent) or flags real movement. - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::SchemaApply); - graph_moving_aborted = true; - continue; - } - } - // Crash point: the manifest moved, the ledger does not record it yet. - // A failure here acknowledges nothing; the sweep rolls forward. - if let Err(diagnostic) = failpoints::maybe_fail("cluster_apply.after_schema_apply") { - diagnostics.push(diagnostic); - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - changes, - state.resource_statuses, - diagnostics, - ); - } - completed_op_sidecars.push(sidecar_path); - } - - if !failed_graphs.is_empty() { - demote_dependents_of_failed_graphs(&mut changes, &failed_graphs, &desired.dependencies); - } - - for change in &changes { - match change.disposition { - Some(ApplyDisposition::Deferred) => diagnostics.push(Diagnostic::warning( - "apply_unsupported_change", - change.resource.clone(), - "graph/schema changes are not applied in this stage; they are deferred to the graph-lifecycle phase", - )), - Some(ApplyDisposition::Blocked) => diagnostics.push(Diagnostic::warning( - "apply_dependency_blocked", - change.resource.clone(), - format!( - "blocked by an unapplied or missing dependency ({})", - change.reason.as_deref().unwrap_or("dependency") - ), - )), - _ => {} - } - } - - // Payload phase: content-addressed writes before the state CAS. Any - // failure aborts before state moves; blobs already written are inert. - // Gate on payload-phase errors only β€” sweep errors (e.g. a kept row-5 - // sidecar) must not abort the run, or their statuses would never persist. - let errors_before_payloads = count_errors(&diagnostics); - for change in &changes { - if change.disposition != Some(ApplyDisposition::Applied) - || change.operation == PlanOperation::Delete - { - continue; - } - let kind = resource_kind(&change.resource); - let digest = change - .after_digest - .as_deref() - .expect("create/update always carries an after digest"); - if ClusterStore::payload_relative(&kind, digest).is_none() { - continue; - } - let Some(source) = source_paths.get(change.resource.as_str()) else { - diagnostics.push(Diagnostic::error( - "resource_payload_write_error", - change.resource.clone(), - "no source file recorded for resource", - )); - continue; - }; - if let Err(diagnostic) = - write_resource_payload(&backend, &kind, Path::new(source), digest, &change.resource) - .await - { - diagnostics.push(diagnostic); - } - } - if count_errors(&diagnostics) > errors_before_payloads { - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - changes, - state.resource_statuses, - diagnostics, - ); - } - - // Crash point: payloads are on disk, state has not moved. A failure here - // must leave state.json byte-identical and acknowledge nothing; re-running - // apply repairs via the skip-if-exists blob reuse. - if let Err(diagnostic) = failpoints::maybe_fail("cluster_apply.after_payload_phase") { - diagnostics.push(diagnostic); - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - changes, - state.resource_statuses, - diagnostics, - ); - } - - // Approved graph deletes execute LAST (RFC-004 Β§D5): catalog writes for - // surviving resources land first, then the irreversible work. - let graph_deletes_to_run: Vec = changes - .iter() - .filter(|change| { - change.disposition == Some(ApplyDisposition::Applied) - && change.operation == PlanOperation::Delete - && matches!(resource_kind(&change.resource), ResourceKind::Graph(_)) - }) - .filter_map(|change| change.resource.strip_prefix("graph.").map(str::to_string)) - .collect(); - let mut executed_deletes: Vec<(String, Option)> = Vec::new(); // (graph_id, approval_id) - let mut consumed_approval_ids: Vec = Vec::new(); - for graph_id in &graph_deletes_to_run { - if graph_moving_aborted { - diagnostics.push(Diagnostic::warning( - "graph_delete_skipped", - graph_address(graph_id), - "skipped after an earlier graph-moving operation failed in this run", - )); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphDelete); - continue; - } - let graph_addr = graph_address(graph_id); - // Re-locate the consumable approval (classification verified one exists). - let approval_id = approval_artifacts - .iter() - .map(|(_, artifact)| artifact) - .find(|artifact| { - artifact.consumed_at.is_none() - && artifact.resource == graph_addr - && artifact.bound_config_digest == desired.config_digest - }) - .map(|artifact| artifact.approval_id.clone()); - let graph_uri = backend.graph_root(graph_id); - let observed_manifest_version = match Omnigraph::open_read_only(&graph_uri).await { - Ok(db) => match db.snapshot_of(ReadTarget::branch("main")).await { - Ok(snapshot) => Some(snapshot.version()), - Err(_) => None, - }, - Err(_) => None, // partial/unopenable roots still get deleted - }; - let sidecar = RecoverySidecar { - schema_version: 1, - operation_id: Ulid::new().to_string(), - started_at: now_rfc3339(), - actor: options.actor.clone(), - kind: RecoverySidecarKind::GraphDelete, - graph_id: graph_id.clone(), - graph_uri: graph_uri.clone(), - observed_manifest_version, - expected_manifest_version: None, // no post-op manifest exists - desired_schema_digest: String::new(), - state_cas_base: expected_cas.clone(), - approval_id: approval_id.clone(), - }; - let sidecar_path = match backend.write_recovery_sidecar(&sidecar).await { - Ok(path) => path, - Err(diagnostic) => { - diagnostics.push(diagnostic); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphDelete); - graph_moving_aborted = true; - continue; - } - }; - if let Err(diagnostic) = failpoints::maybe_fail("cluster_apply.before_graph_delete") { - // Simulated crash before removal: row 8 retires the intent and - // the still-valid approval lets a later run retry. - diagnostics.push(diagnostic); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphDelete); - graph_moving_aborted = true; - continue; - } - // Prefix delete through the storage layer: remove_dir_all locally, - // list+delete on object stores (idempotent; already-gone is fine). - match backend.delete_graph_root(&graph_uri).await { - Ok(()) => {} - Err(err) => { - diagnostics.push(Diagnostic::error( - "graph_delete_failed", - graph_addr.clone(), - format!("could not remove graph root '{graph_uri}': {err}"), - )); - failed_graphs.insert(graph_id.clone(), FailedGraphOrigin::GraphDelete); - graph_moving_aborted = true; - continue; - } - } - // Crash point: the root is gone, the ledger does not record it yet. - // The sweep rolls forward (row 7b) and consumes the approval. - if let Err(diagnostic) = failpoints::maybe_fail("cluster_apply.after_graph_delete") { - diagnostics.push(diagnostic); - return early_return( - display_path(&desired.config_dir), - Some(desired.config_digest), - observations, - changes, - state.resource_statuses, - diagnostics, - ); - } - executed_deletes.push((graph_id.clone(), approval_id.clone())); - if let Some(approval_id) = approval_id { - consumed_approval_ids.push(approval_id); - } - completed_op_sidecars.push(sidecar_path); - } - if !failed_graphs.is_empty() { - demote_dependents_of_failed_graphs(&mut changes, &failed_graphs, &desired.dependencies); - } - - // State mutation. Apply owns query/policy statuses only; graph/schema - // statuses belong to refresh/import observation and must not be clobbered - // (the sweep above is the one exception: it owns recovery statuses). - let mut new_state = state.clone(); - for change in &changes { - match change.disposition { - Some(ApplyDisposition::Applied) => match change.operation { - PlanOperation::Create | PlanOperation::Update => { - new_state.applied_revision.resources.insert( - change.resource.clone(), - StateResource { - digest: change - .after_digest - .clone() - .expect("create/update always carries an after digest"), - // Policies record their applied bindings so the - // ledger is serving-sufficient (RFC-005 Β§D3). - applies_to: desired - .policy_bindings - .get(&change.resource) - .cloned(), - }, - ); - set_resource_status_applied(&mut new_state, &change.resource); - } - PlanOperation::Delete => { - new_state.applied_revision.resources.remove(&change.resource); - new_state.resource_statuses.remove(&change.resource); - } - }, - Some(ApplyDisposition::Blocked) => { - // The sweep owns recovery statuses (Drifted/Error with their - // conditions); a generic Blocked must not clobber them. - if change.reason.as_deref() != Some("cluster_recovery_pending") { - set_resource_status( - &mut new_state, - &change.resource, - ResourceLifecycleStatus::Blocked, - change.reason.as_deref().unwrap_or("dependency_not_applied"), - "waiting on an unapplied or missing dependency", - ); - } - } - _ => {} - } - } - for (graph_id, approval_id) in &executed_deletes { - tombstone_graph_subtree( - &mut new_state, - graph_id, - approval_id.as_deref(), - options.actor.as_deref(), - ); - if let Some(approval_id) = approval_id { - record_approval_consumed(&mut new_state, approval_id, "apply"); - } - } - recompute_state_graph_digests(&mut new_state, &desired); - - let mut residual = diff_resources( - &state_resource_digests(&new_state), - &desired.resource_digests, - ); - append_policy_binding_changes(&mut residual, Some(&new_state), &desired); - let converged = residual.is_empty(); - if converged { - new_state.applied_revision.config_digest = Some(desired.config_digest.clone()); - } - - let after_value = - serde_json::to_value(&new_state).expect("cluster state must serialize deterministically"); - let mut state_written = false; - let mut state_write_failed = false; - if after_value != before_value { - new_state.state_revision = new_state.state_revision.saturating_add(1); - // The failpoint error routes through state_write_failed so the - // persisted-statuses revert contract below is exercised; a cfg_callback - // on this point can mutate state.json to simulate a concurrent writer, - // making write_state's CAS check fail organically. - let write_result = match failpoints::maybe_fail("cluster_apply.before_state_write") { - Ok(()) => { - backend - .write_state(&new_state, expected_cas.as_deref(), &mut observations) - .await - } - Err(diagnostic) => Err(diagnostic), - }; - match write_result { - Ok(()) => state_written = true, - Err(diagnostic) => { - diagnostics.push(diagnostic); - state_write_failed = true; - } - } - } - // Completed (rows 2/4) sweep sidecars are deleted only once their outcome - // is durably recorded; on a failed write they stay and re-sweep next run. - if !state_write_failed { - for sidecar_uri in sweep - .completed_sidecars - .iter() - .chain(completed_op_sidecars.iter()) - { - backend.delete_object(sidecar_uri).await; - } - let mut all_consumed = sweep.consumed_approvals.clone(); - all_consumed.extend(consumed_approval_ids.iter().cloned()); - mark_approvals_consumed(&backend, &all_consumed).await; - } - // On a failed state write, report the statuses that are actually on disk - // (the pre-apply snapshot), not the in-memory mutations that were never - // persisted β€” automation reading `resource_statuses` independently of `ok` - // must not see phantom status updates. - let resource_statuses = if state_write_failed { - state.resource_statuses - } else { - new_state.resource_statuses - }; - - let applied_count = changes - .iter() - .filter(|change| change.disposition == Some(ApplyDisposition::Applied)) - .count(); - let deferred_count = changes - .iter() - .filter(|change| { - matches!( - change.disposition, - Some(ApplyDisposition::Deferred) | Some(ApplyDisposition::Blocked) - ) - }) - .count(); - - ApplyOutput { - ok: !has_errors(&diagnostics), - config_dir: display_path(&desired.config_dir), - actor: options.actor.clone(), - desired_revision: DesiredRevision { - config_digest: Some(desired.config_digest), - }, - state_observations: observations, - changes, - applied_count, - deferred_count, - converged, - state_written, - resource_statuses, - diagnostics, - } -} - -/// Record a digest-bound human approval for a gated (irreversible) change β€” -/// today: graph deletes. The artifact binds to the exact desired config -/// digest and the change's before/after digests, so config or state drift -/// invalidates it automatically (a stale approval can never authorize a -/// different change). -pub async fn approve_config_dir( - config_dir: impl AsRef, - resource: &str, - approved_by: &str, -) -> ApproveOutput { - let outcome = load_desired(config_dir.as_ref()); - let mut diagnostics = outcome.diagnostics; - let storage_root = outcome - .desired - .as_ref() - .and_then(|desired| desired.storage_root.clone()); - let backend = match store_for(&outcome.config_dir, storage_root.as_deref()) { - Ok(backend) => backend, - Err(diagnostic) => { - diagnostics.push(diagnostic); - ClusterStore::for_config_dir(&outcome.config_dir) - } - }; - let mut observations = backend.observations(); - - let fail = |config_dir: String, diagnostics: Vec| ApproveOutput { - ok: false, - config_dir, - approval_id: None, - resource: None, - operation: None, - approved_by: None, - diagnostics, - }; - - let Some(desired) = outcome.desired else { - return fail(display_path(&outcome.config_dir), diagnostics); - }; - if has_errors(&diagnostics) { - return fail(display_path(&desired.config_dir), diagnostics); - } - - let _lock_guard = if desired.state_lock { - match backend.acquire_lock("approve", &mut observations).await { - Ok(guard) => Some(guard), - Err(diagnostic) => { - diagnostics.push(diagnostic); - return fail(display_path(&desired.config_dir), diagnostics); - } - } - } else { - diagnostics.push(Diagnostic::warning( - "state_lock_disabled", - "state.lock", - "state.lock is false; approve ran without acquiring the cluster state lock", - )); - None - }; - - let state = match backend.read_state(&mut observations).await { - Ok(snapshot) => match snapshot.state { - Some(state) => state, - None => { - diagnostics.push(Diagnostic::error( - "state_missing", - CLUSTER_STATE_FILE, - "approve requires an existing state.json; run `cluster import` first", - )); - return fail(display_path(&desired.config_dir), diagnostics); - } - }, - Err(diagnostic) => { - diagnostics.push(diagnostic); - return fail(display_path(&desired.config_dir), diagnostics); - } - }; - - let prior_resources = state_resource_digests(&state); - let changes = diff_resources(&prior_resources, &desired.resource_digests); - let gates = compute_approvals(&changes, &BTreeSet::new()); - let Some(change) = changes.iter().find(|change| { - change.resource == resource && gates.iter().any(|gate| gate.resource == resource) - }) else { - diagnostics.push(Diagnostic::error( - "approval_not_required", - resource, - "no pending change for this resource requires approval (check `cluster plan`)", - )); - return fail(display_path(&desired.config_dir), diagnostics); - }; - - let artifact = ApprovalArtifact { - schema_version: 1, - approval_id: Ulid::new().to_string(), - resource: change.resource.clone(), - operation: match change.operation { - PlanOperation::Create => "create", - PlanOperation::Update => "update", - PlanOperation::Delete => "delete", - } - .to_string(), - reason: gates - .iter() - .find(|gate| gate.resource == resource) - .map(|gate| gate.reason.clone()) - .unwrap_or_default(), - bound_config_digest: desired.config_digest.clone(), - bound_before_digest: change.before_digest.clone(), - bound_after_digest: change.after_digest.clone(), - approved_by: approved_by.to_string(), - created_at: now_rfc3339(), - consumed_at: None, - consumed_by_operation: None, - }; - if let Err(diagnostic) = backend.write_approval_artifact(&artifact).await { - diagnostics.push(diagnostic); - return fail(display_path(&desired.config_dir), diagnostics); - } - - ApproveOutput { - ok: !has_errors(&diagnostics), - config_dir: display_path(&desired.config_dir), - approval_id: Some(artifact.approval_id), - resource: Some(artifact.resource), - operation: Some(change.operation.clone()), - approved_by: Some(artifact.approved_by), - diagnostics, - } -} - - -pub async fn status_config_dir(config_dir: impl AsRef) -> StatusOutput { - let parsed = parse_cluster_config(config_dir.as_ref()); - let mut diagnostics = parsed.diagnostics; - let storage_root = parsed.raw.as_ref().and_then(|raw| { - raw.storage - .as_deref() - .map(str::trim) - .filter(|root| !root.is_empty()) - .map(|root| root.trim_end_matches('/').to_string()) - }); - let backend = match store_for(&parsed.config_dir, storage_root.as_deref()) { - Ok(backend) => backend, - Err(diagnostic) => { - diagnostics.push(diagnostic); - ClusterStore::for_config_dir(&parsed.config_dir) - } - }; - let mut observations = backend.observations(); - backend.observe_lock(&mut observations, &mut diagnostics).await; - warn_pending_recovery_sidecars(&parsed.config_dir, &mut diagnostics); - - let mut resource_digests = BTreeMap::new(); - let mut resource_statuses = BTreeMap::new(); - let mut state_observation_records = BTreeMap::new(); - - if let Some(raw) = parsed.raw.as_ref() { - let _settings = validate_cluster_header(raw, &mut diagnostics); - if !has_errors(&diagnostics) { - match backend.read_state(&mut observations).await { - Ok(snapshot) => { - if let Some(state) = snapshot.state { - // Read-only point-in-time catalog check: report the - // findings as diagnostics; persisting Drifted statuses - // is refresh's job. Status never writes state. - for (address, finding) in - verify_catalog_payloads(&backend, &state).await - { - diagnostics.push(payload_finding_diagnostic(&address, &finding)); - } - resource_digests = state_resource_digests(&state); - resource_statuses = state.resource_statuses; - state_observation_records = state.observations; - } else { - diagnostics.push(Diagnostic::warning( - "state_missing", - CLUSTER_STATE_FILE, - "state.json is missing; no applied cluster revision has been recorded", - )); - } - } - Err(diagnostic) => diagnostics.push(diagnostic), - } - } - } - - StatusOutput { - ok: !has_errors(&diagnostics), - config_dir: display_path(&parsed.config_dir), - state_observations: observations, - resource_digests, - resource_statuses, - observations: state_observation_records, - diagnostics, - } -} - -pub async fn force_unlock_config_dir( - config_dir: impl AsRef, - lock_id: impl AsRef, -) -> ForceUnlockOutput { - let parsed = parse_cluster_config(config_dir.as_ref()); - let mut diagnostics = parsed.diagnostics; - let storage_root = parsed.raw.as_ref().and_then(|raw| { - raw.storage - .as_deref() - .map(str::trim) - .filter(|root| !root.is_empty()) - .map(|root| root.trim_end_matches('/').to_string()) - }); - let backend = match store_for(&parsed.config_dir, storage_root.as_deref()) { - Ok(backend) => backend, - Err(diagnostic) => { - diagnostics.push(diagnostic); - ClusterStore::for_config_dir(&parsed.config_dir) - } - }; - let mut observations = backend.observations(); - let mut lock_removed = false; - - if let Some(raw) = parsed.raw.as_ref() { - let _settings = validate_cluster_header(raw, &mut diagnostics); - if !has_errors(&diagnostics) { - match backend.force_unlock(lock_id.as_ref(), &mut observations).await { - Ok(()) => lock_removed = true, - Err(diagnostic) => diagnostics.push(diagnostic), - } - } - } - - ForceUnlockOutput { - ok: !has_errors(&diagnostics), - config_dir: display_path(&parsed.config_dir), - state_observations: observations, - lock_removed, - diagnostics, - } -} - -pub async fn refresh_config_dir(config_dir: impl AsRef) -> StateSyncOutput { - sync_config_dir(config_dir.as_ref(), StateSyncOperation::Refresh).await -} - -pub async fn import_config_dir(config_dir: impl AsRef) -> StateSyncOutput { - sync_config_dir(config_dir.as_ref(), StateSyncOperation::Import).await -} - -async fn sync_config_dir(config_dir: &Path, operation: StateSyncOperation) -> StateSyncOutput { - let outcome = load_desired(config_dir); - let mut diagnostics = outcome.diagnostics; - let storage_root = outcome - .desired - .as_ref() - .and_then(|desired| desired.storage_root.clone()); - let backend = match store_for(&outcome.config_dir, storage_root.as_deref()) { - Ok(backend) => backend, - Err(diagnostic) => { - diagnostics.push(diagnostic); - ClusterStore::for_config_dir(&outcome.config_dir) - } - }; - let mut observations = backend.observations(); - - let Some(desired) = outcome.desired else { - return StateSyncOutput { - ok: false, - operation, - config_dir: display_path(&outcome.config_dir), - state_observations: observations, - resource_digests: BTreeMap::new(), - resource_statuses: BTreeMap::new(), - observations: BTreeMap::new(), - diagnostics, - }; - }; - - if has_errors(&diagnostics) { - return StateSyncOutput { - ok: false, - operation, - config_dir: display_path(&desired.config_dir), - state_observations: observations, - resource_digests: desired.resource_digests, - resource_statuses: BTreeMap::new(), - observations: BTreeMap::new(), - diagnostics, - }; - } - - let operation_label = state_sync_operation_label(operation); - let _lock_guard = if desired.state_lock { - match backend.acquire_lock(operation_label, &mut observations).await { - Ok(guard) => Some(guard), - Err(diagnostic) => { - diagnostics.push(diagnostic); - None - } - } - } else { - diagnostics.push(Diagnostic::warning( - "state_lock_disabled", - "state.lock", - format!( - "state.lock is false; {operation_label} wrote state without acquiring the cluster state lock" - ), - )); - None - }; - - if has_errors(&diagnostics) { - return StateSyncOutput { - ok: false, - operation, - config_dir: display_path(&desired.config_dir), - state_observations: observations, - resource_digests: desired.resource_digests, - resource_statuses: BTreeMap::new(), - observations: BTreeMap::new(), - diagnostics, - }; - } - - let snapshot = match backend.read_state(&mut observations).await { - Ok(snapshot) => snapshot, - Err(diagnostic) => { - diagnostics.push(diagnostic); - return StateSyncOutput { - ok: false, - operation, - config_dir: display_path(&desired.config_dir), - state_observations: observations, - resource_digests: desired.resource_digests, - resource_statuses: BTreeMap::new(), - observations: BTreeMap::new(), - diagnostics, - }; - } - }; - - let expected_cas = snapshot.state_cas; - let mut state = match (operation, snapshot.state) { - (StateSyncOperation::Refresh, Some(state)) => state, - (StateSyncOperation::Refresh, None) => { - diagnostics.push(Diagnostic::error( - "state_missing", - CLUSTER_STATE_FILE, - "refresh requires an existing state.json; run `cluster import` to bootstrap state", - )); - return StateSyncOutput { - ok: false, - operation, - config_dir: display_path(&desired.config_dir), - state_observations: observations, - resource_digests: BTreeMap::new(), - resource_statuses: BTreeMap::new(), - observations: BTreeMap::new(), - diagnostics, - }; - } - (StateSyncOperation::Import, Some(state)) => { - diagnostics.push(Diagnostic::error( - "state_already_exists", - CLUSTER_STATE_FILE, - "import creates initial state only when state.json is missing; use `cluster refresh` for an existing state ledger", - )); - return StateSyncOutput { - ok: false, - operation, - config_dir: display_path(&desired.config_dir), - state_observations: observations, - resource_digests: state_resource_digests(&state), - resource_statuses: state.resource_statuses, - observations: state.observations, - diagnostics, - }; - } - (StateSyncOperation::Import, None) => initial_import_state(&desired), - }; - - // Recovery sweep first (RFC-004 Β§D3): classify any interrupted graph - // operation before observation/verification so a rolled-forward outcome - // is what those passes see. - let sweep = sweep_recovery_sidecars(&backend, &mut state, &mut diagnostics).await; - - // Catalog payload verification must run BEFORE graph observation: removing - // a drifted query digest first means the live-graph composite recompute - // below already excludes it, so the persisted graph. composite stays - // consistent and the next plan shows exactly the create + derived update. - for (address, finding) in verify_catalog_payloads(&backend, &state).await { - diagnostics.push(payload_finding_diagnostic(&address, &finding)); - match finding { - PayloadFinding::Missing => { - state.applied_revision.resources.remove(&address); - set_resource_status( - &mut state, - &address, - ResourceLifecycleStatus::Drifted, - "payload_missing", - "catalog payload blob is missing; re-run `cluster apply` to republish", - ); - } - PayloadFinding::Mismatch { .. } => { - state.applied_revision.resources.remove(&address); - set_resource_status( - &mut state, - &address, - ResourceLifecycleStatus::Drifted, - "payload_mismatch", - "catalog payload blob does not match the recorded digest; re-run `cluster apply` to republish", - ); - } - // Transient IO must not trigger a spurious republish: keep the - // digest, surface the error, let a later clean refresh converge. - PayloadFinding::ReadError(error) => { - set_resource_status( - &mut state, - &address, - ResourceLifecycleStatus::Error, - "payload_read_error", - &error, - ); - } - } - } - - let graph_error_count = observe_declared_graphs(&desired, &backend, &mut state).await; - if graph_error_count > 0 { - diagnostics.push(Diagnostic::error( - "graph_observation_error", - CLUSTER_GRAPHS_DIR, - format!("{graph_error_count} graph observation(s) failed"), - )); - } - - if operation == StateSyncOperation::Import && has_errors(&diagnostics) { - return StateSyncOutput { - ok: false, - operation, - config_dir: display_path(&desired.config_dir), - state_observations: observations, - resource_digests: state_resource_digests(&state), - resource_statuses: state.resource_statuses, - observations: state.observations, - diagnostics, - }; - } - - if operation == StateSyncOperation::Import { - state.state_revision = 1; - } else { - state.state_revision = state.state_revision.saturating_add(1); - } - - match backend.write_state(&state, expected_cas.as_deref(), &mut observations).await { - Ok(()) => { - // Completed sweep sidecars are deleted only after their outcome - // is durably recorded; on failure they stay and re-sweep. - for sidecar_uri in &sweep.completed_sidecars { - backend.delete_object(sidecar_uri).await; - } - mark_approvals_consumed(&backend, &sweep.consumed_approvals).await; - } - Err(diagnostic) => diagnostics.push(diagnostic), - } - - let resource_digests = state_resource_digests(&state); - let ok = !has_errors(&diagnostics); - - StateSyncOutput { - ok, - operation, - config_dir: display_path(&desired.config_dir), - state_observations: observations, - resource_digests, - resource_statuses: state.resource_statuses, - observations: state.observations, - diagnostics, - } -} - - - - -#[derive(Debug, PartialEq, Eq)] -enum PayloadFinding { - Missing, - Mismatch { actual_digest: String }, - ReadError(String), -} - -/// Verify every catalog-backed resource digest in state against its -/// content-addressed blob under `__cluster/resources/`. Graph, schema, and -/// unknown addresses have no payloads and are skipped. Read-only; findings -/// are deterministic (BTreeMap order). Payloads are small (queries, policy -/// bundles), so a full digest re-hash is cheap. -async fn verify_catalog_payloads( - backend: &ClusterStore, - state: &ClusterState, -) -> Vec<(String, PayloadFinding)> { - let mut findings = Vec::new(); - for (address, resource) in &state.applied_revision.resources { - let kind = resource_kind(address); - if ClusterStore::payload_relative(&kind, &resource.digest).is_none() { - continue; - } - match backend.read_payload(&kind, &resource.digest).await { - Ok(Some(text)) => { - let actual_digest = sha256_hex(text.as_bytes()); - if actual_digest != resource.digest { - findings.push((address.clone(), PayloadFinding::Mismatch { actual_digest })); - } - } - Ok(None) => findings.push((address.clone(), PayloadFinding::Missing)), - Err(err) => { - findings.push((address.clone(), PayloadFinding::ReadError(err))); - } - } - } - findings -} - -fn payload_finding_diagnostic(address: &str, finding: &PayloadFinding) -> Diagnostic { - match finding { - PayloadFinding::Missing => Diagnostic::warning( - "catalog_payload_missing", - address, - "catalog payload blob is missing; re-run `cluster apply` to republish", - ), - PayloadFinding::Mismatch { actual_digest } => Diagnostic::warning( - "catalog_payload_mismatch", - address, - format!( - "catalog payload blob does not match the recorded digest (actual sha256:{actual_digest}); re-run `cluster apply` to republish" - ), - ), - // An unverifiable blob must not report healthy. - PayloadFinding::ReadError(error) => { - Diagnostic::error("catalog_payload_read_error", address, error.clone()) - } - } -} - -/// Write one content-addressed payload blob. Idempotent: an existing -/// digest-named file is trusted as-is. The digest re-check is the apply-side -/// TOCTOU detector β€” the source file changing between `load_desired` and the -/// payload write must fail loudly, never publish mismatched content. -async fn write_resource_payload( - backend: &ClusterStore, - kind: &ResourceKind, - source: &Path, - expected_digest: &str, - resource: &str, -) -> Result<(), Diagnostic> { - if backend.payload_exists(kind, expected_digest).await { - // Content-addressed: an existing digest-named object is identical. - return Ok(()); - } - let bytes = fs::read(source).map_err(|err| { - Diagnostic::error( - "resource_payload_write_error", - resource, - format!("could not read resource source '{}': {err}", source.display()), - ) - })?; - if sha256_hex(&bytes) != expected_digest { - // The apply-side TOCTOU detector: the source changing between - // load_desired and this write must fail loudly, never publish - // mismatched content. - return Err(Diagnostic::error( - "resource_content_changed", - resource, - format!( - "resource source '{}' changed while apply was running; re-run `cluster apply`", - source.display() - ), - )); - } - let content = String::from_utf8(bytes).map_err(|err| { - Diagnostic::error( - "resource_payload_write_error", - resource, - format!("resource source is not valid UTF-8: {err}"), - ) - })?; - backend - .write_payload(kind, expected_digest, &content) - .await - .map_err(|err| { - Diagnostic::error( - "resource_payload_write_error", - resource, - format!("could not write payload: {err}"), - ) - }) -} - -/// Recompute the composite `graph.` digests for state-resident graphs from -/// state's own schema/query components. Without this, an applied query change -/// would leave the prior composite digest in state and `graph.` would show -/// a phantom update in every later plan β€” apply could never converge. -fn recompute_state_graph_digests(state: &mut ClusterState, desired: &DesiredCluster) { - for graph in &desired.graphs { - let graph_address = graph_address(&graph.id); - if !state.applied_revision.resources.contains_key(&graph_address) { - continue; - } - let schema_digest = state - .applied_revision - .resources - .get(&schema_address(&graph.id)) - .map(|resource| resource.digest.clone()); - let query_digests = state_query_digests_for_graph(state, &graph.id); - let digest = graph_digest(&graph.id, schema_digest.as_ref(), Some(&query_digests)); - state - .applied_revision - .resources - .insert(graph_address, StateResource { digest, applies_to: None }); - } -} - -fn duplicate_key_diagnostics(text: &str) -> Vec { - #[derive(Debug)] - struct Frame { - indent: isize, - path: String, - keys: BTreeSet, - } - - let mut diagnostics = Vec::new(); - let mut stack = vec![Frame { - indent: -1, - path: String::new(), - keys: BTreeSet::new(), - }]; - - for (line_idx, line) in text.lines().enumerate() { - let line_without_comment = strip_comment(line); - if line_without_comment.trim().is_empty() { - continue; - } - let indent = line_without_comment - .chars() - .take_while(|ch| *ch == ' ') - .count() as isize; - let trimmed = line_without_comment.trim_start(); - if trimmed.starts_with('-') { - continue; - } - let Some((raw_key, raw_value)) = trimmed.split_once(':') else { - continue; - }; - let key = raw_key.trim(); - if key.is_empty() || key.starts_with('{') || key.starts_with('[') { - continue; - } - - while stack.last().is_some_and(|frame| indent <= frame.indent) { - stack.pop(); - } - let parent = stack.last_mut().expect("root frame is always present"); - let full_path = if parent.path.is_empty() { - key.to_string() - } else { - format!("{}.{}", parent.path, key) - }; - if !parent.keys.insert(key.to_string()) { - diagnostics.push(Diagnostic::error( - "duplicate_yaml_key", - full_path.clone(), - format!("duplicate YAML key `{key}` on line {}", line_idx + 1), - )); - } - if raw_value.trim().is_empty() { - stack.push(Frame { - indent, - path: full_path, - keys: BTreeSet::new(), - }); - } - } - - diagnostics -} - - -fn strip_comment(line: &str) -> String { - let mut in_single_quote = false; - let mut in_double_quote = false; - let mut escaped = false; - - for (idx, ch) in line.char_indices() { - if escaped { - escaped = false; - continue; - } - match ch { - '\\' if in_double_quote => escaped = true, - '\'' if !in_double_quote => in_single_quote = !in_single_quote, - '"' if !in_single_quote => in_double_quote = !in_double_quote, - '#' if !in_single_quote && !in_double_quote => return line[..idx].to_string(), - _ => {} - } - } - - line.to_string() -} - - -fn state_query_digests_for_graph(state: &ClusterState, graph_id: &str) -> BTreeMap { - let prefix = format!("query.{graph_id}."); - state - .applied_revision - .resources - .iter() - .filter_map(|(address, resource)| { - address - .strip_prefix(&prefix) - .map(|name| (name.to_string(), resource.digest.clone())) - }) - .collect() -} - -fn set_resource_status_applied(state: &mut ClusterState, address: &str) { - state.resource_statuses.insert( - address.to_string(), - ResourceStatusRecord { - status: ResourceLifecycleStatus::Applied, - conditions: Vec::new(), - message: None, - }, - ); -} - -fn set_resource_status( - state: &mut ClusterState, - address: &str, - status: ResourceLifecycleStatus, - condition: &str, - message: &str, -) { - state.resource_statuses.insert( - address.to_string(), - ResourceStatusRecord { - status, - conditions: vec![condition.to_string()], - message: Some(message.to_string()), - }, - ); -} - -fn graph_digest( - graph_id: &str, - schema_digest: Option<&String>, - query_digests: Option<&BTreeMap>, -) -> String { - let mut input = format!( - "graph\0{graph_id}\0schema\0{}\0", - schema_digest.map_or("", String::as_str) - ); - if let Some(query_digests) = query_digests { - for (name, digest) in query_digests { - input.push_str("query\0"); - input.push_str(name); - input.push('\0'); - input.push_str(digest); - input.push('\0'); - } - } - sha256_hex(input.as_bytes()) -} - -fn desired_config_digest( - raw: &RawClusterConfig, - resource_digests: &BTreeMap, -) -> String { - let mut input = String::from("cluster-config\0"); - // Hash parsed semantics, not raw YAML bytes, so comments and formatting do - // not create a new desired revision and the digest cannot drift from parse. - let config_semantics = - serde_json::to_string(raw).expect("raw cluster config must serialize deterministically"); - input.push_str(&config_semantics); - input.push('\0'); - for (address, digest) in resource_digests { - input.push_str(address); - input.push('\0'); - input.push_str(digest); - input.push('\0'); - } - sha256_hex(input.as_bytes()) -} - -fn sha256_hex(bytes: &[u8]) -> String { - let digest = Sha256::digest(bytes); - const HEX: &[u8; 16] = b"0123456789abcdef"; - let mut out = String::with_capacity(digest.len() * 2); - for byte in digest { - out.push(HEX[(byte >> 4) as usize] as char); - out.push(HEX[(byte & 0x0f) as usize] as char); - } - out -} - -fn now_rfc3339() -> String { - OffsetDateTime::now_utc() - .format(&Rfc3339) - .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string()) -} - -fn lock_age_seconds(created_at: &str) -> Option { - let created_at = OffsetDateTime::parse(created_at, &Rfc3339).ok()?; - Some( - (OffsetDateTime::now_utc() - created_at) - .whole_seconds() - .max(0) as u64, - ) -} - -fn state_sync_operation_label(operation: StateSyncOperation) -> &'static str { - match operation { - StateSyncOperation::Refresh => "refresh", - StateSyncOperation::Import => "import", - } -} - -fn has_errors(diagnostics: &[Diagnostic]) -> bool { - diagnostics - .iter() - .any(|diagnostic| diagnostic.severity == DiagnosticSeverity::Error) -} - -fn count_errors(diagnostics: &[Diagnostic]) -> usize { - diagnostics - .iter() - .filter(|diagnostic| diagnostic.severity == DiagnosticSeverity::Error) - .count() -} - -fn display_path(path: &Path) -> String { - path.display().to_string() -} - - -#[cfg(test)] -#[path = "tests.rs"] -mod tests; diff --git a/crates/omnigraph-cluster/src/serve.rs b/crates/omnigraph-cluster/src/serve.rs deleted file mode 100644 index 4abd0bf..0000000 --- a/crates/omnigraph-cluster/src/serve.rs +++ /dev/null @@ -1,188 +0,0 @@ -//! Phase-5 serving snapshot: the read-only loader a `--cluster` server -//! boots from (moved verbatim from lib.rs in the modularization). - -use super::*; - -/// One graph in a serving snapshot: its id and on-disk root. -#[derive(Debug, Clone)] -pub struct ServingGraph { - pub graph_id: String, - pub root: PathBuf, -} - -/// One stored query: its graph binding, registry name, and verified source. -#[derive(Debug, Clone)] -pub struct ServingQuery { - pub graph_id: String, - pub name: String, - pub source: String, -} - -/// One policy bundle: its verified catalog blob path and applied bindings -/// (normalized typed refs: `cluster` | `graph.`). -#[derive(Debug, Clone)] -pub struct ServingPolicy { - pub name: String, - /// The policy bundle CONTENT, digest-verified against the applied - /// revision at read time. Content, not a path: the catalog may live on - /// object storage, and the server must not re-read mutable state. - pub source: String, - pub applies_to: Vec, -} - -/// Everything a server needs to boot from the cluster catalog (RFC-005 Β§D2). -#[derive(Debug, Clone)] -pub struct ServingSnapshot { - pub graphs: Vec, - pub queries: Vec, - pub policies: Vec, -} - -/// Read the applied revision as a serving snapshot β€” the read-only loader for -/// the Phase-5 server boot. All-or-nothing per RFC-005 Β§D4: every readiness -/// failure is collected and the whole snapshot refused; no partial serving. -/// Takes no lock: the state file is replaced atomically, so this reads a -/// consistent point-in-time ledger. -pub async fn read_serving_snapshot( - config_dir: impl AsRef, -) -> Result> { - let config_dir = config_dir.as_ref().to_path_buf(); - // The declared storage: root decides where the ledger/catalog/graphs - // live; config parse errors surface through the normal validation path. - let parsed = parse_cluster_config(&config_dir); - let storage_root = parsed.raw.as_ref().and_then(|raw| { - raw.storage - .as_deref() - .map(str::trim) - .filter(|root| !root.is_empty()) - .map(|root| root.trim_end_matches('/').to_string()) - }); - let backend = match storage_root.as_deref() { - Some(root) => match ClusterStore::for_storage_root(root) { - Ok(backend) => backend, - Err(diagnostic) => return Err(vec![diagnostic]), - }, - None => ClusterStore::for_config_dir(&config_dir), - }; - read_snapshot_with_store(backend).await -} - -/// Read the applied revision directly from a storage root URI β€” config-free -/// serving: a `--cluster s3://bucket/prefix` server needs no local files at -/// all, only the bucket and credentials. The ledger and catalog ARE the -/// deployment artifact. -pub async fn read_serving_snapshot_from_storage( - storage_root: &str, -) -> Result> { - let backend = - ClusterStore::for_storage_root(storage_root).map_err(|diagnostic| vec![diagnostic])?; - read_snapshot_with_store(backend).await -} - -async fn read_snapshot_with_store( - backend: ClusterStore, -) -> Result> { - let mut diagnostics: Vec = Vec::new(); - - // A ledger a sweep is about to rewrite must not start serving. - let sidecars = backend.list_recovery_sidecars(&mut diagnostics).await; - if !sidecars.is_empty() { - diagnostics.push(Diagnostic::error( - "cluster_recovery_pending", - CLUSTER_RECOVERIES_DIR, - format!( - "{} interrupted operation(s) await recovery; run any state-mutating cluster command (e.g. `cluster apply`) to sweep, then retry", - sidecars.len() - ), - )); - } - - let mut observations = backend.observations(); - let state = match backend.read_state(&mut observations).await { - Ok(snapshot) => match snapshot.state { - Some(state) => Some(state), - None => { - diagnostics.push(Diagnostic::error( - "cluster_state_missing", - CLUSTER_STATE_FILE, - "no cluster state ledger; run `cluster import` and `cluster apply` first", - )); - None - } - }, - Err(diagnostic) => { - diagnostics.push(diagnostic); - None - } - }; - let Some(state) = state else { - return Err(diagnostics); - }; - - let mut graphs = Vec::new(); - let mut queries = Vec::new(); - let mut policies = Vec::new(); - for (address, entry) in &state.applied_revision.resources { - match resource_kind(address) { - ResourceKind::Graph(graph_id) => { - graphs.push(ServingGraph { - root: PathBuf::from(backend.graph_root(&graph_id)), - graph_id, - }); - } - ResourceKind::Schema(_) => {} - kind @ ResourceKind::Query { .. } => { - let ResourceKind::Query { graph, name } = &kind else { - unreachable!() - }; - match backend.read_verified_payload(&kind, &entry.digest, address).await { - Ok(source) => queries.push(ServingQuery { - graph_id: graph.clone(), - name: name.clone(), - source, - }), - Err(diagnostic) => diagnostics.push(diagnostic), - } - } - kind @ ResourceKind::Policy(_) => { - let ResourceKind::Policy(name) = &kind else { - unreachable!() - }; - let Some(applies_to) = entry.applies_to.clone() else { - diagnostics.push(Diagnostic::error( - "policy_bindings_missing", - address.clone(), - "no applied applies_to bindings recorded (ledger predates binding metadata); re-run `cluster apply` to backfill", - )); - continue; - }; - match backend.read_verified_payload(&kind, &entry.digest, address).await { - Ok(source) => policies.push(ServingPolicy { - name: name.clone(), - source, - applies_to, - }), - Err(diagnostic) => diagnostics.push(diagnostic), - } - } - ResourceKind::Unknown => {} - } - } - - if graphs.is_empty() { - diagnostics.push(Diagnostic::error( - "cluster_empty", - CLUSTER_STATE_FILE, - "the applied revision records no graphs; apply a cluster with at least one graph before serving from it", - )); - } - if has_errors(&diagnostics) { - return Err(diagnostics); - } - Ok(ServingSnapshot { - graphs, - queries, - policies, - }) -} - diff --git a/crates/omnigraph-cluster/src/store.rs b/crates/omnigraph-cluster/src/store.rs deleted file mode 100644 index 4d33d2c..0000000 --- a/crates/omnigraph-cluster/src/store.rs +++ /dev/null @@ -1,813 +0,0 @@ -//! The cluster's storage layer: every stored byte (state ledger, lock, -//! recovery sidecars, approval artifacts, catalog payloads) goes through the -//! engine's `StorageAdapter`, so `file://` and `s3://` are one code path -//! (RFC-006). Declared configuration β€” `cluster.yaml` and the schema/query/ -//! policy sources it references β€” deliberately does NOT live here: config is -//! read from the operator's working tree (Terraform's config-local / -//! state-remote split). -//! -//! Raw `fs::*` for cluster state outside this module is a deny-list entry. - -use std::path::Path; -use std::process; -use std::sync::Arc; - -use omnigraph::storage::{StorageAdapter, StorageKind, storage_for_uri, storage_kind_for_uri}; -use time::OffsetDateTime; -use time::format_description::well_known::Rfc3339; -use ulid::Ulid; - -use crate::{ - ApprovalArtifact, CLUSTER_APPROVALS_DIR, CLUSTER_LOCK_FILE, CLUSTER_RECOVERIES_DIR, - CLUSTER_RESOURCES_DIR, CLUSTER_STATE_FILE, ClusterState, Diagnostic, RecoverySidecar, - ResourceKind, StateLockFile, StateObservations, sha256_hex, -}; - -#[derive(Debug, Clone)] -pub(crate) struct ClusterStore { - adapter: Arc, - /// Normalized storage-root URI, no trailing slash: `file:///abs/dir` - /// (the default config-dir layout) or `s3://bucket/prefix`. - root: String, - /// What observations/diagnostics display for stored locations: the plain - /// local path for `file://` roots (byte-compatible with the pre-store - /// outputs), the URI otherwise. - display_root: String, -} - -#[derive(Debug)] -pub(crate) struct StateSnapshot { - pub(crate) state: Option, - /// Content identity (`sha256:`) β€” the public CAS vocabulary. - pub(crate) state_cas: Option, -} - -#[derive(Debug)] -pub(crate) struct StateLockGuard { - adapter: Arc, - uri: String, - kind: StorageKind, -} - -impl Drop for StateLockGuard { - fn drop(&mut self) { - match self.kind { - // Deterministic release on the file backend (tests assert the - // lock is gone the moment a command returns). - StorageKind::Local => { - let path = self.uri.trim_start_matches("file://"); - let _ = std::fs::remove_file(path); - } - // Object stores need an async delete, and it must COMPLETE - // before a short-lived CLI process exits β€” a spawned task dies - // with the runtime and leaks the lock (caught by the s3 smoke - // test: import's lock survived into the next command). On the - // multi-thread runtime (the CLI and the gated s3 tests), - // block_in_place waits for the delete; on a current-thread - // runtime that's not allowed, so fall back to a spawn β€” - // best-effort, with `force-unlock` as the documented recovery, - // same as a crash. - StorageKind::S3 => { - let adapter = Arc::clone(&self.adapter); - let uri = self.uri.clone(); - if let Ok(handle) = tokio::runtime::Handle::try_current() { - if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread { - tokio::task::block_in_place(move || { - handle.block_on(async move { - let _ = adapter.delete(&uri).await; - }); - }); - } else { - handle.spawn(async move { - let _ = adapter.delete(&uri).await; - }); - } - } - } - } - } -} - -impl ClusterStore { - /// The default layout: storage root = the config directory itself - /// (`file://`), byte-compatible with every pre-existing - /// cluster on disk. - pub(crate) fn for_config_dir(config_dir: &Path) -> Self { - let absolute = - std::path::absolute(config_dir).unwrap_or_else(|_| config_dir.to_path_buf()); - let display_root = absolute - .to_string_lossy() - .trim_end_matches('/') - .to_string(); - let root = format!("file://{display_root}"); - let adapter = storage_for_uri(&root) - .expect("local storage adapter construction is infallible for file:// roots"); - Self { - adapter, - root, - display_root, - } - } - - /// An explicit `storage:` root. `file://` URIs and plain paths normalize - /// to the local backend; `s3://bucket/prefix` to the S3 backend (env- - /// driven credentials/endpoint β€” the same contract as graph storage). - pub(crate) fn for_storage_root(root_uri: &str) -> Result { - let trimmed = root_uri.trim_end_matches('/'); - if storage_kind_for_uri(trimmed) == StorageKind::Local { - let path = trimmed.trim_start_matches("file://"); - return Ok(Self::for_config_dir(Path::new(path))); - } - let adapter = storage_for_uri(trimmed).map_err(|err| { - Diagnostic::error( - "storage_root_invalid", - "storage", - format!("could not initialize storage for '{root_uri}': {err}"), - ) - })?; - Ok(Self { - adapter, - root: trimmed.to_string(), - display_root: trimmed.to_string(), - }) - } - - pub(crate) fn kind(&self) -> StorageKind { - storage_kind_for_uri(&self.root) - } - - fn uri(&self, relative: &str) -> String { - format!("{}/{}", self.root, relative) - } - - fn display(&self, relative: &str) -> String { - format!("{}/{}", self.display_root, relative) - } - - /// Derived graph root for ``: `/graphs/.omni`. A plain - /// local path for `file://` roots (byte-compatible, directly usable by - /// the engine); the S3 URI the engine opens natively otherwise. - pub(crate) fn graph_root(&self, graph_id: &str) -> String { - match self.kind() { - StorageKind::Local => format!("{}/graphs/{graph_id}.omni", self.display_root), - StorageKind::S3 => format!("{}/graphs/{graph_id}.omni", self.root), - } - } - - /// `read_text_versioned`, returning None for a missing object (probed - /// via `exists` β€” the engine error type doesn't discriminate NotFound). - async fn read_versioned_opt(&self, uri: &str) -> Result, String> { - match self.adapter.exists(uri).await { - Ok(false) => return Ok(None), - Ok(true) => {} - Err(err) => return Err(err.to_string()), - } - self.adapter - .read_text_versioned(uri) - .await - .map(Some) - .map_err(|err| err.to_string()) - } - - /// JSON object write with the strongest atomicity the backend offers: - /// temp + rename on the filesystem (no torn JSON after a crash; the - /// pre-port behavior), a single atomic PUT on object stores (where - /// copy+delete would be weaker, not stronger). - async fn put_json(&self, relative: &str, payload: &str) -> Result<(), String> { - let target = self.uri(relative); - match self.kind() { - StorageKind::Local => { - let tmp = format!("{target}.tmp.{}", Ulid::new()); - self.adapter - .write_text(&tmp, payload) - .await - .map_err(|err| err.to_string())?; - if let Err(err) = self.adapter.rename_text(&tmp, &target).await { - let _ = self.adapter.delete(&tmp).await; - return Err(err.to_string()); - } - Ok(()) - } - StorageKind::S3 => self - .adapter - .write_text(&target, payload) - .await - .map_err(|err| err.to_string()), - } - } - - /// Shared list-and-parse for the sidecar/approval directories: id - /// (filename) order; unparseable objects warn and stay for the operator. - async fn list_json_dir( - &self, - dir: &str, - diagnostics: &mut Vec, - list_error_code: &'static str, - parse_error_code: &'static str, - version_ok: impl Fn(&T) -> bool, - version_error_code: &'static str, - ) -> Vec<(String, T)> { - let dir_uri = self.uri(dir); - let mut uris = match self.adapter.list_dir(&dir_uri).await { - Ok(uris) => uris, - Err(err) => { - diagnostics.push(Diagnostic::warning( - list_error_code, - dir, - format!("could not list '{dir}': {err}"), - )); - return Vec::new(); - } - }; - uris.retain(|uri| uri.ends_with(".json")); - uris.sort(); - let mut out = Vec::new(); - for uri in uris { - match self.adapter.read_text(&uri).await { - Ok(text) => match serde_json::from_str::(&text) { - Ok(value) if version_ok(&value) => out.push((uri, value)), - Ok(_) => diagnostics.push(Diagnostic::warning( - version_error_code, - uri.clone(), - "unsupported schema version; leaving it in place".to_string(), - )), - Err(err) => diagnostics.push(Diagnostic::warning( - parse_error_code, - uri.clone(), - format!("could not parse ({err}); leaving it in place"), - )), - }, - Err(err) => diagnostics.push(Diagnostic::warning( - parse_error_code, - uri.clone(), - format!("could not read ({err}); leaving it in place"), - )), - } - } - out - } - - /// Best-effort object removal (sidecar retirement after a CAS lands, - /// lock cleanup) β€” failures are recoverable by the next sweep. - pub(crate) async fn delete_object(&self, uri: &str) { - let _ = self.adapter.delete(uri).await; - } - - /// Recursive prefix delete for graph roots (approved deletes). Idempotent; - /// S3 non-atomicity is tolerated by the delete protocol's retry shape. - pub(crate) async fn delete_graph_root(&self, graph_uri: &str) -> Result<(), String> { - self.adapter - .delete_prefix(graph_uri) - .await - .map_err(|err| err.to_string()) - } - - /// Existence probe for graph roots in sweep classification. A bare local - /// path or any URI works β€” resolved through the same adapter machinery - /// the engine uses. - pub(crate) async fn graph_root_exists(&self, graph_uri: &str) -> bool { - match storage_kind_for_uri(graph_uri) { - StorageKind::Local => Path::new(graph_uri.trim_start_matches("file://")).exists(), - StorageKind::S3 => match storage_for_uri(graph_uri) { - Ok(adapter) => !adapter - .list_dir(graph_uri) - .await - .map(|entries| entries.is_empty()) - .unwrap_or(true), - Err(_) => false, - }, - } - } - - // ---- approvals ---- - - pub(crate) async fn list_approval_artifacts( - &self, - diagnostics: &mut Vec, - ) -> Vec<(String, ApprovalArtifact)> { - self.list_json_dir( - CLUSTER_APPROVALS_DIR, - diagnostics, - "approval_read_error", - "invalid_approval_artifact", - |artifact: &ApprovalArtifact| artifact.schema_version == 1, - "unsupported_approval_version", - ) - .await - } - - pub(crate) async fn write_approval_artifact( - &self, - artifact: &ApprovalArtifact, - ) -> Result { - let relative = format!("{CLUSTER_APPROVALS_DIR}/{}.json", artifact.approval_id); - let mut payload = serde_json::to_string_pretty(artifact).map_err(|err| { - Diagnostic::error( - "approval_write_error", - self.display(&relative), - format!("could not encode approval artifact: {err}"), - ) - })?; - payload.push('\n'); - self.put_json(&relative, &payload).await.map_err(|err| { - Diagnostic::error( - "approval_write_error", - self.display(&relative), - format!("could not write approval artifact: {err}"), - ) - })?; - Ok(self.uri(&relative)) - } - - // ---- recovery sidecars ---- - - pub(crate) async fn list_recovery_sidecars( - &self, - diagnostics: &mut Vec, - ) -> Vec<(String, RecoverySidecar)> { - self.list_json_dir( - CLUSTER_RECOVERIES_DIR, - diagnostics, - "recovery_sidecar_read_error", - "invalid_recovery_sidecar", - |sidecar: &RecoverySidecar| sidecar.schema_version == 1, - "unsupported_recovery_sidecar_version", - ) - .await - } - - pub(crate) async fn write_recovery_sidecar( - &self, - sidecar: &RecoverySidecar, - ) -> Result { - let relative = format!("{CLUSTER_RECOVERIES_DIR}/{}.json", sidecar.operation_id); - let mut payload = serde_json::to_string_pretty(sidecar).map_err(|err| { - Diagnostic::error( - "recovery_sidecar_write_error", - self.display(&relative), - format!("could not encode recovery sidecar: {err}"), - ) - })?; - payload.push('\n'); - self.put_json(&relative, &payload).await.map_err(|err| { - Diagnostic::error( - "recovery_sidecar_write_error", - self.display(&relative), - format!("could not write recovery sidecar: {err}"), - ) - })?; - Ok(self.uri(&relative)) - } - - // ---- catalog payloads ---- - - /// Content-addressed catalog location for a query/policy payload - /// (extensions fixed per kind, same as the pre-port layout). - pub(crate) fn payload_relative(kind: &ResourceKind, digest: &str) -> Option { - match kind { - ResourceKind::Query { graph, name } => Some(format!( - "{CLUSTER_RESOURCES_DIR}/query/{graph}/{name}/{digest}.gq" - )), - ResourceKind::Policy(name) => Some(format!( - "{CLUSTER_RESOURCES_DIR}/policy/{name}/{digest}.yaml" - )), - _ => None, - } - } - - pub(crate) fn payload_display(&self, kind: &ResourceKind, digest: &str) -> Option { - Self::payload_relative(kind, digest).map(|relative| self.display(&relative)) - } - - pub(crate) async fn payload_exists(&self, kind: &ResourceKind, digest: &str) -> bool { - let Some(relative) = Self::payload_relative(kind, digest) else { - return false; - }; - self.adapter - .exists(&self.uri(&relative)) - .await - .unwrap_or(false) - } - - /// Raw payload read: `Ok(None)` for a missing blob, `Err` for transport - /// failures β€” callers classify (verify loops need the three-way split). - pub(crate) async fn read_payload( - &self, - kind: &ResourceKind, - digest: &str, - ) -> Result, String> { - let Some(relative) = Self::payload_relative(kind, digest) else { - return Ok(None); - }; - let uri = self.uri(&relative); - match self.adapter.exists(&uri).await { - Ok(false) => return Ok(None), - Ok(true) => {} - Err(err) => return Err(err.to_string()), - } - self.adapter - .read_text(&uri) - .await - .map(Some) - .map_err(|err| { - format!( - "could not read catalog payload '{}': {err}", - self.display(&relative) - ) - }) - } - - /// Idempotent content-addressed write: a payload already present at its - /// digest is by definition identical. - pub(crate) async fn write_payload( - &self, - kind: &ResourceKind, - digest: &str, - content: &str, - ) -> Result<(), String> { - let Some(relative) = Self::payload_relative(kind, digest) else { - return Err("resource kind has no payload".to_string()); - }; - if self - .adapter - .exists(&self.uri(&relative)) - .await - .map_err(|err| err.to_string())? - { - return Ok(()); - } - self.put_json(&relative, content).await - } - - /// Read a catalog payload and verify it against its recorded digest. - pub(crate) async fn read_verified_payload( - &self, - kind: &ResourceKind, - digest: &str, - address: &str, - ) -> Result { - let Some(relative) = Self::payload_relative(kind, digest) else { - return Err(Diagnostic::error( - "catalog_payload_missing", - address, - "resource kind has no payload", - )); - }; - let uri = self.uri(&relative); - let text = self.adapter.read_text(&uri).await.map_err(|err| { - Diagnostic::error( - "catalog_payload_missing", - address, - format!( - "catalog blob '{}' unreadable ({err}); run `cluster refresh` then `cluster apply`, and restart", - self.display(&relative) - ), - ) - })?; - if sha256_hex(text.as_bytes()) != digest { - return Err(Diagnostic::error( - "catalog_payload_digest_mismatch", - address, - format!( - "catalog blob '{}' does not match its recorded digest; run `cluster refresh` then `cluster apply`, and restart", - self.display(&relative) - ), - )); - } - Ok(text) - } - - // ---- observations ---- - - pub(crate) fn observations(&self) -> StateObservations { - StateObservations { - state_path: self.display(CLUSTER_STATE_FILE), - lock_path: self.display(CLUSTER_LOCK_FILE), - state_found: false, - applied_config_digest: None, - state_revision: 0, - state_cas: None, - resource_count: 0, - locked: false, - lock_id: None, - lock_acquired: false, - acquired_lock_id: None, - lock_operation: None, - lock_created_at: None, - lock_pid: None, - lock_age_seconds: None, - } - } - - // ---- state ledger ---- - - pub(crate) async fn read_state( - &self, - observations: &mut StateObservations, - ) -> Result { - let state_uri = self.uri(CLUSTER_STATE_FILE); - let (text, _version) = match self.read_versioned_opt(&state_uri).await { - Ok(Some(read)) => read, - Ok(None) => { - return Ok(StateSnapshot { - state: None, - state_cas: None, - }); - } - Err(err) => { - return Err(Diagnostic::error( - "state_read_error", - CLUSTER_STATE_FILE, - format!("could not read state file: {err}"), - )); - } - }; - - observations.state_found = true; - let state_cas = format!("sha256:{}", sha256_hex(text.as_bytes())); - observations.state_cas = Some(state_cas.clone()); - - let state = serde_json::from_str::(&text).map_err(|err| { - Diagnostic::error( - "invalid_state_json", - CLUSTER_STATE_FILE, - format!("could not parse state JSON: {err}"), - ) - })?; - - if state.version != 1 { - return Err(Diagnostic::error( - "unsupported_state_version", - "state.version", - format!( - "unsupported cluster state version {}; this build supports version 1", - state.version - ), - )); - } - - observations.applied_config_digest = state.applied_revision.config_digest.clone(); - observations.state_revision = state.state_revision; - observations.resource_count = state.applied_revision.resources.len(); - - Ok(StateSnapshot { - state: Some(state), - state_cas: Some(state_cas), - }) - } - - /// CAS-guarded ledger replace. The public contract stays content-level - /// (`expected_cas` = `sha256:` from the snapshot the command read); - /// the physical swap is token-conditioned on a fresh read, so a writer - /// that raced us between the fresh read and the put loses with - /// `state_cas_mismatch` β€” never a silent overwrite. On S3 the token is - /// the object's ETag and the put is conditional (If-Match); locally it - /// is a content token over the same temp+rename flow as before the port. - pub(crate) async fn write_state( - &self, - state: &ClusterState, - expected_cas: Option<&str>, - observations: &mut StateObservations, - ) -> Result<(), Diagnostic> { - let state_uri = self.uri(CLUSTER_STATE_FILE); - let current = self.read_versioned_opt(&state_uri).await.map_err(|err| { - Diagnostic::error( - "state_write_error", - CLUSTER_STATE_FILE, - format!("could not read state file before write: {err}"), - ) - })?; - let current_cas = current - .as_ref() - .map(|(text, _)| format!("sha256:{}", sha256_hex(text.as_bytes()))); - if current_cas.as_deref() != expected_cas { - return Err(state_cas_mismatch()); - } - - let mut payload = serde_json::to_string_pretty(state).map_err(|err| { - Diagnostic::error( - "state_write_error", - CLUSTER_STATE_FILE, - format!("could not encode state JSON: {err}"), - ) - })?; - payload.push('\n'); - - let written = match current { - None => self - .adapter - .write_text_if_absent(&state_uri, &payload) - .await - .map_err(|err| { - Diagnostic::error( - "state_write_error", - CLUSTER_STATE_FILE, - format!("could not create state.json: {err}"), - ) - })?, - Some((_, version)) => self - .adapter - .write_text_if_match(&state_uri, &payload, &version) - .await - .map_err(|err| { - Diagnostic::error( - "state_write_error", - CLUSTER_STATE_FILE, - format!("could not replace state.json: {err}"), - ) - })? - .is_some(), - }; - if !written { - return Err(state_cas_mismatch()); - } - - observations.state_found = true; - observations.applied_config_digest = state.applied_revision.config_digest.clone(); - observations.state_revision = state.state_revision; - observations.state_cas = Some(format!("sha256:{}", sha256_hex(payload.as_bytes()))); - observations.resource_count = state.applied_revision.resources.len(); - Ok(()) - } - - // ---- lock ---- - - pub(crate) async fn acquire_lock( - &self, - operation: &str, - observations: &mut StateObservations, - ) -> Result { - let lock_uri = self.uri(CLUSTER_LOCK_FILE); - let lock_id = Ulid::new().to_string(); - let lock = StateLockFile { - version: 1, - lock_id: lock_id.clone(), - operation: operation.to_string(), - created_at: OffsetDateTime::now_utc() - .format(&Rfc3339) - .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string()), - pid: process::id(), - }; - let payload = serde_json::to_string_pretty(&lock).map_err(|err| { - Diagnostic::error( - "state_lock_error", - CLUSTER_LOCK_FILE, - format!("could not encode state lock: {err}"), - ) - })?; - - match self.adapter.write_text_if_absent(&lock_uri, &payload).await { - Ok(true) => { - observations.lock_acquired = true; - observations.acquired_lock_id = Some(lock_id); - Ok(StateLockGuard { - adapter: Arc::clone(&self.adapter), - uri: lock_uri, - kind: self.kind(), - }) - } - Ok(false) => { - self.observe_lock_metadata_lossy(observations).await; - Err(Diagnostic::error( - "state_lock_held", - CLUSTER_LOCK_FILE, - state_lock_held_message(observations), - )) - } - Err(err) => Err(Diagnostic::error( - "state_lock_error", - CLUSTER_LOCK_FILE, - format!("could not write state lock: {err}"), - )), - } - } - - pub(crate) async fn force_unlock( - &self, - lock_id: &str, - observations: &mut StateObservations, - ) -> Result<(), Diagnostic> { - let lock_uri = self.uri(CLUSTER_LOCK_FILE); - let text = match self.read_versioned_opt(&lock_uri).await { - Ok(Some((text, _))) => text, - Ok(None) => { - return Err(Diagnostic::error( - "state_lock_missing", - CLUSTER_LOCK_FILE, - "no cluster state lock is present", - )); - } - Err(err) => { - return Err(Diagnostic::error( - "state_lock_read_error", - CLUSTER_LOCK_FILE, - format!("could not read state lock: {err}"), - )); - } - }; - let lock = parse_lock_file_for_unlock(&text)?; - observations.observe_lock_metadata(&lock); - observations.locked = true; - if lock.lock_id != lock_id { - return Err(Diagnostic::error( - "state_lock_id_mismatch", - CLUSTER_LOCK_FILE, - format!( - "lock id mismatch: held lock is {}, refusing to remove (pass the exact id from `cluster status`)", - lock.lock_id - ), - )); - } - self.adapter.delete(&lock_uri).await.map_err(|err| { - Diagnostic::error( - "state_lock_error", - CLUSTER_LOCK_FILE, - format!("could not remove state lock: {err}"), - ) - })?; - observations.locked = false; - Ok(()) - } - - pub(crate) async fn observe_lock( - &self, - observations: &mut StateObservations, - diagnostics: &mut Vec, - ) { - let lock_uri = self.uri(CLUSTER_LOCK_FILE); - match self.read_versioned_opt(&lock_uri).await { - Ok(Some((text, _))) => { - observations.locked = true; - match serde_json::from_str::(&text) { - Ok(lock) if lock.version == 1 => observations.observe_lock_metadata(&lock), - Ok(lock) => diagnostics.push(Diagnostic::warning( - "unsupported_state_lock_version", - CLUSTER_LOCK_FILE, - format!("unsupported cluster state lock version {}", lock.version), - )), - Err(err) => diagnostics.push(Diagnostic::warning( - "invalid_state_lock", - CLUSTER_LOCK_FILE, - format!("could not parse state lock: {err}"), - )), - } - } - Ok(None) => {} - Err(err) => diagnostics.push(Diagnostic::warning( - "state_lock_read_error", - CLUSTER_LOCK_FILE, - format!("could not read state lock: {err}"), - )), - } - } - - pub(crate) async fn observe_lock_metadata_lossy( - &self, - observations: &mut StateObservations, - ) { - observations.locked = true; - let lock_uri = self.uri(CLUSTER_LOCK_FILE); - if let Ok(Some((text, _))) = self.read_versioned_opt(&lock_uri).await { - if let Ok(lock) = serde_json::from_str::(&text) { - if lock.version == 1 { - observations.observe_lock_metadata(&lock); - } - } - } - } -} - -fn state_cas_mismatch() -> Diagnostic { - Diagnostic::error( - "state_cas_mismatch", - CLUSTER_STATE_FILE, - "state.json changed while the command was running; re-run the command against the latest state", - ) -} - -pub(crate) fn parse_lock_file_for_unlock(text: &str) -> Result { - let lock = serde_json::from_str::(text).map_err(|err| { - Diagnostic::error( - "invalid_state_lock", - CLUSTER_LOCK_FILE, - format!("could not parse state lock: {err}"), - ) - })?; - if lock.version != 1 { - return Err(Diagnostic::error( - "unsupported_state_lock_version", - CLUSTER_LOCK_FILE, - format!("unsupported cluster state lock version {}", lock.version), - )); - } - Ok(lock) -} - -pub(crate) fn state_lock_held_message(observations: &StateObservations) -> String { - match observations.lock_id.as_deref() { - Some(lock_id) => format!( - "cluster state lock already exists (lock id {lock_id}); run `omnigraph cluster force-unlock {lock_id}` only after confirming no cluster operation is active" - ), - None => "cluster state lock already exists; remove it only after confirming no cluster operation is active".to_string(), - } -} diff --git a/crates/omnigraph-cluster/src/sweep.rs b/crates/omnigraph-cluster/src/sweep.rs deleted file mode 100644 index 7aecb01..0000000 --- a/crates/omnigraph-cluster/src/sweep.rs +++ /dev/null @@ -1,388 +0,0 @@ -//! The recovery sweep: RFC-004's roll-forward-only sidecar -//! classification (moved verbatim from lib.rs in the modularization). - -use super::*; - -/// Recovery sweep (RFC-004 Β§D3): runs at the start of every state-mutating -/// cluster command, under the state lock, before the command's own work. -/// Roll-forward-only β€” the engine's own sidecars make each graph-level -/// operation atomic within the graph, so the cluster never rolls a graph -/// back; it converges the ledger to observable reality or refuses loudly. -/// Mutations ride the calling command's CAS-checked state write; completed -/// sidecars are deleted only after that write lands. -pub(crate) async fn sweep_recovery_sidecars( - backend: &ClusterStore, - state: &mut ClusterState, - diagnostics: &mut Vec, -) -> SweepOutcome { - let mut outcome = SweepOutcome::default(); - for (path, sidecar) in backend.list_recovery_sidecars(diagnostics).await { - match sidecar.kind { - RecoverySidecarKind::GraphCreate => { - sweep_graph_create_sidecar(backend, path, sidecar, state, diagnostics, &mut outcome).await; - } - RecoverySidecarKind::SchemaApply => { - sweep_schema_apply_sidecar(path, sidecar, state, diagnostics, &mut outcome).await; - } - RecoverySidecarKind::GraphDelete => { - sweep_graph_delete_sidecar(backend, path, sidecar, state, diagnostics, &mut outcome).await; - } - } - } - outcome -} - -pub(crate) async fn sweep_graph_create_sidecar( - backend: &ClusterStore, - path: String, - sidecar: RecoverySidecar, - state: &mut ClusterState, - diagnostics: &mut Vec, - outcome: &mut SweepOutcome, -) { - let graph_address = graph_address(&sidecar.graph_id); - let schema_addr = schema_address(&sidecar.graph_id); - - // Row 1: nothing moved β€” the init never landed. The sidecar is pure - // intent; retire it (deferred to the command's post-CAS cleanup, like - // every other completed sidecar β€” a failed CAS simply re-sweeps it) and - // let the command's own plan re-propose the create. - if !backend.graph_root_exists(&sidecar.graph_uri).await { - outcome.completed_sidecars.push(path); - return; - } - - match Omnigraph::open_read_only(&sidecar.graph_uri).await { - Ok(db) => { - let live_digest = sha256_hex(db.schema_source().as_bytes()); - let recorded = state - .applied_revision - .resources - .get(&schema_addr) - .map(|resource| resource.digest.clone()); - if recorded.as_deref() == Some(live_digest.as_str()) { - // Row 2: crash fell between the state CAS and sidecar delete. - outcome.completed_sidecars.push(path); - } else if live_digest == sidecar.desired_schema_digest { - // Row 4: the create completed on the graph; roll the cluster - // state forward to observable reality. - state.applied_revision.resources.insert( - schema_addr.clone(), - StateResource { - digest: live_digest.clone(), - applies_to: None, - }, - ); - let query_digests = state_query_digests_for_graph(state, &sidecar.graph_id); - let composite = - graph_digest(&sidecar.graph_id, Some(&live_digest), Some(&query_digests)); - state - .applied_revision - .resources - .insert(graph_address.clone(), StateResource { digest: composite, applies_to: None }); - set_resource_status_applied(state, &graph_address); - set_resource_status_applied(state, &schema_addr); - state.recovery_records.insert( - sidecar.operation_id.clone(), - json!({ - "kind": "graph_create", - "graph_id": sidecar.graph_id, - "outcome": "rolled_forward", - "recovered_at": now_rfc3339(), - "actor": sidecar.actor, - }), - ); - diagnostics.push(Diagnostic::warning( - "cluster_recovery_rolled_forward", - graph_address.clone(), - "an interrupted graph create had completed on the graph; cluster state was rolled forward to match", - )); - outcome.completed_sidecars.push(path); - } else { - // Row 6: the graph moved to something the sidecar did not - // intend. Refuse to guess; require refresh + operator re-plan. - set_resource_status( - state, - &graph_address, - ResourceLifecycleStatus::Drifted, - "actual_applied_state_pending", - "graph state does not match the interrupted operation; run `cluster refresh` and re-plan", - ); - set_resource_status( - state, - &schema_addr, - ResourceLifecycleStatus::Drifted, - "actual_applied_state_pending", - "graph state does not match the interrupted operation; run `cluster refresh` and re-plan", - ); - diagnostics.push(Diagnostic::warning( - "cluster_recovery_pending", - graph_address.clone(), - "an interrupted graph create left unexpected graph state; graph-moving work is blocked until repaired", - )); - outcome.pending_graphs.insert(sidecar.graph_id.clone()); - } - } - Err(err) => { - // Row 5: partial root (the engine's documented init gap). Never - // auto-delete β€” reconciler deletes are the same data-loss class - // as human deletes; the operator removes the root explicitly. - set_resource_status( - state, - &graph_address, - ResourceLifecycleStatus::Error, - "graph_create_incomplete", - "graph root exists but cannot be opened; remove the graph root and re-run `cluster apply`", - ); - set_resource_status( - state, - &schema_addr, - ResourceLifecycleStatus::Error, - "graph_create_incomplete", - "graph root exists but cannot be opened; remove the graph root and re-run `cluster apply`", - ); - diagnostics.push(Diagnostic::error( - "graph_create_incomplete", - graph_address.clone(), - format!( - "graph root '{}' exists but cannot be opened ({err}); remove the graph root and re-run `cluster apply`", - sidecar.graph_uri - ), - )); - outcome.pending_graphs.insert(sidecar.graph_id.clone()); - } - } -} - -pub(crate) async fn sweep_schema_apply_sidecar( - path: String, - sidecar: RecoverySidecar, - state: &mut ClusterState, - diagnostics: &mut Vec, - outcome: &mut SweepOutcome, -) { - let graph_address = graph_address(&sidecar.graph_id); - let schema_addr = schema_address(&sidecar.graph_id); - - // Digest-based classification: robust to unrelated manifest movement; - // the sidecar's version pins stay forensic. - let live_digest = match Omnigraph::open_read_only(&sidecar.graph_uri).await { - Ok(db) => sha256_hex(db.schema_source().as_bytes()), - Err(err) => { - // Cannot verify the interrupted operation β€” refuse to guess. - diagnostics.push(Diagnostic::warning( - "cluster_recovery_pending", - graph_address.clone(), - format!( - "an interrupted schema apply cannot be verified (graph '{}' did not open: {err}); graph-moving work is blocked until repaired", - sidecar.graph_uri - ), - )); - outcome.pending_graphs.insert(sidecar.graph_id.clone()); - return; - } - }; - - let recorded = state - .applied_revision - .resources - .get(&schema_addr) - .map(|resource| resource.digest.clone()); - if recorded.as_deref() == Some(live_digest.as_str()) { - // Ledger consistent with the live graph (the apply never landed, or - // landed and was recorded): the sidecar is stale intent β€” retire it. - outcome.completed_sidecars.push(path); - } else if live_digest == sidecar.desired_schema_digest { - // RFC-004 Β§D3 row 3: the schema apply completed on the graph; roll - // the cluster state forward to observable reality. - state.applied_revision.resources.insert( - schema_addr.clone(), - StateResource { - digest: live_digest.clone(), - applies_to: None, - }, - ); - let query_digests = state_query_digests_for_graph(state, &sidecar.graph_id); - let composite = graph_digest(&sidecar.graph_id, Some(&live_digest), Some(&query_digests)); - state - .applied_revision - .resources - .insert(graph_address.clone(), StateResource { digest: composite, applies_to: None }); - set_resource_status_applied(state, &graph_address); - set_resource_status_applied(state, &schema_addr); - state.recovery_records.insert( - sidecar.operation_id.clone(), - json!({ - "kind": "schema_apply", - "graph_id": sidecar.graph_id, - "outcome": "rolled_forward", - "recovered_at": now_rfc3339(), - "actor": sidecar.actor, - }), - ); - diagnostics.push(Diagnostic::warning( - "cluster_recovery_rolled_forward", - graph_address.clone(), - "an interrupted schema apply had completed on the graph; cluster state was rolled forward to match", - )); - outcome.completed_sidecars.push(path); - } else { - // Row 6: live schema is neither the recorded nor the desired digest. - set_resource_status( - state, - &graph_address, - ResourceLifecycleStatus::Drifted, - "actual_applied_state_pending", - "graph state does not match the interrupted operation; run `cluster refresh` and re-plan", - ); - set_resource_status( - state, - &schema_addr, - ResourceLifecycleStatus::Drifted, - "actual_applied_state_pending", - "graph state does not match the interrupted operation; run `cluster refresh` and re-plan", - ); - diagnostics.push(Diagnostic::warning( - "cluster_recovery_pending", - graph_address.clone(), - "an interrupted schema apply left unexpected graph state; graph-moving work is blocked until repaired", - )); - outcome.pending_graphs.insert(sidecar.graph_id.clone()); - } -} - -pub(crate) async fn sweep_graph_delete_sidecar( - backend: &ClusterStore, - path: String, - sidecar: RecoverySidecar, - state: &mut ClusterState, - diagnostics: &mut Vec, - outcome: &mut SweepOutcome, -) { - let graph_address = graph_address(&sidecar.graph_id); - - if backend.graph_root_exists(&sidecar.graph_uri).await { - // Row 8: the delete never completed. Prefix removal is idempotent and - // works on partial roots, so the repair is simply the re-proposed, - // still-approved delete on a later run β€” retire the stale intent. - diagnostics.push(Diagnostic::warning( - "graph_delete_incomplete", - graph_address, - "a previous graph delete did not complete; it will be re-proposed by plan and can be retried under its approval", - )); - outcome.completed_sidecars.push(path); - return; - } - - if !state.applied_revision.resources.contains_key(&graph_address) { - // Row 7: already tombstoned (or never recorded); crash fell between - // the state CAS and sidecar delete. - outcome.completed_sidecars.push(path); - return; - } - - // Row 7b: the root is gone, the ledger is stale β€” roll forward the - // tombstone, consume the approval the sidecar carries, audit. - tombstone_graph_subtree(state, &sidecar.graph_id, sidecar.approval_id.as_deref(), sidecar.actor.as_deref()); - state.recovery_records.insert( - sidecar.operation_id.clone(), - json!({ - "kind": "graph_delete", - "graph_id": sidecar.graph_id, - "outcome": "rolled_forward", - "recovered_at": now_rfc3339(), - "actor": sidecar.actor, - }), - ); - if let Some(approval_id) = &sidecar.approval_id { - record_approval_consumed(state, approval_id, &sidecar.operation_id); - outcome.consumed_approvals.push(approval_id.clone()); - } - diagnostics.push(Diagnostic::warning( - "cluster_recovery_rolled_forward", - graph_address, - "an interrupted graph delete had completed on disk; cluster state was rolled forward to match", - )); - outcome.completed_sidecars.push(path); -} - -/// Remove a graph's subtree (graph, schema, queries) from the ledger and -/// leave a tombstone observation. Idempotent. -pub(crate) fn tombstone_graph_subtree( - state: &mut ClusterState, - graph_id: &str, - approval_id: Option<&str>, - actor: Option<&str>, -) { - let graph_addr = graph_address(graph_id); - let schema_addr = schema_address(graph_id); - let query_prefix = format!("query.{graph_id}."); - state.applied_revision.resources.remove(&graph_addr); - state.applied_revision.resources.remove(&schema_addr); - state - .applied_revision - .resources - .retain(|address, _| !address.starts_with(&query_prefix)); - state.resource_statuses.remove(&graph_addr); - state.resource_statuses.remove(&schema_addr); - state - .resource_statuses - .retain(|address, _| !address.starts_with(&query_prefix)); - state.observations.insert( - graph_addr, - json!({ - "kind": "tombstone", - "deleted_at": now_rfc3339(), - "approval_id": approval_id, - "actor": actor, - }), - ); -} - -/// Record approval consumption in the state ledger. The artifact FILE is -/// rewritten with consumed_at only after the state write lands, so a failed -/// CAS leaves the approval valid for the retry. -pub(crate) fn record_approval_consumed(state: &mut ClusterState, approval_id: &str, operation_id: &str) { - state.approval_records.insert( - approval_id.to_string(), - json!({ - "consumed_at": now_rfc3339(), - "consumed_by_operation": operation_id, - }), - ); -} - -/// Mark approval artifact files consumed on disk (post-CAS). -pub(crate) async fn mark_approvals_consumed(backend: &ClusterStore, approval_ids: &[String]) { - if approval_ids.is_empty() { - return; - } - let mut sink = Vec::new(); - for (_, mut artifact) in backend.list_approval_artifacts(&mut sink).await { - if approval_ids.contains(&artifact.approval_id) && artifact.consumed_at.is_none() { - artifact.consumed_at = Some(now_rfc3339()); - let _ = backend.write_approval_artifact(&artifact).await; - } - } -} - -/// Read-only commands report pending sidecars without acting on them. -pub(crate) fn warn_pending_recovery_sidecars(config_dir: &Path, diagnostics: &mut Vec) { - let recoveries_dir = config_dir.join(CLUSTER_RECOVERIES_DIR); - let Ok(entries) = fs::read_dir(&recoveries_dir) else { - return; - }; - let mut names: Vec = entries - .flatten() - .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "json")) - .map(|entry| entry.file_name().to_string_lossy().into_owned()) - .collect(); - names.sort(); - for name in names { - diagnostics.push(Diagnostic::warning( - "cluster_recovery_pending", - format!("{CLUSTER_RECOVERIES_DIR}/{name}"), - "a recovery sidecar from an interrupted apply is pending; the next state-mutating command will classify it", - )); - } -} diff --git a/crates/omnigraph-cluster/src/tests.rs b/crates/omnigraph-cluster/src/tests.rs deleted file mode 100644 index 63e7da7..0000000 --- a/crates/omnigraph-cluster/src/tests.rs +++ /dev/null @@ -1,3085 +0,0 @@ -//! In-source test suite, moved verbatim from lib.rs (modularization). -//! Indentation is preserved exactly β€” embedded raw-string fixtures -//! (cluster.yaml/JSON bodies) are content, not formatting. -#![allow(clippy::all)] - - use std::fs; - use std::path::Path; - - use omnigraph::db::Omnigraph; - use serde_json::json; - use tempfile::tempdir; - - use super::*; - - const SCHEMA: &str = r#" -node Person { - name: String @key - age: I32? -} -"#; - - const QUERY: &str = r#" -query find_person($name: String) { - match { $p: Person { name: $name } } - return { $p.name, $p.age } -} -"#; - - fn fixture() -> tempfile::TempDir { - let dir = tempdir().unwrap(); - fs::write(dir.path().join("people.pg"), SCHEMA).unwrap(); - fs::write(dir.path().join("people.gq"), QUERY).unwrap(); - fs::write(dir.path().join("base.policy.yaml"), "rules: []\n").unwrap(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -metadata: - name: test -state: - backend: cluster - lock: true -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -policies: - base: - file: ./base.policy.yaml - applies_to: [knowledge] -"#, - ) - .unwrap(); - dir - } - - async fn init_derived_graph(root: &Path) { - let graph_dir = root.join(CLUSTER_GRAPHS_DIR); - fs::create_dir_all(&graph_dir).unwrap(); - let graph = graph_dir.join("knowledge.omni"); - Omnigraph::init(graph.to_string_lossy().as_ref(), SCHEMA) - .await - .unwrap(); - } - - fn write_lock_file(config_dir: &Path, lock_id: &str, operation: &str) { - let state_dir = config_dir.join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("lock.json"), - json!({ - "version": 1, - "lock_id": lock_id, - "operation": operation, - "created_at": "1970-01-01T00:00:00Z", - "pid": 123 - }) - .to_string(), - ) - .unwrap(); - } - - #[test] - fn valid_minimal_config() { - let dir = fixture(); - let out = validate_config_dir(dir.path()); - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.resource_digests.contains_key("graph.knowledge")); - assert!(out.resource_digests.contains_key("schema.knowledge")); - assert!( - out.dependencies - .iter() - .any(|dep| dep.from == "policy.base" && dep.to == "graph.knowledge") - ); - } - - #[test] - fn unknown_field_rejection() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - "version: 1\ngraphs: {}\nwat: true\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert!(out.diagnostics[0].message.contains("unknown field")); - } - - #[test] - fn future_phase_field_rejection() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - "version: 1\ngraphs: {}\npipelines: {}\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert_eq!(out.diagnostics[0].code, "future_phase_field"); - } - - #[test] - fn duplicate_yaml_key_rejection() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - "version: 1\ngraphs: {}\ngraphs: {}\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert_eq!(out.diagnostics[0].code, "duplicate_yaml_key"); - } - - #[test] - fn duplicate_yaml_key_rejection_keeps_quoted_hashes() { - let diagnostics = - duplicate_key_diagnostics("\"name#display\": one\n\"name#display\": two\n"); - assert_eq!(diagnostics.len(), 1); - assert_eq!(diagnostics[0].code, "duplicate_yaml_key"); - } - - #[test] - fn missing_schema_query_and_policy_files() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -graphs: - knowledge: - schema: ./missing.pg - queries: - find_person: { file: ./missing.gq } -policies: - base: - file: ./missing.policy.yaml - applies_to: [knowledge] -"#, - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - let codes: BTreeSet<_> = out.diagnostics.iter().map(|d| d.code.as_str()).collect(); - assert!(codes.contains("schema_file_missing")); - assert!(codes.contains("query_file_missing")); - assert!(codes.contains("policy_file_missing")); - } - - #[test] - fn wrong_kind_and_dangling_refs_fail() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -graphs: - knowledge: - schema: ./people.pg -policies: - base: - file: ./base.policy.yaml - applies_to: [query.knowledge.find_person, missing] -"#, - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - let codes: BTreeSet<_> = out.diagnostics.iter().map(|d| d.code.as_str()).collect(); - assert!(codes.contains("wrong_kind_reference")); - assert!(codes.contains("dangling_graph_reference")); - } - - #[test] - fn query_key_mismatch_fails() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -graphs: - knowledge: - schema: ./people.pg - queries: - different: { file: ./people.gq } -"#, - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert_eq!(out.diagnostics[0].code, "query_key_mismatch"); - } - - #[test] - fn query_typecheck_failure_fails() { - let dir = fixture(); - fs::write( - dir.path().join("people.gq"), - "query find_person() { match { $d: DoesNotExist } return { $d.name } }\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "query_typecheck_error") - ); - } - - #[tokio::test] - async fn missing_state_plans_creates() { - let dir = fixture(); - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(!out.state_observations.state_found); - assert!(!out.state_observations.locked); - assert!(out.state_observations.lock_acquired); - assert!( - out.changes - .iter() - .all(|c| c.operation == PlanOperation::Create) - ); - assert!(out.changes.iter().any(|c| c.resource == "graph.knowledge")); - assert!(!dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn config_digest_ignores_yaml_comments_and_formatting() { - let dir = fixture(); - let first = plan_config_dir(dir.path()).await; - assert!(first.ok, "{:?}", first.diagnostics); - - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -# Same semantic config as the fixture, intentionally rendered differently. -version: 1 -metadata: { name: test } -state: { backend: cluster, lock: true } -graphs: - knowledge: - schema: ./people.pg - queries: { find_person: { file: ./people.gq } } -policies: - base: - file: ./base.policy.yaml - applies_to: - - knowledge -"#, - ) - .unwrap(); - - let second = plan_config_dir(dir.path()).await; - assert!(second.ok, "{:?}", second.diagnostics); - assert_eq!( - first.desired_revision.config_digest, - second.desired_revision.config_digest - ); - } - - #[tokio::test] - async fn existing_state_plans_update_and_delete_deterministically() { - let dir = fixture(); - let first = plan_config_dir(dir.path()).await; - let state_dir = dir.path().join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - serde_json::to_string_pretty(&json!({ - "version": 1, - "applied_revision": { - "config_digest": "old", - "resources": { - "graph.knowledge": { "digest": first.resource_digests["graph.knowledge"] }, - "policy.old": { "digest": "abc" }, - "schema.knowledge": { "digest": "old-schema" } - } - } - })) - .unwrap(), - ) - .unwrap(); - - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - let rendered: Vec<_> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), &change.operation)) - .collect(); - assert_eq!( - rendered, - vec![ - ("policy.base", &PlanOperation::Create), - ("policy.old", &PlanOperation::Delete), - ("query.knowledge.find_person", &PlanOperation::Create), - ("schema.knowledge", &PlanOperation::Update), - ] - ); - } - - #[tokio::test] - async fn old_minimal_state_json_still_plans_with_default_revision() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{ - "version": 1, - "applied_revision": { - "config_digest": "old", - "resources": { - "graph.knowledge": { "digest": "old-graph" } - } - } -}"#, - ) - .unwrap(); - - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!(out.state_observations.state_revision, 0); - assert!(out.state_observations.state_cas.is_some()); - assert!(out.changes.iter().any(|change| { - change.resource == "graph.knowledge" && change.operation == PlanOperation::Update - })); - } - - #[tokio::test] - async fn extended_state_json_status_surfaces_statuses() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - let state = r#"{ - "version": 1, - "state_revision": 42, - "applied_revision": { - "config_digest": "applied-config", - "resources": { - "graph.knowledge": { "digest": "graph-digest" } - } - }, - "resource_statuses": { - "graph.knowledge": { - "status": "applied", - "conditions": ["healthy"], - "message": "ready" - } - }, - "approval_records": {}, - "recovery_records": {}, - "observations": { - "graph.knowledge": { "manifest_version": 12 } - } -}"#; - fs::write(state_dir.join("state.json"), state).unwrap(); - - let out = status_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.state_observations.state_found); - assert_eq!(out.state_observations.state_revision, 42); - assert_eq!( - out.state_observations.state_cas.as_deref(), - Some(format!("sha256:{}", sha256_hex(state.as_bytes())).as_str()) - ); - assert_eq!( - out.resource_digests - .get("graph.knowledge") - .map(String::as_str), - Some("graph-digest") - ); - assert_eq!( - out.resource_statuses["graph.knowledge"].status, - ResourceLifecycleStatus::Applied - ); - } - - #[tokio::test] - async fn missing_state_status_succeeds_with_warning() { - let dir = fixture(); - let out = status_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(!out.state_observations.state_found); - assert_eq!(out.state_observations.state_revision, 0); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_missing") - ); - } - - #[tokio::test] - async fn invalid_state_status_fails() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write(state_dir.join("state.json"), "{").unwrap(); - - let out = status_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(out.state_observations.state_found); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "invalid_state_json") - ); - } - - #[tokio::test] - async fn status_surfaces_full_lock_metadata() { - let dir = fixture(); - write_lock_file(dir.path(), "held-lock", "refresh"); - - let out = status_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.state_observations.locked); - assert_eq!(out.state_observations.lock_id.as_deref(), Some("held-lock")); - assert_eq!( - out.state_observations.lock_operation.as_deref(), - Some("refresh") - ); - assert_eq!( - out.state_observations.lock_created_at.as_deref(), - Some("1970-01-01T00:00:00Z") - ); - assert_eq!(out.state_observations.lock_pid, Some(123)); - assert!(out.state_observations.lock_age_seconds.is_some()); - } - - #[tokio::test] - async fn force_unlock_matching_id_removes_lock() { - let dir = fixture(); - write_lock_file(dir.path(), "held-lock", "plan"); - - let out = force_unlock_config_dir(dir.path(), "held-lock").await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.lock_removed); - assert_eq!(out.state_observations.lock_id.as_deref(), Some("held-lock")); - assert_eq!( - out.state_observations.lock_operation.as_deref(), - Some("plan") - ); - assert!(!dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn force_unlock_wrong_id_fails_and_preserves_lock() { - let dir = fixture(); - write_lock_file(dir.path(), "held-lock", "plan"); - - let out = force_unlock_config_dir(dir.path(), "other-lock").await; - assert!(!out.ok); - assert!(!out.lock_removed); - assert_eq!(out.state_observations.lock_id.as_deref(), Some("held-lock")); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_id_mismatch") - ); - assert!(dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn force_unlock_missing_lock_fails() { - let dir = fixture(); - - let out = force_unlock_config_dir(dir.path(), "held-lock").await; - assert!(!out.ok); - assert!(!out.lock_removed); - assert!(!out.state_observations.locked); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_missing") - ); - } - - #[tokio::test] - async fn force_unlock_invalid_lock_json_fails_and_preserves_lock() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write(state_dir.join("lock.json"), "{").unwrap(); - - let out = force_unlock_config_dir(dir.path(), "held-lock").await; - assert!(!out.ok); - assert!(!out.lock_removed); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "invalid_state_lock") - ); - assert!(dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn force_unlock_unsupported_lock_version_fails_and_preserves_lock() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("lock.json"), - r#"{"version":2,"lock_id":"held-lock","operation":"plan","created_at":"1970-01-01T00:00:00Z","pid":123}"#, - ) - .unwrap(); - - let out = force_unlock_config_dir(dir.path(), "held-lock").await; - assert!(!out.ok); - assert!(!out.lock_removed); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "unsupported_state_lock_version") - ); - assert!(dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn force_unlock_external_state_backend_rejected() { - let dir = fixture(); - write_lock_file(dir.path(), "held-lock", "plan"); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -state: - backend: s3://state-bucket/cluster -graphs: - knowledge: - schema: ./people.pg -"#, - ) - .unwrap(); - - let out = force_unlock_config_dir(dir.path(), "held-lock").await; - assert!(!out.ok); - assert!(!out.lock_removed); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "unsupported_state_backend") - ); - assert!(dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn plan_succeeds_after_force_unlock() { - let dir = fixture(); - write_lock_file(dir.path(), "held-lock", "plan"); - - let locked = plan_config_dir(dir.path()).await; - assert!(!locked.ok); - assert!( - locked - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_held") - ); - - let unlocked = force_unlock_config_dir(dir.path(), "held-lock").await; - assert!(unlocked.ok, "{:?}", unlocked.diagnostics); - - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - } - - #[tokio::test] - async fn plan_reports_state_cas_revision_and_removes_lock() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - let state = r#"{ - "version": 1, - "state_revision": 7, - "applied_revision": { - "config_digest": "old", - "resources": { - "graph.knowledge": { "digest": "old-graph" } - } - } -}"#; - fs::write(state_dir.join("state.json"), state).unwrap(); - - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!(out.state_observations.state_revision, 7); - assert_eq!( - out.state_observations.state_cas.as_deref(), - Some(format!("sha256:{}", sha256_hex(state.as_bytes())).as_str()) - ); - assert!(!out.state_observations.locked); - assert!(out.state_observations.lock_id.is_none()); - assert!(out.state_observations.lock_acquired); - assert!(out.state_observations.acquired_lock_id.is_some()); - assert!( - !dir.path().join(CLUSTER_LOCK_FILE).exists(), - "plan must release lock before returning" - ); - } - - #[tokio::test] - async fn existing_lock_makes_plan_fail() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("lock.json"), - r#"{ - "version": 1, - "lock_id": "held-lock", - "operation": "plan", - "created_at": "2026-06-08T00:00:00Z", - "pid": 123 -}"#, - ) - .unwrap(); - - let out = plan_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(out.state_observations.locked); - assert_eq!(out.state_observations.lock_id.as_deref(), Some("held-lock")); - assert!(!out.state_observations.lock_acquired); - assert!(out.state_observations.acquired_lock_id.is_none()); - assert_eq!( - out.state_observations.lock_operation.as_deref(), - Some("plan") - ); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_held") - ); - assert!(out.diagnostics.iter().any(|diagnostic| { - diagnostic.code == "state_lock_held" - && diagnostic.message.contains("force-unlock held-lock") - })); - } - - #[tokio::test] - async fn state_lock_false_bypasses_lock_with_warning() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -state: - backend: cluster - lock: false -graphs: - knowledge: - schema: ./people.pg -"#, - ) - .unwrap(); - - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(!out.state_observations.locked); - assert!(!out.state_observations.lock_acquired); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_disabled") - ); - assert!(!dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[test] - fn external_state_backend_rejected() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - "version: 1\nstate:\n backend: s3://bucket/state\ngraphs: {}\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert_eq!(out.diagnostics[0].code, "unsupported_state_backend"); - } - - #[tokio::test] - async fn external_state_backend_plan_rejected() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - "version: 1\nstate:\n backend: s3://bucket/state\ngraphs: {}\n", - ) - .unwrap(); - let out = plan_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "unsupported_state_backend") - ); - } - - #[tokio::test] - async fn import_missing_state_creates_state_with_graph_observation() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - - let out = import_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!(out.state_observations.state_revision, 1); - assert!(out.state_observations.state_cas.is_some()); - assert!(!out.state_observations.locked); - assert!(out.state_observations.lock_acquired); - assert!(out.state_observations.acquired_lock_id.is_some()); - assert!(!dir.path().join(CLUSTER_LOCK_FILE).exists()); - assert_eq!( - out.resource_digests - .get("schema.knowledge") - .map(String::as_str), - Some(sha256_hex(SCHEMA.as_bytes()).as_str()) - ); - assert!(out.observations["graph.knowledge"]["manifest_version"].is_number()); - assert_eq!( - out.observations["graph.knowledge"]["schema_matches_desired"], - true - ); - - let state: serde_json::Value = - serde_json::from_str(&fs::read_to_string(dir.path().join(CLUSTER_STATE_FILE)).unwrap()) - .unwrap(); - assert_eq!(state["state_revision"], 1); - assert_eq!( - state["resource_statuses"]["graph.knowledge"]["status"], - "applied" - ); - } - - #[tokio::test] - async fn import_existing_state_fails() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"applied_revision":{"resources":{}}}"#, - ) - .unwrap(); - - let out = import_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_already_exists") - ); - } - - #[tokio::test] - async fn refresh_missing_state_fails() { - let dir = fixture(); - let out = refresh_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_missing") - ); - } - - #[tokio::test] - async fn refresh_existing_minimal_state_increments_revision_and_updates_cas() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"applied_revision":{"config_digest":"old","resources":{"graph.knowledge":{"digest":"old"}}}}"#, - ) - .unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!(out.state_observations.state_revision, 1); - assert!(out.state_observations.state_cas.is_some()); - assert!(!out.state_observations.locked); - assert!(out.state_observations.lock_acquired); - assert_eq!( - out.resource_statuses["graph.knowledge"].status, - ResourceLifecycleStatus::Applied - ); - assert!(!dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn refresh_records_live_schema_digest_and_manifest_version() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"state_revision":4,"applied_revision":{"resources":{}}}"#, - ) - .unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!(out.state_observations.state_revision, 5); - assert_eq!( - out.observations["graph.knowledge"]["schema_digest"], - sha256_hex(SCHEMA.as_bytes()) - ); - assert!(out.observations["graph.knowledge"]["manifest_version"].is_u64()); - } - - #[tokio::test] - async fn missing_derived_graph_root_marks_drifted_and_plans_creates() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"applied_revision":{"resources":{"graph.knowledge":{"digest":"old-graph"},"schema.knowledge":{"digest":"old-schema"}}}}"#, - ) - .unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!( - out.resource_statuses["graph.knowledge"].status, - ResourceLifecycleStatus::Drifted - ); - assert!(!out.resource_digests.contains_key("graph.knowledge")); - assert_eq!(out.observations["graph.knowledge"]["exists"], false); - - let plan = plan_config_dir(dir.path()).await; - assert!(plan.ok, "{:?}", plan.diagnostics); - assert!(plan.changes.iter().any(|change| { - change.resource == "graph.knowledge" && change.operation == PlanOperation::Create - })); - assert!(plan.changes.iter().any(|change| { - change.resource == "schema.knowledge" && change.operation == PlanOperation::Create - })); - } - - #[tokio::test] - async fn live_schema_mismatch_marks_drifted_and_causes_plan_update() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - fs::write( - dir.path().join("people.pg"), - SCHEMA.replace("age: I32?", "age: I32?\n nickname: String?"), - ) - .unwrap(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"applied_revision":{"resources":{"graph.knowledge":{"digest":"old-graph"},"schema.knowledge":{"digest":"old-schema"}}}}"#, - ) - .unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!( - out.resource_statuses["schema.knowledge"].status, - ResourceLifecycleStatus::Drifted - ); - assert_eq!( - out.observations["graph.knowledge"]["schema_matches_desired"], - false - ); - - let plan = plan_config_dir(dir.path()).await; - assert!(plan.ok, "{:?}", plan.diagnostics); - assert!(plan.changes.iter().any(|change| { - change.resource == "schema.knowledge" && change.operation == PlanOperation::Update - })); - } - - #[tokio::test] - async fn existing_lock_makes_refresh_fail() { - let dir = fixture(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"applied_revision":{"resources":{}}}"#, - ) - .unwrap(); - fs::write( - state_dir.join("lock.json"), - r#"{"version":1,"lock_id":"held-lock","operation":"refresh","created_at":"2026-06-08T00:00:00Z","pid":123}"#, - ) - .unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(out.state_observations.locked); - assert_eq!(out.state_observations.lock_id.as_deref(), Some("held-lock")); - assert!(!out.state_observations.lock_acquired); - assert_eq!( - out.state_observations.lock_operation.as_deref(), - Some("refresh") - ); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_held") - ); - assert!(out.diagnostics.iter().any(|diagnostic| { - diagnostic.code == "state_lock_held" - && diagnostic.message.contains("force-unlock held-lock") - })); - } - - #[tokio::test] - async fn state_lock_false_bypasses_refresh_lock_with_warning() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -state: - backend: cluster - lock: false -graphs: - knowledge: - schema: ./people.pg -"#, - ) - .unwrap(); - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{"version":1,"applied_revision":{"resources":{}}}"#, - ) - .unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(!out.state_observations.locked); - assert!(!out.state_observations.lock_acquired); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_disabled") - ); - } - - #[tokio::test] - async fn external_state_backend_refresh_rejected() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - "version: 1\nstate:\n backend: s3://bucket/state\ngraphs: {}\n", - ) - .unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "unsupported_state_backend") - ); - } - - #[tokio::test] - async fn import_graph_open_error_does_not_create_state() { - let dir = fixture(); - fs::create_dir_all(dir.path().join(CLUSTER_GRAPHS_DIR).join("knowledge.omni")).unwrap(); - - let out = import_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "graph_observation_error") - ); - assert!(!dir.path().join(CLUSTER_STATE_FILE).exists()); - } - - // ---- config-only apply (Stage 3A) ---- - - /// Seed a state.json that simulates "graph exists with the desired schema, - /// queries/policies not yet applied" by borrowing the desired digests. - fn write_applyable_state(config_dir: &Path) { - let out = validate_config_dir(config_dir); - assert!(out.ok, "{:?}", out.diagnostics); - let schema_digest = out.resource_digests.get("schema.knowledge").unwrap().clone(); - let graph_composite = - graph_digest("knowledge", Some(&schema_digest), Some(&BTreeMap::new())); - write_state_resources( - config_dir, - &[ - ("graph.knowledge", graph_composite.as_str()), - ("schema.knowledge", schema_digest.as_str()), - ], - ); - } - - fn write_state_resources(config_dir: &Path, resources: &[(&str, &str)]) { - let resource_map: serde_json::Map = resources - .iter() - .map(|(address, digest)| ((*address).to_string(), json!({ "digest": digest }))) - .collect(); - let state_dir = config_dir.join(CLUSTER_STATE_DIR); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - serde_json::to_string_pretty(&json!({ - "version": 1, - "state_revision": 1, - "applied_revision": { "resources": resource_map } - })) - .unwrap(), - ) - .unwrap(); - } - - fn read_state_json(config_dir: &Path) -> serde_json::Value { - serde_json::from_str(&fs::read_to_string(config_dir.join(CLUSTER_STATE_FILE)).unwrap()) - .unwrap() - } - - fn query_payload_path(config_dir: &Path, digest: &str) -> std::path::PathBuf { - config_dir - .join(CLUSTER_RESOURCES_DIR) - .join("query/knowledge/find_person") - .join(format!("{digest}.gq")) - } - - fn policy_payload_path(config_dir: &Path, digest: &str) -> std::path::PathBuf { - config_dir - .join(CLUSTER_RESOURCES_DIR) - .join("policy/base") - .join(format!("{digest}.yaml")) - } - - #[tokio::test] - async fn apply_without_state_fails_with_state_missing() { - let dir = fixture(); - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_missing" - && diagnostic.message.contains("cluster import")) - ); - assert!(!dir.path().join(CLUSTER_STATE_FILE).exists()); - assert!(!dir.path().join(CLUSTER_RESOURCES_DIR).exists()); - assert!(!dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn apply_writes_payloads_state_and_statuses() { - let dir = fixture(); - write_applyable_state(dir.path()); - let desired = validate_config_dir(dir.path()); - let query_digest = desired - .resource_digests - .get("query.knowledge.find_person") - .unwrap() - .clone(); - let policy_digest = desired.resource_digests.get("policy.base").unwrap().clone(); - let schema_digest = desired - .resource_digests - .get("schema.knowledge") - .unwrap() - .clone(); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!(out.applied_count, 2); - assert_eq!(out.deferred_count, 0); - assert!(out.converged); - assert!(out.state_written); - - let query_blob = query_payload_path(dir.path(), &query_digest); - assert_eq!(fs::read_to_string(&query_blob).unwrap(), QUERY); - let policy_blob = policy_payload_path(dir.path(), &policy_digest); - assert_eq!(fs::read_to_string(&policy_blob).unwrap(), "rules: []\n"); - - let state = read_state_json(dir.path()); - assert_eq!(state["state_revision"], 2); - let resources = &state["applied_revision"]["resources"]; - assert_eq!( - resources["query.knowledge.find_person"]["digest"], - query_digest - ); - assert_eq!(resources["policy.base"]["digest"], policy_digest); - let expected_composite = graph_digest( - "knowledge", - Some(&schema_digest), - Some( - &[("find_person".to_string(), query_digest.clone())] - .into_iter() - .collect(), - ), - ); - assert_eq!(resources["graph.knowledge"]["digest"], expected_composite); - assert_eq!( - state["applied_revision"]["config_digest"], - desired_revision_digest(&out) - ); - assert_eq!( - state["resource_statuses"]["query.knowledge.find_person"]["status"], - "applied" - ); - assert_eq!(state["resource_statuses"]["policy.base"]["status"], "applied"); - assert!(!dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - fn desired_revision_digest(out: &ApplyOutput) -> String { - out.desired_revision.config_digest.clone().unwrap() - } - - #[tokio::test] - async fn apply_update_changes_query_digest_and_keeps_old_blob() { - let dir = fixture(); - let desired = validate_config_dir(dir.path()); - let schema_digest = desired - .resource_digests - .get("schema.knowledge") - .unwrap() - .clone(); - let old_digest = "0".repeat(64); - let graph_composite = - graph_digest("knowledge", Some(&schema_digest), Some(&BTreeMap::new())); - write_state_resources( - dir.path(), - &[ - ("graph.knowledge", graph_composite.as_str()), - ("schema.knowledge", schema_digest.as_str()), - ("query.knowledge.find_person", old_digest.as_str()), - ], - ); - let old_blob = query_payload_path(dir.path(), &old_digest); - fs::create_dir_all(old_blob.parent().unwrap()).unwrap(); - fs::write(&old_blob, "old query source").unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - let new_digest = desired - .resource_digests - .get("query.knowledge.find_person") - .unwrap(); - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["query.knowledge.find_person"]["digest"], - *new_digest - ); - assert_eq!(fs::read_to_string(&old_blob).unwrap(), "old query source"); - assert!(query_payload_path(dir.path(), new_digest).exists()); - } - - #[tokio::test] - async fn apply_deletes_removed_resources_but_keeps_blobs() { - let dir = fixture(); - let desired = validate_config_dir(dir.path()); - let schema_digest = desired - .resource_digests - .get("schema.knowledge") - .unwrap() - .clone(); - let stale_query_digest = "1".repeat(64); - let stale_policy_digest = "2".repeat(64); - let graph_composite = - graph_digest("knowledge", Some(&schema_digest), Some(&BTreeMap::new())); - write_state_resources( - dir.path(), - &[ - ("graph.knowledge", graph_composite.as_str()), - ("schema.knowledge", schema_digest.as_str()), - ("query.knowledge.orphan", stale_query_digest.as_str()), - ("policy.old", stale_policy_digest.as_str()), - ], - ); - let stale_blob = dir - .path() - .join(CLUSTER_RESOURCES_DIR) - .join("policy/old") - .join(format!("{stale_policy_digest}.yaml")); - fs::create_dir_all(stale_blob.parent().unwrap()).unwrap(); - fs::write(&stale_blob, "old policy").unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.converged); - let state = read_state_json(dir.path()); - let resources = &state["applied_revision"]["resources"]; - assert!(resources.get("query.knowledge.orphan").is_none()); - assert!(resources.get("policy.old").is_none()); - assert!( - state["resource_statuses"] - .get("query.knowledge.orphan") - .is_none() - ); - // Deleted resources leave their content-addressed blobs in place; GC is - // a later stage. - assert_eq!(fs::read_to_string(&stale_blob).unwrap(), "old policy"); - // The composite no longer includes the orphan query. - let query_digest = desired - .resource_digests - .get("query.knowledge.find_person") - .unwrap() - .clone(); - let expected_composite = graph_digest( - "knowledge", - Some(&schema_digest), - Some(&[("find_person".to_string(), query_digest)].into_iter().collect()), - ); - assert_eq!(resources["graph.knowledge"]["digest"], expected_composite); - } - - #[tokio::test] - async fn apply_schema_update_and_dependent_query_in_one_run() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - // Schema update + a query update that depends on the new field: one - // apply executes the schema migration first, then the catalog write. - fs::write(dir.path().join("people.pg"), SCHEMA_V2).unwrap(); - fs::write( - dir.path().join("people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name, $p.bio }\n}\n", - ) - .unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.converged, "{out:?}"); - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - assert_eq!( - by_resource["schema.knowledge"].disposition, - Some(ApplyDisposition::Applied) - ); - assert_eq!( - by_resource["query.knowledge.find_person"].disposition, - Some(ApplyDisposition::Applied) - ); - assert_eq!( - by_resource["graph.knowledge"].disposition, - Some(ApplyDisposition::Derived) - ); - // The live graph carries the new schema. - let db = Omnigraph::open_read_only(&derived_graph_uri(dir.path(), "knowledge")) - .await - .unwrap(); - let desired = validate_config_dir(dir.path()); - assert_eq!( - sha256_hex(db.schema_source().as_bytes()), - desired.resource_digests["schema.knowledge"] - ); - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["schema.knowledge"]["digest"], - desired.resource_digests["schema.knowledge"] - ); - // Sidecar retired after the CAS landed. - assert!( - !dir.path().join(CLUSTER_RECOVERIES_DIR).exists() - || fs::read_dir(dir.path().join(CLUSTER_RECOVERIES_DIR)) - .unwrap() - .next() - .is_none() - ); - } - - #[tokio::test] - async fn apply_unsupported_schema_change_fails_loudly() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - // Property type changes are unsupported by the engine planner. - fs::write( - dir.path().join("people.pg"), - "\nnode Person {\n name: String @key\n age: I64?\n}\n", - ) - .unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(out.diagnostics.iter().any(|diagnostic| { - diagnostic.code == "schema_apply_failed" - && diagnostic.message.contains("changing property type") - })); - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - assert_eq!( - by_resource["schema.knowledge"].disposition, - Some(ApplyDisposition::Blocked) - ); - assert_eq!( - by_resource["schema.knowledge"].reason.as_deref(), - Some("schema_apply_failed") - ); - // The live schema and the ledger are unchanged. - let state = read_state_json(dir.path()); - let desired = validate_config_dir(dir.path()); - assert_ne!( - state["applied_revision"]["resources"]["schema.knowledge"]["digest"], - desired.resource_digests["schema.knowledge"] - ); - // Second run: the sweep retires the stale sidecar (ledger consistent) - // and the run fails just as loudly β€” idempotent loudness. - let second = apply_config_dir(dir.path()).await; - assert!(!second.ok); - assert!( - second - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "schema_apply_failed") - ); - } - - #[tokio::test] - async fn apply_blocks_schema_update_while_recovery_pending() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_state_resources(dir.path(), &[("schema.knowledge", "stale-digest")]); - fs::write(dir.path().join("people.pg"), SCHEMA_V2).unwrap(); - // A pending sidecar whose intent matches neither live nor recorded. - write_schema_apply_sidecar(dir.path(), "knowledge", "intended-digest", "01PENDS"); - - let out = apply_config_dir(dir.path()).await; - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - assert_eq!( - by_resource["schema.knowledge"].disposition, - Some(ApplyDisposition::Blocked) - ); - assert_eq!( - by_resource["schema.knowledge"].reason.as_deref(), - Some("cluster_recovery_pending") - ); - } - - #[tokio::test] - async fn apply_creates_graph_and_unblocks_dependents() { - let dir = fixture(); - write_state_resources(dir.path(), &[]); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.converged, "{out:?}"); - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - // Stage 4A: the create executes, and its dependents apply in-run. - assert_eq!( - by_resource["graph.knowledge"].disposition, - Some(ApplyDisposition::Applied) - ); - assert_eq!( - by_resource["schema.knowledge"].disposition, - Some(ApplyDisposition::Applied) - ); - assert_eq!( - by_resource["query.knowledge.find_person"].disposition, - Some(ApplyDisposition::Applied) - ); - assert_eq!( - by_resource["policy.base"].disposition, - Some(ApplyDisposition::Applied) - ); - // The graph exists on disk and opens; state records everything. - let graph_uri = derived_graph_uri(dir.path(), "knowledge"); - let db = Omnigraph::open_read_only(&graph_uri).await.unwrap(); - let desired = validate_config_dir(dir.path()); - assert_eq!( - sha256_hex(db.schema_source().as_bytes()), - desired.resource_digests["schema.knowledge"] - ); - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["schema.knowledge"]["digest"], - desired.resource_digests["schema.knowledge"] - ); - assert_eq!( - state["resource_statuses"]["graph.knowledge"]["status"], - "applied" - ); - // The create's sidecar was retired after the state CAS landed. - assert!( - !dir.path().join(CLUSTER_RECOVERIES_DIR).exists() - || fs::read_dir(dir.path().join(CLUSTER_RECOVERIES_DIR)) - .unwrap() - .next() - .is_none() - ); - } - - #[tokio::test] - async fn apply_create_failure_blocks_dependents_and_keeps_sidecar() { - let dir = fixture(); - write_state_resources(dir.path(), &[]); - // Make the init fail its strict preflight: a junk _schema.pg already - // sits at the derived root (the engine refuses to overwrite it). - let root = dir.path().join(CLUSTER_GRAPHS_DIR).join("knowledge.omni"); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("_schema.pg"), "junk").unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "graph_create_failed") - ); - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - // Dependents are demoted: the run tells the truth about what executed. - assert_eq!( - by_resource["graph.knowledge"].disposition, - Some(ApplyDisposition::Blocked) - ); - assert_eq!( - by_resource["query.knowledge.find_person"].disposition, - Some(ApplyDisposition::Blocked) - ); - assert_eq!( - by_resource["query.knowledge.find_person"].reason.as_deref(), - Some("dependency_not_applied") - ); - assert_eq!( - by_resource["policy.base"].disposition, - Some(ApplyDisposition::Blocked) - ); - assert!(!out.converged); - // The sidecar stays for the sweep to classify next run. - assert!( - fs::read_dir(dir.path().join(CLUSTER_RECOVERIES_DIR)) - .unwrap() - .next() - .is_some() - ); - // No graph digests moved. - let state = read_state_json(dir.path()); - assert!( - state["applied_revision"]["resources"] - .as_object() - .unwrap() - .is_empty() - ); - } - - #[tokio::test] - async fn apply_blocks_graph_delete_without_approval() { - let dir = fixture(); - let desired = validate_config_dir(dir.path()); - let schema_digest = desired - .resource_digests - .get("schema.knowledge") - .unwrap() - .clone(); - let graph_composite = - graph_digest("knowledge", Some(&schema_digest), Some(&BTreeMap::new())); - write_state_resources( - dir.path(), - &[ - ("graph.knowledge", graph_composite.as_str()), - ("schema.knowledge", schema_digest.as_str()), - ("graph.old", "3333"), - ("schema.old", "4444"), - ("query.old.q", "5555"), - ], - ); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(!out.converged); - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - // Stage 4C: deletes are gated, not deferred β€” every subtree change - // blocks on the single graph-level approval. - assert_eq!( - by_resource["graph.old"].disposition, - Some(ApplyDisposition::Blocked) - ); - assert_eq!( - by_resource["graph.old"].reason.as_deref(), - Some("approval_required") - ); - assert_eq!( - by_resource["schema.old"].reason.as_deref(), - Some("approval_required") - ); - assert_eq!( - by_resource["query.old.q"].reason.as_deref(), - Some("approval_required") - ); - // State intact; nothing destroyed without the artifact. - let state = read_state_json(dir.path()); - let resources = &state["applied_revision"]["resources"]; - assert_eq!(resources["graph.old"]["digest"], "3333"); - assert_eq!(resources["schema.old"]["digest"], "4444"); - assert_eq!(resources["query.old.q"]["digest"], "5555"); - } - - #[tokio::test] - async fn approve_writes_digest_bound_artifact() { - let dir = fixture(); - write_applyable_state(dir.path()); - // Seed a deletable subtree. - let state = read_state_json(dir.path()); - let graph_digest_str = state["applied_revision"]["resources"]["graph.knowledge"]["digest"] - .as_str() - .unwrap() - .to_string(); - let schema_digest_str = state["applied_revision"]["resources"]["schema.knowledge"] - ["digest"] - .as_str() - .unwrap() - .to_string(); - write_state_resources( - dir.path(), - &[ - ("graph.knowledge", graph_digest_str.as_str()), - ("schema.knowledge", schema_digest_str.as_str()), - ("graph.old", "3333"), - ("schema.old", "4444"), - ], - ); - - let out = approve_config_dir(dir.path(), "graph.old", "andrew").await; - assert!(out.ok, "{:?}", out.diagnostics); - let approval_id = out.approval_id.clone().unwrap(); - let artifact: serde_json::Value = serde_json::from_str( - &fs::read_to_string( - dir.path() - .join(CLUSTER_APPROVALS_DIR) - .join(format!("{approval_id}.json")), - ) - .unwrap(), - ) - .unwrap(); - assert_eq!(artifact["resource"], "graph.old"); - assert_eq!(artifact["operation"], "delete"); - assert_eq!(artifact["approved_by"], "andrew"); - assert_eq!(artifact["bound_before_digest"], "3333"); - assert!(artifact["bound_after_digest"].is_null()); - assert!(artifact["bound_config_digest"].is_string()); - assert!(artifact["consumed_at"].is_null()); - - // A non-gated address is refused. - let not_gated = approve_config_dir(dir.path(), "query.knowledge.find_person", "andrew").await; - assert!(!not_gated.ok); - assert!( - not_gated - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "approval_not_required") - ); - } - - #[tokio::test] - async fn stale_approval_is_ignored() { - let dir = fixture(); - write_applyable_state(dir.path()); - let state = read_state_json(dir.path()); - let graph_digest_str = state["applied_revision"]["resources"]["graph.knowledge"]["digest"] - .as_str() - .unwrap() - .to_string(); - let schema_digest_str = state["applied_revision"]["resources"]["schema.knowledge"] - ["digest"] - .as_str() - .unwrap() - .to_string(); - write_state_resources( - dir.path(), - &[ - ("graph.knowledge", graph_digest_str.as_str()), - ("schema.knowledge", schema_digest_str.as_str()), - ("graph.old", "3333"), - ], - ); - let approved = approve_config_dir(dir.path(), "graph.old", "andrew").await; - assert!(approved.ok, "{:?}", approved.diagnostics); - // The config moves after approval: the bound config digest no longer - // matches and the artifact authorizes nothing. - fs::write(dir.path().join("base.policy.yaml"), "rules: [] # moved\n").unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "approval_stale"), - "{:?}", - out.diagnostics - ); - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - assert_eq!( - by_resource["graph.old"].reason.as_deref(), - Some("approval_required") - ); - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["graph.old"]["digest"], - "3333" - ); - } - - #[tokio::test] - async fn compute_approvals_one_gate_per_subtree() { - let dir = fixture(); - write_applyable_state(dir.path()); - let state = read_state_json(dir.path()); - let g = state["applied_revision"]["resources"]["graph.knowledge"]["digest"] - .as_str() - .unwrap() - .to_string(); - let sc = state["applied_revision"]["resources"]["schema.knowledge"]["digest"] - .as_str() - .unwrap() - .to_string(); - write_state_resources( - dir.path(), - &[ - ("graph.knowledge", g.as_str()), - ("schema.knowledge", sc.as_str()), - ("graph.old", "3333"), - ("schema.old", "4444"), - ("query.old.q", "5555"), - ], - ); - let plan = plan_config_dir(dir.path()).await; - let gated: Vec<&str> = plan - .approvals_required - .iter() - .map(|gate| gate.resource.as_str()) - .collect(); - assert_eq!(gated, vec!["graph.old"], "{plan:?}"); - assert!(!plan.approvals_required[0].satisfied); - } - - #[tokio::test] - async fn apply_is_idempotent() { - let dir = fixture(); - write_applyable_state(dir.path()); - - let first = apply_config_dir(dir.path()).await; - assert!(first.ok, "{:?}", first.diagnostics); - assert!(first.state_written); - let state_after_first = fs::read_to_string(dir.path().join(CLUSTER_STATE_FILE)).unwrap(); - - let second = apply_config_dir(dir.path()).await; - assert!(second.ok, "{:?}", second.diagnostics); - assert!(second.changes.is_empty()); - assert_eq!(second.applied_count, 0); - assert!(second.converged); - assert!(!second.state_written); - let state_after_second = fs::read_to_string(dir.path().join(CLUSTER_STATE_FILE)).unwrap(); - assert_eq!(state_after_first, state_after_second); - assert_eq!(second.state_observations.state_revision, 2); - } - - #[tokio::test] - async fn apply_respects_held_lock() { - let dir = fixture(); - write_applyable_state(dir.path()); - write_lock_file(dir.path(), "held-lock", "plan"); - - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_held") - ); - // The held lock survives a refused apply, and nothing was written. - assert!(dir.path().join(CLUSTER_LOCK_FILE).exists()); - assert!(!dir.path().join(CLUSTER_RESOURCES_DIR).exists()); - let state = read_state_json(dir.path()); - assert_eq!(state["state_revision"], 1); - } - - #[tokio::test] - async fn apply_state_lock_false_bypasses_with_warning() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -state: - backend: cluster - lock: false -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -"#, - ) - .unwrap(); - write_applyable_state(dir.path()); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.state_written); - assert!(!out.state_observations.lock_acquired); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_lock_disabled") - ); - assert!(!dir.path().join(CLUSTER_LOCK_FILE).exists()); - } - - #[tokio::test] - async fn apply_skips_existing_payload_blob() { - let dir = fixture(); - write_applyable_state(dir.path()); - let desired = validate_config_dir(dir.path()); - let query_digest = desired - .resource_digests - .get("query.knowledge.find_person") - .unwrap() - .clone(); - // Content-addressed blobs are trusted by name: an existing file is - // never rewritten. - let blob = query_payload_path(dir.path(), &query_digest); - fs::create_dir_all(blob.parent().unwrap()).unwrap(); - fs::write(&blob, "pre-existing").unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert_eq!(fs::read_to_string(&blob).unwrap(), "pre-existing"); - } - - #[tokio::test] - async fn apply_invalid_config_fails_before_lock() { - let dir = fixture(); - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - "version: 1\nnot_a_field: true\n", - ) - .unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - // Config errors bail before the lock or any state directory exists. - assert!(!dir.path().join(CLUSTER_STATE_DIR).exists()); - } - - /// When the state write fails after payloads landed, the output must - /// report the statuses actually on disk β€” not the unpersisted in-memory - /// mutations (phantom `applied` entries would mislead automation that - /// reads `resource_statuses` independently of `ok`). - #[cfg(unix)] - #[tokio::test] - async fn apply_state_write_failure_reports_persisted_statuses() { - use std::os::unix::fs::PermissionsExt; - - let dir = fixture(); - // lock: false so the only write into __cluster/ is state.json itself. - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -state: - backend: cluster - lock: false -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -"#, - ) - .unwrap(); - write_applyable_state(dir.path()); - // Pre-create the payload blob so the payload phase is a no-op and the - // failure lands exactly at the state write. - let desired = validate_config_dir(dir.path()); - let query_digest = desired - .resource_digests - .get("query.knowledge.find_person") - .unwrap(); - let blob = query_payload_path(dir.path(), query_digest); - fs::create_dir_all(blob.parent().unwrap()).unwrap(); - fs::write(&blob, QUERY).unwrap(); - - let state_dir = dir.path().join(CLUSTER_STATE_DIR); - fs::set_permissions(&state_dir, fs::Permissions::from_mode(0o555)).unwrap(); - // Running as root ignores permission bits; skip rather than flake. - if fs::write(state_dir.join("probe"), b"x").is_ok() { - let _ = fs::remove_file(state_dir.join("probe")); - fs::set_permissions(&state_dir, fs::Permissions::from_mode(0o755)).unwrap(); - eprintln!("skipping: permissions are not enforced (running as root)"); - return; - } - - let out = apply_config_dir(dir.path()).await; - fs::set_permissions(&state_dir, fs::Permissions::from_mode(0o755)).unwrap(); - - assert!(!out.ok); - assert!(!out.state_written); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_write_error"), - "{:?}", - out.diagnostics - ); - // The seeded state has no statuses; the failed apply must not invent - // the in-memory `applied` ones it failed to persist. - assert!( - out.resource_statuses.is_empty(), - "unpersisted statuses leaked into output: {:?}", - out.resource_statuses - ); - } - - // ---- catalog payload verification (Stage 3B) ---- - - /// Converge a fixture dir and return the query blob path. - async fn converge_fixture(config_dir: &Path) -> std::path::PathBuf { - write_applyable_state(config_dir); - let out = apply_config_dir(config_dir).await; - assert!(out.ok && out.converged, "{:?}", out.diagnostics); - let desired = validate_config_dir(config_dir); - query_payload_path( - config_dir, - desired - .resource_digests - .get("query.knowledge.find_person") - .unwrap(), - ) - } - - #[tokio::test] - async fn status_reports_missing_payload_read_only() { - let dir = fixture(); - let blob = converge_fixture(dir.path()).await; - let state_before = fs::read_to_string(dir.path().join(CLUSTER_STATE_FILE)).unwrap(); - fs::remove_file(&blob).unwrap(); - - let out = status_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.diagnostics.iter().any(|diagnostic| { - diagnostic.code == "catalog_payload_missing" - && diagnostic.path == "query.knowledge.find_person" - })); - // Read-only: persisted statuses and state bytes untouched. - assert_eq!( - out.resource_statuses["query.knowledge.find_person"].status, - ResourceLifecycleStatus::Applied - ); - assert_eq!( - fs::read_to_string(dir.path().join(CLUSTER_STATE_FILE)).unwrap(), - state_before - ); - } - - #[tokio::test] - async fn refresh_removes_digest_and_drifts_on_missing_payload() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - let blob = converge_fixture(dir.path()).await; - fs::remove_file(&blob).unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "catalog_payload_missing") - ); - let status = &out.resource_statuses["query.knowledge.find_person"]; - assert_eq!(status.status, ResourceLifecycleStatus::Drifted); - assert!(status.conditions.contains(&"payload_missing".to_string())); - let state = read_state_json(dir.path()); - assert!( - state["applied_revision"]["resources"] - .get("query.knowledge.find_person") - .is_none(), - "{state}" - ); - } - - #[tokio::test] - async fn refresh_drifts_on_corrupted_payload() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - let blob = converge_fixture(dir.path()).await; - fs::write(&blob, "corrupted content").unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - let status = &out.resource_statuses["query.knowledge.find_person"]; - assert_eq!(status.status, ResourceLifecycleStatus::Drifted); - assert!(status.conditions.contains(&"payload_mismatch".to_string())); - let state = read_state_json(dir.path()); - assert!( - state["applied_revision"]["resources"] - .get("query.knowledge.find_person") - .is_none() - ); - } - - #[tokio::test] - async fn refresh_flags_unreadable_payload_as_error() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - let blob = converge_fixture(dir.path()).await; - // A same-named directory yields a non-NotFound IO error portably. - fs::remove_file(&blob).unwrap(); - fs::create_dir(&blob).unwrap(); - - let out = refresh_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "catalog_payload_read_error") - ); - let status = &out.resource_statuses["query.knowledge.find_person"]; - assert_eq!(status.status, ResourceLifecycleStatus::Error); - assert!(status.conditions.contains(&"payload_read_error".to_string())); - // Transient IO keeps the digest: no spurious republish. - let state = read_state_json(dir.path()); - assert!( - state["applied_revision"]["resources"] - .get("query.knowledge.find_person") - .is_some() - ); - } - - #[tokio::test] - async fn payload_drift_self_heals_through_refresh_plan_apply() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - let blob = converge_fixture(dir.path()).await; - let original = fs::read_to_string(&blob).unwrap(); - fs::remove_file(&blob).unwrap(); - - let refresh = refresh_config_dir(dir.path()).await; - assert!(refresh.ok, "{:?}", refresh.diagnostics); - - let plan = plan_config_dir(dir.path()).await; - let query_change = plan - .changes - .iter() - .find(|change| change.resource == "query.knowledge.find_person") - .expect("plan must propose recreating the query"); - assert_eq!(query_change.operation, PlanOperation::Create); - assert_eq!(query_change.disposition, Some(ApplyDisposition::Applied)); - - let apply = apply_config_dir(dir.path()).await; - assert!(apply.ok && apply.converged, "{:?}", apply.diagnostics); - assert_eq!(fs::read_to_string(&blob).unwrap(), original); - - let status = status_config_dir(dir.path()).await; - assert!( - !status - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code.starts_with("catalog_payload")), - "{:?}", - status.diagnostics - ); - } - - #[tokio::test] - async fn verification_skips_graph_and_schema_resources() { - let dir = fixture(); - write_applyable_state(dir.path()); // graph + schema digests only, no blobs - - let out = status_config_dir(dir.path()).await; - assert!( - !out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code.starts_with("catalog_payload")), - "{:?}", - out.diagnostics - ); - } - - // ---- recovery sidecars + sweep (Stage 4A) ---- - - fn derived_graph_uri(config_dir: &Path, graph_id: &str) -> String { - display_path( - &config_dir - .join(CLUSTER_GRAPHS_DIR) - .join(format!("{graph_id}.omni")), - ) - } - - fn write_create_sidecar( - config_dir: &Path, - graph_id: &str, - desired_schema_digest: &str, - operation_id: &str, - ) -> PathBuf { - let dir = config_dir.join(CLUSTER_RECOVERIES_DIR); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join(format!("{operation_id}.json")); - fs::write( - &path, - serde_json::to_string_pretty(&json!({ - "schema_version": 1, - "operation_id": operation_id, - "started_at": "1970-01-01T00:00:00Z", - "kind": "graph_create", - "graph_id": graph_id, - "graph_uri": derived_graph_uri(config_dir, graph_id), - "desired_schema_digest": desired_schema_digest, - })) - .unwrap(), - ) - .unwrap(); - path - } - - #[tokio::test] - async fn sweep_removes_sidecar_when_root_absent() { - let dir = fixture(); - write_applyable_state(dir.path()); - let sidecar = write_create_sidecar(dir.path(), "knowledge", "irrelevant", "01ROW1"); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - // Row 1: nothing moved; intent removed, run proceeds normally. - assert!(!sidecar.exists()); - assert!(out.converged); - } - - #[tokio::test] - async fn sweep_rolls_forward_completed_create() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_state_resources(dir.path(), &[]); // state predates the create - let desired = validate_config_dir(dir.path()); - let schema_digest = desired.resource_digests["schema.knowledge"].clone(); - let sidecar = write_create_sidecar(dir.path(), "knowledge", &schema_digest, "01ROW4"); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_rolled_forward") - ); - // Row 4: ledger converged to observable reality, audit recorded, - // sidecar retired after the CAS landed. - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["schema.knowledge"]["digest"], - schema_digest - ); - assert!( - state["recovery_records"] - .as_object() - .unwrap() - .values() - .any(|record| record["outcome"] == "rolled_forward" - && record["graph_id"] == "knowledge") - ); - assert!(!sidecar.exists()); - // With the graph rolled forward, the same run converges the catalog. - assert!(out.converged, "{out:?}"); - } - - #[tokio::test] - async fn sweep_completes_already_recorded_create() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); // state already records graph+schema - let desired = validate_config_dir(dir.path()); - let sidecar = write_create_sidecar( - dir.path(), - "knowledge", - &desired.resource_digests["schema.knowledge"], - "01ROW2", - ); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - // Row 2: outcome was already durable; no audit entry, sidecar retired. - assert!(!sidecar.exists()); - let state = read_state_json(dir.path()); - assert!( - state["recovery_records"] - .as_object() - .is_none_or(|records| records.is_empty()), - "{state}" - ); - } - - #[tokio::test] - async fn sweep_keeps_sidecar_for_incomplete_root() { - let dir = fixture(); - write_applyable_state(dir.path()); - // A root that exists but cannot be opened: the engine's partial-init gap. - let root = dir.path().join(CLUSTER_GRAPHS_DIR).join("knowledge.omni"); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("_schema.pg"), "junk").unwrap(); - let sidecar = write_create_sidecar(dir.path(), "knowledge", "whatever", "01ROW5"); - - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "graph_create_incomplete") - ); - // Row 5: never auto-delete; sidecar and root stay for the operator, - // and the Error status is persisted by the run's state write. - assert!(sidecar.exists()); - assert!(root.exists()); - let state = read_state_json(dir.path()); - assert_eq!(state["resource_statuses"]["graph.knowledge"]["status"], "error"); - assert!( - state["resource_statuses"]["graph.knowledge"]["conditions"] - .as_array() - .unwrap() - .iter() - .any(|condition| condition == "graph_create_incomplete") - ); - } - - #[tokio::test] - async fn sweep_flags_unexpected_schema_as_pending() { - let dir = fixture(); - write_state_resources(dir.path(), &[]); - // Live graph exists with a schema the sidecar never intended. - let graph_dir = dir.path().join(CLUSTER_GRAPHS_DIR); - fs::create_dir_all(&graph_dir).unwrap(); - Omnigraph::init( - &derived_graph_uri(dir.path(), "knowledge"), - "\nnode Other {\n name: String @key\n}\n", - ) - .await - .unwrap(); - let desired = validate_config_dir(dir.path()); - let sidecar = write_create_sidecar( - dir.path(), - "knowledge", - &desired.resource_digests["schema.knowledge"], - "01ROW6", - ); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); // warning, not error - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_pending") - ); - // Row 6: refuse to guess; sidecar kept, Drifted persisted. - assert!(sidecar.exists()); - let state = read_state_json(dir.path()); - assert_eq!( - state["resource_statuses"]["graph.knowledge"]["status"], - "drifted" - ); - assert!( - state["resource_statuses"]["graph.knowledge"]["conditions"] - .as_array() - .unwrap() - .iter() - .any(|condition| condition == "actual_applied_state_pending") - ); - } - - #[tokio::test] - async fn apply_blocks_create_while_recovery_pending() { - let dir = fixture(); - write_state_resources(dir.path(), &[]); - // A kept (row 5) sidecar: partial root that cannot be opened. - let root = dir.path().join(CLUSTER_GRAPHS_DIR).join("knowledge.omni"); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("_schema.pg"), "junk").unwrap(); - let sidecar = write_create_sidecar(dir.path(), "knowledge", "whatever", "01PEND"); - - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); // row 5 is an error condition - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - // The pending recovery blocks the create and its dependents; the - // executor never attempts the init. - assert_eq!( - by_resource["graph.knowledge"].disposition, - Some(ApplyDisposition::Blocked) - ); - assert_eq!( - by_resource["graph.knowledge"].reason.as_deref(), - Some("cluster_recovery_pending") - ); - assert_eq!( - by_resource["query.knowledge.find_person"].reason.as_deref(), - Some("cluster_recovery_pending") - ); - assert_eq!( - by_resource["policy.base"].reason.as_deref(), - Some("cluster_recovery_pending") - ); - assert!(sidecar.exists()); - // The sweep's Error status is what persists β€” not a generic Blocked. - let state = read_state_json(dir.path()); - assert_eq!(state["resource_statuses"]["graph.knowledge"]["status"], "error"); - } - - #[tokio::test] - async fn plan_embeds_migration_preview_for_schema_update() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - fs::write( - dir.path().join("people.pg"), - "\nnode Person {\n name: String @key\n age: I32?\n bio: String?\n}\n", - ) - .unwrap(); - - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - let schema_change = out - .changes - .iter() - .find(|change| change.resource == "schema.knowledge") - .unwrap(); - let migration = schema_change.migration.as_ref().expect("preview embedded"); - assert!(migration.supported); - assert!( - serde_json::to_string(&migration.steps) - .unwrap() - .contains("add_property"), - "{migration:?}" - ); - } - - #[tokio::test] - async fn plan_warns_when_preview_unavailable() { - let dir = fixture(); - write_applyable_state(dir.path()); // digests recorded, but no live root - fs::write( - dir.path().join("people.pg"), - "\nnode Person {\n name: String @key\n age: I32?\n bio: String?\n}\n", - ) - .unwrap(); - - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - let schema_change = out - .changes - .iter() - .find(|change| change.resource == "schema.knowledge") - .unwrap(); - assert!(schema_change.migration.is_none()); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "schema_preview_unavailable") - ); - } - - fn write_schema_apply_sidecar( - config_dir: &Path, - graph_id: &str, - desired_schema_digest: &str, - operation_id: &str, - ) -> PathBuf { - let dir = config_dir.join(CLUSTER_RECOVERIES_DIR); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join(format!("{operation_id}.json")); - fs::write( - &path, - serde_json::to_string_pretty(&json!({ - "schema_version": 1, - "operation_id": operation_id, - "started_at": "1970-01-01T00:00:00Z", - "kind": "schema_apply", - "graph_id": graph_id, - "graph_uri": derived_graph_uri(config_dir, graph_id), - "desired_schema_digest": desired_schema_digest, - })) - .unwrap(), - ) - .unwrap(); - path - } - - const SCHEMA_V2: &str = "\nnode Person {\n name: String @key\n age: I32?\n bio: String?\n}\n"; - - #[tokio::test] - async fn sweep_retires_schema_sidecar_when_ledger_consistent() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); // state digest == live digest - let sidecar = - write_schema_apply_sidecar(dir.path(), "knowledge", "never-applied", "01SROW1"); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(!sidecar.exists()); - let state = read_state_json(dir.path()); - assert!( - state["recovery_records"] - .as_object() - .is_none_or(|records| records.is_empty()) - ); - } - - #[tokio::test] - async fn sweep_rolls_forward_completed_schema_apply() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - // The schema apply completed on the graph out-of-process... - let graph_uri = derived_graph_uri(dir.path(), "knowledge"); - let db = Omnigraph::open(&graph_uri).await.unwrap(); - db.apply_schema(SCHEMA_V2).await.unwrap(); - // ...the desired config matches it, and the sidecar records the intent. - fs::write(dir.path().join("people.pg"), SCHEMA_V2).unwrap(); - let desired = validate_config_dir(dir.path()); - let v2_digest = desired.resource_digests["schema.knowledge"].clone(); - let sidecar = write_schema_apply_sidecar(dir.path(), "knowledge", &v2_digest, "01SROW3"); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_rolled_forward") - ); - assert!(!sidecar.exists()); - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["schema.knowledge"]["digest"], - v2_digest - ); - assert!( - state["recovery_records"] - .as_object() - .unwrap() - .values() - .any(|record| record["kind"] == "schema_apply" - && record["outcome"] == "rolled_forward") - ); - assert!(out.converged, "{out:?}"); - } - - #[tokio::test] - async fn sweep_flags_unexpected_schema_apply_state_as_pending() { - let dir = fixture(); - init_derived_graph(dir.path()).await; // live = v1 - write_state_resources(dir.path(), &[("schema.knowledge", "stale-digest")]); - // Sidecar intended a digest that is neither live nor recorded. - let sidecar = - write_schema_apply_sidecar(dir.path(), "knowledge", "intended-digest", "01SROW6"); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); // warnings only - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_pending") - ); - assert!(sidecar.exists()); - let state = read_state_json(dir.path()); - assert_eq!( - state["resource_statuses"]["schema.knowledge"]["status"], - "drifted" - ); - } - - #[tokio::test] - async fn sweep_keeps_schema_sidecar_for_unopenable_root() { - let dir = fixture(); - write_applyable_state(dir.path()); - let root = dir.path().join(CLUSTER_GRAPHS_DIR).join("knowledge.omni"); - fs::create_dir_all(&root).unwrap(); // exists, won't open - let sidecar = - write_schema_apply_sidecar(dir.path(), "knowledge", "whatever", "01SROWX"); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); // warning: cannot verify - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_pending") - ); - assert!(sidecar.exists()); - } - - /// Seed: converged knowledge subtree + a stale `old` graph subtree with a - /// real directory on disk. - fn seed_deletable_state(config_dir: &Path) { - write_applyable_state(config_dir); - let state = read_state_json(config_dir); - let g = state["applied_revision"]["resources"]["graph.knowledge"]["digest"] - .as_str() - .unwrap() - .to_string(); - let sc = state["applied_revision"]["resources"]["schema.knowledge"]["digest"] - .as_str() - .unwrap() - .to_string(); - write_state_resources( - config_dir, - &[ - ("graph.knowledge", g.as_str()), - ("schema.knowledge", sc.as_str()), - ("graph.old", "3333"), - ("schema.old", "4444"), - ("query.old.q", "5555"), - ], - ); - let root = config_dir.join(CLUSTER_GRAPHS_DIR).join("old.omni"); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("_schema.pg"), "stale").unwrap(); - } - - #[tokio::test] - async fn apply_executes_approved_graph_delete() { - let dir = fixture(); - seed_deletable_state(dir.path()); - let approved = approve_config_dir(dir.path(), "graph.old", "andrew").await; - assert!(approved.ok, "{:?}", approved.diagnostics); - let approval_id = approved.approval_id.clone().unwrap(); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.converged, "{out:?}"); - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - assert_eq!(by_resource["graph.old"].disposition, Some(ApplyDisposition::Applied)); - assert_eq!(by_resource["schema.old"].disposition, Some(ApplyDisposition::Applied)); - assert_eq!(by_resource["query.old.q"].disposition, Some(ApplyDisposition::Applied)); - // The root is gone; the subtree is tombstoned out of the ledger. - assert!(!dir.path().join(CLUSTER_GRAPHS_DIR).join("old.omni").exists()); - let state = read_state_json(dir.path()); - let resources = state["applied_revision"]["resources"].as_object().unwrap(); - assert!(!resources.contains_key("graph.old")); - assert!(!resources.contains_key("schema.old")); - assert!(!resources.contains_key("query.old.q")); - assert_eq!(state["observations"]["graph.old"]["kind"], "tombstone"); - assert_eq!(state["observations"]["graph.old"]["approval_id"], approval_id); - // Approval consumed in BOTH stores: ledger summary + artifact file. - assert!(state["approval_records"][&approval_id]["consumed_at"].is_string()); - let artifact: serde_json::Value = serde_json::from_str( - &fs::read_to_string( - dir.path() - .join(CLUSTER_APPROVALS_DIR) - .join(format!("{approval_id}.json")), - ) - .unwrap(), - ) - .unwrap(); - assert!(artifact["consumed_at"].is_string(), "{artifact}"); - // Sidecar retired. - assert!( - fs::read_dir(dir.path().join(CLUSTER_RECOVERIES_DIR)) - .map(|mut entries| entries.next().is_none()) - .unwrap_or(true) - ); - // A consumed approval authorizes nothing further (idempotent re-apply). - let again = apply_config_dir(dir.path()).await; - assert!(again.ok && again.converged && !again.state_written, "{again:?}"); - } - - fn write_delete_sidecar( - config_dir: &Path, - graph_id: &str, - approval_id: Option<&str>, - operation_id: &str, - ) -> PathBuf { - let dir = config_dir.join(CLUSTER_RECOVERIES_DIR); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join(format!("{operation_id}.json")); - fs::write( - &path, - serde_json::to_string_pretty(&json!({ - "schema_version": 1, - "operation_id": operation_id, - "started_at": "1970-01-01T00:00:00Z", - "kind": "graph_delete", - "graph_id": graph_id, - "graph_uri": derived_graph_uri(config_dir, graph_id), - "desired_schema_digest": "", - "approval_id": approval_id, - })) - .unwrap(), - ) - .unwrap(); - path - } - - #[tokio::test] - async fn sweep_retires_delete_sidecar_when_tombstoned() { - let dir = fixture(); - write_applyable_state(dir.path()); // no graph.old in state, no root - let sidecar = write_delete_sidecar(dir.path(), "old", None, "01DROW7"); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!(!sidecar.exists()); - let state = read_state_json(dir.path()); - assert!( - state["recovery_records"] - .as_object() - .is_none_or(|records| records.is_empty()) - ); - } - - #[tokio::test] - async fn sweep_rolls_forward_completed_delete() { - let dir = fixture(); - seed_deletable_state(dir.path()); - // Approve, then simulate: root removed, state stale, sidecar present. - let approved = approve_config_dir(dir.path(), "graph.old", "andrew").await; - let approval_id = approved.approval_id.unwrap(); - fs::remove_dir_all(dir.path().join(CLUSTER_GRAPHS_DIR).join("old.omni")).unwrap(); - let sidecar = write_delete_sidecar(dir.path(), "old", Some(&approval_id), "01DROW7B"); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_rolled_forward") - ); - assert!(!sidecar.exists()); - let state = read_state_json(dir.path()); - assert!( - !state["applied_revision"]["resources"] - .as_object() - .unwrap() - .contains_key("graph.old") - ); - assert_eq!(state["observations"]["graph.old"]["kind"], "tombstone"); - assert!(state["approval_records"][&approval_id]["consumed_at"].is_string()); - assert!( - state["recovery_records"] - .as_object() - .unwrap() - .values() - .any(|record| record["kind"] == "graph_delete" - && record["outcome"] == "rolled_forward") - ); - // The artifact file is marked consumed post-CAS. - let artifact: serde_json::Value = serde_json::from_str( - &fs::read_to_string( - dir.path() - .join(CLUSTER_APPROVALS_DIR) - .join(format!("{approval_id}.json")), - ) - .unwrap(), - ) - .unwrap(); - assert!(artifact["consumed_at"].is_string()); - assert!(out.converged, "{out:?}"); - } - - #[tokio::test] - async fn sweep_reproposes_incomplete_delete() { - let dir = fixture(); - seed_deletable_state(dir.path()); // root present - let approved = approve_config_dir(dir.path(), "graph.old", "andrew").await; - assert!(approved.ok); - let sidecar = write_delete_sidecar(dir.path(), "old", approved.approval_id.as_deref(), "01DROW8"); - - // Row 8: the stale intent is retired with a warning, and the same run - // re-executes the still-approved delete to completion. - let out = apply_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "graph_delete_incomplete") - ); - assert!(!sidecar.exists()); - assert!(!dir.path().join(CLUSTER_GRAPHS_DIR).join("old.omni").exists()); - assert!(out.converged, "{out:?}"); - } - - // ---- policy bindings in the applied revision (5A) ---- - - #[tokio::test] - async fn apply_records_policy_bindings() { - let dir = fixture(); - write_applyable_state(dir.path()); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok && out.converged, "{:?}", out.diagnostics); - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["policy.base"]["applies_to"], - serde_json::json!(["graph.knowledge"]), - "{state}" - ); - // Non-policy entries carry no bindings field at all. - assert!( - state["applied_revision"]["resources"]["query.knowledge.find_person"] - .get("applies_to") - .is_none() - ); - } - - #[tokio::test] - async fn binding_change_is_a_visible_plan_change() { - let dir = fixture(); - write_applyable_state(dir.path()); - let converge = apply_config_dir(dir.path()).await; - assert!(converge.converged, "{converge:?}"); - // Edit ONLY applies_to: the policy file digest is unchanged. - fs::write( - dir.path().join(CLUSTER_CONFIG_FILE), - r#" -version: 1 -metadata: - name: test -state: - backend: cluster - lock: true -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -policies: - base: - file: ./base.policy.yaml - applies_to: [cluster, knowledge] -"#, - ) - .unwrap(); - - let plan = plan_config_dir(dir.path()).await; - let change = plan - .changes - .iter() - .find(|change| change.resource == "policy.base") - .expect("binding change must be visible in plan"); - assert!(change.binding_change); - assert_eq!(change.operation, PlanOperation::Update); - assert_eq!(change.before_digest, change.after_digest); - - let out = apply_config_dir(dir.path()).await; - assert!(out.ok && out.converged, "{out:?}"); - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["policy.base"]["applies_to"], - serde_json::json!(["cluster", "graph.knowledge"]) - ); - // Idempotent: a second run sees no changes. - let again = apply_config_dir(dir.path()).await; - assert!(again.changes.is_empty() && !again.state_written, "{again:?}"); - } - - #[tokio::test] - async fn pre_5a_state_backfills_bindings() { - let dir = fixture(); - write_applyable_state(dir.path()); - let converge = apply_config_dir(dir.path()).await; - assert!(converge.converged, "{converge:?}"); - // Strip the bindings from the state entry (a pre-5A ledger). - let mut state: serde_json::Value = serde_json::from_str( - &fs::read_to_string(dir.path().join(CLUSTER_STATE_FILE)).unwrap(), - ) - .unwrap(); - state["applied_revision"]["resources"]["policy.base"] - .as_object_mut() - .unwrap() - .remove("applies_to"); - fs::write( - dir.path().join(CLUSTER_STATE_FILE), - serde_json::to_string_pretty(&state).unwrap(), - ) - .unwrap(); - - let plan = plan_config_dir(dir.path()).await; - assert!( - plan.changes - .iter() - .any(|change| change.resource == "policy.base" && change.binding_change), - "{plan:?}" - ); - let out = apply_config_dir(dir.path()).await; - assert!(out.ok && out.converged, "{out:?}"); - let healed = read_state_json(dir.path()); - assert_eq!( - healed["applied_revision"]["resources"]["policy.base"]["applies_to"], - serde_json::json!(["graph.knowledge"]) - ); - } - - #[tokio::test] - async fn bindings_survive_refresh() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - let converge = apply_config_dir(dir.path()).await; - assert!(converge.converged, "{converge:?}"); - - let refresh = refresh_config_dir(dir.path()).await; - assert!(refresh.ok, "{:?}", refresh.diagnostics); - let state = read_state_json(dir.path()); - assert_eq!( - state["applied_revision"]["resources"]["policy.base"]["applies_to"], - serde_json::json!(["graph.knowledge"]) - ); - } - - // ---- serving snapshot (5B read-only loader) ---- - - // ---- storage: root (RFC-006) ---- - - #[tokio::test] - async fn storage_root_defaults_to_config_dir_layout() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - let out = apply_config_dir(dir.path()).await; - assert!(out.converged, "{out:?}"); - // No storage: key β€” the original on-disk layout, byte-compatible. - assert!(dir.path().join(CLUSTER_STATE_FILE).exists()); - assert!(dir.path().join(CLUSTER_RESOURCES_DIR).exists()); - assert!(dir.path().join("graphs/knowledge.omni").exists()); - } - - #[tokio::test] - async fn storage_root_file_uri_relocates_the_cluster() { - let dir = fixture(); - let storage = tempfile::tempdir().unwrap(); - let storage_path = storage.path().to_string_lossy().to_string(); - let mut config = fs::read_to_string(dir.path().join("cluster.yaml")).unwrap(); - config = config.replace("version: 1\n", &format!("version: 1\nstorage: {storage_path}\n")); - fs::write(dir.path().join("cluster.yaml"), config).unwrap(); - - let import = import_config_dir(dir.path()).await; - assert!(import.ok, "{:?}", import.diagnostics); - let out = apply_config_dir(dir.path()).await; - assert!(out.ok && out.converged, "{:?}", out.diagnostics); - - // Everything lives under the declared root; nothing under config dir. - assert!(storage.path().join("__cluster/state.json").exists()); - assert!(storage.path().join("graphs/knowledge.omni").exists()); - assert!(storage.path().join(CLUSTER_RESOURCES_DIR).exists()); - assert!(!dir.path().join(CLUSTER_STATE_FILE).exists()); - assert!(!dir.path().join("graphs").exists()); - - // The serving snapshot follows the root. - let snapshot = read_serving_snapshot(dir.path()).await.unwrap(); - assert!( - snapshot.graphs[0] - .root - .starts_with(storage.path()), - "{:?}", - snapshot.graphs[0].root - ); - } - - #[test] - fn storage_root_invalid_uri_fails_validation() { - let dir = fixture(); - let mut config = fs::read_to_string(dir.path().join("cluster.yaml")).unwrap(); - config = config.replace("version: 1\n", "version: 1\nstorage: \"s3://\"\n"); - fs::write(dir.path().join("cluster.yaml"), config).unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "invalid_storage_root"), - "{:?}", - out.diagnostics - ); - } - - #[tokio::test] - async fn serving_snapshot_reads_converged_cluster() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - let converge = apply_config_dir(dir.path()).await; - assert!(converge.converged, "{converge:?}"); - - let snapshot = read_serving_snapshot(dir.path()).await.expect("converged cluster must serve"); - assert_eq!(snapshot.graphs.len(), 1); - assert_eq!(snapshot.graphs[0].graph_id, "knowledge"); - assert!(snapshot.graphs[0].root.ends_with("graphs/knowledge.omni")); - assert_eq!(snapshot.queries.len(), 1); - assert_eq!(snapshot.queries[0].name, "find_person"); - assert!(snapshot.queries[0].source.contains("query find_person")); - assert_eq!(snapshot.policies.len(), 1); - assert_eq!(snapshot.policies[0].applies_to, vec!["graph.knowledge"]); - // Content, not a path: the catalog may live on object storage. - // The fixture bundle is `rules: []` β€” assert the verified text. - assert!(snapshot.policies[0].source.contains("rules:")); - } - - #[tokio::test] - async fn serving_snapshot_refuses_missing_state() { - let dir = fixture(); - let err = read_serving_snapshot(dir.path()).await.unwrap_err(); - assert!( - err.iter().any(|diagnostic| diagnostic.code == "cluster_state_missing"), - "{err:?}" - ); - } - - #[tokio::test] - async fn serving_snapshot_refuses_pending_recovery() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - apply_config_dir(dir.path()).await; - write_schema_apply_sidecar(dir.path(), "knowledge", "whatever", "01SERVE"); - - let err = read_serving_snapshot(dir.path()).await.unwrap_err(); - assert!( - err.iter().any(|diagnostic| diagnostic.code == "cluster_recovery_pending"), - "{err:?}" - ); - } - - #[tokio::test] - async fn serving_snapshot_refuses_tampered_blob_and_stripped_bindings() { - let dir = fixture(); - init_derived_graph(dir.path()).await; - write_applyable_state(dir.path()); - apply_config_dir(dir.path()).await; - // Tamper with the query blob... - let snapshot = read_serving_snapshot(dir.path()).await.unwrap(); - let desired = validate_config_dir(dir.path()); - let query_digest = &desired.resource_digests["query.knowledge.find_person"]; - let blob = dir - .path() - .join(CLUSTER_RESOURCES_DIR) - .join("query/knowledge/find_person") - .join(format!("{query_digest}.gq")); - fs::write(&blob, "tampered").unwrap(); - // ...and strip the policy bindings (pre-5A ledger). - let mut state: serde_json::Value = serde_json::from_str( - &fs::read_to_string(dir.path().join(CLUSTER_STATE_FILE)).unwrap(), - ) - .unwrap(); - state["applied_revision"]["resources"]["policy.base"] - .as_object_mut() - .unwrap() - .remove("applies_to"); - fs::write( - dir.path().join(CLUSTER_STATE_FILE), - serde_json::to_string_pretty(&state).unwrap(), - ) - .unwrap(); - - let err = read_serving_snapshot(dir.path()).await.unwrap_err(); - assert!( - err.iter() - .any(|diagnostic| diagnostic.code == "catalog_payload_digest_mismatch"), - "{err:?}" - ); - assert!( - err.iter().any(|diagnostic| diagnostic.code == "policy_bindings_missing"), - "{err:?}" - ); - let _ = snapshot; // the pre-tamper read succeeded - } - - #[tokio::test] - async fn serving_snapshot_refuses_empty_cluster() { - let dir = fixture(); - write_state_resources(dir.path(), &[]); // state exists, no graphs - - let err = read_serving_snapshot(dir.path()).await.unwrap_err(); - assert!( - err.iter().any(|diagnostic| diagnostic.code == "cluster_empty"), - "{err:?}" - ); - } - - // ---- query discovery (Terraform-style declaration) ---- - - #[test] - fn queries_directory_discovers_every_declaration() { - let dir = tempfile::tempdir().unwrap(); - fs::write(dir.path().join("people.pg"), "\nnode Person {\n name: String @key\n}\n").unwrap(); - fs::create_dir(dir.path().join("queries")).unwrap(); - fs::write( - dir.path().join("queries/people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n\nquery all_people() {\n match { $p: Person }\n return { $p.name }\n}\n", - ) - .unwrap(); - fs::write( - dir.path().join("queries/extra.gq"), - "\nquery count_people() {\n match { $p: Person }\n return { count($p) }\n}\n", - ) - .unwrap(); - fs::write(dir.path().join("queries/notes.txt"), "ignored").unwrap(); - fs::write( - dir.path().join("cluster.yaml"), - "version: 1\ngraphs:\n knowledge:\n schema: ./people.pg\n queries: ./queries/\n", - ) - .unwrap(); - - let out = validate_config_dir(dir.path()); - assert!(out.ok, "{:?}", out.diagnostics); - let names: Vec<&str> = out - .resource_digests - .keys() - .filter_map(|address| address.strip_prefix("query.knowledge.")) - .collect(); - assert_eq!(names, vec!["all_people", "count_people", "find_person"]); - } - - #[test] - fn queries_list_and_single_file_forms_discover() { - let dir = tempfile::tempdir().unwrap(); - fs::write(dir.path().join("people.pg"), "\nnode Person {\n name: String @key\n}\n").unwrap(); - fs::write( - dir.path().join("a.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n", - ) - .unwrap(); - fs::write( - dir.path().join("b.gq"), - "\nquery all_people() {\n match { $p: Person }\n return { $p.name }\n}\n", - ) - .unwrap(); - fs::write( - dir.path().join("cluster.yaml"), - "version: 1\ngraphs:\n knowledge:\n schema: ./people.pg\n queries: [./a.gq, ./b.gq]\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.resource_digests.contains_key("query.knowledge.find_person")); - assert!(out.resource_digests.contains_key("query.knowledge.all_people")); - - // Single-file string form - fs::write( - dir.path().join("cluster.yaml"), - "version: 1\ngraphs:\n knowledge:\n schema: ./people.pg\n queries: ./a.gq\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(out.ok, "{:?}", out.diagnostics); - assert!(out.resource_digests.contains_key("query.knowledge.find_person")); - assert!(!out.resource_digests.contains_key("query.knowledge.all_people")); - } - - #[test] - fn query_discovery_rejects_duplicates_and_parse_errors() { - let dir = tempfile::tempdir().unwrap(); - fs::write(dir.path().join("people.pg"), "\nnode Person {\n name: String @key\n}\n").unwrap(); - let decl = "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n"; - fs::write(dir.path().join("a.gq"), decl).unwrap(); - fs::write(dir.path().join("b.gq"), decl).unwrap(); - fs::write( - dir.path().join("cluster.yaml"), - "version: 1\ngraphs:\n knowledge:\n schema: ./people.pg\n queries: [./a.gq, ./b.gq]\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "duplicate_query_name"), - "{:?}", - out.diagnostics - ); - - fs::write(dir.path().join("broken.gq"), "query {{{ nope").unwrap(); - fs::write( - dir.path().join("cluster.yaml"), - "version: 1\ngraphs:\n knowledge:\n schema: ./people.pg\n queries: ./broken.gq\n", - ) - .unwrap(); - let out = validate_config_dir(dir.path()); - assert!(!out.ok); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "query_parse_error"), - "{:?}", - out.diagnostics - ); - } - - #[tokio::test] - async fn status_warns_on_pending_recovery_sidecar() { - let dir = fixture(); - write_applyable_state(dir.path()); - write_create_sidecar(dir.path(), "knowledge", "irrelevant", "01STATUS"); - - let out = status_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_pending" - && diagnostic.severity == DiagnosticSeverity::Warning) - ); - } - - #[tokio::test] - async fn plan_annotates_apply_dispositions() { - let dir = fixture(); - let out = plan_config_dir(dir.path()).await; - assert!(out.ok, "{:?}", out.diagnostics); - let by_resource: BTreeMap<&str, &PlanChange> = out - .changes - .iter() - .map(|change| (change.resource.as_str(), change)) - .collect(); - // Stage 4A: graph/schema creates are executable, and dependents ride - // the same run β€” plan previews exactly that. - assert_eq!( - by_resource["graph.knowledge"].disposition, - Some(ApplyDisposition::Applied) - ); - assert_eq!( - by_resource["schema.knowledge"].disposition, - Some(ApplyDisposition::Applied) - ); - assert_eq!( - by_resource["query.knowledge.find_person"].disposition, - Some(ApplyDisposition::Applied) - ); - assert_eq!( - by_resource["policy.base"].disposition, - Some(ApplyDisposition::Applied) - ); - } diff --git a/crates/omnigraph-cluster/src/types.rs b/crates/omnigraph-cluster/src/types.rs deleted file mode 100644 index e44e2f4..0000000 --- a/crates/omnigraph-cluster/src/types.rs +++ /dev/null @@ -1,520 +0,0 @@ -//! Public output/diagnostic types and internal state/sidecar/approval -//! models (moved verbatim from lib.rs in the modularization). - -use super::*; - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum DiagnosticSeverity { - Error, - Warning, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct Diagnostic { - pub code: String, - pub severity: DiagnosticSeverity, - pub path: String, - pub message: String, -} - -impl Diagnostic { - pub(crate) fn error(code: impl Into, path: impl Into, message: impl Into) -> Self { - Self { - code: code.into(), - severity: DiagnosticSeverity::Error, - path: path.into(), - message: message.into(), - } - } - - pub(crate) fn warning( - code: impl Into, - path: impl Into, - message: impl Into, - ) -> Self { - Self { - code: code.into(), - severity: DiagnosticSeverity::Warning, - path: path.into(), - message: message.into(), - } - } -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct ResourceSummary { - pub address: String, - pub kind: String, - pub digest: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq, PartialOrd, Ord)] -pub struct Dependency { - pub from: String, - pub to: String, -} - -#[derive(Debug, Clone, Serialize)] -pub struct ValidateOutput { - pub ok: bool, - pub config_dir: String, - pub config_file: String, - pub resource_digests: BTreeMap, - pub resources: Vec, - pub dependencies: Vec, - pub diagnostics: Vec, -} - -#[derive(Debug, Clone, Serialize)] -pub struct DesiredRevision { - #[serde(skip_serializing_if = "Option::is_none")] - pub config_digest: Option, -} - -#[derive(Debug, Clone, Serialize)] -pub struct StateObservations { - pub state_path: String, - pub lock_path: String, - pub state_found: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub applied_config_digest: Option, - pub state_revision: u64, - #[serde(skip_serializing_if = "Option::is_none")] - pub state_cas: Option, - pub resource_count: usize, - pub locked: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub lock_id: Option, - pub lock_acquired: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub acquired_lock_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub lock_operation: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub lock_created_at: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub lock_pid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub lock_age_seconds: Option, -} - -impl StateObservations { - pub(crate) fn observe_lock_metadata(&mut self, lock: &StateLockFile) { - self.locked = true; - self.lock_id = Some(lock.lock_id.clone()); - self.lock_operation = Some(lock.operation.clone()); - self.lock_created_at = Some(lock.created_at.clone()); - self.lock_pid = Some(lock.pid); - self.lock_age_seconds = lock_age_seconds(&lock.created_at); - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ResourceLifecycleStatus { - Pending, - Planned, - Applying, - Applied, - Drifted, - Blocked, - Error, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ResourceStatusRecord { - pub status: ResourceLifecycleStatus, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub conditions: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub message: Option, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum PlanOperation { - Create, - Update, - Delete, -} - -/// How `cluster apply` treats a planned change in the current stage. -/// -/// `Applied` changes execute (config-only query/policy catalog writes). -/// `Derived` marks a `graph.` composite-digest update that converges -/// automatically once its applied query digests land in state. `Deferred` -/// changes need a later phase (graph/schema lifecycle or schema content). -/// `Blocked` query/policy changes are gated by an unapplied or missing -/// dependency. -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ApplyDisposition { - Applied, - Derived, - Deferred, - Blocked, -} - -#[derive(Debug, Clone, Serialize, PartialEq)] -pub struct PlanChange { - pub resource: String, - pub operation: PlanOperation, - #[serde(skip_serializing_if = "Option::is_none")] - pub before_digest: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub after_digest: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub disposition: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// True for a policy change whose file digest is unchanged but whose - /// `applies_to` bindings differ from the applied revision (including the - /// pre-5A backfill case). - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - pub binding_change: bool, - /// For schema updates: the engine's migration plan against the live - /// graph (RFC-004 Β§D7's data-aware preview). Absent when the preview is - /// unavailable (warning `schema_preview_unavailable`). - #[serde(skip_serializing_if = "Option::is_none")] - pub migration: Option, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct BlastRadius { - pub resource: String, - pub affected: Vec, -} - -#[derive(Debug, Clone, Serialize, PartialEq, Eq)] -pub struct ApprovalRequirement { - pub resource: String, - pub reason: String, - /// True when a valid (digest-matching, unconsumed) approval artifact is - /// pending for this change. - pub satisfied: bool, -} - -#[derive(Debug, Clone, Serialize)] -pub struct PlanOutput { - pub ok: bool, - pub config_dir: String, - pub desired_revision: DesiredRevision, - pub resource_digests: BTreeMap, - pub dependencies: Vec, - pub state_observations: StateObservations, - pub changes: Vec, - pub blast_radius: Vec, - pub approvals_required: Vec, - pub diagnostics: Vec, -} - -#[derive(Debug, Clone, Serialize)] -pub struct StatusOutput { - pub ok: bool, - pub config_dir: String, - pub state_observations: StateObservations, - pub resource_digests: BTreeMap, - pub resource_statuses: BTreeMap, - pub observations: BTreeMap, - pub diagnostics: Vec, -} - -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum StateSyncOperation { - Refresh, - Import, -} - -#[derive(Debug, Clone, Serialize)] -pub struct StateSyncOutput { - pub ok: bool, - pub operation: StateSyncOperation, - pub config_dir: String, - pub state_observations: StateObservations, - pub resource_digests: BTreeMap, - pub resource_statuses: BTreeMap, - pub observations: BTreeMap, - pub diagnostics: Vec, -} - -#[derive(Debug, Clone, Serialize)] -pub struct ForceUnlockOutput { - pub ok: bool, - pub config_dir: String, - pub state_observations: StateObservations, - pub lock_removed: bool, - pub diagnostics: Vec, -} - -/// Output of config-only `cluster apply`. "Applied" means recorded in the -/// local cluster catalog (`__cluster/`); nothing applied here serves traffic β€” -/// the server still boots from `omnigraph.yaml` until the server-boot stage. -#[derive(Debug, Clone, Serialize)] -pub struct ApplyOutput { - pub ok: bool, - pub config_dir: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub actor: Option, - pub desired_revision: DesiredRevision, - pub state_observations: StateObservations, - /// Every planned change, with `disposition`/`reason` always populated. - pub changes: Vec, - pub applied_count: usize, - /// Deferred + Blocked changes (Derived composite updates count as neither). - pub deferred_count: usize, - /// True when state matches the desired revision after this apply. - pub converged: bool, - /// False for a no-op re-apply: state bytes (and revision) were left untouched. - pub state_written: bool, - /// The statuses as persisted: post-apply on success, the pre-apply on-disk - /// snapshot when the state write fails (never unpersisted in-memory state). - pub resource_statuses: BTreeMap, - pub diagnostics: Vec, -} - -/// A digest-bound human approval for an irreversible operation (RFC-004 -/// Β§D4). Written by `cluster approve`, consumed by apply. The file is never -/// deleted on consumption β€” it is rewritten with `consumed_at` and also -/// summarized into the state ledger's `approval_records`, so the audit fact -/// survives the loss of either store (axiom 11). -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ApprovalArtifact { - pub(crate) schema_version: u32, - pub(crate) approval_id: String, - pub(crate) resource: String, - pub(crate) operation: String, - pub(crate) reason: String, - pub(crate) bound_config_digest: String, - #[serde(default)] - pub(crate) bound_before_digest: Option, - #[serde(default)] - pub(crate) bound_after_digest: Option, - pub(crate) approved_by: String, - pub(crate) created_at: String, - #[serde(default)] - pub(crate) consumed_at: Option, - #[serde(default)] - pub(crate) consumed_by_operation: Option, -} - -#[derive(Debug, Clone, Serialize)] -pub struct ApproveOutput { - pub ok: bool, - pub config_dir: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub approval_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub resource: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub operation: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub approved_by: Option, - pub diagnostics: Vec, -} - -#[derive(Debug, Clone)] -pub(crate) struct DesiredCluster { - pub(crate) config_dir: PathBuf, - pub(crate) config_digest: String, - /// The declared `storage:` root, if any (None β‡’ the config dir itself). - pub(crate) storage_root: Option, - pub(crate) state_lock: bool, - pub(crate) graphs: Vec, - pub(crate) resource_digests: BTreeMap, - pub(crate) resources: Vec, - pub(crate) dependencies: Vec, - /// `policy.` address -> normalized applies_to refs. - pub(crate) policy_bindings: BTreeMap>, -} - -#[derive(Debug, Clone)] -pub(crate) struct DesiredGraph { - pub(crate) id: String, - pub(crate) schema_digest: String, -} - -#[derive(Debug)] -pub(crate) struct ParsedConfig { - pub(crate) raw: Option, - pub(crate) diagnostics: Vec, - pub(crate) config_dir: PathBuf, - pub(crate) config_file: PathBuf, -} - -#[derive(Debug, Clone)] -pub(crate) struct ClusterSettings { - pub(crate) state_lock: bool, - pub(crate) storage_root: Option, -} - -#[derive(Debug)] -pub(crate) struct LoadOutcome { - pub(crate) desired: Option, - pub(crate) diagnostics: Vec, - pub(crate) config_dir: PathBuf, - pub(crate) config_file: PathBuf, -} - -#[derive(Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct RawClusterConfig { - pub(crate) version: u32, - #[serde(default)] - pub(crate) metadata: Metadata, - /// Storage root URI for everything the cluster stores: the state - /// ledger, catalog, sidecars, approvals, and derived graph roots. - /// Absent β‡’ `file://` (the original layout, byte-compatible). - /// `s3://bucket/prefix` puts the whole cluster on object storage. - #[serde(default)] - pub(crate) storage: Option, - #[serde(default)] - pub(crate) state: StateConfig, - #[serde(default)] - pub(crate) graphs: BTreeMap, - #[serde(default)] - pub(crate) policies: BTreeMap, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct Metadata { - pub(crate) name: Option, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct StateConfig { - pub(crate) backend: Option, - pub(crate) lock: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct GraphConfig { - pub(crate) schema: PathBuf, - #[serde(default)] - pub(crate) queries: QueriesDecl, -} - -/// How a graph declares its stored queries. Terraform-style: the `.gq` -/// files ARE the declaration β€” point at them (or a directory) and every -#[derive(Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct QueryConfig { - pub(crate) file: PathBuf, -} - -#[derive(Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct PolicyConfig { - pub(crate) file: PathBuf, - pub(crate) applies_to: Vec, -} - -// Stage 2A/2B accept these forward-compatible state sections so existing -// ledgers won't churn while approval/recovery semantics are staged later. -#[allow(dead_code)] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ClusterState { - pub(crate) version: u32, - #[serde(default)] - pub(crate) state_revision: u64, - pub(crate) applied_revision: AppliedRevisionState, - #[serde(default)] - pub(crate) resource_statuses: BTreeMap, - #[serde(default)] - pub(crate) approval_records: BTreeMap, - #[serde(default)] - pub(crate) recovery_records: BTreeMap, - #[serde(default)] - pub(crate) observations: BTreeMap, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct AppliedRevisionState { - #[serde(default)] - pub(crate) config_digest: Option, - #[serde(default)] - pub(crate) resources: BTreeMap, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct StateResource { - pub(crate) digest: String, - /// Policy resources only: the applied `applies_to` bindings, normalized - /// to typed refs (`cluster` | `graph.`). Recorded so the state - /// ledger is serving-sufficient for the Phase-5 server boot (RFC-005 - /// Β§D3). Absent on pre-5A entries (backfilled by the next apply) and on - /// non-policy resources. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub(crate) applies_to: Option>, -} - -#[derive(Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct StateLockFile { - pub(crate) version: u32, - pub(crate) lock_id: String, - pub(crate) operation: String, - pub(crate) created_at: String, - pub(crate) pid: u32, -} - -/// Recovery-intent record for a graph-moving apply operation (RFC-004 Β§D2). -/// Written under the state lock before the engine call that can create or -/// move a graph manifest; deleted only after the cluster state CAS that -/// records the outcome lands. The sweep (Β§D3) classifies survivors. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct RecoverySidecar { - pub(crate) schema_version: u32, - pub(crate) operation_id: String, - pub(crate) started_at: String, - #[serde(default)] - pub(crate) actor: Option, - pub(crate) kind: RecoverySidecarKind, - pub(crate) graph_id: String, - pub(crate) graph_uri: String, - #[serde(default)] - pub(crate) observed_manifest_version: Option, - #[serde(default)] - pub(crate) expected_manifest_version: Option, - pub(crate) desired_schema_digest: String, - #[serde(default)] - pub(crate) state_cas_base: Option, - /// For graph_delete: the approval this operation consumes; lets a sweep - /// roll-forward consume it too. - #[serde(default)] - pub(crate) approval_id: Option, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub(crate) enum RecoverySidecarKind { - GraphCreate, - SchemaApply, - GraphDelete, -} - -#[derive(Debug, Default)] -pub(crate) struct SweepOutcome { - /// Graphs whose sidecar was kept (rows 5/6): graph-moving work for them - /// is blocked until the operator repairs and re-observes. - pub(crate) pending_graphs: BTreeSet, - /// Sidecars whose outcome is recorded (rows 2/4): deleted only after the - /// command's state write lands, so a CAS failure re-sweeps them. - /// Store URIs (the storage layer addresses everything by URI). - pub(crate) completed_sidecars: Vec, - /// Approval artifacts consumed by a roll-forward (delete row 7b): their - /// files are rewritten with consumed_at only after the state write lands. - pub(crate) consumed_approvals: Vec, -} diff --git a/crates/omnigraph-cluster/tests/failpoints.rs b/crates/omnigraph-cluster/tests/failpoints.rs deleted file mode 100644 index 5cdf2d4..0000000 --- a/crates/omnigraph-cluster/tests/failpoints.rs +++ /dev/null @@ -1,593 +0,0 @@ -//! Fault-injection tests for the cluster apply protocol. -//! -//! These live in an integration binary (not in-source) deliberately: the fail -//! crate's registry is process-global, so a configured `cluster_apply.*` -//! action would fire inside any concurrently running normal apply test in the -//! lib-test process. A separate binary isolates the registry by construction β€” -//! same reason the engine keeps its failpoint suite in `tests/failpoints.rs`. - -#![cfg(feature = "failpoints")] - -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; - -use fail::FailScenario; -use omnigraph_cluster::failpoints::ScopedFailPoint; -use omnigraph::db::Omnigraph; -use omnigraph_cluster::{ - ApplyOptions, apply_config_dir, apply_config_dir_with_options, approve_config_dir, - validate_config_dir, -}; -use tempfile::tempdir; - -const SCHEMA: &str = r#" -node Person { - name: String @key - age: I32? -} -"#; - -const QUERY: &str = r#" -query find_person($name: String) { - match { $p: Person { name: $name } } - return { $p.name, $p.age } -} -"#; - -fn fixture() -> tempfile::TempDir { - let dir = tempdir().unwrap(); - fs::write(dir.path().join("people.pg"), SCHEMA).unwrap(); - fs::write(dir.path().join("people.gq"), QUERY).unwrap(); - fs::write(dir.path().join("base.policy.yaml"), "rules: []\n").unwrap(); - fs::write( - dir.path().join("cluster.yaml"), - r#" -version: 1 -state: - backend: cluster - lock: true -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -policies: - base: - file: ./base.policy.yaml - applies_to: [knowledge] -"#, - ) - .unwrap(); - dir -} - -/// Seed a state.json where the graph/schema digests match desired, so query -/// and policy changes are applicable. Digests are borrowed from the public -/// validate output; the graph composite is a placeholder that apply converges -/// as a Derived update. -fn seed_applyable_state(config_dir: &Path) -> BTreeMap { - let validate = validate_config_dir(config_dir); - assert!(validate.ok, "{:?}", validate.diagnostics); - let schema_digest = validate.resource_digests["schema.knowledge"].clone(); - let state_dir = config_dir.join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - format!( - r#"{{ - "version": 1, - "state_revision": 1, - "applied_revision": {{ - "resources": {{ - "graph.knowledge": {{ "digest": "seed" }}, - "schema.knowledge": {{ "digest": "{schema_digest}" }} - }} - }} -}} -"# - ), - ) - .unwrap(); - validate.resource_digests -} - -fn state_path(config_dir: &Path) -> PathBuf { - config_dir.join("__cluster/state.json") -} - -fn query_blob(config_dir: &Path, digests: &BTreeMap) -> PathBuf { - config_dir - .join("__cluster/resources/query/knowledge/find_person") - .join(format!("{}.gq", digests["query.knowledge.find_person"])) -} - -#[tokio::test] -async fn failpoint_wiring_returns_injected_diagnostic() { - let scenario = FailScenario::setup(); - let dir = fixture(); - seed_applyable_state(dir.path()); - - let _failpoint = ScopedFailPoint::new("cluster_apply.after_payload_phase", "return"); - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(out.diagnostics.iter().any(|diagnostic| { - diagnostic.code == "injected_failpoint" - && diagnostic - .message - .contains("cluster_apply.after_payload_phase") - })); - drop(_failpoint); - scenario.teardown(); -} - -/// Crash between the payload phase and the state write: blobs are on disk, -/// state.json is byte-identical, nothing is acknowledged β€” and a plain re-run -/// repairs by trusting the existing content-addressed blobs. -#[tokio::test] -async fn apply_crash_after_payload_phase_leaves_state_unmoved_then_recovers() { - let scenario = FailScenario::setup(); - let dir = fixture(); - let digests = seed_applyable_state(dir.path()); - let state_before = fs::read(state_path(dir.path())).unwrap(); - - { - let _failpoint = ScopedFailPoint::new("cluster_apply.after_payload_phase", "return"); - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(!out.state_written); - assert!(!out.converged); - assert_eq!(out.applied_count, 0); - // Persisted pre-apply snapshot: no phantom Applied statuses. - assert!( - !out.resource_statuses - .contains_key("query.knowledge.find_person"), - "{:?}", - out.resource_statuses - ); - // State has not moved; payloads are inert on disk; the lock released. - assert_eq!(fs::read(state_path(dir.path())).unwrap(), state_before); - assert!(query_blob(dir.path(), &digests).exists()); - assert!(!dir.path().join("__cluster/lock.json").exists()); - } - - // The repair is a plain re-run: existing blobs are trusted by digest. - let recovered = apply_config_dir(dir.path()).await; - assert!(recovered.ok, "{:?}", recovered.diagnostics); - assert!(recovered.converged); - assert!(recovered.state_written); - assert_eq!( - recovered.resource_statuses["query.knowledge.find_person"].status, - omnigraph_cluster::ResourceLifecycleStatus::Applied - ); - scenario.teardown(); -} - -/// A concurrent writer mutating state.json between apply's read and its write -/// (possible under `state.lock: false`) must surface `state_cas_mismatch`, -/// acknowledge nothing, and leave the concurrent writer's state on disk. -#[tokio::test] -async fn apply_cas_race_surfaces_state_cas_mismatch() { - let scenario = FailScenario::setup(); - let dir = fixture(); - let digests = seed_applyable_state(dir.path()); - - // Simulate the concurrent writer at the exact race window: rewrite - // state.json (valid JSON, graph/schema digests preserved, revision 99) - // after apply read it but before apply writes. RAII-guarded so a panic - // inside apply cannot leak the callback into the global registry. - let race_path = state_path(dir.path()); - let failpoint = - ScopedFailPoint::with_callback("cluster_apply.before_state_write", move || { - let mut state: serde_json::Value = - serde_json::from_str(&fs::read_to_string(&race_path).unwrap()).unwrap(); - state["state_revision"] = serde_json::json!(99); - fs::write(&race_path, serde_json::to_string_pretty(&state).unwrap()).unwrap(); - }); - - let out = apply_config_dir(dir.path()).await; - drop(failpoint); - - assert!(!out.ok); - assert!(!out.state_written); - assert!( - out.diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "state_cas_mismatch"), - "{:?}", - out.diagnostics - ); - // Persisted snapshot, not the unwritten in-memory mutations. - assert!( - !out.resource_statuses - .contains_key("query.knowledge.find_person") - ); - // The concurrent writer's state is what's on disk; apply's mutation never landed. - let state: serde_json::Value = - serde_json::from_str(&fs::read_to_string(state_path(dir.path())).unwrap()).unwrap(); - assert_eq!(state["state_revision"], 99); - assert!( - state["applied_revision"]["resources"] - .get("query.knowledge.find_person") - .is_none() - ); - // Blobs written before the race are inert. - assert!(query_blob(dir.path(), &digests).exists()); - - // Recovery is a plain re-run against the rewritten state. - let recovered = apply_config_dir(dir.path()).await; - assert!(recovered.ok, "{:?}", recovered.diagnostics); - assert!(recovered.converged); - scenario.teardown(); -} - -fn seed_empty_state(config_dir: &Path) { - let state_dir = config_dir.join("__cluster"); - fs::create_dir_all(&state_dir).unwrap(); - fs::write( - state_dir.join("state.json"), - r#"{ - "version": 1, - "state_revision": 1, - "applied_revision": { "resources": {} } -} -"#, - ) - .unwrap(); -} - -fn recovery_sidecars(config_dir: &Path) -> Vec { - match fs::read_dir(config_dir.join("__cluster/recoveries")) { - Ok(entries) => { - let mut paths: Vec = entries - .flatten() - .map(|entry| entry.path()) - .filter(|path| path.extension().is_some_and(|ext| ext == "json")) - .collect(); - paths.sort(); - paths - } - Err(_) => Vec::new(), - } -} - -/// Crash before the init: the create-intent sidecar survives, nothing moved. -/// The next run's sweep removes the intent (row 1) and the same run creates -/// the graph and converges. -#[tokio::test] -async fn create_crash_before_init_recovers_via_sweep() { - let scenario = FailScenario::setup(); - let dir = fixture(); - seed_empty_state(dir.path()); - - { - let _failpoint = ScopedFailPoint::new("cluster_apply.before_graph_create", "return"); - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(out.diagnostics.iter().any(|diagnostic| { - diagnostic.code == "injected_failpoint" - && diagnostic - .message - .contains("cluster_apply.before_graph_create") - })); - assert_eq!(recovery_sidecars(dir.path()).len(), 1); - assert!(!dir.path().join("graphs/knowledge.omni").exists()); - // No resource digest moved. - let state: serde_json::Value = serde_json::from_str( - &fs::read_to_string(dir.path().join("__cluster/state.json")).unwrap(), - ) - .unwrap(); - assert!( - state["applied_revision"]["resources"] - .as_object() - .unwrap() - .is_empty() - ); - } - - let recovered = apply_config_dir(dir.path()).await; - assert!(recovered.ok, "{:?}", recovered.diagnostics); - assert!(recovered.converged); - assert!(dir.path().join("graphs/knowledge.omni").exists()); - assert!(recovery_sidecars(dir.path()).is_empty()); - scenario.teardown(); -} - -/// Crash after the init but before the state CAS: the graph exists, the -/// ledger is stale, nothing was acknowledged. The next run's sweep rolls the -/// ledger forward (row 4) with an audit entry, and the run converges. -#[tokio::test] -async fn create_crash_after_init_rolls_state_forward() { - let scenario = FailScenario::setup(); - let dir = fixture(); - seed_empty_state(dir.path()); - let state_before = fs::read(dir.path().join("__cluster/state.json")).unwrap(); - - { - let _failpoint = ScopedFailPoint::new("cluster_apply.after_graph_create", "return"); - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(!out.state_written); - // The graph exists; the cluster state is byte-identical (no ack). - assert!(dir.path().join("graphs/knowledge.omni").exists()); - assert_eq!( - fs::read(dir.path().join("__cluster/state.json")).unwrap(), - state_before - ); - // The sidecar carries the post-init manifest pin. - let sidecars = recovery_sidecars(dir.path()); - assert_eq!(sidecars.len(), 1); - let sidecar: serde_json::Value = - serde_json::from_str(&fs::read_to_string(&sidecars[0]).unwrap()).unwrap(); - assert!( - sidecar["expected_manifest_version"].is_number(), - "{sidecar}" - ); - } - - let recovered = apply_config_dir(dir.path()).await; - assert!(recovered.ok, "{:?}", recovered.diagnostics); - assert!( - recovered - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_rolled_forward") - ); - assert!(recovered.converged); - assert!(recovery_sidecars(dir.path()).is_empty()); - let state: serde_json::Value = serde_json::from_str( - &fs::read_to_string(dir.path().join("__cluster/state.json")).unwrap(), - ) - .unwrap(); - assert!( - state["recovery_records"] - .as_object() - .unwrap() - .values() - .any(|record| record["outcome"] == "rolled_forward") - ); - scenario.teardown(); -} - -const SCHEMA_V2: &str = r#" -node Person { - name: String @key - age: I32? - bio: String? -} -"#; - -async fn converge_with_live_graph(dir: &Path) { - let graph_dir = dir.join("graphs"); - fs::create_dir_all(&graph_dir).unwrap(); - Omnigraph::init( - graph_dir.join("knowledge.omni").to_string_lossy().as_ref(), - SCHEMA, - ) - .await - .unwrap(); - seed_applyable_state(dir); - let out = apply_config_dir(dir).await; - assert!(out.ok && out.converged, "{:?}", out.diagnostics); -} - -async fn live_schema_digest(dir: &Path) -> String { - let uri = dir.join("graphs/knowledge.omni"); - let db = Omnigraph::open_read_only(uri.to_string_lossy().as_ref()) - .await - .unwrap(); - use sha2::{Digest, Sha256}; - let digest = Sha256::digest(db.schema_source().as_bytes()); - digest.iter().map(|byte| format!("{byte:02x}")).collect() -} - -/// Crash before the engine schema apply: sidecar (with actor) survives, the -/// live schema and ledger are untouched; the next run's sweep retires the -/// stale intent and the same run applies and converges. -#[tokio::test] -async fn schema_crash_before_apply_recovers_via_sweep() { - let scenario = FailScenario::setup(); - let dir = fixture(); - converge_with_live_graph(dir.path()).await; - let pre_digest = live_schema_digest(dir.path()).await; - fs::write(dir.path().join("people.pg"), SCHEMA_V2).unwrap(); - - { - let _failpoint = ScopedFailPoint::new("cluster_apply.before_schema_apply", "return"); - let out = apply_config_dir_with_options( - dir.path(), - ApplyOptions { - actor: Some("test-actor".to_string()), - }, - ) - .await; - assert!(!out.ok); - assert_eq!(out.actor.as_deref(), Some("test-actor")); - let sidecars = recovery_sidecars(dir.path()); - assert_eq!(sidecars.len(), 1); - let sidecar: serde_json::Value = - serde_json::from_str(&fs::read_to_string(&sidecars[0]).unwrap()).unwrap(); - assert_eq!(sidecar["kind"], "schema_apply"); - assert_eq!(sidecar["actor"], "test-actor"); - // Nothing moved. - assert_eq!(live_schema_digest(dir.path()).await, pre_digest); - } - - let recovered = apply_config_dir(dir.path()).await; - assert!(recovered.ok, "{:?}", recovered.diagnostics); - assert!(recovered.converged); - assert!(recovery_sidecars(dir.path()).is_empty()); - assert_ne!(live_schema_digest(dir.path()).await, pre_digest); - scenario.teardown(); -} - -/// Crash after the engine schema apply, before the state CAS: the manifest -/// moved, the ledger is stale, nothing acknowledged; the next run's sweep -/// rolls the ledger forward with an audit entry and the run converges. -#[tokio::test] -async fn schema_crash_after_apply_rolls_state_forward() { - let scenario = FailScenario::setup(); - let dir = fixture(); - converge_with_live_graph(dir.path()).await; - fs::write(dir.path().join("people.pg"), SCHEMA_V2).unwrap(); - let state_before = fs::read(state_path(dir.path())).unwrap(); - let desired = validate_config_dir(dir.path()); - let v2_digest = desired.resource_digests["schema.knowledge"].clone(); - - { - let _failpoint = ScopedFailPoint::new("cluster_apply.after_schema_apply", "return"); - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(!out.state_written); - // The live schema moved; the ledger is byte-identical (no ack). - assert_eq!(live_schema_digest(dir.path()).await, v2_digest); - assert_eq!(fs::read(state_path(dir.path())).unwrap(), state_before); - let sidecars = recovery_sidecars(dir.path()); - assert_eq!(sidecars.len(), 1); - let sidecar: serde_json::Value = - serde_json::from_str(&fs::read_to_string(&sidecars[0]).unwrap()).unwrap(); - assert!(sidecar["expected_manifest_version"].is_number(), "{sidecar}"); - } - - let recovered = apply_config_dir(dir.path()).await; - assert!(recovered.ok, "{:?}", recovered.diagnostics); - assert!( - recovered - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_rolled_forward") - ); - assert!(recovered.converged); - assert!(recovery_sidecars(dir.path()).is_empty()); - let state: serde_json::Value = - serde_json::from_str(&fs::read_to_string(state_path(dir.path())).unwrap()).unwrap(); - assert_eq!( - state["applied_revision"]["resources"]["schema.knowledge"]["digest"], - v2_digest - ); - scenario.teardown(); -} - -/// Seed: converged state + a stale `old` graph subtree with a real root and -/// a valid approval for its delete. Returns the approval id. -async fn seed_approved_delete(dir: &Path) -> String { - let digests = seed_applyable_state(dir); - let graph_digest = digests["graph.knowledge"].clone(); - let schema_digest = digests["schema.knowledge"].clone(); - let state_dir = dir.join("__cluster"); - fs::write( - state_dir.join("state.json"), - format!( - r#"{{ - "version": 1, - "state_revision": 1, - "applied_revision": {{ - "resources": {{ - "graph.knowledge": {{ "digest": "{graph_digest}" }}, - "schema.knowledge": {{ "digest": "{schema_digest}" }}, - "graph.old": {{ "digest": "3333" }}, - "schema.old": {{ "digest": "4444" }} - }} - }} -}} -"# - ), - ) - .unwrap(); - let root = dir.join("graphs/old.omni"); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("_schema.pg"), "stale").unwrap(); - let approved = approve_config_dir(dir, "graph.old", "test-actor").await; - assert!(approved.ok, "{:?}", approved.diagnostics); - approved.approval_id.unwrap() -} - -/// Crash before the removal: root intact, approval unconsumed, no ack; the -/// next run retires the stale intent (row 8) and the still-approved delete -/// completes in the same run. -#[tokio::test] -async fn delete_crash_before_removal_reproposes() { - let scenario = FailScenario::setup(); - let dir = fixture(); - let approval_id = seed_approved_delete(dir.path()).await; - - { - let _failpoint = ScopedFailPoint::new("cluster_apply.before_graph_delete", "return"); - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(dir.path().join("graphs/old.omni").exists()); - assert_eq!(recovery_sidecars(dir.path()).len(), 1); - // The approval is untouched (file unconsumed). - let artifact: serde_json::Value = serde_json::from_str( - &fs::read_to_string( - dir.path() - .join("__cluster/approvals") - .join(format!("{approval_id}.json")), - ) - .unwrap(), - ) - .unwrap(); - assert!(artifact["consumed_at"].is_null()); - } - - let recovered = apply_config_dir(dir.path()).await; - assert!(recovered.ok, "{:?}", recovered.diagnostics); - assert!( - recovered - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "graph_delete_incomplete") - ); - assert!(recovered.converged); - assert!(!dir.path().join("graphs/old.omni").exists()); - assert!(recovery_sidecars(dir.path()).is_empty()); - scenario.teardown(); -} - -/// Crash after the removal, before the state CAS: root gone, ledger stale, -/// nothing acknowledged; the next run's sweep rolls the tombstone forward, -/// consumes the approval the sidecar carries, and audits the recovery. -#[tokio::test] -async fn delete_crash_after_removal_rolls_forward() { - let scenario = FailScenario::setup(); - let dir = fixture(); - let approval_id = seed_approved_delete(dir.path()).await; - let state_before = fs::read(state_path(dir.path())).unwrap(); - - { - let _failpoint = ScopedFailPoint::new("cluster_apply.after_graph_delete", "return"); - let out = apply_config_dir(dir.path()).await; - assert!(!out.ok); - assert!(!out.state_written); - assert!(!dir.path().join("graphs/old.omni").exists()); - assert_eq!(fs::read(state_path(dir.path())).unwrap(), state_before); - let sidecars = recovery_sidecars(dir.path()); - assert_eq!(sidecars.len(), 1); - let sidecar: serde_json::Value = - serde_json::from_str(&fs::read_to_string(&sidecars[0]).unwrap()).unwrap(); - assert_eq!(sidecar["approval_id"], approval_id.as_str()); - } - - let recovered = apply_config_dir(dir.path()).await; - assert!(recovered.ok, "{:?}", recovered.diagnostics); - assert!( - recovered - .diagnostics - .iter() - .any(|diagnostic| diagnostic.code == "cluster_recovery_rolled_forward") - ); - assert!(recovered.converged); - let state: serde_json::Value = - serde_json::from_str(&fs::read_to_string(state_path(dir.path())).unwrap()).unwrap(); - assert_eq!(state["observations"]["graph.old"]["kind"], "tombstone"); - assert!(state["approval_records"][&approval_id]["consumed_at"].is_string()); - assert!( - state["recovery_records"] - .as_object() - .unwrap() - .values() - .any(|record| record["kind"] == "graph_delete") - ); - scenario.teardown(); -} diff --git a/crates/omnigraph-cluster/tests/s3_cluster.rs b/crates/omnigraph-cluster/tests/s3_cluster.rs deleted file mode 100644 index 3c7cef3..0000000 --- a/crates/omnigraph-cluster/tests/s3_cluster.rs +++ /dev/null @@ -1,162 +0,0 @@ -//! Cluster-on-object-storage end-to-end (RFC-006): the full control-plane -//! lifecycle with `storage: s3://…` β€” import, apply (graph roots + catalog -//! on the bucket), serving snapshots from both the config dir and the bare -//! storage URI, schema evolution, and the approved delete (prefix removal). -//! -//! Gated like every S3 suite: skips unless `OMNIGRAPH_S3_TEST_BUCKET` is -//! set (CI runs it against containerized RustFS; locally use the RustFS -//! binary + `AWS_*` env, see docs/dev/testing.md). -//! -//! Runtime flavor is multi_thread on purpose: the state-lock guard's -//! drop-time release uses block_in_place on object stores, which is the -//! production (CLI) runtime shape β€” and the lock-release regression this -//! suite pins (a spawned delete dying with a short-lived runtime) only -//! reproduces realistically under it. - -use std::env; -use std::fs; - -use omnigraph_cluster::{ - apply_config_dir, import_config_dir, read_serving_snapshot, - read_serving_snapshot_from_storage, status_config_dir, validate_config_dir, -}; -use ulid::Ulid; - -const SCHEMA_V1: &str = "node Person {\n name: String @key\n}\n"; -const SCHEMA_V2: &str = "node Person {\n name: String @key\n title: String?\n}\n"; -const FIND_PERSON_GQ: &str = "query find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n"; -const POLICY_YAML: &str = r#" -version: 1 -actors: - - id: act-admin - roles: [admin] -rules: - - effect: permit - actions: [read, change, schema_apply, branch_create, branch_delete, branch_merge] - roles: [admin] -"#; - -/// Unique per-run storage root under the test bucket, or None to skip. -fn s3_storage_root(suite: &str) -> Option { - let bucket = env::var("OMNIGRAPH_S3_TEST_BUCKET").ok()?; - Some(format!("s3://{bucket}/cluster-e2e/{suite}-{}", Ulid::new())) -} - -fn write_cluster_fixture(dir: &std::path::Path, storage_root: &str, schema: &str) { - fs::write(dir.join("people.pg"), schema).unwrap(); - fs::create_dir_all(dir.join("queries")).unwrap(); - fs::write(dir.join("queries/people.gq"), FIND_PERSON_GQ).unwrap(); - fs::write(dir.join("intel.policy.yaml"), POLICY_YAML).unwrap(); - fs::write( - dir.join("cluster.yaml"), - format!( - r#"version: 1 -storage: {storage_root} -graphs: - knowledge: - schema: people.pg - queries: queries/ -policies: - intel: - file: intel.policy.yaml - applies_to: [graph.knowledge] -"# - ), - ) - .unwrap(); -} - -#[tokio::test(flavor = "multi_thread")] -async fn s3_cluster_full_lifecycle_import_apply_serve_evolve_delete() { - let Some(root) = s3_storage_root("lifecycle") else { - eprintln!("skipping s3 cluster e2e: OMNIGRAPH_S3_TEST_BUCKET is not set"); - return; - }; - let dir = tempfile::tempdir().unwrap(); - write_cluster_fixture(dir.path(), &root, SCHEMA_V1); - - // validate is config-only and must pass before any bucket I/O. - let validate = validate_config_dir(dir.path()); - assert!(validate.ok, "{:?}", validate.diagnostics); - - let import = import_config_dir(dir.path()).await; - assert!(import.ok, "{:?}", import.diagnostics); - - // The lock-release regression (caught live on the first smoke): the - // guard's drop must COMPLETE its bucket delete before the command - // returns β€” a follow-up command finding `state_lock_held` means the - // release was spawned into a dying runtime. - let status = status_config_dir(dir.path()).await; - assert!(status.ok, "{:?}", status.diagnostics); - assert!( - !status.state_observations.locked, - "import leaked the state lock on the bucket: {:?}", - status.state_observations - ); - - let apply = apply_config_dir(dir.path()).await; - assert!(apply.ok && apply.converged, "{:?}", apply.diagnostics); - - // Nothing stored locally: the config dir holds only declared sources. - assert!(!dir.path().join("__cluster").exists()); - assert!(!dir.path().join("graphs").exists()); - - // Serving snapshot resolves through cluster.yaml's storage: key… - let via_config = read_serving_snapshot(dir.path()).await.unwrap(); - assert_eq!(via_config.graphs.len(), 1); - let graph_root = via_config.graphs[0].root.to_string_lossy().to_string(); - assert!( - graph_root.starts_with("s3://") && graph_root.ends_with("graphs/knowledge.omni"), - "{graph_root}" - ); - assert_eq!(via_config.queries.len(), 1); - assert_eq!(via_config.policies.len(), 1); - assert!( - via_config.policies[0].source.contains("act-admin"), - "policy must carry verified content, not a path" - ); - - // …and config-free, straight from the bucket URI (the deployment - // payoff: a server needs only the URI and credentials). - let via_uri = read_serving_snapshot_from_storage(&root).await.unwrap(); - assert_eq!(via_uri.graphs.len(), 1); - assert_eq!( - via_uri.graphs[0].root.to_string_lossy(), - via_config.graphs[0].root.to_string_lossy() - ); - assert_eq!(via_uri.policies.len(), 1); - - // Schema evolution converges on the bucket. - write_cluster_fixture(dir.path(), &root, SCHEMA_V2); - let evolve = apply_config_dir(dir.path()).await; - assert!(evolve.ok && evolve.converged, "{:?}", evolve.diagnostics); - - // Approved delete: drop the graph from the config; the plan demands an - // approval, the approved apply prefix-deletes the bucket root. - fs::write( - dir.path().join("cluster.yaml"), - format!("version: 1\nstorage: {root}\ngraphs: {{}}\n"), - ) - .unwrap(); - let plan = omnigraph_cluster::plan_config_dir(dir.path()).await; - assert!(plan.ok, "{:?}", plan.diagnostics); - let approval = plan - .approvals_required - .first() - .expect("graph delete requires approval"); - let approve = omnigraph_cluster::approve_config_dir( - dir.path(), - &approval.resource, - "e2e-operator", - ) - .await; - assert!(approve.ok, "{:?}", approve.diagnostics); - let delete = apply_config_dir(dir.path()).await; - assert!(delete.ok && delete.converged, "{:?}", delete.diagnostics); - - let after = read_serving_snapshot_from_storage(&root).await; - assert!( - after.is_err(), - "an empty cluster must refuse to serve, got {after:?}" - ); -} diff --git a/crates/omnigraph-compiler/Cargo.toml b/crates/omnigraph-compiler/Cargo.toml index 8db46e6..545db83 100644 --- a/crates/omnigraph-compiler/Cargo.toml +++ b/crates/omnigraph-compiler/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-compiler" -version = "0.6.2" +version = "0.6.1" edition = "2024" description = "Schema/query compiler for Omnigraph. Zero Lance dependency." license = "MIT" diff --git a/crates/omnigraph-policy/Cargo.toml b/crates/omnigraph-policy/Cargo.toml index 0df2a12..3d14fc5 100644 --- a/crates/omnigraph-policy/Cargo.toml +++ b/crates/omnigraph-policy/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-policy" -version = "0.6.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 46b380a..cb59796 100644 --- a/crates/omnigraph-policy/src/lib.rs +++ b/crates/omnigraph-policy/src/lib.rs @@ -277,14 +277,7 @@ pub struct PolicyEngine { impl PolicyConfig { pub fn load(path: &Path) -> Result { - Self::from_source(&fs::read_to_string(path)?) - } - - /// Parse + validate a policy from YAML source. The from-content twin of - /// `load` for callers whose policies don't live on the local filesystem - /// (e.g. a cluster catalog on object storage). - pub fn from_source(source: &str) -> Result { - let config: Self = serde_yaml::from_str(source)?; + let config: Self = serde_yaml::from_str(&fs::read_to_string(path)?)?; config.validate()?; Ok(config) } @@ -472,26 +465,13 @@ impl PolicyEngine { PolicyCompiler::compile(&config, graph_id) } - /// `load_graph` from YAML content instead of a file path β€” for policies - /// that live in a non-filesystem catalog (cluster object storage). - pub fn load_graph_from_source(source: &str, graph_id: &str) -> Result { - let config = PolicyConfig::from_source(source)?; - validate_kind_alignment(&config, PolicyEngineKind::Graph)?; - PolicyCompiler::compile(&config, graph_id) - } - /// 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 { - Self::load_server_from_source(&fs::read_to_string(path)?) - } - - /// `load_server` from YAML content instead of a file path. - pub fn load_server_from_source(source: &str) -> Result { - let config = PolicyConfig::from_source(source)?; + 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 @@ -1022,42 +1002,6 @@ impl PolicyChecker for PolicyEngine { #[cfg(test)] mod tests { - - #[test] - fn from_source_twins_match_path_loaders() { - let yaml = r#" -version: 1 -groups: - readers: ["act-r"] -protected_branches: [main] -rules: - - id: r1 - allow: - actors: { group: readers } - actions: [read] - branch_scope: any -"#; - let config = PolicyConfig::from_source(yaml).unwrap(); - assert_eq!(config.version, 1); - let engine = PolicyEngine::load_graph_from_source(yaml, "g1").unwrap(); - drop(engine); - - let server_yaml = r#" -version: 1 -kind: server -groups: - admins: ["act-a"] -rules: - - id: s1 - allow: - actors: { group: admins } - actions: [graph_list] -"#; - PolicyEngine::load_server_from_source(server_yaml).unwrap(); - // Kind misalignment stays loud through the from-source path. - assert!(PolicyEngine::load_graph_from_source(server_yaml, "g1").is_err()); - assert!(PolicyEngine::load_server_from_source(yaml).is_err()); - } use super::{ PolicyAction, PolicyCompiler, PolicyConfig, PolicyEngine, PolicyExpectation, PolicyRequest, PolicyTestCase, PolicyTestConfig, diff --git a/crates/omnigraph-server/Cargo.toml b/crates/omnigraph-server/Cargo.toml index 5393221..5994aa1 100644 --- a/crates/omnigraph-server/Cargo.toml +++ b/crates/omnigraph-server/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-server" -version = "0.6.2" +version = "0.6.1" edition = "2024" description = "HTTP server for the Omnigraph graph database." license = "MIT" @@ -19,10 +19,9 @@ default = [] aws = ["dep:aws-config", "dep:aws-sdk-secretsmanager"] [dependencies] -omnigraph = { package = "omnigraph-engine", path = "../omnigraph", version = "0.6.2" } -omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.2" } -omnigraph-policy = { path = "../omnigraph-policy", version = "0.6.2" } -omnigraph-cluster = { path = "../omnigraph-cluster", version = "0.6.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 } diff --git a/crates/omnigraph-server/src/api.rs b/crates/omnigraph-server/src/api.rs index ff3cf67..4a6024f 100644 --- a/crates/omnigraph-server/src/api.rs +++ b/crates/omnigraph-server/src/api.rs @@ -1,6 +1,6 @@ use omnigraph::db::{GraphCommit, MergeOutcome, ReadTarget, SchemaApplyResult, Snapshot}; use omnigraph::error::{MergeConflict, MergeConflictKind}; -use omnigraph::loader::{LoadMode, LoadResult}; +use omnigraph::loader::{IngestResult, LoadMode}; use crate::queries::StoredQuery; use omnigraph_compiler::SchemaMigrationStep; use omnigraph_compiler::query::ast::Param; @@ -208,9 +208,7 @@ pub struct IngestTableOutput { pub struct IngestOutput { pub uri: String, pub branch: String, - /// Base branch a fork was requested from (the request's `from`), echoed - /// even when the branch already existed. `null` when `from` was absent. - pub base_branch: Option, + pub base_branch: String, pub branch_created: bool, #[schema(value_type = LoadModeSchema)] pub mode: LoadMode, @@ -495,12 +493,9 @@ pub struct SchemaOutput { #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct IngestRequest { - /// Target branch. Defaults to `main`. Without `from`, the branch must - /// already exist β€” a missing branch is a 404, never an implicit fork. + /// Target branch. Created from `from` if it does not yet exist. Defaults to `main`. pub branch: Option, - /// Parent branch used to create `branch` if it does not exist. Branch - /// creation is opt-in by presence of this field; omit it to require an - /// existing branch. + /// Parent branch used to create `branch` if it does not exist. Defaults to `main`. pub from: Option, /// How existing rows are handled. Defaults to `merge`. #[schema(value_type = Option)] @@ -647,23 +642,18 @@ pub fn read_output(query_name: String, target: &ReadTarget, result: QueryResult) } } -pub fn ingest_output( - uri: &str, - result: &LoadResult, - mode: LoadMode, - actor_id: Option, -) -> IngestOutput { +pub fn ingest_output(uri: &str, result: &IngestResult, actor_id: Option) -> IngestOutput { IngestOutput { uri: uri.to_string(), branch: result.branch.clone(), base_branch: result.base_branch.clone(), branch_created: result.branch_created, - mode, + mode: result.mode, tables: result - .to_ingest_tables() - .into_iter() + .tables + .iter() .map(|table| IngestTableOutput { - table_key: table.table_key, + table_key: table.table_key.clone(), rows_loaded: table.rows_loaded, }) .collect(), diff --git a/crates/omnigraph-server/src/config.rs b/crates/omnigraph-server/src/config.rs index 15b957d..b308b72 100644 --- a/crates/omnigraph-server/src/config.rs +++ b/crates/omnigraph-server/src/config.rs @@ -526,49 +526,19 @@ pub fn default_config_path() -> PathBuf { PathBuf::from(DEFAULT_CONFIG_FILE) } -/// `OMNIGRAPH_CONFIG` env var: a first-class stand-in for `--config`, one -/// name with one meaning in both binaries (the container entrypoint already -/// uses it for the server; RFC-007 Β§D1 extends it to the CLI). -pub const CONFIG_PATH_ENV: &str = "OMNIGRAPH_CONFIG"; - -/// RFC-008 stage 4 β€” opt-in strict mode: when set, loading a legacy -/// `omnigraph.yaml` is a hard error instead of a warning. For teams that -/// finished migrating and want regressions caught (a stray legacy file -/// would otherwise silently outrank operator config during the window). -/// The rehearsal for stage 5's removal. -pub const NO_LEGACY_CONFIG_ENV: &str = "OMNIGRAPH_NO_LEGACY_CONFIG"; - pub fn load_config(config_path: Option<&PathBuf>) -> Result { - let env_path = env::var_os(CONFIG_PATH_ENV).map(PathBuf::from); - let strict = env::var_os(NO_LEGACY_CONFIG_ENV).is_some(); - load_config_in(&env::current_dir()?, config_path, env_path.as_ref(), strict) + load_config_in(&env::current_dir()?, config_path) } -fn load_config_in( - cwd: &Path, - config_path: Option<&PathBuf>, - env_path: Option<&PathBuf>, - strict_no_legacy: bool, -) -> Result { - // Precedence: explicit --config flag > $OMNIGRAPH_CONFIG > ./omnigraph.yaml. - let explicit_path = config_path.or(env_path).cloned(); +fn load_config_in(cwd: &Path, config_path: Option<&PathBuf>) -> Result { + let explicit_path = config_path.cloned(); let config_path = explicit_path.or_else(|| { let default_path = cwd.join(DEFAULT_CONFIG_FILE); default_path.exists().then_some(default_path) }); let mut config = if let Some(path) = &config_path { - if strict_no_legacy { - // Strict refuses the FILE, not its absence β€” flag-less - // invocations on migrated setups keep working. - bail!( - "legacy config '{}' refused: {NO_LEGACY_CONFIG_ENV} is set (RFC-008 strict mode); run `omnigraph config migrate`, then remove the file β€” or unset the variable", - path.display() - ); - } - let text = fs::read_to_string(path)?; - warn_yaml_deprecation_once(path, &text); - serde_yaml::from_str::(&text)? + serde_yaml::from_str::(&fs::read_to_string(path)?)? } else { OmnigraphConfig::default() }; @@ -582,74 +552,6 @@ fn load_config_in( Ok(config) } -/// RFC-008 stage 1: suppress the legacy-config deprecation warning -/// (one process), for CI logs during the deprecation window. -pub const SUPPRESS_YAML_DEPRECATION_ENV: &str = "OMNIGRAPH_SUPPRESS_YAML_DEPRECATION"; - -/// RFC-008's migration map (the "Where every key goes" table), applied to -/// the keys actually present in a loaded file β€” never a generic banner. -/// Keys are `(yaml pointer, destination)`; the pointer is matched against -/// the file's real top-level/nested keys. -const YAML_DEPRECATION_MAP: &[(&str, &str)] = &[ - ("graphs", "cluster.yaml `graphs:` (team surface) β€” or flags/env for the zero-config tier"), - ("queries", "the cluster catalog (`.gq` discovery in cluster.yaml)"), - ("policy", "cluster.yaml `policies:` + `applies_to` bindings"), - ("server", "flags/env (`--bind`); meaningless under cluster boot"), - ("auth", "the operator credentials chain (`omnigraph login `)"), - ("aliases", "operator `aliases:` (bindings) + catalog stored queries (content)"), - ("query", "obsolete β€” cluster query discovery replaced `query.roots`"), - ("project", "cluster.yaml `metadata.name`"), - ("cli.actor", "`operator.actor` in ~/.omnigraph/config.yaml"), - ("cli.output_format", "`defaults.output` in ~/.omnigraph/config.yaml"), - ("cli.table_max_column_width", "`defaults.table_max_column_width` in ~/.omnigraph/config.yaml"), - ("cli.table_cell_layout", "`defaults.table_cell_layout` in ~/.omnigraph/config.yaml"), - ("cli.graph", "explicit `--target`/`--server` (no operator default-target yet)"), - ("cli.branch", "explicit `--branch`"), -]; - -/// Emit the per-key deprecation block once per process when a legacy -/// `omnigraph.yaml` is actually loaded. `omnigraph config migrate` -/// produces the split these lines describe. -fn warn_yaml_deprecation_once(path: &Path, text: &str) { - static WARNED: std::sync::OnceLock<()> = std::sync::OnceLock::new(); - if env::var_os(SUPPRESS_YAML_DEPRECATION_ENV).is_some() { - return; - } - let lines = yaml_deprecation_lines(text); - if lines.is_empty() { - return; - } - WARNED.get_or_init(|| { - eprintln!( - "warning: '{}' is deprecated (RFC-008) β€” its keys have new homes; run `omnigraph config migrate` for the split, set {SUPPRESS_YAML_DEPRECATION_ENV}=1 to silence:", - path.display() - ); - for line in &lines { - eprintln!(" {line}"); - } - }); -} - -fn yaml_deprecation_lines(text: &str) -> Vec { - let Ok(mapping) = serde_yaml::from_str::(text) else { - return Vec::new(); - }; - let present = |pointer: &str| -> bool { - match pointer.split_once('.') { - None => mapping.contains_key(pointer), - Some((outer, inner)) => mapping - .get(outer) - .and_then(|value| value.as_mapping()) - .is_some_and(|nested| nested.contains_key(inner)), - } - }; - YAML_DEPRECATION_MAP - .iter() - .filter(|(pointer, _)| present(pointer)) - .map(|(pointer, destination)| format!("`{pointer}` -> {destination}")) - .collect() -} - fn absolute_base_dir(cwd: &Path, path: &Path) -> Result { let path = if path.is_absolute() { path.to_path_buf() @@ -673,63 +575,6 @@ mod tests { ReadOutputFormat, TableCellLayout, graph_resource_id_for_selection, load_config_in, }; - #[test] - fn env_config_path_stands_in_for_the_flag_but_loses_to_it() { - let temp = tempdir().unwrap(); - let flag_path = temp.path().join("flag.yaml"); - let env_path = temp.path().join("env.yaml"); - fs::write(&flag_path, "cli:\n actor: act-flag\n").unwrap(); - fs::write(&env_path, "cli:\n actor: act-env\n").unwrap(); - - // $OMNIGRAPH_CONFIG used when no flag… - let config = load_config_in(temp.path(), None, Some(&env_path), false).unwrap(); - assert_eq!(config.cli.actor.as_deref(), Some("act-env")); - - // …loses to an explicit --config… - let config = load_config_in(temp.path(), Some(&flag_path), Some(&env_path), false).unwrap(); - assert_eq!(config.cli.actor.as_deref(), Some("act-flag")); - - // …and beats the cwd default file. - fs::write(temp.path().join("omnigraph.yaml"), "cli:\n actor: act-cwd\n").unwrap(); - let config = load_config_in(temp.path(), None, Some(&env_path), false).unwrap(); - assert_eq!(config.cli.actor.as_deref(), Some("act-env")); - } - - #[test] - fn strict_mode_refuses_the_file_not_its_absence() { - let temp = tempdir().unwrap(); - // No file: strict mode changes nothing (defaults load). - let config = load_config_in(temp.path(), None, None, true).unwrap(); - assert!(config.cli.actor.is_none()); - - // File present: strict refuses with the migrate pointer. - fs::write(temp.path().join("omnigraph.yaml"), "cli:\n actor: a\n").unwrap(); - let err = load_config_in(temp.path(), None, None, true).unwrap_err(); - let message = err.to_string(); - assert!( - message.contains("OMNIGRAPH_NO_LEGACY_CONFIG") && message.contains("config migrate"), - "{message}" - ); - // Without strict, the same file loads. - assert!(load_config_in(temp.path(), None, None, false).is_ok()); - } - - #[test] - fn yaml_deprecation_lines_name_present_keys_only() { - let lines = super::yaml_deprecation_lines( - "graphs:\n g:\n uri: /tmp/x\ncli:\n actor: a\n branch: main\n", - ); - let joined = lines.join("\n"); - assert!(joined.contains("`graphs` ->"), "{joined}"); - assert!(joined.contains("`cli.actor` -> `operator.actor`"), "{joined}"); - assert!(joined.contains("`cli.branch` ->"), "{joined}"); - assert!(!joined.contains("`aliases`"), "{joined}"); - assert!(!joined.contains("`cli.output_format`"), "{joined}"); - - assert!(super::yaml_deprecation_lines("").is_empty()); - assert!(super::yaml_deprecation_lines("not: [valid").is_empty()); - } - #[test] fn load_config_reads_yaml_defaults_from_current_dir() { let temp = tempdir().unwrap(); @@ -753,7 +598,7 @@ policy: {} ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); assert_eq!(config.cli_graph_name(), Some("local")); assert_eq!(config.cli_branch(), "main"); assert_eq!(config.cli_output_format(), ReadOutputFormat::Kv); @@ -788,7 +633,7 @@ policy: {} ) .unwrap(); - let config = load_config_in(&child, None, None, false).unwrap(); + let config = load_config_in(&child, None).unwrap(); assert!(config.graphs.is_empty()); } @@ -812,7 +657,7 @@ policy: {} "graphs:\n local:\n uri: ./demo.omni\n", ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).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")); @@ -835,7 +680,7 @@ policy: {} "graphs:\n local:\n uri: ./demo.omni\npolicy:\n file: ./top.yaml\n", ) .unwrap(); - let incoherent = load_config_in(temp2.path(), None, None, false).unwrap(); + let incoherent = load_config_in(temp2.path(), None).unwrap(); let err = incoherent .resolve_graph_selection(Some("local")) .unwrap_err() @@ -860,7 +705,7 @@ policy: {} server:\n graph: local\ncli:\n graph: prod\n", ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); assert_eq!( config.resolve_policy_tooling_graph_selection().unwrap(), Some("prod") @@ -872,7 +717,7 @@ policy: {} "graphs:\n local:\n uri: ./local.omni\nserver:\n graph: local\n", ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); assert_eq!( config.resolve_policy_tooling_graph_selection().unwrap(), Some("local") @@ -880,7 +725,7 @@ policy: {} let temp = tempdir().unwrap(); fs::write(temp.path().join("omnigraph.yaml"), "policy: {}\n").unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); assert_eq!(config.resolve_policy_tooling_graph_selection().unwrap(), None); let temp = tempdir().unwrap(); @@ -889,7 +734,7 @@ policy: {} "graphs:\n local:\n uri: ./local.omni\nserver:\n graph: ghost\n", ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); let err = config .resolve_policy_tooling_graph_selection() .unwrap_err() @@ -915,7 +760,7 @@ policy: {} ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); let resolved = config.resolve_query_path(Path::new("test.gq")).unwrap(); assert_eq!(resolved, temp.path().join("queries").join("test.gq")); } @@ -932,7 +777,7 @@ policy: {} fs::write(ambient_dir.join("local.gq"), "query ambient { return {} }").unwrap(); let config = - load_config_in(&ambient_dir, Some(&config_dir.join("omnigraph.yaml")), None, false).unwrap(); + load_config_in(&ambient_dir, Some(&config_dir.join("omnigraph.yaml"))).unwrap(); let resolved = config.resolve_query_path(Path::new("local.gq")).unwrap(); assert_eq!(resolved, config_dir.join("local.gq")); @@ -962,7 +807,7 @@ queries: ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); // Per-graph registry (multi-graph mode). let prod = config.target_query_entries("prod").unwrap(); @@ -1003,7 +848,7 @@ queries: policy:\n file: ./prod.yaml\n bare:\n uri: s3://b/bare\n", ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); // Named graph with its own policy β†’ per-graph (not top-level). assert!( @@ -1039,7 +884,7 @@ queries: ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); // Additive: no `queries:` anywhere β†’ empty registries everywhere. assert!(config.query_entries().is_empty()); assert!( @@ -1059,7 +904,7 @@ queries: ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); assert_eq!( config.resolve_policy_file().unwrap(), temp.path().join("policy.yaml") @@ -1082,7 +927,7 @@ cli: ) .unwrap(); - let config = load_config_in(temp.path(), None, None, false).unwrap(); + let config = load_config_in(temp.path(), None).unwrap(); assert_eq!( config.graph_bearer_token_env( Some("https://override.example.com"), diff --git a/crates/omnigraph-server/src/handlers.rs b/crates/omnigraph-server/src/handlers.rs deleted file mode 100644 index 2ead0e3..0000000 --- a/crates/omnigraph-server/src/handlers.rs +++ /dev/null @@ -1,1666 +0,0 @@ -//! HTTP route handlers, the bearer-auth middleware, per-request -//! authorization, and the cluster-prefix OpenAPI rewrite (moved -//! verbatim from lib.rs in the modularization). - -use super::*; - -/// Liveness probe. -/// -/// Returns server status and version. Unauthenticated; safe to call from any -/// caller. Use this to confirm the server is reachable before invoking other -/// endpoints. -#[utoipa::path( - get, - path = "/healthz", - tag = "health", - operation_id = "health", - responses( - (status = 200, description = "Server is healthy", body = HealthOutput), - ), -)] -pub(crate) async fn server_health() -> Json { - Json(HealthOutput { - status: "ok".to_string(), - version: SERVER_VERSION.to_string(), - source_version: SERVER_SOURCE_VERSION.map(str::to_string), - }) -} - -#[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). -pub(crate) 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 })) -} - -pub(crate) 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. -pub(crate) 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; -} - -pub(crate) 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()); - } - } -} - -pub(crate) 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`. -pub(crate) 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}")); - } - } -} - -pub(crate) 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() -} - -pub(crate) fn strip_security(doc: &mut utoipa::openapi::OpenApi) { - if let Some(components) = doc.components.as_mut() { - components.security_schemes.clear(); - } - for path_item in doc.paths.paths.values_mut() { - for op in [ - path_item.get.as_mut(), - path_item.post.as_mut(), - path_item.put.as_mut(), - path_item.delete.as_mut(), - path_item.options.as_mut(), - path_item.head.as_mut(), - path_item.patch.as_mut(), - path_item.trace.as_mut(), - ] - .into_iter() - .flatten() - { - op.security = None; - } - } -} - -pub(crate) async fn require_bearer_auth( - State(state): State, - mut request: Request, - next: Next, -) -> std::result::Result { - if !state.requires_bearer_auth() { - return Ok(next.run(request).await); - } - - let Some(header) = request - .headers() - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - else { - return Err(ApiError::unauthorized("missing bearer token")); - }; - - let Some(provided_token) = header.strip_prefix("Bearer ") else { - return Err(ApiError::unauthorized("missing bearer token")); - }; - - let Some(actor) = state.authenticate_bearer_token(provided_token) else { - return Err(ApiError::unauthorized("invalid bearer token")); - }; - 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). -pub(crate) 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) -} - -pub(crate) fn log_policy_decision(actor_id: &str, request: &PolicyRequest, decision: &PolicyDecision) { - info!( - actor_id = actor_id, - action = %request.action, - branch = request.branch.as_deref().unwrap_or(""), - target_branch = request.target_branch.as_deref().unwrap_or(""), - allowed = decision.allowed, - matched_rule_id = decision.matched_rule_id.as_deref().unwrap_or(""), - "policy decision" - ); -} - -/// 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. -pub(crate) 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`. -pub(crate) 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. - // 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. 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(), - )); - } - 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 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`. - let actor_id = actor.actor_id.as_ref(); - let decision = engine - .authorize(actor_id, &request) - .map_err(|err| ApiError::internal(format!("policy: {err}")))?; - log_policy_decision(actor_id, &request, &decision); - if decision.allowed { - Ok(Authz::Allowed) - } else { - 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. -pub(crate) 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)), - } -} - -#[utoipa::path( - get, - path = "/snapshot", - tag = "snapshots", - operation_id = "getSnapshot", - params(SnapshotQuery), - responses( - (status = 200, description = "Database snapshot", body = api::SnapshotOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// Read the current snapshot of a branch. -/// -/// Returns the manifest version plus per-table metadata (path, version, row -/// count) for every table on the branch. Defaults to `main` when `branch` is -/// omitted. Read-only. -pub(crate) async fn server_snapshot( - Extension(handle): Extension>, - actor: Option>, - Query(query): Query, -) -> std::result::Result, ApiError> { - let branch = query.branch.unwrap_or_else(|| "main".to_string()); - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::Read, - branch: Some(branch.clone()), - target_branch: None, - }, - )?; - let snapshot = { - let db = &handle.engine; - db.snapshot_of(ReadTarget::branch(branch.as_str())) - .await - .map_err(ApiError::from_omni)? - }; - 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. -pub(crate) 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", - tag = "queries", - operation_id = "read", - request_body = ReadRequest, - responses( - (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" = [])), -)] -#[deprecated(note = "use POST /query instead; /read is kept indefinitely for byte-stable back-compat")] -/// **Deprecated** β€” use [`POST /query`](#tag/queries/operation/query) instead. -/// -/// 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. -pub(crate) async fn server_read( - Extension(handle): Extension>, - actor: Option>, - Json(request): Json, -) -> std::result::Result<([(HeaderName, HeaderValue); 2], Json), ApiError> { - let (selected_name, target, result) = run_query( - handle, - actor.as_ref().map(|Extension(actor)| actor), - &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)), - )) -} - -#[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. -pub(crate) 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))) -} - -#[utoipa::path( - post, - path = "/export", - tag = "queries", - operation_id = "export", - request_body = ExportRequest, - responses( - (status = 200, description = "Exported data as NDJSON", content_type = "application/x-ndjson"), - (status = 400, description = "Bad request", body = ErrorOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// Stream the contents of a branch as NDJSON. -/// -/// Emits one JSON object per line (`application/x-ndjson`). Filter with -/// `type_names` (node/edge type names) and/or `table_keys`; both empty -/// streams the entire branch. Suitable for large exports β€” the response is -/// streamed, not buffered. Read-only. -pub(crate) async fn server_export( - Extension(handle): Extension>, - actor: Option>, - Json(request): Json, -) -> std::result::Result { - let branch = request.branch.unwrap_or_else(|| "main".to_string()); - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::Export, - branch: Some(branch.clone()), - target_branch: None, - }, - )?; - 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::>(); - tokio::spawn(async move { - let result = { - let mut writer = ExportStreamWriter { sender: tx.clone() }; - engine - .export_jsonl_to_writer(&branch, &type_names, &table_keys, &mut writer) - .await - }; - if let Err(err) = result { - let _ = tx.send(Err(io::Error::other(err.to_string()))); - } - }); - let body = Body::from_stream(stream::unfold(rx, |mut rx| async move { - rx.recv().await.map(|item| (item, rx)) - })); - Ok(( - StatusCode::OK, - [(CONTENT_TYPE, "application/x-ndjson; charset=utf-8")], - body, - ) - .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. -pub(crate) 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. -pub(crate) 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. -pub(crate) 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), - (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" = [])), -)] -/// 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. -/// -/// Pairs with `POST /query` (read-only). The legacy `POST /change` route -/// has identical semantics and is kept as a deprecated alias. -pub(crate) async fn server_mutate( - State(state): State, - Extension(handle): Extension>, - actor: Option>, - Json(request): Json, -) -> std::result::Result, ApiError> { - let branch = request.branch.unwrap_or_else(|| "main".to_string()); - 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)] -pub(crate) struct QueryNamePath { - name: String, -} - -pub(crate) 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). -pub(crate) 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 { - 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). -pub(crate) 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, - }, - )?; - 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(QueriesCatalogOutput { queries })) -} - -#[utoipa::path( - get, - path = "/schema", - tag = "schema", - operation_id = "getSchema", - responses( - (status = 200, description = "Current schema source", body = SchemaOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// Read the current schema source. -/// -/// Returns the project's schema as a single string in `.pg` source form. -/// Useful for clients that want to introspect available types and tables -/// before constructing GQ queries. Read-only. -pub(crate) async fn server_schema_get( - 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: None, - target_branch: None, - }, - )?; - let schema_source = { - let db = &handle.engine; - db.schema_source().to_string() - }; - Ok(Json(SchemaOutput { schema_source })) -} - -#[utoipa::path( - post, - path = "/schema/apply", - tag = "mutations", - operation_id = "applySchema", - request_body = SchemaApplyRequest, - responses( - (status = 200, description = "Schema apply results", body = SchemaApplyOutput), - (status = 400, description = "Bad request", body = ErrorOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// Apply a schema migration. -/// -/// Diffs `schema_source` against the current schema and applies the resulting -/// migration steps (add/drop type, add/drop column, etc.). **Destructive**: -/// some steps drop data. Returns the list of steps applied; if `applied` is -/// false the diff was unsupported and no changes were made. -pub(crate) async fn server_schema_apply( - State(state): State, - Extension(handle): Extension>, - actor: Option>, - Json(request): Json, -) -> std::result::Result, ApiError> { - let actor_arc = actor - .as_ref() - .map(|Extension(actor)| Arc::clone(&actor.actor_id)) - .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor - .as_ref() - .map(|Extension(actor)| actor.actor_id.as_ref()); - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::SchemaApply, - branch: None, - target_branch: Some("main".to_string()), - }, - )?; - let est_bytes = request.schema_source.len() as u64; - let _admission = state - .workload - .try_admit(&actor_arc, est_bytes) - .map_err(ApiError::from_workload_reject)?; - let result = { - 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_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(handle.uri.as_str(), result))) -} - -#[utoipa::path( - post, - path = "/ingest", - tag = "mutations", - operation_id = "ingest", - request_body = IngestRequest, - responses( - (status = 200, description = "Ingest results", body = IngestOutput), - (status = 400, description = "Bad request", body = ErrorOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// Bulk-load NDJSON data into a branch. -/// -/// `data` is NDJSON with one record per line. `mode` controls behavior on -/// existing rows: `merge` upserts by id (default), `append` blindly inserts, -/// `overwrite` replaces table contents. Branch creation is opt-in by -/// presence of `from`: with `from` set, a missing `branch` is created from -/// it; without `from`, `branch` must already exist β€” a missing branch is a -/// 404, never an implicit fork. **Destructive** when `mode` is `overwrite` -/// or when the load produces conflicting writes. -pub(crate) async fn server_ingest( - State(state): State, - Extension(handle): Extension>, - actor: Option>, - Json(request): Json, -) -> std::result::Result, ApiError> { - let branch = request.branch.unwrap_or_else(|| "main".to_string()); - let from = request.from; - let mode = request.mode.unwrap_or(omnigraph::loader::LoadMode::Merge); - let actor_arc = actor - .as_ref() - .map(|Extension(actor)| Arc::clone(&actor.actor_id)) - .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor - .as_ref() - .map(|Extension(actor)| actor.actor_id.as_ref()); - - let branch_exists = { - let db = &handle.engine; - db.branch_list() - .await - .map_err(ApiError::from_omni)? - .into_iter() - .any(|name| name == branch) - }; - - if !branch_exists { - match from.as_deref() { - // Fork-if-missing is opt-in by presence of `from`; without it a - // typo'd branch name must surface as an error, not silently - // create a fork and land the data there. - None => { - return Err(ApiError::not_found(format!( - "branch '{branch}' not found; pass `from` to create it" - ))); - } - Some(from) => authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::BranchCreate, - branch: Some(from.to_string()), - target_branch: Some(branch.clone()), - }, - )?, - } - } - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::Change, - branch: Some(branch.clone()), - target_branch: None, - }, - )?; - let est_bytes = request.data.len() as u64; - let _admission = state - .workload - .try_admit(&actor_arc, est_bytes) - .map_err(ApiError::from_workload_reject)?; - - let result = { - let db = &handle.engine; - db.load_as(&branch, from.as_deref(), &request.data, mode, actor_id) - .await - .map_err(ApiError::from_omni)? - }; - - Ok(Json(ingest_output( - handle.uri.as_str(), - &result, - mode, - actor_id.map(str::to_string), - ))) -} - -#[utoipa::path( - get, - path = "/branches", - tag = "branches", - operation_id = "listBranches", - responses( - (status = 200, description = "List of branches", body = BranchListOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// List all branches. -/// -/// Returns branch names sorted alphabetically. Read-only. -pub(crate) async fn server_branch_list( - 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: None, - target_branch: None, - }, - )?; - let mut branches = { - let db = &handle.engine; - db.branch_list().await.map_err(ApiError::from_omni)? - }; - branches.sort(); - Ok(Json(BranchListOutput { branches })) -} - -#[utoipa::path( - post, - path = "/branches", - tag = "branches", - operation_id = "createBranch", - request_body = BranchCreateRequest, - responses( - (status = 200, description = "Branch created", body = BranchCreateOutput), - (status = 400, description = "Bad request", body = ErrorOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - (status = 409, description = "Branch already exists", body = ErrorOutput), - (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// Create a new branch. -/// -/// Forks `name` off of `from` (defaults to `main`). The new branch shares -/// table data with its parent until it is mutated. Returns 409 if `name` -/// already exists. -pub(crate) async fn server_branch_create( - State(state): State, - 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.actor_id)) - .unwrap_or_else(|| Arc::::from("anonymous")); - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::BranchCreate, - branch: Some(from.clone()), - target_branch: Some(request.name.clone()), - }, - )?; - // Branch metadata only β€” small constant bytes estimate. The Lance - // shallow-clone work is bounded by the parent's manifest size, not - // the request body. - let _admission = state - .workload - .try_admit(&actor_arc, 256) - .map_err(ApiError::from_workload_reject)?; - { - let db = &handle.engine; - db.branch_create_from_as( - ReadTarget::branch(&from), - &request.name, - actor.as_ref().map(|Extension(a)| a.actor_id.as_ref()), - ) - .await - .map_err(ApiError::from_omni)?; - } - Ok(Json(BranchCreateOutput { - uri: handle.uri.clone(), - from, - name: request.name, - 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)] -pub(crate) struct BranchPath { - branch: String, -} - -#[utoipa::path( - delete, - path = "/branches/{branch}", - tag = "branches", - operation_id = "deleteBranch", - params( - ("branch" = String, Path, description = "Branch name to delete"), - ), - responses( - (status = 200, description = "Branch deleted", body = BranchDeleteOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - (status = 404, description = "Branch not found", body = ErrorOutput), - (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// Delete a branch. -/// -/// **Irreversible.** Removes the branch pointer; commits remain reachable -/// only if referenced by another branch. Returns 404 if the branch does not -/// exist. -pub(crate) async fn server_branch_delete( - State(state): State, - 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.actor_id)) - .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor - .as_ref() - .map(|Extension(actor)| actor.actor_id.as_ref()); - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::BranchDelete, - branch: None, - target_branch: Some(branch.clone()), - }, - )?; - // Metadata-only manifest tombstone β€” small constant estimate. - let _admission = state - .workload - .try_admit(&actor_arc, 256) - .map_err(ApiError::from_workload_reject)?; - { - let db = &handle.engine; - db.branch_delete_as(&branch, actor_id) - .await - .map_err(ApiError::from_omni)?; - } - Ok(Json(BranchDeleteOutput { - uri: handle.uri.clone(), - name: branch, - actor_id: actor_id.map(str::to_string), - })) -} - -#[utoipa::path( - post, - path = "/branches/merge", - tag = "branches", - operation_id = "mergeBranches", - request_body = BranchMergeRequest, - responses( - (status = 200, description = "Branches merged", body = BranchMergeOutput), - (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" = [])), -)] -/// Merge one branch into another. -/// -/// Merges `source` into `target` (defaults to `main`). Outcome is one of -/// `already_up_to_date`, `fast_forward`, or `merged`. Returns 409 with the -/// list of conflicts if the merge cannot be completed; the target is left -/// unchanged in that case. **Destructive** to `target` on success. -pub(crate) async fn server_branch_merge( - State(state): State, - 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.actor_id)) - .unwrap_or_else(|| Arc::::from("anonymous")); - let actor_id = actor - .as_ref() - .map(|Extension(actor)| actor.actor_id.as_ref()); - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::BranchMerge, - branch: Some(request.source.clone()), - target_branch: Some(target.clone()), - }, - )?; - // Merge body is small JSON; the heavy work is in the engine but is - // bounded per-(table, branch) by the writer queue. Small constant - // estimate suffices for the actor in-flight count. - let _admission = state - .workload - .try_admit(&actor_arc, 256) - .map_err(ApiError::from_workload_reject)?; - let outcome = { - let db = &handle.engine; - db.branch_merge_as(&request.source, &target, actor_id) - .await - .map_err(ApiError::from_omni)? - }; - Ok(Json(BranchMergeOutput { - source: request.source, - target, - outcome: outcome.into(), - actor_id: actor_id.map(str::to_string), - })) -} - -#[utoipa::path( - get, - path = "/commits", - tag = "commits", - operation_id = "listCommits", - params(CommitListQuery), - responses( - (status = 200, description = "List of commits", body = CommitListOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] -/// List commits. -/// -/// Filter by `branch` to get the commits on a single branch (most recent -/// first); omit to list across all branches. Read-only. -pub(crate) async fn server_commit_list( - Extension(handle): Extension>, - actor: Option>, - Query(query): Query, -) -> std::result::Result, ApiError> { - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::Read, - branch: query.branch.clone(), - target_branch: None, - }, - )?; - let commits = { - let db = &handle.engine; - db.list_commits(query.branch.as_deref()) - .await - .map_err(ApiError::from_omni)? - }; - Ok(Json(CommitListOutput { - commits: commits.iter().map(api::commit_output).collect(), - })) -} - -/// Path-param shape for [`server_commit_show`]. See [`BranchPath`] -/// for the design rationale β€” same pattern, different field name. -#[derive(Deserialize)] -pub(crate) struct CommitPath { - commit_id: String, -} - -#[utoipa::path( - get, - path = "/commits/{commit_id}", - tag = "commits", - operation_id = "getCommit", - params( - ("commit_id" = String, Path, description = "Commit identifier"), - ), - responses( - (status = 200, description = "Commit details", body = api::CommitOutput), - (status = 401, description = "Unauthorized", body = ErrorOutput), - (status = 403, description = "Forbidden", body = ErrorOutput), - (status = 404, description = "Commit not found", body = ErrorOutput), - ), - security(("bearer_token" = [])), -)] - -/// Get a single commit. -/// -/// Returns the commit's manifest version, parent commit(s), and creation -/// metadata. Read-only. -pub(crate) async fn server_commit_show( - Extension(handle): Extension>, - actor: Option>, - Path(CommitPath { commit_id }): Path, -) -> std::result::Result, ApiError> { - authorize_request( - actor.as_ref().map(|Extension(actor)| actor), - handle.policy.as_deref(), - PolicyRequest { - action: PolicyAction::Read, - branch: None, - target_branch: None, - }, - )?; - let commit = { - let db = &handle.engine; - db.get_commit(&commit_id) - .await - .map_err(ApiError::from_omni)? - }; - Ok(Json(api::commit_output(&commit))) -} - -pub(crate) fn read_target_from_request(branch: Option, snapshot: Option) -> ReadTarget { - if let Some(snapshot) = snapshot { - ReadTarget::snapshot(omnigraph::db::SnapshotId::new(snapshot)) - } else { - ReadTarget::branch(branch.unwrap_or_else(|| "main".to_string())) - } -} - -pub(crate) fn select_named_query_decl( - query_source: &str, - requested_name: Option<&str>, -) -> Result { - let parsed = parse_query(query_source)?; - let query = if let Some(name) = requested_name { - parsed - .queries - .into_iter() - .find(|query| query.name == name) - .ok_or_else(|| color_eyre::eyre::eyre!("query '{}' not found", name))? - } else if parsed.queries.len() == 1 { - parsed.queries.into_iter().next().unwrap() - } else { - bail!("query file contains multiple queries; pass --name"); - }; - Ok(query) -} - -pub(crate) 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)) -} - -pub(crate) fn query_params_from_json( - query_params: &[omnigraph_compiler::query::ast::Param], - params_json: Option<&Value>, -) -> Result { - json_params_to_param_map(params_json, query_params, JsonParamMode::Standard) - .map_err(|err| color_eyre::eyre::eyre!(err.to_string())) -} - diff --git a/crates/omnigraph-server/src/lib.rs b/crates/omnigraph-server/src/lib.rs index 3bde2a7..60ebef3 100644 --- a/crates/omnigraph-server/src/lib.rs +++ b/crates/omnigraph-server/src/lib.rs @@ -1,9 +1,4 @@ pub mod api; -mod handlers; -mod settings; -pub use settings::{load_server_settings, classify_server_runtime_state, server_config_is_multi, ServerRuntimeState}; -use settings::*; -use handlers::*; pub mod auth; pub mod config; pub mod graph_id; @@ -19,7 +14,7 @@ pub use registry::{GraphHandle, GraphRegistry, InsertError, RegistryLookup, Regi use crate::queries::{QueryRegistry, check, format_check_breakages}; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{HashMap, HashSet}; use std::fs; use std::io; use std::io::Write; @@ -45,7 +40,7 @@ use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post}; use axum::{Json, Router}; -use color_eyre::eyre::{Result, WrapErr, bail, eyre}; +use color_eyre::eyre::{Result, WrapErr, bail}; pub use config::{ AliasCommand, AliasConfig, CliDefaults, DEFAULT_CONFIG_FILE, OmnigraphConfig, PolicySettings, ProjectConfig, QueryDefaults, ReadOutputFormat, ServerDefaults, TableCellLayout, TargetConfig, @@ -93,27 +88,27 @@ fn hash_bearer_token(token: &str) -> BearerTokenHash { description = "HTTP API for the Omnigraph graph database", ), paths( - handlers::server_health, - handlers::server_graphs_list, - handlers::server_snapshot, + server_health, + server_graphs_list, + server_snapshot, // deprecated; the #[deprecated] attribute on the handler // surfaces as `deprecated: true` on the OpenAPI operation. - #[allow(deprecated)] handlers::server_read, - handlers::server_query, - handlers::server_export, - #[allow(deprecated)] handlers::server_change, - handlers::server_mutate, - handlers::server_list_queries, - handlers::server_invoke_query, - handlers::server_schema_apply, - handlers::server_schema_get, - handlers::server_ingest, - handlers::server_branch_list, - handlers::server_branch_create, - handlers::server_branch_delete, - handlers::server_branch_merge, - handlers::server_commit_list, - handlers::server_commit_show, + #[allow(deprecated)] server_read, + server_query, + server_export, + #[allow(deprecated)] server_change, + server_mutate, + server_list_queries, + server_invoke_query, + server_schema_apply, + server_schema_get, + server_ingest, + server_branch_list, + server_branch_create, + server_branch_delete, + server_branch_merge, + server_commit_list, + server_commit_show, ), modifiers(&SecurityAddon), )] @@ -193,28 +188,18 @@ pub enum ServerConfigMode { config_path: PathBuf, /// `server.policy.file` (server-level Cedar policy for the /// management endpoints). Wired into `GET /graphs` authorization. - server_policy: Option, + server_policy_file: Option, }, } -/// Where a Cedar policy bundle comes from at startup. File-based for -/// omnigraph.yaml deployments; inline (digest-verified catalog content) -/// for cluster-mode boots, where the catalog may live on object storage -/// and the server must not re-read mutable state after the snapshot. -#[derive(Debug, Clone)] -pub enum PolicySource { - File(PathBuf), - Inline(String), -} - /// One graph's startup-time configuration: id, opened URI, optional -/// per-graph policy source. Constructed by `load_server_settings` +/// per-graph policy file path. Constructed by `load_server_settings` /// in multi mode; consumed by `serve`'s parallel open loop. #[derive(Debug, Clone)] pub struct GraphStartupConfig { pub graph_id: String, pub uri: String, - pub policy: Option, + 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. @@ -903,6 +888,213 @@ fn format_registry_load_errors(label: &str, errors: &[queries::LoadError]) -> St format!("graph '{label}': stored-query registry failed to load:\n {joined}") } +pub fn load_server_settings( + config_path: Option<&PathBuf>, + cli_uri: Option, + cli_target: Option, + cli_bind: Option, + cli_allow_unauthenticated: bool, +) -> Result { + let config = load_config(config_path)?; + let bind = cli_bind.unwrap_or_else(|| config.server_bind().to_string()); + // 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. + let env_unauth = std::env::var("OMNIGRAPH_UNAUTHENTICATED") + .ok() + .map(|v| { + let trimmed = v.trim(); + !trimmed.is_empty() && trimmed != "0" && !trimmed.eq_ignore_ascii_case("false") + }) + .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 { + mode, + bind, + 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. +/// +/// * **Open** β€” neither tokens nor policy; requires explicit +/// `allow_unauthenticated`. Effectively a "trust the network" dev +/// mode. `serve()` refuses to start in this shape without the flag, +/// so the only way to reach this state at runtime is via deliberate +/// operator opt-in. +/// * **DefaultDeny** β€” tokens configured but no policy file. The +/// 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 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, + DefaultDeny, + PolicyEnabled, +} + +/// Compute the [`ServerRuntimeState`] from the configured inputs. +/// 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, + allow_unauthenticated: bool, +) -> Result { + match (has_tokens, has_policy, allow_unauthenticated) { + (false, false, false) => bail!( + "server has no bearer tokens and no policy file configured. This is a fully \ + open server β€” pass `--unauthenticated` (or set OMNIGRAPH_UNAUTHENTICATED=1) \ + if you actually want that, otherwise configure bearer tokens (see \ + docs/user/server.md) and/or `policy.file` in omnigraph.yaml." + ), + (false, false, true) => Ok(ServerRuntimeState::Open), + (true, false, _) => Ok(ServerRuntimeState::DefaultDeny), + (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 { // The per-graph protected routes, identical in single + multi mode. @@ -1004,9 +1196,9 @@ pub async fn serve(config: ServerConfig) -> Result<()> { ServerConfigMode::Single { policy_file, .. } => policy_file.is_some(), ServerConfigMode::Multi { graphs, - server_policy, + server_policy_file, .. - } => server_policy.is_some() || graphs.iter().any(|g| g.policy.is_some()), + } => server_policy_file.is_some() || graphs.iter().any(|g| g.policy_file.is_some()), }; let runtime_state = classify_server_runtime_state( !tokens.is_empty(), @@ -1055,7 +1247,7 @@ pub async fn serve(config: ServerConfig) -> Result<()> { ServerConfigMode::Multi { graphs, config_path, - server_policy, + server_policy_file, } => { info!( bind = %bind, @@ -1064,7 +1256,7 @@ pub async fn serve(config: ServerConfig) -> Result<()> { config = %config_path.display(), "serving omnigraph" ); - open_multi_graph_state(graphs, tokens, server_policy.as_ref(), config_path).await? + open_multi_graph_state(graphs, tokens, server_policy_file.as_ref(), config_path).await? } }; @@ -1075,14 +1267,6 @@ pub async fn serve(config: ServerConfig) -> Result<()> { Ok(()) } -/// Load a graph-scoped policy bundle from either source kind. -fn load_graph_policy(source: &PolicySource, graph_id: &str) -> Result { - match source { - PolicySource::File(path) => Ok(PolicyEngine::load_graph(path, graph_id)?), - PolicySource::Inline(text) => Ok(PolicyEngine::load_graph_from_source(text, graph_id)?), - } -} - /// 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` @@ -1091,10 +1275,10 @@ fn load_graph_policy(source: &PolicySource, graph_id: &str) -> Result, tokens: Vec<(String, String)>, - server_policy_source: Option<&PolicySource>, + server_policy_file: Option<&PathBuf>, config_path: PathBuf, ) -> Result { use futures::{StreamExt, TryStreamExt}; @@ -1107,11 +1291,8 @@ pub async fn open_multi_graph_state( // 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_source { - Some(PolicySource::File(path)) => Some(PolicyEngine::load_server(path)?), - Some(PolicySource::Inline(source)) => { - Some(PolicyEngine::load_server_from_source(source)?) - } + let server_policy = match server_policy_file { + Some(path) => Some(PolicyEngine::load_server(path)?), None => None, }; @@ -1149,9 +1330,9 @@ async fn open_single_graph(cfg: GraphStartupConfig) -> Result> // 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 { - Some(source) => { - let policy = load_graph_policy(source, 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)) @@ -1176,4 +1357,2309 @@ async fn shutdown_signal() { info!("shutdown signal received"); } +#[utoipa::path( + get, + path = "/healthz", + tag = "health", + operation_id = "health", + responses( + (status = 200, description = "Server is healthy", body = HealthOutput), + ), +)] +/// Liveness probe. +/// +/// Returns server status and version. Unauthenticated; safe to call from any +/// caller. Use this to confirm the server is reachable before invoking other +/// endpoints. +async fn server_health() -> Json { + Json(HealthOutput { + status: "ok".to_string(), + version: SERVER_VERSION.to_string(), + source_version: SERVER_SOURCE_VERSION.map(str::to_string), + }) +} +#[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(); + } + for path_item in doc.paths.paths.values_mut() { + for op in [ + path_item.get.as_mut(), + path_item.post.as_mut(), + path_item.put.as_mut(), + path_item.delete.as_mut(), + path_item.options.as_mut(), + path_item.head.as_mut(), + path_item.patch.as_mut(), + path_item.trace.as_mut(), + ] + .into_iter() + .flatten() + { + op.security = None; + } + } +} + +async fn require_bearer_auth( + State(state): State, + mut request: Request, + next: Next, +) -> std::result::Result { + if !state.requires_bearer_auth() { + return Ok(next.run(request).await); + } + + let Some(header) = request + .headers() + .get(AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + else { + return Err(ApiError::unauthorized("missing bearer token")); + }; + + let Some(provided_token) = header.strip_prefix("Bearer ") else { + return Err(ApiError::unauthorized("missing bearer token")); + }; + + let Some(actor) = state.authenticate_bearer_token(provided_token) else { + return Err(ApiError::unauthorized("invalid bearer token")); + }; + 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, + action = %request.action, + branch = request.branch.as_deref().unwrap_or(""), + target_branch = request.target_branch.as_deref().unwrap_or(""), + allowed = decision.allowed, + matched_rule_id = decision.matched_rule_id.as_deref().unwrap_or(""), + "policy decision" + ); +} + +/// 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. + // 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. 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(), + )); + } + 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 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`. + let actor_id = actor.actor_id.as_ref(); + let decision = engine + .authorize(actor_id, &request) + .map_err(|err| ApiError::internal(format!("policy: {err}")))?; + log_policy_decision(actor_id, &request, &decision); + if decision.allowed { + Ok(Authz::Allowed) + } else { + 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)), + } +} + +#[utoipa::path( + get, + path = "/snapshot", + tag = "snapshots", + operation_id = "getSnapshot", + params(SnapshotQuery), + responses( + (status = 200, description = "Database snapshot", body = api::SnapshotOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Read the current snapshot of a branch. +/// +/// Returns the manifest version plus per-table metadata (path, version, row +/// count) for every table on the branch. Defaults to `main` when `branch` is +/// omitted. Read-only. +async fn server_snapshot( + Extension(handle): Extension>, + actor: Option>, + Query(query): Query, +) -> std::result::Result, ApiError> { + let branch = query.branch.unwrap_or_else(|| "main".to_string()); + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::Read, + branch: Some(branch.clone()), + target_branch: None, + }, + )?; + let snapshot = { + let db = &handle.engine; + db.snapshot_of(ReadTarget::branch(branch.as_str())) + .await + .map_err(ApiError::from_omni)? + }; + 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", + tag = "queries", + operation_id = "read", + request_body = ReadRequest, + responses( + (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" = [])), +)] +#[deprecated(note = "use POST /query instead; /read is kept indefinitely for byte-stable back-compat")] +/// **Deprecated** β€” use [`POST /query`](#tag/queries/operation/query) instead. +/// +/// 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( + Extension(handle): Extension>, + actor: Option>, + Json(request): Json, +) -> std::result::Result<([(HeaderName, HeaderValue); 2], Json), ApiError> { + let (selected_name, target, result) = run_query( + handle, + actor.as_ref().map(|Extension(actor)| actor), + &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)), + )) +} + +#[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))) +} + +#[utoipa::path( + post, + path = "/export", + tag = "queries", + operation_id = "export", + request_body = ExportRequest, + responses( + (status = 200, description = "Exported data as NDJSON", content_type = "application/x-ndjson"), + (status = 400, description = "Bad request", body = ErrorOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Stream the contents of a branch as NDJSON. +/// +/// Emits one JSON object per line (`application/x-ndjson`). Filter with +/// `type_names` (node/edge type names) and/or `table_keys`; both empty +/// streams the entire branch. Suitable for large exports β€” the response is +/// streamed, not buffered. Read-only. +async fn server_export( + Extension(handle): Extension>, + actor: Option>, + Json(request): Json, +) -> std::result::Result { + let branch = request.branch.unwrap_or_else(|| "main".to_string()); + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::Export, + branch: Some(branch.clone()), + target_branch: None, + }, + )?; + 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::>(); + tokio::spawn(async move { + let result = { + let mut writer = ExportStreamWriter { sender: tx.clone() }; + engine + .export_jsonl_to_writer(&branch, &type_names, &table_keys, &mut writer) + .await + }; + if let Err(err) = result { + let _ = tx.send(Err(io::Error::other(err.to_string()))); + } + }); + let body = Body::from_stream(stream::unfold(rx, |mut rx| async move { + rx.recv().await.map(|item| (item, rx)) + })); + Ok(( + StatusCode::OK, + [(CONTENT_TYPE, "application/x-ndjson; charset=utf-8")], + body, + ) + .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), + (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" = [])), +)] +/// 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. +/// +/// 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, + Extension(handle): Extension>, + actor: Option>, + Json(request): Json, +) -> std::result::Result, ApiError> { + let branch = request.branch.unwrap_or_else(|| "main".to_string()); + 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 { + 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, + }, + )?; + 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(QueriesCatalogOutput { queries })) +} + +#[utoipa::path( + get, + path = "/schema", + tag = "schema", + operation_id = "getSchema", + responses( + (status = 200, description = "Current schema source", body = SchemaOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Read the current schema source. +/// +/// Returns the project's schema as a single string in `.pg` source form. +/// Useful for clients that want to introspect available types and tables +/// before constructing GQ queries. Read-only. +async fn server_schema_get( + 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: None, + target_branch: None, + }, + )?; + let schema_source = { + let db = &handle.engine; + db.schema_source().to_string() + }; + Ok(Json(SchemaOutput { schema_source })) +} + +#[utoipa::path( + post, + path = "/schema/apply", + tag = "mutations", + operation_id = "applySchema", + request_body = SchemaApplyRequest, + responses( + (status = 200, description = "Schema apply results", body = SchemaApplyOutput), + (status = 400, description = "Bad request", body = ErrorOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Apply a schema migration. +/// +/// Diffs `schema_source` against the current schema and applies the resulting +/// migration steps (add/drop type, add/drop column, etc.). **Destructive**: +/// some steps drop data. Returns the list of steps applied; if `applied` is +/// false the diff was unsupported and no changes were made. +async fn server_schema_apply( + State(state): State, + Extension(handle): Extension>, + actor: Option>, + Json(request): Json, +) -> std::result::Result, ApiError> { + let actor_arc = actor + .as_ref() + .map(|Extension(actor)| Arc::clone(&actor.actor_id)) + .unwrap_or_else(|| Arc::::from("anonymous")); + let actor_id = actor + .as_ref() + .map(|Extension(actor)| actor.actor_id.as_ref()); + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::SchemaApply, + branch: None, + target_branch: Some("main".to_string()), + }, + )?; + let est_bytes = request.schema_source.len() as u64; + let _admission = state + .workload + .try_admit(&actor_arc, est_bytes) + .map_err(ApiError::from_workload_reject)?; + let result = { + 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_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(handle.uri.as_str(), result))) +} + +#[utoipa::path( + post, + path = "/ingest", + tag = "mutations", + operation_id = "ingest", + request_body = IngestRequest, + responses( + (status = 200, description = "Ingest results", body = IngestOutput), + (status = 400, description = "Bad request", body = ErrorOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Bulk-ingest NDJSON data into a branch. +/// +/// `data` is NDJSON with one record per line. `mode` controls behavior on +/// existing rows: `merge` upserts by id (default), `append` blindly inserts, +/// `overwrite` replaces table contents. If `branch` does not exist it is +/// created from `from` (defaults to `main`). **Destructive** when `mode` is +/// `overwrite` or when ingest produces conflicting writes. +async fn server_ingest( + State(state): State, + Extension(handle): Extension>, + actor: Option>, + Json(request): Json, +) -> std::result::Result, ApiError> { + let branch = request.branch.unwrap_or_else(|| "main".to_string()); + let from = request.from.unwrap_or_else(|| "main".to_string()); + let mode = request.mode.unwrap_or(omnigraph::loader::LoadMode::Merge); + let actor_arc = actor + .as_ref() + .map(|Extension(actor)| Arc::clone(&actor.actor_id)) + .unwrap_or_else(|| Arc::::from("anonymous")); + let actor_id = actor + .as_ref() + .map(|Extension(actor)| actor.actor_id.as_ref()); + + let branch_exists = { + let db = &handle.engine; + db.branch_list() + .await + .map_err(ApiError::from_omni)? + .into_iter() + .any(|name| name == branch) + }; + + if !branch_exists { + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::BranchCreate, + branch: Some(from.clone()), + target_branch: Some(branch.clone()), + }, + )?; + } + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::Change, + branch: Some(branch.clone()), + target_branch: None, + }, + )?; + let est_bytes = request.data.len() as u64; + let _admission = state + .workload + .try_admit(&actor_arc, est_bytes) + .map_err(ApiError::from_workload_reject)?; + + let result = { + 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( + handle.uri.as_str(), + &result, + actor_id.map(str::to_string), + ))) +} + +#[utoipa::path( + get, + path = "/branches", + tag = "branches", + operation_id = "listBranches", + responses( + (status = 200, description = "List of branches", body = BranchListOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// List all branches. +/// +/// Returns branch names sorted alphabetically. Read-only. +async fn server_branch_list( + 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: None, + target_branch: None, + }, + )?; + let mut branches = { + let db = &handle.engine; + db.branch_list().await.map_err(ApiError::from_omni)? + }; + branches.sort(); + Ok(Json(BranchListOutput { branches })) +} + +#[utoipa::path( + post, + path = "/branches", + tag = "branches", + operation_id = "createBranch", + request_body = BranchCreateRequest, + responses( + (status = 200, description = "Branch created", body = BranchCreateOutput), + (status = 400, description = "Bad request", body = ErrorOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + (status = 409, description = "Branch already exists", body = ErrorOutput), + (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Create a new branch. +/// +/// Forks `name` off of `from` (defaults to `main`). The new branch shares +/// table data with its parent until it is mutated. Returns 409 if `name` +/// already exists. +async fn server_branch_create( + State(state): State, + 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.actor_id)) + .unwrap_or_else(|| Arc::::from("anonymous")); + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::BranchCreate, + branch: Some(from.clone()), + target_branch: Some(request.name.clone()), + }, + )?; + // Branch metadata only β€” small constant bytes estimate. The Lance + // shallow-clone work is bounded by the parent's manifest size, not + // the request body. + let _admission = state + .workload + .try_admit(&actor_arc, 256) + .map_err(ApiError::from_workload_reject)?; + { + let db = &handle.engine; + db.branch_create_from_as( + ReadTarget::branch(&from), + &request.name, + actor.as_ref().map(|Extension(a)| a.actor_id.as_ref()), + ) + .await + .map_err(ApiError::from_omni)?; + } + Ok(Json(BranchCreateOutput { + uri: handle.uri.clone(), + from, + name: request.name, + 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}", + tag = "branches", + operation_id = "deleteBranch", + params( + ("branch" = String, Path, description = "Branch name to delete"), + ), + responses( + (status = 200, description = "Branch deleted", body = BranchDeleteOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + (status = 404, description = "Branch not found", body = ErrorOutput), + (status = 429, description = "Per-actor admission cap exceeded; honor `Retry-After` header", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// Delete a branch. +/// +/// **Irreversible.** Removes the branch pointer; commits remain reachable +/// only if referenced by another branch. Returns 404 if the branch does not +/// exist. +async fn server_branch_delete( + State(state): State, + 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.actor_id)) + .unwrap_or_else(|| Arc::::from("anonymous")); + let actor_id = actor + .as_ref() + .map(|Extension(actor)| actor.actor_id.as_ref()); + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::BranchDelete, + branch: None, + target_branch: Some(branch.clone()), + }, + )?; + // Metadata-only manifest tombstone β€” small constant estimate. + let _admission = state + .workload + .try_admit(&actor_arc, 256) + .map_err(ApiError::from_workload_reject)?; + { + let db = &handle.engine; + db.branch_delete_as(&branch, actor_id) + .await + .map_err(ApiError::from_omni)?; + } + Ok(Json(BranchDeleteOutput { + uri: handle.uri.clone(), + name: branch, + actor_id: actor_id.map(str::to_string), + })) +} + +#[utoipa::path( + post, + path = "/branches/merge", + tag = "branches", + operation_id = "mergeBranches", + request_body = BranchMergeRequest, + responses( + (status = 200, description = "Branches merged", body = BranchMergeOutput), + (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" = [])), +)] +/// Merge one branch into another. +/// +/// Merges `source` into `target` (defaults to `main`). Outcome is one of +/// `already_up_to_date`, `fast_forward`, or `merged`. Returns 409 with the +/// list of conflicts if the merge cannot be completed; the target is left +/// unchanged in that case. **Destructive** to `target` on success. +async fn server_branch_merge( + State(state): State, + 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.actor_id)) + .unwrap_or_else(|| Arc::::from("anonymous")); + let actor_id = actor + .as_ref() + .map(|Extension(actor)| actor.actor_id.as_ref()); + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::BranchMerge, + branch: Some(request.source.clone()), + target_branch: Some(target.clone()), + }, + )?; + // Merge body is small JSON; the heavy work is in the engine but is + // bounded per-(table, branch) by the writer queue. Small constant + // estimate suffices for the actor in-flight count. + let _admission = state + .workload + .try_admit(&actor_arc, 256) + .map_err(ApiError::from_workload_reject)?; + let outcome = { + let db = &handle.engine; + db.branch_merge_as(&request.source, &target, actor_id) + .await + .map_err(ApiError::from_omni)? + }; + Ok(Json(BranchMergeOutput { + source: request.source, + target, + outcome: outcome.into(), + actor_id: actor_id.map(str::to_string), + })) +} + +#[utoipa::path( + get, + path = "/commits", + tag = "commits", + operation_id = "listCommits", + params(CommitListQuery), + responses( + (status = 200, description = "List of commits", body = CommitListOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + ), + security(("bearer_token" = [])), +)] +/// List commits. +/// +/// 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( + Extension(handle): Extension>, + actor: Option>, + Query(query): Query, +) -> std::result::Result, ApiError> { + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::Read, + branch: query.branch.clone(), + target_branch: None, + }, + )?; + let commits = { + let db = &handle.engine; + db.list_commits(query.branch.as_deref()) + .await + .map_err(ApiError::from_omni)? + }; + Ok(Json(CommitListOutput { + commits: commits.iter().map(api::commit_output).collect(), + })) +} + +/// 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}", + tag = "commits", + operation_id = "getCommit", + params( + ("commit_id" = String, Path, description = "Commit identifier"), + ), + responses( + (status = 200, description = "Commit details", body = api::CommitOutput), + (status = 401, description = "Unauthorized", body = ErrorOutput), + (status = 403, description = "Forbidden", body = ErrorOutput), + (status = 404, description = "Commit not found", body = ErrorOutput), + ), + 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( + Extension(handle): Extension>, + actor: Option>, + Path(CommitPath { commit_id }): Path, +) -> std::result::Result, ApiError> { + authorize_request( + actor.as_ref().map(|Extension(actor)| actor), + handle.policy.as_deref(), + PolicyRequest { + action: PolicyAction::Read, + branch: None, + target_branch: None, + }, + )?; + let commit = { + let db = &handle.engine; + db.get_commit(&commit_id) + .await + .map_err(ApiError::from_omni)? + }; + Ok(Json(api::commit_output(&commit))) +} + +fn read_target_from_request(branch: Option, snapshot: Option) -> ReadTarget { + if let Some(snapshot) = snapshot { + ReadTarget::snapshot(omnigraph::db::SnapshotId::new(snapshot)) + } else { + ReadTarget::branch(branch.unwrap_or_else(|| "main".to_string())) + } +} + +fn select_named_query_decl( + query_source: &str, + requested_name: Option<&str>, +) -> Result { + let parsed = parse_query(query_source)?; + let query = if let Some(name) = requested_name { + parsed + .queries + .into_iter() + .find(|query| query.name == name) + .ok_or_else(|| color_eyre::eyre::eyre!("query '{}' not found", name))? + } else if parsed.queries.len() == 1 { + parsed.queries.into_iter().next().unwrap() + } 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)) +} + +fn query_params_from_json( + query_params: &[omnigraph_compiler::query::ast::Param], + params_json: Option<&Value>, +) -> Result { + json_params_to_param_map(params_json, query_params, JsonParamMode::Standard) + .map_err(|err| color_eyre::eyre::eyre!(err.to_string())) +} + +fn normalize_bearer_token(value: Option) -> Option { + value + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) +} + +fn normalize_bearer_actor(value: String) -> Result { + let value = value.trim().to_string(); + if value.is_empty() { + bail!("bearer token actor names must not be blank"); + } + Ok(value) +} + +fn parse_bearer_tokens_json(value: &str) -> Result> { + let entries: HashMap = serde_json::from_str(value) + .wrap_err("OMNIGRAPH_SERVER_BEARER_TOKENS_JSON must be a JSON object of actor->token")?; + Ok(entries.into_iter().collect()) +} + +fn read_bearer_tokens_file(path: &str) -> Result> { + let contents = fs::read_to_string(path) + .wrap_err_with(|| format!("failed to read bearer tokens file at {path}"))?; + parse_bearer_tokens_json(&contents) + .wrap_err_with(|| format!("failed to parse bearer tokens file at {path}")) +} + +fn validate_bearer_tokens(entries: Vec<(String, String)>) -> Result> { + let mut seen_actors = HashSet::new(); + let mut seen_tokens = HashSet::new(); + let mut normalized = Vec::with_capacity(entries.len()); + + for (actor, token) in entries { + let actor = normalize_bearer_actor(actor)?; + let Some(token) = normalize_bearer_token(Some(token)) else { + bail!("bearer token for actor '{actor}' must not be blank"); + }; + if !seen_actors.insert(actor.clone()) { + bail!("duplicate bearer token actor '{actor}'"); + } + if !seen_tokens.insert(token.clone()) { + bail!("duplicate bearer token value configured"); + } + normalized.push((actor, token)); + } + + normalized.sort_by(|(left, _), (right, _)| left.cmp(right)); + Ok(normalized) +} + +fn server_bearer_tokens_from_env() -> Result> { + let mut entries = Vec::new(); + + if let Some(token) = normalize_bearer_token(std::env::var("OMNIGRAPH_SERVER_BEARER_TOKEN").ok()) + { + entries.push(("default".to_string(), token)); + } + + if let Some(path) = + normalize_bearer_token(std::env::var("OMNIGRAPH_SERVER_BEARER_TOKENS_FILE").ok()) + { + entries.extend(read_bearer_tokens_file(&path)?); + } else if let Some(json) = + normalize_bearer_token(std::env::var("OMNIGRAPH_SERVER_BEARER_TOKENS_JSON").ok()) + { + entries.extend(parse_bearer_tokens_json(&json)?); + } + + validate_bearer_tokens(entries) +} + +#[cfg(test)] +mod tests { + use super::{ + 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!( + hash_bearer_token("stable-input"), + hash_bearer_token("stable-input"), + ); + } + + #[test] + fn hash_bearer_token_differs_for_different_inputs() { + assert_ne!(hash_bearer_token("token-a"), hash_bearer_token("token-b")); + } + + #[test] + fn hash_bearer_token_matches_known_sha256_vector() { + // SHA-256("abc"). If this ever fails, the hash function was swapped. + let hash = hash_bearer_token("abc"); + let hex: String = hash.iter().map(|b| format!("{:02x}", b)).collect(); + assert_eq!( + hex, + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } + + #[test] + fn server_settings_load_from_yaml_config() { + let temp = tempdir().unwrap(); + let config = temp.path().join("omnigraph.yaml"); + fs::write( + &config, + r#" +graphs: + local: + uri: /tmp/demo.omni +server: + graph: local + bind: 0.0.0.0:9090 +"#, + ) + .unwrap(); + + let settings = load_server_settings(Some(&config), None, None, None, false).unwrap(); + 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"); + } + + #[test] + fn server_settings_cli_flags_override_yaml_config() { + let temp = tempdir().unwrap(); + let config = temp.path().join("omnigraph.yaml"); + fs::write( + &config, + r#" +graphs: + local: + uri: /tmp/demo.omni +server: + graph: local + bind: 127.0.0.1:8080 +"#, + ) + .unwrap(); + + let settings = load_server_settings( + Some(&config), + Some("/tmp/override.omni".to_string()), + None, + Some("0.0.0.0:9999".to_string()), + false, + ) + .unwrap(); + 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"); + } + + #[test] + fn server_settings_can_resolve_named_target() { + let temp = tempdir().unwrap(); + let config = temp.path().join("omnigraph.yaml"); + fs::write( + &config, + r#" +graphs: + local: + uri: ./demo.omni + dev: + uri: http://127.0.0.1:8080 +server: + graph: local + bind: 127.0.0.1:8080 +"#, + ) + .unwrap(); + + let settings = + load_server_settings(Some(&config), None, Some("dev".to_string()), None, false) + .unwrap(); + 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("no graph to serve"), + "expected mode-inference error, got: {error}", + ); + } + + #[test] + fn classify_open_requires_explicit_unauthenticated_flag() { + // State 1: no tokens, no policy, no flag β†’ refuse to start. + let error = classify_server_runtime_state(false, false, false).unwrap_err(); + let msg = error.to_string(); + assert!( + msg.contains("--unauthenticated"), + "expected refusal message mentioning --unauthenticated, got: {msg}" + ); + + // Same matrix cell but with the flag set β†’ Open mode permitted. + assert_eq!( + classify_server_runtime_state(false, false, true).unwrap(), + ServerRuntimeState::Open + ); + } + + #[test] + fn classify_tokens_without_policy_is_default_deny() { + // State 2: tokens configured, no policy β†’ DefaultDeny regardless + // of the flag (the flag opts into the fully-open dev mode; it + // doesn't downgrade default-deny back to open). + assert_eq!( + classify_server_runtime_state(true, false, false).unwrap(), + ServerRuntimeState::DefaultDeny + ); + assert_eq!( + classify_server_runtime_state(true, false, true).unwrap(), + ServerRuntimeState::DefaultDeny + ); + } + + #[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() { + // MR-723 PR A: pin the integration boundary that the classifier + // is actually called by `serve()` before any side-effecting + // work (Lance dataset open, TcpListener::bind). The classifier + // itself is unit-tested above; this test guards the propagation + // path from `classify_server_runtime_state` through serve's + // `?` so a future refactor that drops the call returns red. + // + // Marked `#[serial]` because we have to clear all bearer-token + // env vars, and another test in this module setting any of them + // concurrently would corrupt the read inside `resolve_token_source`. + 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(); + // Graph path doesn't need to exist β€” classifier fires before + // `AppState::open_with_bearer_tokens_and_policy`. + let config = ServerConfig { + 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(), + allow_unauthenticated: false, + }; + let result = serve(config).await; + 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"), + "expected refusal message naming the misconfiguration, got: {msg}", + ); + } + + #[test] + #[serial] + fn unauthenticated_env_var_classification() { + // MR-723 PR A: closes the gap where the env-var read path inside + // `load_server_settings` was structurally implemented but not + // exercised by any test. Three properties to pin, all in one + // sequential test because `cargo test` runs the mod test suite + // in parallel and `OMNIGRAPH_UNAUTHENTICATED` is process-global + // β€” interleaving with another test that sets the same env var + // (concurrent classifier tests, even the bearer-token suite + // sharing `EnvGuard`) corrupts the read. Sequential within one + // test fn is the simplest race-free shape. + let temp = tempdir().unwrap(); + let config_path = temp.path().join("omnigraph.yaml"); + fs::write( + &config_path, + r#" +graphs: + local: + uri: /tmp/demo-unauth.omni +server: + graph: local +"#, + ) + .unwrap(); + + // Truthy values flip Open mode on, even with CLI flag off. + for value in ["1", "true", "yes", "TRUE", "anything"] { + let _guard = EnvGuard::set(&[("OMNIGRAPH_UNAUTHENTICATED", Some(value))]); + let settings = load_server_settings(Some(&config_path), None, None, None, false) + .expect("settings load should succeed"); + assert!( + settings.allow_unauthenticated, + "OMNIGRAPH_UNAUTHENTICATED={value:?} should enable Open mode", + ); + } + + // Falsy values keep refusal behavior, even with CLI flag off. + for value in ["0", "false", "FALSE", ""] { + let _guard = EnvGuard::set(&[("OMNIGRAPH_UNAUTHENTICATED", Some(value))]); + let settings = load_server_settings(Some(&config_path), None, None, None, false) + .expect("settings load should succeed"); + assert!( + !settings.allow_unauthenticated, + "OMNIGRAPH_UNAUTHENTICATED={value:?} should NOT enable Open mode", + ); + } + + // Unset env var: also false. + let _guard = EnvGuard::set(&[("OMNIGRAPH_UNAUTHENTICATED", None)]); + let settings = load_server_settings(Some(&config_path), None, None, None, false) + .expect("settings load should succeed"); + assert!( + !settings.allow_unauthenticated, + "OMNIGRAPH_UNAUTHENTICATED unset should NOT enable Open mode", + ); + drop(_guard); + + // CLI flag wins even when env is falsy β€” `serve()` honors the + // OR of both inputs. + let _guard = EnvGuard::set(&[("OMNIGRAPH_UNAUTHENTICATED", Some("0"))]); + let settings = load_server_settings(Some(&config_path), None, None, None, true) + .expect("settings load should succeed"); + assert!( + settings.allow_unauthenticated, + "--unauthenticated CLI flag should win even when env is falsy", + ); + } + + #[test] + 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(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); + assert_eq!(normalize_bearer_token(Some(" ".to_string())), None); + assert_eq!( + normalize_bearer_token(Some(" demo-token ".to_string())).as_deref(), + Some("demo-token") + ); + } + + struct EnvGuard { + saved: Vec<(&'static str, Option)>, + } + + impl EnvGuard { + fn set(vars: &[(&'static str, Option<&str>)]) -> Self { + let saved = vars + .iter() + .map(|(name, _)| (*name, env::var(name).ok())) + .collect::>(); + for (name, value) in vars { + unsafe { + match value { + Some(value) => env::set_var(name, value), + None => env::remove_var(name), + } + } + } + Self { saved } + } + } + + impl Drop for EnvGuard { + fn drop(&mut self) { + for (name, value) in self.saved.drain(..) { + unsafe { + match value { + Some(value) => env::set_var(name, value), + None => env::remove_var(name), + } + } + } + } + } + + #[test] + fn parse_bearer_tokens_json_reads_actor_token_map() { + let tokens = parse_bearer_tokens_json(r#"{"alice":" token-a ","bob":"token-b"}"#).unwrap(); + assert_eq!(tokens.len(), 2); + assert!(tokens.contains(&("alice".to_string(), " token-a ".to_string()))); + assert!(tokens.contains(&("bob".to_string(), "token-b".to_string()))); + } + + #[test] + #[serial] + fn server_bearer_tokens_from_env_reads_legacy_token_and_token_file() { + let temp = tempdir().unwrap(); + let tokens_path = temp.path().join("tokens.json"); + fs::write( + &tokens_path, + r#"{"team-01":"token-one","team-02":"token-two"}"#, + ) + .unwrap(); + + let _guard = EnvGuard::set(&[ + ("OMNIGRAPH_SERVER_BEARER_TOKEN", Some(" legacy-token ")), + ( + "OMNIGRAPH_SERVER_BEARER_TOKENS_FILE", + Some(tokens_path.to_str().unwrap()), + ), + ("OMNIGRAPH_SERVER_BEARER_TOKENS_JSON", None), + ]); + + let tokens = server_bearer_tokens_from_env().unwrap(); + assert_eq!( + tokens, + vec![ + ("default".to_string(), "legacy-token".to_string()), + ("team-01".to_string(), "token-one".to_string()), + ("team-02".to_string(), "token-two".to_string()), + ] + ); + } +} diff --git a/crates/omnigraph-server/src/main.rs b/crates/omnigraph-server/src/main.rs index a138d12..4e1c256 100644 --- a/crates/omnigraph-server/src/main.rs +++ b/crates/omnigraph-server/src/main.rs @@ -14,12 +14,6 @@ struct Cli { target: Option, #[arg(long)] config: Option, - /// Boot from a cluster: either a config directory (storage resolved - /// through cluster.yaml) or a storage-root URI directly - /// (s3://bucket/prefix β€” config-free serving from the bucket). - /// Exclusive: cannot combine with , --target, or --config. - #[arg(long)] - cluster: Option, #[arg(long)] bind: Option, /// Run without bearer tokens and without a policy file (MR-723). @@ -38,12 +32,10 @@ async fn main() -> Result<()> { let cli = Cli::parse(); let settings: ServerConfig = load_server_settings( cli.config.as_ref(), - cli.cluster.as_ref(), cli.uri, cli.target, cli.bind, cli.unauthenticated, - ) - .await?; + )?; serve(settings).await } diff --git a/crates/omnigraph-server/src/settings.rs b/crates/omnigraph-server/src/settings.rs deleted file mode 100644 index 59c437b..0000000 --- a/crates/omnigraph-server/src/settings.rs +++ /dev/null @@ -1,1006 +0,0 @@ -//! Server settings: omnigraph.yaml/CLI/env resolution, mode inference -//! (single vs multi vs cluster), bearer-token sources, and runtime-state -//! classification (moved verbatim from lib.rs in the modularization). - -use super::*; - -/// Build serving settings from a cluster directory's applied revision -/// (RFC-005 Β§D2): graphs at derived roots, stored queries from verified -/// catalog blob content, policy bundles from blob paths with their applied -/// bindings. Always multi-graph routing. The unauthenticated/env handling -/// matches the omnigraph.yaml path. -pub(crate) async fn load_cluster_settings( - cluster_dir: &PathBuf, - cli_bind: Option, - cli_allow_unauthenticated: bool, -) -> Result { - // `--cluster` accepts either a config directory (the ledger location is - // resolved through cluster.yaml's `storage:` key) or a storage-root URI - // directly (`s3://bucket/prefix`) β€” config-free serving: the ledger and - // catalog on the bucket ARE the deployment artifact. - // Any scheme-qualified argument (s3://, file://) is a storage root; a - // bare path is a config directory. - let cluster_arg = cluster_dir.to_string_lossy(); - let snapshot = if cluster_arg.contains("://") { - omnigraph_cluster::read_serving_snapshot_from_storage(cluster_arg.as_ref()).await - } else { - omnigraph_cluster::read_serving_snapshot(cluster_dir).await - } - .map_err(|diagnostics| { - let details = diagnostics - .iter() - .map(|diagnostic| format!("[{}] {}: {}", diagnostic.code, diagnostic.path, diagnostic.message)) - .collect::>() - .join("\n "); - eyre!("the cluster at '{}' is not ready to serve:\n {details}", cluster_dir.display()) - })?; - - // Bindings -> Cedar slots. The serving pipeline loads one bundle per - // graph plus one server-level bundle; stacked bundles per scope are a - // later slice β€” refuse loudly rather than silently merging policy. - let mut server_policy: Option = None; - let mut graph_policies: BTreeMap = BTreeMap::new(); - for policy in &snapshot.policies { - for binding in &policy.applies_to { - if binding == "cluster" { - if server_policy - .replace(PolicySource::Inline(policy.source.clone())) - .is_some() - { - bail!( - "multiple policy bundles bind the cluster scope; cluster-mode serving supports one bundle per scope β€” split or merge bundles (multi-bundle scopes are a later slice)" - ); - } - } else if let Some(graph_id) = binding.strip_prefix("graph.") { - if graph_policies - .insert( - graph_id.to_string(), - PolicySource::Inline(policy.source.clone()), - ) - .is_some() - { - bail!( - "multiple policy bundles bind graph '{graph_id}'; cluster-mode serving supports one bundle per scope β€” split or merge bundles (multi-bundle scopes are a later slice)" - ); - } - } else { - bail!("unrecognized policy binding '{binding}' in the applied revision"); - } - } - } - - let mut graphs = Vec::new(); - for graph in &snapshot.graphs { - let specs: Vec = snapshot - .queries - .iter() - .filter(|query| query.graph_id == graph.graph_id) - .map(|query| queries::RegistrySpec { - name: query.name.clone(), - source: query.source.clone(), - // The Β§D5 bridge: the cluster registry has no expose flag - // (exposure becomes a policy decision in Phase 6) β€” cluster - // mode lists every stored query. - expose: true, - tool_name: None, - }) - .collect(); - let registry = QueryRegistry::from_specs(specs).map_err(|errors| { - let details = errors - .iter() - .map(|error| error.to_string()) - .collect::>() - .join("\n "); - eyre!( - "stored queries in the applied revision failed to parse:\n {details}\nrun `cluster refresh` then `cluster apply`, and restart" - ) - })?; - graphs.push(GraphStartupConfig { - graph_id: graph.graph_id.clone(), - uri: graph.root.to_string_lossy().to_string(), - policy: graph_policies.get(&graph.graph_id).cloned(), - queries: registry, - }); - } - - let env_unauth = std::env::var("OMNIGRAPH_UNAUTHENTICATED") - .ok() - .map(|v| { - let trimmed = v.trim(); - !trimmed.is_empty() && trimmed != "0" && !trimmed.eq_ignore_ascii_case("false") - }) - .unwrap_or(false); - - Ok(ServerConfig { - mode: ServerConfigMode::Multi { - graphs, - config_path: cluster_dir.clone(), - server_policy, - }, - bind: cli_bind.unwrap_or_else(|| "127.0.0.1:8080".to_string()), - allow_unauthenticated: cli_allow_unauthenticated || env_unauth, - }) -} - -pub async fn load_server_settings( - config_path: Option<&PathBuf>, - cli_cluster: Option<&PathBuf>, - cli_uri: Option, - cli_target: Option, - cli_bind: Option, - cli_allow_unauthenticated: bool, -) -> Result { - // Rule 0 (RFC-005): --cluster is an exclusive boot source. It is checked - // before anything reads omnigraph.yaml β€” in cluster mode that file is - // never opened, not even the implicit current-directory search. - if let Some(cluster_dir) = cli_cluster { - if cli_uri.is_some() || cli_target.is_some() || config_path.is_some() { - bail!( - "--cluster is an exclusive boot source; it cannot combine with a graph URI, --target, or --config (axiom 15: a deployment serves from one source)" - ); - } - return load_cluster_settings(cluster_dir, cli_bind, cli_allow_unauthenticated).await; - } - let config = load_config(config_path)?; - let bind = cli_bind.unwrap_or_else(|| config.server_bind().to_string()); - // 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. - let env_unauth = std::env::var("OMNIGRAPH_UNAUTHENTICATED") - .ok() - .map(|v| { - let trimmed = v.trim(); - !trimmed.is_empty() && trimmed != "0" && !trimmed.eq_ignore_ascii_case("false") - }) - .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: config.resolve_target_policy_file(name).map(PolicySource::File), - queries, - }); - } - let config_path = config_path - .cloned() - .expect("has_explicit_config implies config_path is Some"); - let server_policy = config.resolve_server_policy_file().map(PolicySource::File); - ServerConfigMode::Multi { - graphs, - config_path, - server_policy, - } - } 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 { - mode, - bind, - 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. -/// -/// * **Open** β€” neither tokens nor policy; requires explicit -/// `allow_unauthenticated`. Effectively a "trust the network" dev -/// mode. `serve()` refuses to start in this shape without the flag, -/// so the only way to reach this state at runtime is via deliberate -/// operator opt-in. -/// * **DefaultDeny** β€” tokens configured but no policy file. The -/// 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 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, - DefaultDeny, - PolicyEnabled, -} - -/// Compute the [`ServerRuntimeState`] from the configured inputs. -/// 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, - allow_unauthenticated: bool, -) -> Result { - match (has_tokens, has_policy, allow_unauthenticated) { - (false, false, false) => bail!( - "server has no bearer tokens and no policy file configured. This is a fully \ - open server β€” pass `--unauthenticated` (or set OMNIGRAPH_UNAUTHENTICATED=1) \ - if you actually want that, otherwise configure bearer tokens (see \ - docs/user/server.md) and/or `policy.file` in omnigraph.yaml." - ), - (false, false, true) => Ok(ServerRuntimeState::Open), - (true, false, _) => Ok(ServerRuntimeState::DefaultDeny), - (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(crate) fn normalize_bearer_token(value: Option) -> Option { - value - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) -} - -pub(crate) fn normalize_bearer_actor(value: String) -> Result { - let value = value.trim().to_string(); - if value.is_empty() { - bail!("bearer token actor names must not be blank"); - } - Ok(value) -} - -pub(crate) fn parse_bearer_tokens_json(value: &str) -> Result> { - let entries: HashMap = serde_json::from_str(value) - .wrap_err("OMNIGRAPH_SERVER_BEARER_TOKENS_JSON must be a JSON object of actor->token")?; - Ok(entries.into_iter().collect()) -} - -pub(crate) fn read_bearer_tokens_file(path: &str) -> Result> { - let contents = fs::read_to_string(path) - .wrap_err_with(|| format!("failed to read bearer tokens file at {path}"))?; - parse_bearer_tokens_json(&contents) - .wrap_err_with(|| format!("failed to parse bearer tokens file at {path}")) -} - -pub(crate) fn validate_bearer_tokens(entries: Vec<(String, String)>) -> Result> { - let mut seen_actors = HashSet::new(); - let mut seen_tokens = HashSet::new(); - let mut normalized = Vec::with_capacity(entries.len()); - - for (actor, token) in entries { - let actor = normalize_bearer_actor(actor)?; - let Some(token) = normalize_bearer_token(Some(token)) else { - bail!("bearer token for actor '{actor}' must not be blank"); - }; - if !seen_actors.insert(actor.clone()) { - bail!("duplicate bearer token actor '{actor}'"); - } - if !seen_tokens.insert(token.clone()) { - bail!("duplicate bearer token value configured"); - } - normalized.push((actor, token)); - } - - normalized.sort_by(|(left, _), (right, _)| left.cmp(right)); - Ok(normalized) -} - -pub(crate) fn server_bearer_tokens_from_env() -> Result> { - let mut entries = Vec::new(); - - if let Some(token) = normalize_bearer_token(std::env::var("OMNIGRAPH_SERVER_BEARER_TOKEN").ok()) - { - entries.push(("default".to_string(), token)); - } - - if let Some(path) = - normalize_bearer_token(std::env::var("OMNIGRAPH_SERVER_BEARER_TOKENS_FILE").ok()) - { - entries.extend(read_bearer_tokens_file(&path)?); - } else if let Some(json) = - normalize_bearer_token(std::env::var("OMNIGRAPH_SERVER_BEARER_TOKENS_JSON").ok()) - { - entries.extend(parse_bearer_tokens_json(&json)?); - } - - validate_bearer_tokens(entries) -} - -#[cfg(test)] -mod tests { - use super::{ - 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!( - hash_bearer_token("stable-input"), - hash_bearer_token("stable-input"), - ); - } - - #[test] - fn hash_bearer_token_differs_for_different_inputs() { - assert_ne!(hash_bearer_token("token-a"), hash_bearer_token("token-b")); - } - - #[test] - fn hash_bearer_token_matches_known_sha256_vector() { - // SHA-256("abc"). If this ever fails, the hash function was swapped. - let hash = hash_bearer_token("abc"); - let hex: String = hash.iter().map(|b| format!("{:02x}", b)).collect(); - assert_eq!( - hex, - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); - } - - #[tokio::test] - async fn server_settings_load_from_yaml_config() { - let temp = tempdir().unwrap(); - let config = temp.path().join("omnigraph.yaml"); - fs::write( - &config, - r#" -graphs: - local: - uri: /tmp/demo.omni -server: - graph: local - bind: 0.0.0.0:9090 -"#, - ) - .unwrap(); - - let settings = load_server_settings(Some(&config), None, None, None, None, false).await.unwrap(); - 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"); - } - - #[tokio::test] - async fn server_settings_cli_flags_override_yaml_config() { - let temp = tempdir().unwrap(); - let config = temp.path().join("omnigraph.yaml"); - fs::write( - &config, - r#" -graphs: - local: - uri: /tmp/demo.omni -server: - graph: local - bind: 127.0.0.1:8080 -"#, - ) - .unwrap(); - - let settings = load_server_settings( - Some(&config), - None, - Some("/tmp/override.omni".to_string()), - None, - Some("0.0.0.0:9999".to_string()), - false, - ) - .await - .unwrap(); - 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"); - } - - #[tokio::test] - async fn server_settings_can_resolve_named_target() { - let temp = tempdir().unwrap(); - let config = temp.path().join("omnigraph.yaml"); - fs::write( - &config, - r#" -graphs: - local: - uri: ./demo.omni - dev: - uri: http://127.0.0.1:8080 -server: - graph: local - bind: 127.0.0.1:8080 -"#, - ) - .unwrap(); - - let settings = - load_server_settings(Some(&config), None, None, Some("dev".to_string()), None, false) - .await - .unwrap(); - 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"), - } - } - - #[tokio::test] - async fn server_settings_require_uri_from_cli_or_config() { - let error = load_server_settings(None, None, None, None, None, false).await.unwrap_err(); - assert!( - error.to_string().contains("no graph to serve"), - "expected mode-inference error, got: {error}", - ); - } - - #[test] - fn classify_open_requires_explicit_unauthenticated_flag() { - // State 1: no tokens, no policy, no flag β†’ refuse to start. - let error = classify_server_runtime_state(false, false, false).unwrap_err(); - let msg = error.to_string(); - assert!( - msg.contains("--unauthenticated"), - "expected refusal message mentioning --unauthenticated, got: {msg}" - ); - - // Same matrix cell but with the flag set β†’ Open mode permitted. - assert_eq!( - classify_server_runtime_state(false, false, true).unwrap(), - ServerRuntimeState::Open - ); - } - - #[test] - fn classify_tokens_without_policy_is_default_deny() { - // State 2: tokens configured, no policy β†’ DefaultDeny regardless - // of the flag (the flag opts into the fully-open dev mode; it - // doesn't downgrade default-deny back to open). - assert_eq!( - classify_server_runtime_state(true, false, false).unwrap(), - ServerRuntimeState::DefaultDeny - ); - assert_eq!( - classify_server_runtime_state(true, false, true).unwrap(), - ServerRuntimeState::DefaultDeny - ); - } - - #[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: None, - queries: crate::queries::QueryRegistry::default(), - }], - config_path: temp.path().join("omnigraph.yaml"), - server_policy: Some(crate::PolicySource::File(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() { - // MR-723 PR A: pin the integration boundary that the classifier - // is actually called by `serve()` before any side-effecting - // work (Lance dataset open, TcpListener::bind). The classifier - // itself is unit-tested above; this test guards the propagation - // path from `classify_server_runtime_state` through serve's - // `?` so a future refactor that drops the call returns red. - // - // Marked `#[serial]` because we have to clear all bearer-token - // env vars, and another test in this module setting any of them - // concurrently would corrupt the read inside `resolve_token_source`. - 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(); - // Graph path doesn't need to exist β€” classifier fires before - // `AppState::open_with_bearer_tokens_and_policy`. - let config = ServerConfig { - 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(), - allow_unauthenticated: false, - }; - let result = serve(config).await; - 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"), - "expected refusal message naming the misconfiguration, got: {msg}", - ); - } - - #[tokio::test] - #[serial] - async fn unauthenticated_env_var_classification() { - // MR-723 PR A: closes the gap where the env-var read path inside - // `load_server_settings` was structurally implemented but not - // exercised by any test. Three properties to pin, all in one - // sequential test because `cargo test` runs the mod test suite - // in parallel and `OMNIGRAPH_UNAUTHENTICATED` is process-global - // β€” interleaving with another test that sets the same env var - // (concurrent classifier tests, even the bearer-token suite - // sharing `EnvGuard`) corrupts the read. Sequential within one - // test fn is the simplest race-free shape. - let temp = tempdir().unwrap(); - let config_path = temp.path().join("omnigraph.yaml"); - fs::write( - &config_path, - r#" -graphs: - local: - uri: /tmp/demo-unauth.omni -server: - graph: local -"#, - ) - .unwrap(); - - // Truthy values flip Open mode on, even with CLI flag off. - for value in ["1", "true", "yes", "TRUE", "anything"] { - let _guard = EnvGuard::set(&[("OMNIGRAPH_UNAUTHENTICATED", Some(value))]); - let settings = load_server_settings(Some(&config_path), None, None, None, None, false).await - .expect("settings load should succeed"); - assert!( - settings.allow_unauthenticated, - "OMNIGRAPH_UNAUTHENTICATED={value:?} should enable Open mode", - ); - } - - // Falsy values keep refusal behavior, even with CLI flag off. - for value in ["0", "false", "FALSE", ""] { - let _guard = EnvGuard::set(&[("OMNIGRAPH_UNAUTHENTICATED", Some(value))]); - let settings = load_server_settings(Some(&config_path), None, None, None, None, false).await - .expect("settings load should succeed"); - assert!( - !settings.allow_unauthenticated, - "OMNIGRAPH_UNAUTHENTICATED={value:?} should NOT enable Open mode", - ); - } - - // Unset env var: also false. - let _guard = EnvGuard::set(&[("OMNIGRAPH_UNAUTHENTICATED", None)]); - let settings = load_server_settings(Some(&config_path), None, None, None, None, false).await - .expect("settings load should succeed"); - assert!( - !settings.allow_unauthenticated, - "OMNIGRAPH_UNAUTHENTICATED unset should NOT enable Open mode", - ); - drop(_guard); - - // CLI flag wins even when env is falsy β€” `serve()` honors the - // OR of both inputs. - let _guard = EnvGuard::set(&[("OMNIGRAPH_UNAUTHENTICATED", Some("0"))]); - let settings = load_server_settings(Some(&config_path), None, None, None, None, true).await - .expect("settings load should succeed"); - assert!( - settings.allow_unauthenticated, - "--unauthenticated CLI flag should win even when env is falsy", - ); - } - - #[test] - 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(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); - assert_eq!(normalize_bearer_token(Some(" ".to_string())), None); - assert_eq!( - normalize_bearer_token(Some(" demo-token ".to_string())).as_deref(), - Some("demo-token") - ); - } - - struct EnvGuard { - saved: Vec<(&'static str, Option)>, - } - - impl EnvGuard { - fn set(vars: &[(&'static str, Option<&str>)]) -> Self { - let saved = vars - .iter() - .map(|(name, _)| (*name, env::var(name).ok())) - .collect::>(); - for (name, value) in vars { - unsafe { - match value { - Some(value) => env::set_var(name, value), - None => env::remove_var(name), - } - } - } - Self { saved } - } - } - - impl Drop for EnvGuard { - fn drop(&mut self) { - for (name, value) in self.saved.drain(..) { - unsafe { - match value { - Some(value) => env::set_var(name, value), - None => env::remove_var(name), - } - } - } - } - } - - #[test] - fn parse_bearer_tokens_json_reads_actor_token_map() { - let tokens = parse_bearer_tokens_json(r#"{"alice":" token-a ","bob":"token-b"}"#).unwrap(); - assert_eq!(tokens.len(), 2); - assert!(tokens.contains(&("alice".to_string(), " token-a ".to_string()))); - assert!(tokens.contains(&("bob".to_string(), "token-b".to_string()))); - } - - #[test] - #[serial] - fn server_bearer_tokens_from_env_reads_legacy_token_and_token_file() { - let temp = tempdir().unwrap(); - let tokens_path = temp.path().join("tokens.json"); - fs::write( - &tokens_path, - r#"{"team-01":"token-one","team-02":"token-two"}"#, - ) - .unwrap(); - - let _guard = EnvGuard::set(&[ - ("OMNIGRAPH_SERVER_BEARER_TOKEN", Some(" legacy-token ")), - ( - "OMNIGRAPH_SERVER_BEARER_TOKENS_FILE", - Some(tokens_path.to_str().unwrap()), - ), - ("OMNIGRAPH_SERVER_BEARER_TOKENS_JSON", None), - ]); - - let tokens = server_bearer_tokens_from_env().unwrap(); - assert_eq!( - tokens, - vec![ - ("default".to_string(), "legacy-token".to_string()), - ("team-01".to_string(), "token-one".to_string()), - ("team-02".to_string(), "token-two".to_string()), - ] - ); - } -} diff --git a/crates/omnigraph-server/tests/auth_policy.rs b/crates/omnigraph-server/tests/auth_policy.rs deleted file mode 100644 index 05c0c56..0000000 --- a/crates/omnigraph-server/tests/auth_policy.rs +++ /dev/null @@ -1,915 +0,0 @@ -//! Bearer auth, actor resolution, Cedar policy decisions, admission. -//! Moved verbatim from tests/server.rs in the modularization. - -use std::env; -use std::fs; -use std::sync::Arc; - -use axum::body::Body; -use axum::http::header::AUTHORIZATION; -use axum::http::{Method, Request, StatusCode}; -use omnigraph::db::{Omnigraph, ReadTarget}; -use omnigraph::error::OmniError; -use omnigraph::loader::LoadMode; -use omnigraph_server::api::{ - BranchCreateRequest, BranchMergeRequest, ChangeRequest, ErrorOutput, ExportRequest, ReadRequest, SchemaApplyRequest, -}; -use omnigraph_server::{AppState, build_app}; -use serde_json::{Value, json}; -use tower::ServiceExt; - - -mod support; -use support::*; - -#[tokio::test(flavor = "multi_thread")] -async fn healthz_succeeds_after_startup() { - let (_temp, app) = app_for_loaded_graph().await; - let (status, body) = json_response( - &app, - Request::builder() - .uri("/healthz") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - - assert_eq!(status, StatusCode::OK); - assert_eq!(body["status"], "ok"); - assert_eq!(body["version"], env!("CARGO_PKG_VERSION")); - match option_env!("OMNIGRAPH_SOURCE_VERSION") { - Some(source_version) => assert_eq!(body["source_version"], source_version), - None => assert!(body.get("source_version").is_none()), - } -} - -#[tokio::test(flavor = "multi_thread")] -async fn protected_routes_require_bearer_token() { - let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; - let (status, body) = json_response( - &app, - Request::builder() - .uri("/branches") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert_eq!(status, StatusCode::UNAUTHORIZED); - assert_eq!( - error.code, - Some(omnigraph_server::api::ErrorCode::Unauthorized) - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn protected_routes_accept_valid_bearer_token_while_healthz_stays_open() { - let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; - - let health = app - .clone() - .oneshot( - Request::builder() - .uri("/healthz") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(health.status(), StatusCode::OK); - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/branches") - .method(Method::GET) - .header("authorization", "Bearer demo-token") - .body(Body::empty()) - .unwrap(), - ) - .await; - - assert_eq!(status, StatusCode::OK); - assert!(body["branches"].is_array()); -} - -#[tokio::test(flavor = "multi_thread")] -async fn protected_routes_accept_any_configured_team_bearer_token() { - 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, - Request::builder() - .uri("/branches") - .method(Method::GET) - .header("authorization", "Bearer token-two") - .body(Body::empty()) - .unwrap(), - ) - .await; - - assert_eq!(status, StatusCode::OK); - assert!(body["branches"].is_array()); -} - -#[tokio::test(flavor = "multi_thread")] -async fn bearer_token_resolves_to_correct_actor_for_policy_decisions() { - let temp = init_loaded_graph().await; - let graph = graph_path(temp.path()); - let policy_path = temp.path().join("policy.yaml"); - fs::write( - &policy_path, - r#" -version: 1 -groups: - readers: [act-a] - writers: [act-b] -protected_branches: [main] -rules: - - id: readers-only - allow: - actors: { group: readers } - actions: [read] - branch_scope: any -"#, - ) - .unwrap(); - let state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - vec![ - ("act-a".to_string(), "token-a".to_string()), - ("act-b".to_string(), "token-b".to_string()), - ], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - - // act-a is authenticated AND authorized. - let (ok_status, _) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .header("authorization", "Bearer token-a") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(ok_status, StatusCode::OK); - - // act-b is authenticated but policy rejects β€” proves the resolved actor - // (not some default) was the policy subject. - let (denied_status, denied_body) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .header("authorization", "Bearer token-b") - .body(Body::empty()) - .unwrap(), - ) - .await; - let denied_error: ErrorOutput = serde_json::from_value(denied_body).unwrap(); - assert_eq!(denied_status, StatusCode::FORBIDDEN); - assert_eq!( - denied_error.code, - Some(omnigraph_server::api::ErrorCode::Forbidden) - ); - - // Unknown token: 401, never reaches the policy engine. - let (bad_status, _) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .header("authorization", "Bearer wrong-token") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(bad_status, StatusCode::UNAUTHORIZED); -} - -#[tokio::test(flavor = "multi_thread")] -async fn actor_id_resolves_from_bearer_token_ignoring_client_supplied_headers() { - 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` β€” - // `act-a` can read main, `act-b` cannot. The asymmetry is what - // makes the spoof-up/spoof-down distinction observable. - fs::write( - &policy_path, - r#" -version: 1 -groups: - readers: [act-a] - writers: [act-b] -protected_branches: [main] -rules: - - id: readers-only - allow: - actors: { group: readers } - actions: [read] - branch_scope: any -"#, - ) - .unwrap(); - let state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - vec![ - ("act-a".to_string(), "token-a".to_string()), - ("act-b".to_string(), "token-b".to_string()), - ], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - - // (1) Spoof-up: bearer for act-b (denied) + X-Actor-Id: act-a (allowed). - // If the server were trusting the header, this would succeed as - // act-a. The contract is: the bearer wins. Expect 403 because - // act-b can't read. - let (spoof_up_status, spoof_up_body) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .header("authorization", "Bearer token-b") - .header("x-actor-id", "act-a") - .body(Body::empty()) - .unwrap(), - ) - .await; - let spoof_up_error: ErrorOutput = serde_json::from_value(spoof_up_body).unwrap(); - assert_eq!( - spoof_up_status, - StatusCode::FORBIDDEN, - "X-Actor-Id must not promote a denied bearer to an allowed actor", - ); - assert_eq!( - spoof_up_error.code, - Some(omnigraph_server::api::ErrorCode::Forbidden), - ); - - // (2) Spoof-down: bearer for act-a (allowed) + X-Actor-Id: act-b (denied). - // If the server were trusting the header, this would fail as act-b. - // The contract is: the bearer wins. Expect 200 because act-a can read. - let (spoof_down_status, _) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .header("authorization", "Bearer token-a") - .header("x-actor-id", "act-b") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!( - spoof_down_status, - StatusCode::OK, - "X-Actor-Id must not demote an allowed bearer to a denied actor", - ); - - // (3) Empty-string spoof attempt: an X-Actor-Id of "" must not - // leak through as the policy subject. Same expectation as (1): - // bearer for act-b is denied regardless of what the header tries. - let (empty_spoof_status, _) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .header("authorization", "Bearer token-b") - .header("x-actor-id", "") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!( - empty_spoof_status, - StatusCode::FORBIDDEN, - "empty X-Actor-Id must not clear the resolved actor", - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn policy_allows_read_but_distinguishes_401_from_403() { - let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( - &[("act-bruno", "team-token"), ("act-ragnor", "admin-token")], - POLICY_YAML, - ) - .await; - - let (missing_status, missing_body) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - let missing_error: ErrorOutput = serde_json::from_value(missing_body).unwrap(); - assert_eq!(missing_status, StatusCode::UNAUTHORIZED); - assert_eq!( - missing_error.code, - Some(omnigraph_server::api::ErrorCode::Unauthorized) - ); - - let (snapshot_status, snapshot_body) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .header("authorization", "Bearer team-token") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(snapshot_status, StatusCode::OK); - assert_eq!(snapshot_body["branch"], "main"); - - let export_request = ExportRequest { - branch: Some("main".to_string()), - type_names: Vec::new(), - table_keys: Vec::new(), - }; - let (forbidden_status, forbidden_body) = json_response( - &app, - Request::builder() - .uri("/export") - .method(Method::POST) - .header("authorization", "Bearer team-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&export_request).unwrap())) - .unwrap(), - ) - .await; - let forbidden_error: ErrorOutput = serde_json::from_value(forbidden_body).unwrap(); - assert_eq!(forbidden_status, StatusCode::FORBIDDEN); - assert_eq!( - forbidden_error.code, - Some(omnigraph_server::api::ErrorCode::Forbidden) - ); - - let response = app - .clone() - .oneshot( - Request::builder() - .uri("/export") - .method(Method::POST) - .header("authorization", "Bearer admin-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&export_request).unwrap())) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::OK); -} - -#[tokio::test(flavor = "multi_thread")] -async fn policy_uses_resolved_branch_for_snapshot_reads() { - let temp = init_loaded_graph().await; - let graph = graph_path(temp.path()); - let snapshot_id = { - 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( - graph.to_string_lossy().to_string(), - vec![("act-bruno".to_string(), "team-token".to_string())], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - - let read = ReadRequest { - query_source: fs::read_to_string(fixture("test.gq")).unwrap(), - query_name: Some("get_person".to_string()), - params: Some(json!({ "name": "Alice" })), - branch: None, - snapshot: Some(snapshot_id), - }; - let (status, body) = json_response( - &app, - Request::builder() - .uri("/read") - .method(Method::POST) - .header("authorization", "Bearer team-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&read).unwrap())) - .unwrap(), - ) - .await; - - assert_eq!(status, StatusCode::OK); - assert_eq!(body["target"]["branch"], Value::Null); - assert_eq!( - body["target"]["snapshot"].as_str(), - read.snapshot.as_deref() - ); - assert_eq!(body["row_count"], 1); -} - -#[tokio::test(flavor = "multi_thread")] -async fn policy_blocks_change_on_protected_main_but_allows_unprotected_branch() { - let temp = init_loaded_graph().await; - let graph = graph_path(temp.path()); - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.branch_create_from(ReadTarget::branch("main"), "feature") - .await - .unwrap(); - drop(db); - - let policy_path = temp.path().join("policy.yaml"); - fs::write(&policy_path, POLICY_YAML).unwrap(); - let state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - vec![("act-bruno".to_string(), "team-token".to_string())], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - - let main_change = ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "Mina", "age": 28 })), - branch: Some("main".to_string()), - }; - let (main_status, main_body) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header("authorization", "Bearer team-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&main_change).unwrap())) - .unwrap(), - ) - .await; - let main_error: ErrorOutput = serde_json::from_value(main_body).unwrap(); - assert_eq!(main_status, StatusCode::FORBIDDEN); - assert_eq!( - main_error.code, - Some(omnigraph_server::api::ErrorCode::Forbidden) - ); - - let feature_change = ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "Mina", "age": 28 })), - branch: Some("feature".to_string()), - }; - let (feature_status, feature_body) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header("authorization", "Bearer team-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&feature_change).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(feature_status, StatusCode::OK); - assert_eq!(feature_body["branch"], "feature"); - assert_eq!(feature_body["affected_nodes"], 1); -} - -#[tokio::test(flavor = "multi_thread")] -async fn policy_blocks_non_admin_merge_to_main_and_allows_admin() { - let temp = init_loaded_graph().await; - let graph = graph_path(temp.path()); - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.branch_create_from(ReadTarget::branch("main"), "feature") - .await - .unwrap(); - db.load( - "feature", - r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#, - LoadMode::Append, - ) - .await - .unwrap(); - drop(db); - - let policy_path = temp.path().join("policy.yaml"); - fs::write(&policy_path, POLICY_YAML).unwrap(); - let state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - vec![ - ("act-bruno".to_string(), "team-token".to_string()), - ("act-ragnor".to_string(), "admin-token".to_string()), - ], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - - let merge = BranchMergeRequest { - source: "feature".to_string(), - target: Some("main".to_string()), - }; - let (deny_status, deny_body) = json_response( - &app, - Request::builder() - .uri("/branches/merge") - .method(Method::POST) - .header("authorization", "Bearer team-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&merge).unwrap())) - .unwrap(), - ) - .await; - let deny_error: ErrorOutput = serde_json::from_value(deny_body).unwrap(); - assert_eq!(deny_status, StatusCode::FORBIDDEN); - assert_eq!( - deny_error.code, - Some(omnigraph_server::api::ErrorCode::Forbidden) - ); - - let (allow_status, allow_body) = json_response( - &app, - Request::builder() - .uri("/branches/merge") - .method(Method::POST) - .header("authorization", "Bearer admin-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&merge).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(allow_status, StatusCode::OK); - assert_eq!(allow_body["actor_id"], "act-ragnor"); -} - -#[tokio::test(flavor = "multi_thread")] -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_graph_with_auth_tokens(&[("act-andrew", "token-one")]).await; - - let change = ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "Mina", "age": 28 })), - branch: Some("main".to_string()), - }; - let (change_status, change_body) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header("authorization", "Bearer token-one") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&change).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(change_status, StatusCode::OK); - assert_eq!(change_body["actor_id"], "act-andrew"); - - let (commits_status, commits_body) = json_response( - &app, - Request::builder() - .uri("/commits?branch=main") - .method(Method::GET) - .header("authorization", "Bearer token-one") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(commits_status, StatusCode::OK); - let head = commits_body["commits"] - .as_array() - .unwrap() - .last() - .expect("head commit should exist"); - assert_eq!(head["actor_id"], "act-andrew"); -} - -#[tokio::test(flavor = "multi_thread")] -async fn authenticated_branch_merge_stamps_merge_actor_on_head_commit() { - let (_temp, app) = app_for_loaded_graph_with_auth_tokens(&[ - ("act-andrew", "token-one"), - ("act-ragnor", "token-two"), - ]) - .await; - - let create = BranchCreateRequest { - from: Some("main".to_string()), - name: "feature".to_string(), - }; - let (create_status, _) = json_response( - &app, - Request::builder() - .uri("/branches") - .method(Method::POST) - .header("authorization", "Bearer token-one") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&create).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(create_status, StatusCode::OK); - - let change = ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "Zoe", "age": 33 })), - branch: Some("feature".to_string()), - }; - let (change_status, _) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header("authorization", "Bearer token-one") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&change).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(change_status, StatusCode::OK); - - let merge = BranchMergeRequest { - source: "feature".to_string(), - target: Some("main".to_string()), - }; - let (merge_status, merge_body) = json_response( - &app, - Request::builder() - .uri("/branches/merge") - .method(Method::POST) - .header("authorization", "Bearer token-two") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&merge).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(merge_status, StatusCode::OK); - assert_eq!(merge_body["actor_id"], "act-ragnor"); - - let (commit_status, commit_body) = json_response( - &app, - Request::builder() - .uri("/commits?branch=main") - .method(Method::GET) - .header("authorization", "Bearer token-two") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(commit_status, StatusCode::OK); - let head = commit_body["commits"] - .as_array() - .unwrap() - .last() - .expect("head commit should exist"); - assert_eq!(head["actor_id"], "act-ragnor"); -} - -#[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_graph().await; - let oversized = "x".repeat(1_100_000); - let response = app - .clone() - .oneshot( - Request::builder() - .uri("/read") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(oversized)) - .unwrap(), - ) - .await - .unwrap(); - - assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); -} - -#[tokio::test(flavor = "multi_thread")] -async fn default_deny_mode_allows_read_for_authenticated_actor() { - let (_temp, app) = app_for_graph_with_auth_tokens_only( - &fs::read_to_string(fixture("test.pg")).unwrap(), - &[("act-andrew", "demo-token")], - ) - .await; - - let (status, _body) = json_response( - &app, - Request::builder() - .uri("/snapshot") - .method(Method::GET) - .header(AUTHORIZATION, "Bearer demo-token") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); -} - -#[tokio::test(flavor = "multi_thread")] -async fn default_deny_mode_rejects_change_with_forbidden() { - 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: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "DefaultDeny", "age": 1 })), - branch: Some("main".to_string()), - }; - let (status, body) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header(AUTHORIZATION, "Bearer demo-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&change).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::FORBIDDEN); - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert!( - error.error.contains("default-deny"), - "expected default-deny in error message, got: {}", - error.error - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn default_deny_mode_rejects_schema_apply_with_forbidden() { - let (_temp, app) = app_for_graph_with_auth_tokens_only( - &fs::read_to_string(fixture("test.pg")).unwrap(), - &[("act-andrew", "demo-token")], - ) - .await; - - let req = SchemaApplyRequest { - schema_source: additive_schema_with_nickname(), - ..Default::default() - }; - let (status, body) = json_response( - &app, - Request::builder() - .uri("/schema/apply") - .method(Method::POST) - .header(AUTHORIZATION, "Bearer demo-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&req).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::FORBIDDEN); - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert!( - error.error.contains("default-deny"), - "expected default-deny in error message, got: {}", - error.error - ); -} - -#[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 graph - // because allowβ†’side-effects. - 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", - ); -} - -#[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 graph is reusable - // because denyβ†’no side-effects. - 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", - ); -} - -#[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 graph β€” - // a successful merge consumes the feature branch's commit on main. - 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", - ); -} - -#[tokio::test(flavor = "multi_thread")] -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, 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", - ); -} diff --git a/crates/omnigraph-server/tests/boot_settings.rs b/crates/omnigraph-server/tests/boot_settings.rs deleted file mode 100644 index 3869d27..0000000 --- a/crates/omnigraph-server/tests/boot_settings.rs +++ /dev/null @@ -1,1022 +0,0 @@ -//! Server settings loading and mode inference (single vs multi). -//! Moved verbatim from tests/server.rs in the modularization. - -use std::fs; - -use axum::Router; -use axum::body::{Body, to_bytes}; -use axum::http::{Method, Request, StatusCode}; -use omnigraph::db::Omnigraph; -use omnigraph_server::{AppState, build_app}; -use serde_json::Value; -use tower::ServiceExt; - - -mod support; -use support::*; - -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. - #[tokio::test] - async 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, None, false).await.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. - #[tokio::test] - async fn mode_inference_cli_uri_is_single() { - let settings = load_server_settings( - None, - None, - Some("/tmp/cli.omni".to_string()), - None, - None, - true, // allow unauth so we get past the runtime-state check - ) - .await - .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. - #[tokio::test] - async 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, None, Some("alpha".into()), None, true) - .await - .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). - #[tokio::test] - async 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, None, true).await.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. - #[tokio::test] - async 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, None, true).await.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"), - } - } - - #[tokio::test] - async 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, None, true).await.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}" - ); - } - - #[tokio::test] - async 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, None, true).await.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}" - ); - } - - #[tokio::test] - async 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, None, Some("prod".to_string()), None, true) - .await - .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}" - ); - } - - #[tokio::test] - async 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, None, Some("prod".to_string()), None, true) - .await - .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:?}"), - } - } - - #[tokio::test] - async 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, None, true).await.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. - #[tokio::test] - async fn mode_inference_no_inputs_errors_with_migration_hint() { - let err = load_server_settings(None, None, None, None, None, true).await.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). - #[tokio::test] - async 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, None, true).await.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). - #[tokio::test] - async 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), - None, - Some("/tmp/cli-override.omni".to_string()), - None, - None, - true, - ) - .await - .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. - #[tokio::test] - async 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, None, true).await.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"); - let omnigraph_server::PolicySource::File(alpha_policy) = - alpha.policy.as_ref().unwrap() - else { - panic!("yaml-configured policy must stay file-based"); - }; - assert_eq!(alpha_policy, &temp.path().join("policies/alpha.yaml")); - assert_eq!(beta.graph_id, "beta"); - assert!(beta.policy.is_none()); - } - - /// `server.policy.file` resolves alongside the graphs map. - #[tokio::test] - async 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, None, true).await.unwrap(); - match settings.mode { - ServerConfigMode::Multi { server_policy, .. } => { - let omnigraph_server::PolicySource::File(path) = server_policy.unwrap() else { - panic!("yaml-configured server policy must stay file-based"); - }; - assert_eq!(path, 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, None, true).await.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-server/tests/data_routes.rs b/crates/omnigraph-server/tests/data_routes.rs deleted file mode 100644 index cef2f9a..0000000 --- a/crates/omnigraph-server/tests/data_routes.rs +++ /dev/null @@ -1,1572 +0,0 @@ -//! Data-plane routes: read/query/change/ingest/branches/snapshot/export. -//! Moved verbatim from tests/server.rs in the modularization. - -use std::fs; -use std::sync::Arc; - -use axum::body::{Body, to_bytes}; -use axum::http::{Method, Request, StatusCode}; -use omnigraph::db::{Omnigraph, ReadTarget}; -use omnigraph::loader::LoadMode; -use omnigraph_server::api::{ - BranchCreateRequest, BranchMergeRequest, ChangeRequest, ErrorOutput, ExportRequest, - IngestRequest, QueryRequest, ReadRequest, -}; -use omnigraph_server::{AppState, build_app}; -use serde_json::{Value, json}; -use serial_test::serial; -use tower::ServiceExt; - - -mod support; -use support::*; - -#[tokio::test(flavor = "multi_thread")] -async fn export_route_returns_jsonl_for_branch_snapshot() { - let token = "demo-token"; - let temp = init_loaded_graph().await; - let graph = graph_path(temp.path()); - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.branch_create_from(ReadTarget::branch("main"), "feature") - .await - .unwrap(); - db.load( - "feature", - r#"{"type":"Person","data":{"name":"Eve","age":29}}"#, - LoadMode::Append, - ) - .await - .unwrap(); - let expected = db - .export_jsonl("feature", &["Person".to_string()], &[]) - .await - .unwrap(); - drop(db); - - // MR-723: tokens-without-policy is now default-deny. Install a - // permit-all policy alongside the bearer token so /export - // (action=Export) passes Cedar evaluation. The test is exercising - // export semantics, not policy β€” the policy is just enough to clear - // the State 3 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( - graph.to_string_lossy().to_string(), - vec![("default".to_string(), token.to_string())], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - - let response = app - .clone() - .oneshot( - Request::builder() - .uri("/export") - .method(Method::POST) - .header("content-type", "application/json") - .header("authorization", format!("Bearer {}", token)) - .body(Body::from( - serde_json::to_vec(&ExportRequest { - branch: Some("feature".to_string()), - type_names: vec!["Person".to_string()], - table_keys: Vec::new(), - }) - .unwrap(), - )) - .unwrap(), - ) - .await - .unwrap(); - - assert_eq!(response.status(), StatusCode::OK); - assert_eq!( - response.headers().get("content-type").unwrap(), - "application/x-ndjson; charset=utf-8" - ); - let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - let text = String::from_utf8(body.to_vec()).unwrap(); - assert_eq!(text, expected); -} - -#[tokio::test(flavor = "multi_thread")] -async fn snapshot_route_returns_manifest_dataset_version() { - 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, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - - assert_eq!(snapshot_status, StatusCode::OK); - assert_eq!(snapshot_body["branch"], "main"); - assert_eq!( - snapshot_body["manifest_version"].as_u64().unwrap(), - expected_manifest_version - ); - assert!(snapshot_body["tables"].is_array()); -} - -#[tokio::test(flavor = "multi_thread")] -async fn ingest_creates_branch_returns_metadata_and_stamps_actor() { - 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()), - mode: Some(LoadMode::Merge), - data: r#"{"type":"Person","data":{"name":"Zoe","age":33}} -{"type":"Person","data":{"name":"Bob","age":26}}"# - .to_string(), - }; - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/ingest") - .method(Method::POST) - .header("authorization", "Bearer token-one") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&ingest).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - assert_eq!(body["branch"], "feature-ingest"); - assert_eq!(body["base_branch"], "main"); - assert_eq!(body["branch_created"], true); - assert_eq!(body["mode"], "merge"); - assert_eq!(body["actor_id"], "act-andrew"); - assert_eq!(body["tables"][0]["table_key"], "node:Person"); - assert_eq!(body["tables"][0]["rows_loaded"], 2); - - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - let snapshot = db - .snapshot_of(ReadTarget::branch("feature-ingest")) - .await - .unwrap(); - let person_ds = snapshot.open("node:Person").await.unwrap(); - assert_eq!(person_ds.count_rows(None).await.unwrap(), 5); - let head = db - .list_commits(Some("feature-ingest")) - .await - .unwrap() - .into_iter() - .last() - .unwrap(); - assert_eq!(head.actor_id.as_deref(), Some("act-andrew")); -} - -#[tokio::test(flavor = "multi_thread")] -async fn ingest_existing_branch_skips_branch_create_policy_check() { - let temp = init_loaded_graph().await; - let graph = graph_path(temp.path()); - { - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.branch_create_from(ReadTarget::branch("main"), "feature") - .await - .unwrap(); - } - let policy_path = temp.path().join("policy.yaml"); - fs::write(&policy_path, POLICY_YAML).unwrap(); - let state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - vec![("act-bruno".to_string(), "team-token".to_string())], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - let ingest = IngestRequest { - branch: Some("feature".to_string()), - from: Some("other-base".to_string()), - mode: Some(LoadMode::Merge), - data: r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#.to_string(), - }; - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/ingest") - .method(Method::POST) - .header("authorization", "Bearer team-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&ingest).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - assert_eq!(body["branch"], "feature"); - assert_eq!(body["branch_created"], false); - assert_eq!(body["base_branch"], "other-base"); -} - -#[tokio::test(flavor = "multi_thread")] -async fn ingest_without_from_returns_404_for_missing_branch_and_creates_nothing() { - let (temp, app) = app_for_loaded_graph().await; - let graph = graph_path(temp.path()); - let ingest = IngestRequest { - branch: Some("feature-typo".to_string()), - from: None, - mode: Some(LoadMode::Merge), - data: r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#.to_string(), - }; - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/ingest") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&ingest).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::NOT_FOUND); - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert_eq!(error.code, Some(omnigraph_server::api::ErrorCode::NotFound)); - - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - assert!( - !db.branch_list() - .await - .unwrap() - .contains(&"feature-typo".to_string()), - "a 404'd ingest must not create the branch" - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn ingest_without_from_loads_into_existing_branch() { - let (temp, app) = app_for_loaded_graph().await; - let graph = graph_path(temp.path()); - { - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.branch_create_from(ReadTarget::branch("main"), "feature") - .await - .unwrap(); - } - let ingest = IngestRequest { - branch: Some("feature".to_string()), - from: None, - mode: Some(LoadMode::Merge), - data: r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#.to_string(), - }; - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/ingest") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&ingest).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - assert_eq!(body["branch"], "feature"); - assert_eq!(body["branch_created"], false); - assert_eq!(body["base_branch"], serde_json::Value::Null); -} - -#[tokio::test(flavor = "multi_thread")] -async fn ingest_denies_missing_branch_without_branch_create_permission() { - let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( - &[("act-bruno", "team-token")], - POLICY_YAML, - ) - .await; - let ingest = IngestRequest { - branch: Some("feature".to_string()), - from: Some("main".to_string()), - mode: Some(LoadMode::Merge), - data: r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#.to_string(), - }; - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/ingest") - .method(Method::POST) - .header("authorization", "Bearer team-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&ingest).unwrap())) - .unwrap(), - ) - .await; - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert_eq!(status, StatusCode::FORBIDDEN); - assert_eq!( - error.code, - Some(omnigraph_server::api::ErrorCode::Forbidden) - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn ingest_denies_when_actor_lacks_change_permission() { - let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( - &[("act-bruno", "team-token")], - INGEST_CREATE_ONLY_POLICY_YAML, - ) - .await; - let ingest = IngestRequest { - branch: Some("feature".to_string()), - from: Some("main".to_string()), - mode: Some(LoadMode::Merge), - data: r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#.to_string(), - }; - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/ingest") - .method(Method::POST) - .header("authorization", "Bearer team-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&ingest).unwrap())) - .unwrap(), - ) - .await; - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert_eq!(status, StatusCode::FORBIDDEN); - assert_eq!( - error.code, - Some(omnigraph_server::api::ErrorCode::Forbidden) - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn ingest_rejects_payloads_over_32_mib() { - let (_temp, app) = app_for_loaded_graph().await; - let oversize = IngestRequest { - branch: Some("feature".to_string()), - from: Some("main".to_string()), - mode: Some(LoadMode::Merge), - data: "x".repeat(33 * 1024 * 1024), - }; - - let response = app - .clone() - .oneshot( - Request::builder() - .uri("/ingest") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&oversize).unwrap())) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); -} - -#[tokio::test(flavor = "multi_thread")] -async fn branch_merge_conflict_response_includes_structured_conflicts() { - let temp = init_loaded_graph().await; - let graph = graph_path(temp.path()); - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.branch_create_from(ReadTarget::branch("main"), "feature") - .await - .unwrap(); - db.mutate( - "main", - MUTATION_QUERIES, - "set_age", - &omnigraph_compiler::json_params_to_param_map( - Some(&json!({"name": "Alice", "age": 31 })), - &omnigraph_compiler::find_named_query(MUTATION_QUERIES, "set_age") - .unwrap() - .params, - omnigraph_compiler::JsonParamMode::Standard, - ) - .unwrap(), - ) - .await - .unwrap(); - db.mutate( - "feature", - MUTATION_QUERIES, - "set_age", - &omnigraph_compiler::json_params_to_param_map( - Some(&json!({"name": "Alice", "age": 32 })), - &omnigraph_compiler::find_named_query(MUTATION_QUERIES, "set_age") - .unwrap() - .params, - omnigraph_compiler::JsonParamMode::Standard, - ) - .unwrap(), - ) - .await - .unwrap(); - drop(db); - - let state = AppState::open(graph.to_string_lossy().to_string()) - .await - .unwrap(); - let app = build_app(state); - let merge = BranchMergeRequest { - source: "feature".to_string(), - target: Some("main".to_string()), - }; - let (status, body) = json_response( - &app, - Request::builder() - .uri("/branches/merge") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&merge).unwrap())) - .unwrap(), - ) - .await; - - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert_eq!(status, StatusCode::CONFLICT); - assert_eq!(error.code, Some(omnigraph_server::api::ErrorCode::Conflict)); - assert!(error.error.contains("merge conflict")); - assert!(error.merge_conflicts.iter().any(|conflict| { - conflict.table_key == "node:Person" - && conflict.row_id.as_deref() == Some("Alice") - && conflict.kind == omnigraph_server::api::MergeConflictKindOutput::DivergentUpdate - })); -} - -#[tokio::test(flavor = "multi_thread")] -async fn repeated_read_after_change_sees_updated_state_from_same_app() { - let (_temp, app) = app_for_loaded_graph().await; - - let change = ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "Mina", "age": 28 })), - branch: Some("main".to_string()), - }; - let (change_status, change_body) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&change).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(change_status, StatusCode::OK); - assert_eq!(change_body["affected_nodes"], 1); - - let read = ReadRequest { - query_source: fs::read_to_string(fixture("test.gq")).unwrap(), - query_name: Some("get_person".to_string()), - params: Some(json!({ "name": "Mina" })), - branch: Some("main".to_string()), - snapshot: None, - }; - let (read_status, read_body) = json_response( - &app, - Request::builder() - .uri("/read") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&read).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(read_status, StatusCode::OK); - assert_eq!(read_body["row_count"], 1); - 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_graph().await; - - let (list_status, list_body) = json_response( - &app, - Request::builder() - .uri("/branches") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(list_status, StatusCode::OK); - assert_eq!(list_body["branches"], json!(["main"])); - - let create = BranchCreateRequest { - from: Some("main".to_string()), - name: "feature".to_string(), - }; - let (create_status, create_body) = json_response( - &app, - Request::builder() - .uri("/branches") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&create).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(create_status, StatusCode::OK); - assert_eq!(create_body["from"], "main"); - assert_eq!(create_body["name"], "feature"); - - let (list_status, list_body) = json_response( - &app, - Request::builder() - .uri("/branches") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(list_status, StatusCode::OK); - assert_eq!(list_body["branches"], json!(["feature", "main"])); - - let change = ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "Zoe", "age": 33 })), - branch: Some("feature".to_string()), - }; - let (change_status, change_body) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&change).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(change_status, StatusCode::OK); - assert_eq!(change_body["branch"], "feature"); - assert_eq!(change_body["affected_nodes"], 1); - - let read_main_before = ReadRequest { - query_source: fs::read_to_string(fixture("test.gq")).unwrap(), - query_name: Some("get_person".to_string()), - params: Some(json!({ "name": "Zoe" })), - branch: Some("main".to_string()), - snapshot: None, - }; - let (read_status, read_body) = json_response( - &app, - Request::builder() - .uri("/read") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&read_main_before).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(read_status, StatusCode::OK); - assert_eq!(read_body["row_count"], 0); - - let merge = BranchMergeRequest { - source: "feature".to_string(), - target: Some("main".to_string()), - }; - let (merge_status, merge_body) = json_response( - &app, - Request::builder() - .uri("/branches/merge") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&merge).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(merge_status, StatusCode::OK); - assert_eq!(merge_body["source"], "feature"); - assert_eq!(merge_body["target"], "main"); - assert_eq!(merge_body["outcome"], "fast_forward"); - - let read_main_after = ReadRequest { - query_source: fs::read_to_string(fixture("test.gq")).unwrap(), - query_name: Some("get_person".to_string()), - params: Some(json!({ "name": "Zoe" })), - branch: Some("main".to_string()), - snapshot: None, - }; - let (read_status, read_body) = json_response( - &app, - Request::builder() - .uri("/read") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&read_main_after).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(read_status, StatusCode::OK); - assert_eq!(read_body["row_count"], 1); - assert_eq!(read_body["rows"][0]["p.name"], "Zoe"); -} - -#[tokio::test(flavor = "multi_thread")] -async fn remote_branch_delete_flow_works() { - let (_temp, app) = app_for_loaded_graph().await; - - let create = BranchCreateRequest { - from: Some("main".to_string()), - name: "feature".to_string(), - }; - let (create_status, _) = json_response( - &app, - Request::builder() - .uri("/branches") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&create).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(create_status, StatusCode::OK); - - let (delete_status, delete_body) = json_response( - &app, - Request::builder() - .uri("/branches/feature") - .method(Method::DELETE) - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(delete_status, StatusCode::OK); - assert_eq!(delete_body["name"], "feature"); - - let (list_status, list_body) = json_response( - &app, - Request::builder() - .uri("/branches") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(list_status, StatusCode::OK); - assert_eq!(list_body["branches"], json!(["main"])); -} - -#[tokio::test(flavor = "multi_thread")] -async fn branch_delete_denies_without_policy_permission() { - let (temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( - &[("act-andrew", "token-admin"), ("act-bruno", "token-team")], - POLICY_YAML, - ) - .await; - let graph = graph_path(temp.path()); - - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.branch_create_from(ReadTarget::branch("main"), "feature") - .await - .unwrap(); - drop(db); - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/branches/feature") - .method(Method::DELETE) - .header("authorization", "Bearer token-team") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::FORBIDDEN); - assert!( - body["error"] - .as_str() - .unwrap() - .contains("policy denied action 'branch_delete'") - ); -} - -#[tokio::test(flavor = "multi_thread")] -#[serial] -async fn remote_read_embeds_string_nearest_queries_with_mock_runtime() { - const EMBED_SCHEMA: &str = r#" -node Doc { - slug: String @key - title: String @index - embedding: Vector(4) @index -} -"#; - const EMBED_QUERY: &str = r#" -query vector_search_string($q: String) { - match { $d: Doc } - return { $d.slug, $d.title } - order { nearest($d.embedding, $q) } - limit 3 -} -"#; - - let alpha = mock_embedding("alpha", 4); - let beta = mock_embedding("beta", 4); - let gamma = mock_embedding("gamma", 4); - let data = format!( - concat!( - r#"{{"type":"Doc","data":{{"slug":"alpha-doc","title":"alpha guide","embedding":[{}]}}}}"#, - "\n", - r#"{{"type":"Doc","data":{{"slug":"beta-doc","title":"beta guide","embedding":[{}]}}}}"#, - "\n", - r#"{{"type":"Doc","data":{{"slug":"gamma-doc","title":"gamma handbook","embedding":[{}]}}}}"# - ), - format_vector(&alpha), - format_vector(&beta), - format_vector(&gamma), - ); - - let _guard = EnvGuard::set(&[ - ("OMNIGRAPH_EMBEDDINGS_MOCK", Some("1")), - ("GEMINI_API_KEY", None), - ]); - 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); - - let read = ReadRequest { - query_source: EMBED_QUERY.to_string(), - query_name: Some("vector_search_string".to_string()), - params: Some(json!({ "q": "alpha" })), - branch: Some("main".to_string()), - snapshot: None, - }; - let (status, body) = json_response( - &app, - Request::builder() - .uri("/read") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&read).unwrap())) - .unwrap(), - ) - .await; - - assert_eq!(status, StatusCode::OK); - assert_eq!(body["row_count"], 3); - assert_eq!(body["rows"][0]["d.slug"], "alpha-doc"); -} - -#[tokio::test(flavor = "multi_thread")] -async fn change_conflict_returns_manifest_conflict_409() { - // A write that races with another writer surfaces as HTTP 409 with - // a structured `manifest_conflict` body β€” `table_key`, `expected`, - // and `actual` β€” so clients can detect-and-retry without parsing - // the message. - 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(graph.to_string_lossy().to_string()) - .await - .unwrap(); - let app = build_app(state); - - { - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.mutate( - "main", - MUTATION_QUERIES, - "set_age", - &omnigraph_compiler::json_params_to_param_map( - Some(&json!({"name": "Alice", "age": 31 })), - &omnigraph_compiler::find_named_query(MUTATION_QUERIES, "set_age") - .unwrap() - .params, - omnigraph_compiler::JsonParamMode::Standard, - ) - .unwrap(), - ) - .await - .unwrap(); - } - - 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(&ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("set_age".to_string()), - params: Some(json!({ "name": "Alice", "age": 33 })), - branch: Some("main".to_string()), - }) - .unwrap(), - )) - .unwrap(), - ) - .await; - - assert_eq!(status, StatusCode::CONFLICT); - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert_eq!(error.code, Some(omnigraph_server::api::ErrorCode::Conflict)); - let conflict = error - .manifest_conflict - .expect("publisher CAS rejection must populate manifest_conflict body"); - assert_eq!(conflict.table_key, "node:Person"); - assert!( - conflict.actual > conflict.expected, - "actual ({}) should be ahead of expected ({})", - conflict.actual, - conflict.expected, - ); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn change_concurrent_inserts_same_key_serialize_without_409() { - // PR 2 Phase 2 (MR-686): pin the design fix for the same-key - // concurrency hazard. Pre-fix, in-process concurrent inserts on - // the same `(table, branch)` rejected with 409 manifest_conflict - // because `ensure_expected_version` fired before the per-table - // queue was acquired and saw Lance HEAD already advanced by a - // peer writer. Post-fix, Insert/Merge skip the strict pre-stage - // check (see `MutationOpKind::strict_pre_stage_version_check`); - // the queue serializes commit_staged; Lance's natural rebase - // handles the in-flight stage; the publisher's CAS on a fresh - // per-branch snapshot under the queue catches genuine cross- - // process drift. - // - // This test spawns N concurrent /change inserts on a single - // 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_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); - - // test.jsonl seeds 4 Persons (Alice, Bob, Charlie, Diana). - const SEED_PERSON_ROWS: u64 = 4; - const N: usize = 12; - - let mut handles = Vec::with_capacity(N); - for i in 0..N { - let app = app.clone(); - handles.push(tokio::spawn(async move { - let body = serde_json::to_vec(&ChangeRequest { - 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()), - }) - .unwrap(); - let req = Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(); - let response = app.oneshot(req).await.unwrap(); - response.status() - })); - } - - let mut statuses = Vec::with_capacity(N); - for h in handles { - statuses.push(h.await.unwrap()); - } - - let bad: Vec<_> = statuses - .iter() - .enumerate() - .filter(|(_, s)| **s != StatusCode::OK) - .collect(); - assert!( - bad.is_empty(), - "expected every concurrent insert to return 200, got non-200 for: {:?}", - bad - ); - - // Verify the inserts actually landed. The status check above only proves - // the publisher CAS didn't reject; the row count proves none of the - // concurrent commits silently overwrote a peer. - let (snapshot_status, snapshot_body) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(snapshot_status, StatusCode::OK); - let person_rows = snapshot_body["tables"] - .as_array() - .and_then(|tables| { - tables - .iter() - .find(|t| t["table_key"].as_str() == Some("node:Person")) - }) - .and_then(|t| t["row_count"].as_u64()) - .expect("snapshot must include node:Person row_count"); - assert_eq!( - person_rows, - SEED_PERSON_ROWS + N as u64, - "expected {} seeded + {} concurrent inserts = {} Person rows; got {}", - SEED_PERSON_ROWS, - N, - SEED_PERSON_ROWS + N as u64, - person_rows, - ); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn change_concurrent_updates_same_key_serialize_via_publisher_cas() { - // Pin Update RYW semantics under in-process concurrency on the same - // `(table, branch)`. With per-table queue serialization and op-kind-aware - // drift detection at commit time, exactly one of N concurrent UPDATEs - // on the same row commits; the rest are rejected as 409 manifest_conflict. - // - // Pre-fix bug class: in `MutationStaging::commit_all`, after queue - // acquisition, the staged Lance transaction is handed straight to - // `commit_staged`. For a writer whose staged dataset is at V0 but - // Lance HEAD has advanced to V1 (because the queue's prior winner - // already published), Lance's transaction conflict resolver fires - // `RetryableCommitConflict` on Update vs Update on the same row. - // That error gets wrapped as `OmniError::Lance()` and the - // API surfaces it as **500 internal**, not 409. Users see "internal - // server error" instead of a retryable conflict, breaking the - // documented 409 contract for in-process drift. - // - // Post-fix invariant: `commit_all` does an op-kind-aware drift check - // before each `commit_staged`. For tables whose tracked op_kind has - // `strict_pre_stage_version_check() == true` (Update / Delete / - // SchemaRewrite), if the staged dataset's version doesn't match the - // fresh manifest pin, return `OmniError::manifest_expected_version_mismatch` - // β†’ 409 ExpectedVersionMismatch. The N-1 losers see a clean 409 - // before Lance's commit_staged ever runs. - // - // Why correct-by-design: closing the class "Lance internal conflict - // surfaces as 500 instead of 409" rather than mapping the specific - // 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_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); - - // Spawn N=8 concurrent UPDATEs on Alice (from test.jsonl, age=30 at V0) - // writing distinct ages. - const N: usize = 8; - let mut handles = Vec::with_capacity(N); - for i in 0..N { - let app = app.clone(); - let target_age = 100 + i as i32; - handles.push(tokio::spawn(async move { - let body = serde_json::to_vec(&ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("set_age".to_string()), - params: Some(json!({ "name": "Alice", "age": target_age })), - branch: Some("main".to_string()), - }) - .unwrap(); - let req = Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(); - let response = app.oneshot(req).await.unwrap(); - let status = response.status(); - let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - (status, body.to_vec()) - })); - } - - let mut results = Vec::with_capacity(N); - for h in handles { - results.push(h.await.unwrap()); - } - let statuses: Vec = results.iter().map(|(s, _)| *s).collect(); - - let ok_count = statuses.iter().filter(|s| **s == StatusCode::OK).count(); - let conflict_count = statuses - .iter() - .filter(|s| **s == StatusCode::CONFLICT) - .count(); - let other: Vec<_> = statuses - .iter() - .enumerate() - .filter(|(_, s)| **s != StatusCode::OK && **s != StatusCode::CONFLICT) - .collect(); - - let other_bodies: Vec<(usize, StatusCode, String)> = other - .iter() - .map(|(i, s)| { - let body_str = String::from_utf8_lossy(&results[*i].1).to_string(); - (*i, **s, body_str) - }) - .collect(); - assert!( - other.is_empty(), - "expected only 200 or 409 statuses, got non-200/409 entries: {:?}", - other_bodies - ); - assert_eq!( - ok_count + conflict_count, - N, - "all responses must be 200 or 409 to satisfy the RYW invariant; statuses: {:?}", - statuses - ); - assert_eq!( - 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. \ - Pre-fix symptom: 1 OK + (N-1) x 500 because Lance's RetryableCommitConflict for \ - Update vs Update on the same row bubbles up as `OmniError::Lance()` and \ - the API maps it to 500 internal, not 409. Statuses: {:?}", - ok_count, - conflict_count, - statuses.len() - ok_count - conflict_count, - statuses, - ); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn change_disjoint_table_concurrency_succeeds_at_http_level() { - // HTTP-level pin for MR-686's disjoint-table promise: concurrent /change - // requests touching different node types must coexist without admission - // rejection or publisher-CAS conflict. The bench harness measures - // throughput; this test is the regression sentinel that catches a - // future change which accidentally re-introduces graph-wide - // serialization on the disjoint path. - // - // Setup: test.jsonl seeds 4 Persons + 2 Companies. Spawn N=4 concurrent - // /change inserts on `node:Person` and N=4 concurrent inserts on - // `node:Company`. All 8 must return 200, and the post-test row counts - // must reflect every insert. - const PERSON_QUERY: &str = r#" -query insert_p($name: String, $age: I32) { - insert Person { name: $name, age: $age } -} -"#; - const COMPANY_QUERY: &str = r#" -query insert_c($name: String) { - insert Company { name: $name } -} -"#; - const SEED_PERSONS: u64 = 4; - const SEED_COMPANIES: u64 = 2; - const PER_TYPE: usize = 4; - - 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 mut handles = Vec::with_capacity(PER_TYPE * 2); - for i in 0..PER_TYPE { - let app_p = app.clone(); - handles.push(tokio::spawn(async move { - let body = serde_json::to_vec(&ChangeRequest { - 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()), - }) - .unwrap(); - let req = Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(); - app_p.oneshot(req).await.unwrap().status() - })); - let app_c = app.clone(); - handles.push(tokio::spawn(async move { - let body = serde_json::to_vec(&ChangeRequest { - query: COMPANY_QUERY.to_string(), - name: Some("insert_c".to_string()), - params: Some(json!({ "name": format!("c-{i}") })), - branch: Some("main".to_string()), - }) - .unwrap(); - let req = Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(); - app_c.oneshot(req).await.unwrap().status() - })); - } - - let mut statuses = Vec::with_capacity(PER_TYPE * 2); - for h in handles { - statuses.push(h.await.unwrap()); - } - - let bad: Vec<_> = statuses - .iter() - .enumerate() - .filter(|(_, s)| **s != StatusCode::OK) - .collect(); - assert!( - bad.is_empty(), - "expected every disjoint /change insert to return 200, got non-200 for: {:?}", - bad, - ); - - // Verify both tables landed every insert. - let (status, body) = json_response( - &app, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - 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(|t| t["row_count"].as_u64()) - .unwrap_or_else(|| panic!("snapshot missing {}", table_key)) - }; - assert_eq!( - lookup_count("node:Person"), - SEED_PERSONS + PER_TYPE as u64, - "Person row count after concurrent inserts", - ); - assert_eq!( - lookup_count("node:Company"), - SEED_COMPANIES + PER_TYPE as u64, - "Company row count after concurrent inserts", - ); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn ingest_per_actor_admission_cap_returns_429() { - // Pin the admission gate on `/ingest`. With per-actor in-flight cap of 1 - // and 8 concurrent requests from the same actor, at least one request - // must be rejected with HTTP 429 and `code: too_many_requests`. - // - // Pre-fix bug class: the admission pattern at `server_change` - // (`crates/omnigraph-server/src/lib.rs:932`) was the only handler - // that called `WorkloadController::try_admit`. A heavy actor sending - // bulk-ingest traffic would exhaust shared engine capacity (Lance I/O - // threads, manifest churn) without ever hitting an admission cap. - // Pinned at the HTTP boundary so future refactors that drop the - // try_admit call from a mutating handler turn this red. - // - // Post-fix invariant: `/ingest`, `/branches/create`, `/branches/delete`, - // `/branches/merge`, and `/schema/apply` all gate on - // `state.workload.try_admit(&actor_arc, est_bytes)` after Cedar - // authorization and before the engine call. Cap exhaustion surfaces as - // 429 with `code: too_many_requests`. - // - // Construct the WorkloadController directly with cap=1 instead of - // mutating `OMNIGRAPH_PER_ACTOR_INFLIGHT_MAX` via EnvGuard. Process-wide - // env vars are visible to concurrently-running tests; the previous - // `EnvGuard + #[serial]` pair leaked the override into any other test - // that called `AppState::open` during the guard's window - // (matrix CI failure on commit 99b0941). Using the explicit - // `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_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 - ); - // MR-723: install a permit-all policy alongside the bearer token so - // /ingest (action=Change) passes Cedar evaluation. The test is - // exercising the admission cap, not policy β€” the policy is just - // 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_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, - ); - let app = build_app(state); - let _temp = temp; - - // Eight concurrent ingests, all from act-flooder. Only one fits in a - // cap=1 in-flight semaphore; the others must 429. - const N: usize = 8; - let barrier = Arc::new(tokio::sync::Barrier::new(N)); - let mut handles = Vec::with_capacity(N); - for i in 0..N { - let app = app.clone(); - let barrier = Arc::clone(&barrier); - handles.push(tokio::spawn(async move { - // Align the 8 tasks at the barrier so they all attempt - // try_admit close in time. - barrier.wait().await; - - let body = serde_json::to_vec(&IngestRequest { - data: format!( - "{{\"type\":\"Person\",\"data\":{{\"name\":\"flooder-{i}\",\"age\":{i}}}}}\n" - ), - branch: Some("main".to_string()), - from: Some("main".to_string()), - mode: Some(omnigraph::loader::LoadMode::Merge), - }) - .unwrap(); - let req = Request::builder() - .uri("/ingest") - .method(Method::POST) - .header("authorization", "Bearer flooder-token") - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(); - let response = app.oneshot(req).await.unwrap(); - let status = response.status(); - let headers = response.headers().clone(); - let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - (status, headers, body.to_vec()) - })); - } - - let mut results = Vec::with_capacity(N); - for h in handles { - results.push(h.await.unwrap()); - } - let statuses: Vec = results.iter().map(|(s, _, _)| *s).collect(); - - let too_many: Vec = statuses - .iter() - .enumerate() - .filter(|(_, s)| **s == StatusCode::TOO_MANY_REQUESTS) - .map(|(i, _)| i) - .collect(); - assert!( - !too_many.is_empty(), - "expected at least one /ingest under cap=1 to return 429; got statuses: {:?}", - statuses, - ); - - // Validate the structured error body for each 429 (body must carry - // the `too_many_requests` code so clients can distinguish it from - // generic conflicts). - for i in &too_many { - let body_value: Value = serde_json::from_slice(&results[*i].2).unwrap(); - let error: ErrorOutput = serde_json::from_value(body_value).unwrap(); - assert_eq!( - error.code, - Some(omnigraph_server::api::ErrorCode::TooManyRequests), - "429 body must carry code=too_many_requests; idx {} got {:?}", - i, - error.code, - ); - } - - // Validate the `Retry-After` header is set on every 429. Pinned by - // the same test so a future refactor that drops the header from - // `IntoResponse for ApiError` turns this red. The constant - // matches `crates/omnigraph-server/src/lib.rs::ApiError::into_response`. - for i in &too_many { - let retry_after = results[*i] - .1 - .get(axum::http::header::RETRY_AFTER) - .and_then(|v| v.to_str().ok()) - .map(str::to_string); - assert!( - retry_after.is_some(), - "429 response must include a Retry-After header; idx {} headers were: {:?}", - i, - results[*i].1, - ); - } -} diff --git a/crates/omnigraph-server/tests/multi_graph.rs b/crates/omnigraph-server/tests/multi_graph.rs deleted file mode 100644 index 5ad847f..0000000 --- a/crates/omnigraph-server/tests/multi_graph.rs +++ /dev/null @@ -1,584 +0,0 @@ -//! Cluster-mode boot and the concurrent branch-ops matrix. -//! Moved verbatim from tests/server.rs in the modularization. - -use std::fs; - -use axum::body::{Body, to_bytes}; -use axum::http::{Method, Request, StatusCode}; -use omnigraph_server::api::ErrorOutput; -use omnigraph_server::{AppState, build_app}; -use serde_json::Value; -use tower::ServiceExt; - - -mod support; -use support::*; - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn concurrent_branch_ops_morphological_matrix() { - // Cell a: Merge Γ— Merge, distinct targets. - // Pre-fix on b09a097/22d76db: branch_merge_impl's swap-restore race - // landed feature_a's content in target_b instead of target_a (and - // vice versa β€” symmetric swap). Identity asserts catch both - // asymmetric and symmetric variants. - { - let cell = "a:mergeΓ—merge:distinct-targets"; - let h = matrix::Harness::new().await; - h.create_branch("main", "feature-a-cella").await; - h.insert_person("feature-a-cella", "EveA-cella", 22).await; - h.create_branch("main", "feature-b-cella").await; - h.insert_person("feature-b-cella", "FrankB-cella", 33).await; - h.create_branch("main", "target-a-cella").await; - h.create_branch("main", "target-b-cella").await; - - 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()), - ) - .await; - assert_eq!(sa.status, StatusCode::OK, "[{}] merge a", cell); - assert_eq!(sb.status, StatusCode::OK, "[{}] merge b", cell); - h.assert_persons("target-a-cella", cell, &["EveA-cella"], &["FrankB-cella"]) - .await; - h.assert_persons("target-b-cella", cell, &["FrankB-cella"], &["EveA-cella"]) - .await; - h.assert_post_op_sentinel(cell, "sentinel-cella").await; - } - - // Cell b: Merge Γ— Merge, same target / distinct sources. - // Both want to land in main. merge_exclusive serializes; both should - // succeed and main should contain BOTH sources' contributions. - { - let cell = "b:mergeΓ—merge:same-target-distinct-sources"; - let h = matrix::Harness::new().await; - h.create_branch("main", "src-x-cellb").await; - h.insert_person("src-x-cellb", "Xavier-cellb", 41).await; - h.create_branch("main", "src-y-cellb").await; - h.insert_person("src-y-cellb", "Yvonne-cellb", 42).await; - - let (sa, sb) = h - .run_pair( - matrix::op_merge("src-x-cellb".to_string(), "main".to_string()), - matrix::op_merge("src-y-cellb".to_string(), "main".to_string()), - ) - .await; - assert_eq!(sa.status, StatusCode::OK, "[{}] merge x", cell); - assert_eq!(sb.status, StatusCode::OK, "[{}] merge y", cell); - h.assert_persons("main", cell, &["Xavier-cellb", "Yvonne-cellb"], &[]) - .await; - h.assert_post_op_sentinel(cell, "sentinel-cellb").await; - } - - // Cell c: Merge Γ— Merge, same source / distinct targets (fanout). - // One source merged into two targets simultaneously. merge_exclusive - // serializes; both targets should reflect the source's content. - { - 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.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()), - ) - .await; - assert_eq!(sa.status, StatusCode::OK, "[{}] merge into tgt-1", cell); - assert_eq!(sb.status, StatusCode::OK, "[{}] merge into tgt-2", cell); - h.assert_persons("tgt-1-cellc", cell, &["Sharon-cellc"], &[]) - .await; - h.assert_persons("tgt-2-cellc", cell, &["Sharon-cellc"], &[]) - .await; - h.assert_post_op_sentinel(cell, "sentinel-cellc").await; - } - - // Cell d: Merge Γ— Change, both touching main. C2 permits both - // succeed, or exactly one clean 409 if the merge detects target - // movement after planning but before acquiring the queue. - { - let cell = "d:mergeΓ—change:into-target"; - let h = matrix::Harness::new().await; - h.create_branch("main", "feature-celld").await; - h.insert_person("feature-celld", "EveD-celld", 22).await; - - let (sa, sb) = h - .run_pair( - matrix::op_merge("feature-celld".to_string(), "main".to_string()), - matrix::op_change_insert("main".to_string(), "FrankD-celld".to_string(), 33), - ) - .await; - assert_eq!(sb.status, StatusCode::OK, "[{}] change", cell); - assert!( - sa.status == StatusCode::OK || sa.status == StatusCode::CONFLICT, - "[{}] merge must be 200 or clean 409, got {}", - cell, - sa.status - ); - if sa.status == StatusCode::OK { - h.assert_persons("main", cell, &["EveD-celld", "FrankD-celld"], &[]) - .await; - } else { - let error: ErrorOutput = serde_json::from_slice(&sa.body).unwrap(); - let conflict = error - .manifest_conflict - .expect("merge 409 must include manifest_conflict"); - assert_eq!( - conflict.table_key, "node:Person", - "[{}] conflict table", - cell - ); - h.assert_persons("main", cell, &["FrankD-celld"], &["EveD-celld"]) - .await; - } - h.assert_post_op_sentinel(cell, "sentinel-celld").await; - } - - // Cell e: Merge Γ— BranchCreateFrom-target. Concurrent fork off the - // merge target while the merge runs. Both should succeed; the new - // branch should have a coherent view (either pre- or post-merge, - // both valid). After both, target = main has the merged content. - { - let cell = "e:mergeΓ—branch_create_from:target"; - let h = matrix::Harness::new().await; - h.create_branch("main", "src-celle").await; - h.insert_person("src-celle", "Eve-celle", 22).await; - - let (sa, sb) = h - .run_pair( - matrix::op_merge("src-celle".to_string(), "main".to_string()), - matrix::op_branch_create("main".to_string(), "fork-celle".to_string()), - ) - .await; - assert_eq!(sa.status, StatusCode::OK, "[{}] merge", cell); - assert_eq!(sb.status, StatusCode::OK, "[{}] branch_create_from", cell); - // Main definitely has Eve. - h.assert_persons("main", cell, &["Eve-celle"], &[]).await; - // fork-celle was forked off main at SOME version; main's current - // count is 5 (4 seeded + Eve). fork-celle has either 4 (pre-merge - // snapshot) or 5 (post-merge snapshot); both are valid timings. - let fork_count = h.person_count("fork-celle").await; - assert!( - fork_count == 4 || fork_count == 5, - "[{}] fork-celle row count must be pre- or post-merge view (4 or 5), got {}", - cell, - fork_count - ); - h.assert_post_op_sentinel(cell, "sentinel-celle").await; - } - - // Cell f: BranchCreateFrom Γ— BranchCreateFrom, distinct parents. - // Pre-fix on f925ad1: swap-restore race in branch_create_from_impl - // forked the new branch off the wrong parent. Identity asserts pin - // that fork-from-A inherits A's content, fork-from-B inherits B's. - { - let cell = "f:branch_create_fromΓ—branch_create_from:distinct-parents"; - let h = matrix::Harness::new().await; - h.create_branch("main", "alpha-cellf").await; - h.insert_person("alpha-cellf", "Eve-cellf", 22).await; - h.create_branch("main", "beta-cellf").await; - - 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()), - ) - .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; - // delta forks off beta β†’ must NOT contain Eve. - h.assert_persons("delta-cellf", cell, &[], &["Eve-cellf"]) - .await; - h.assert_post_op_sentinel(cell, "sentinel-cellf").await; - } - - // Cell g: BranchCreateFrom Γ— BranchDelete, unrelated branches. - // Disjoint branches; both should complete cleanly without - // interference. - { - let cell = "g:branch_create_fromΓ—branch_delete:unrelated"; - let h = matrix::Harness::new().await; - h.create_branch("main", "doomed-cellg").await; - - let (sa, sb) = h - .run_pair( - matrix::op_branch_create("main".to_string(), "newborn-cellg".to_string()), - matrix::op_branch_delete("doomed-cellg".to_string()), - ) - .await; - 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_post_op_sentinel(cell, "sentinel-cellg").await; - } - - // Cell h: BranchDelete Γ— BranchDelete, distinct branches. Both call - // refresh() internally; verify no deadlock and both deletes land. - { - let cell = "h:branch_deleteΓ—branch_delete:distinct"; - let h = matrix::Harness::new().await; - h.create_branch("main", "doomed1-cellh").await; - h.create_branch("main", "doomed2-cellh").await; - - let (sa, sb) = h - .run_pair( - matrix::op_branch_delete("doomed1-cellh".to_string()), - matrix::op_branch_delete("doomed2-cellh".to_string()), - ) - .await; - assert_eq!(sa.status, StatusCode::OK, "[{}] delete 1", cell); - assert_eq!(sb.status, StatusCode::OK, "[{}] delete 2", cell); - // Verify both gone via /branches list (snapshot would still work - // for a deleted branch via parent fallback in some paths, so we - // use the explicit list). - let r = h - .app - .clone() - .oneshot( - Request::builder() - .uri("/branches") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(r.status(), StatusCode::OK); - let body = to_bytes(r.into_body(), usize::MAX).await.unwrap(); - let list_body: Value = serde_json::from_slice(&body).unwrap(); - let branches: Vec<&str> = list_body["branches"] - .as_array() - .unwrap() - .iter() - .filter_map(|v| v.as_str()) - .collect(); - assert!( - !branches.contains(&"doomed1-cellh"), - "[{}] doomed1 still in branch list: {:?}", - cell, - branches - ); - assert!( - !branches.contains(&"doomed2-cellh"), - "[{}] doomed2 still in branch list: {:?}", - cell, - branches - ); - h.assert_post_op_sentinel(cell, "sentinel-cellh").await; - } - - // Cell i: BranchDelete Γ— Change, on a different branch. Delete one - // branch while a /change runs on main. Both should succeed. - { - let cell = "i:branch_deleteΓ—change:distinct-branch"; - let h = matrix::Harness::new().await; - h.create_branch("main", "doomed-celli").await; - - let (sa, sb) = h - .run_pair( - matrix::op_branch_delete("doomed-celli".to_string()), - matrix::op_change_insert("main".to_string(), "Pat-celli".to_string(), 44), - ) - .await; - assert_eq!(sa.status, StatusCode::OK, "[{}] delete", cell); - assert_eq!(sb.status, StatusCode::OK, "[{}] change", cell); - h.assert_persons("main", cell, &["Pat-celli"], &[]).await; - h.assert_post_op_sentinel(cell, "sentinel-celli").await; - } - - // Cell j: BranchCreateFrom Γ— Change, both on main. The fork timing - // determines whether the new branch sees the change (pre or post). - // Both valid. Main must contain the inserted row. - { - let cell = "j:branch_create_fromΓ—change:on-source"; - let h = matrix::Harness::new().await; - - let (sa, sb) = h - .run_pair( - matrix::op_branch_create("main".to_string(), "twin-cellj".to_string()), - matrix::op_change_insert("main".to_string(), "Quincy-cellj".to_string(), 55), - ) - .await; - assert_eq!(sa.status, StatusCode::OK, "[{}] branch_create", cell); - assert_eq!(sb.status, StatusCode::OK, "[{}] change", cell); - h.assert_persons("main", cell, &["Quincy-cellj"], &[]).await; - // twin-cellj has either pre-change view (no Quincy) or - // post-change view (with Quincy); either is valid. - let twin_has_quincy = h.person_exists("twin-cellj", "Quincy-cellj").await; - let _ = twin_has_quincy; // either valid timing β€” just ensure no panic - h.assert_post_op_sentinel(cell, "sentinel-cellj").await; - } - - // Cell k: reopen consistency. Run a representative concurrent pair, - // drop the engine, reopen on a separate handle, verify state matches. - { - let cell = "k:reopen-after-pair"; - let h = matrix::Harness::new().await; - h.create_branch("main", "src-cellk").await; - h.insert_person("src-cellk", "Rita-cellk", 36).await; - - let (sa, sb) = h - .run_pair( - matrix::op_merge("src-cellk".to_string(), "main".to_string()), - matrix::op_change_insert("main".to_string(), "Steve-cellk".to_string(), 37), - ) - .await; - assert_eq!(sb.status, StatusCode::OK, "[{}] change", cell); - assert!( - sa.status == StatusCode::OK || sa.status == StatusCode::CONFLICT, - "[{}] merge must be 200 or clean 409, got {}", - cell, - sa.status - ); - if sa.status == StatusCode::OK { - h.assert_persons("main", cell, &["Rita-cellk", "Steve-cellk"], &[]) - .await; - } else { - let error: ErrorOutput = serde_json::from_slice(&sa.body).unwrap(); - let conflict = error - .manifest_conflict - .expect("merge 409 must include manifest_conflict"); - 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 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. - let r = app2 - .clone() - .oneshot( - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(r.status(), StatusCode::OK, "[{}] reopen snapshot", cell); - let body = to_bytes(r.into_body(), usize::MAX).await.unwrap(); - let v: Value = serde_json::from_slice(&body).unwrap(); - let person_rows = v["tables"] - .as_array() - .and_then(|tables| { - tables - .iter() - .find(|t| t["table_key"].as_str() == Some("node:Person")) - }) - .and_then(|t| t["row_count"].as_u64()) - .expect("reopen snapshot must include node:Person row_count"); - let expected_rows = if sa.status == StatusCode::OK { 6 } else { 5 }; - assert_eq!( - person_rows, expected_rows, - "[{}] reopened main should include seed (4) + committed concurrent writes", - cell, - ); - } -} - -#[tokio::test] -async fn cluster_boot_serves_applied_state() { - let temp = converged_cluster_dir("").await; - let settings = cluster_settings(temp.path()).await.unwrap(); - let omnigraph_server::ServerConfigMode::Multi { - graphs, - config_path, - server_policy, - } = settings.mode - else { - panic!("cluster boot must select multi-graph routing"); - }; - assert_eq!(graphs.len(), 1); - assert_eq!(graphs[0].graph_id, "knowledge"); - assert!(server_policy.is_none()); - - let state = - omnigraph_server::open_multi_graph_state(graphs, Vec::new(), None, config_path) - .await - .unwrap(); - let app = build_app(state); - - // The management surface keeps its closed-by-default contract: without a - // cluster-scoped policy bundle there is no server-level Cedar engine, so - // GET /graphs refuses even in cluster mode. - let (status, body) = json_response( - &app, - Request::builder().uri("/graphs").body(Body::empty()).unwrap(), - ) - .await; - assert_eq!(status, StatusCode::FORBIDDEN, "{body}"); - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/graphs/knowledge/queries") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK, "{body}"); - assert!( - body["queries"] - .as_array() - .unwrap() - .iter() - .any(|q| q["name"] == "find_person"), - "{body}" - ); - - let (status, body) = json_response( - &app, - Request::builder() - .method(Method::POST) - .uri("/graphs/knowledge/queries/find_person") - .header("content-type", "application/json") - .body(Body::from(r#"{"params":{"name":"nobody"}}"#)) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK, "{body}"); -} - -#[tokio::test] -async fn cluster_boot_wires_policy_bindings_into_cedar_slots() { - let temp = tempfile::tempdir().unwrap(); - drop(temp); - let policy_block = r#"policies: - graph_rules: - file: ./graph.policy.yaml - applies_to: [knowledge] - cluster_rules: - file: ./cluster.policy.yaml - applies_to: [cluster] -"#; - let temp = { - let temp = tempfile::tempdir().unwrap(); - fs::write( - temp.path().join("people.pg"), - "\nnode Person {\n name: String @key\n}\n", - ) - .unwrap(); - fs::write( - temp.path().join("people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n", - ) - .unwrap(); - fs::write( - temp.path().join("graph.policy.yaml"), - permit_all_policy_yaml(&["default"]), - ) - .unwrap(); - fs::write( - temp.path().join("cluster.policy.yaml"), - permit_all_policy_yaml(&["default"]).replace("protected_branches: [main]\n", "protected_branches: [main]\nkind: server\n"), - ) - .unwrap(); - fs::write( - temp.path().join("cluster.yaml"), - format!( - r#" -version: 1 -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -{policy_block}"# - ), - ) - .unwrap(); - let import = omnigraph_cluster::import_config_dir(temp.path()).await; - assert!(import.ok, "{:?}", import.diagnostics); - let apply = omnigraph_cluster::apply_config_dir(temp.path()).await; - assert!(apply.ok && apply.converged, "{:?}", apply.diagnostics); - temp - }; - - let settings = cluster_settings(temp.path()).await.unwrap(); - let omnigraph_server::ServerConfigMode::Multi { - graphs, - server_policy, - .. - } = settings.mode - else { - panic!("cluster boot must select multi-graph routing"); - }; - // Cluster boots carry policy CONTENT (digest-verified catalog blobs), - // not paths β€” the catalog may live on object storage. - let omnigraph_server::PolicySource::Inline(graph_policy) = - graphs[0].policy.as_ref().expect("graph-bound bundle") - else { - panic!("cluster-mode graph policy must be inline content"); - }; - assert!(graph_policy.contains("actors:"), "{graph_policy:?}"); - let omnigraph_server::PolicySource::Inline(server_policy) = - server_policy.expect("cluster-bound bundle") - else { - panic!("cluster-mode server policy must be inline content"); - }; - assert!(server_policy.contains("kind: server"), "{server_policy:?}"); -} - -#[tokio::test] -async fn cluster_boot_refusals() { - // Mutual exclusion with --config / URI. - let temp = converged_cluster_dir("").await; - let dir = temp.path().to_path_buf(); - let err = omnigraph_server::load_server_settings( - Some(&dir.join("omnigraph.yaml")), - Some(&dir), - None, - None, - None, - true, - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("exclusive boot source"), "{err}"); - let err = omnigraph_server::load_server_settings( - None, - Some(&dir), - Some("file:///tmp/x.omni".to_string()), - None, - None, - true, - ) - .await - .unwrap_err(); - assert!(err.to_string().contains("exclusive boot source"), "{err}"); - - // Tampered catalog blob refuses boot with the remedy. - let blob_dir = dir.join("__cluster/resources/query/knowledge/find_person"); - let blob = fs::read_dir(&blob_dir).unwrap().next().unwrap().unwrap().path(); - fs::write(&blob, "tampered").unwrap(); - let err = cluster_settings(&dir).await.unwrap_err(); - assert!( - err.to_string().contains("catalog_payload_digest_mismatch"), - "{err}" - ); - assert!(err.to_string().contains("cluster refresh"), "{err}"); - - // Missing state refuses with the import/apply remedy. - let empty = tempfile::tempdir().unwrap(); - let err = cluster_settings(empty.path()).await.unwrap_err(); - assert!(err.to_string().contains("cluster_state_missing"), "{err}"); -} diff --git a/crates/omnigraph-server/tests/s3.rs b/crates/omnigraph-server/tests/s3.rs deleted file mode 100644 index 2c61125..0000000 --- a/crates/omnigraph-server/tests/s3.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! S3-backed single-graph serving (gated on OMNIGRAPH_S3_TEST_BUCKET). -//! Moved verbatim from tests/server.rs in the modularization. - -use std::fs; - -use axum::body::Body; -use axum::http::{Method, Request, StatusCode}; -use omnigraph::db::Omnigraph; -use omnigraph::loader::{LoadMode, load_jsonl}; -use omnigraph_server::api::ReadRequest; -use omnigraph_server::{AppState, build_app}; -use serde_json::json; - - -mod support; -use support::*; - -#[tokio::test(flavor = "multi_thread")] -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; - }; - - Omnigraph::init(&uri, &fs::read_to_string(fixture("test.pg")).unwrap()) - .await - .unwrap(); - let mut db = Omnigraph::open(&uri).await.unwrap(); - load_jsonl( - &mut db, - &fs::read_to_string(fixture("test.jsonl")).unwrap(), - LoadMode::Overwrite, - ) - .await - .unwrap(); - - let app = build_app( - AppState::open_with_bearer_token(uri.clone(), Some("s3-token".to_string())) - .await - .unwrap(), - ); - - let (snapshot_status, snapshot_body) = json_response( - &app, - Request::builder() - .uri("/snapshot") - .method(Method::GET) - .header("authorization", "Bearer s3-token") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(snapshot_status, StatusCode::OK); - assert!(snapshot_body["tables"].is_array()); - - let read = 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 (read_status, read_body) = json_response( - &app, - Request::builder() - .uri("/read") - .method(Method::POST) - .header("authorization", "Bearer s3-token") - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&read).unwrap())) - .unwrap(), - ) - .await; - assert_eq!(read_status, StatusCode::OK); - assert_eq!(read_body["row_count"], 1); - assert_eq!(read_body["rows"][0]["p.name"], "Alice"); -} - -/// Config-free cluster serving (RFC-006): boot `--cluster s3://bucket/prefix` -/// with NO local files at all β€” the ledger and catalog on the bucket are the -/// whole deployment artifact. The fixture cluster is applied from a temp -/// config dir, which is then dropped before the server boots from the URI. -#[tokio::test(flavor = "multi_thread")] -async fn server_boots_cluster_from_bare_storage_uri_and_serves_query() { - let Some(bucket) = std::env::var("OMNIGRAPH_S3_TEST_BUCKET").ok() else { - eprintln!("skipping s3 cluster-serving test: OMNIGRAPH_S3_TEST_BUCKET is not set"); - return; - }; - let unique = format!( - "{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let root = format!("s3://{bucket}/cluster-serve/{unique}"); - - // Apply a one-graph cluster onto the bucket, seed it, then DROP the - // config dir β€” the boot below must need nothing local. - { - let dir = tempfile::tempdir().unwrap(); - fs::write( - dir.path().join("people.pg"), - "node Person {\n name: String @key\n}\n", - ) - .unwrap(); - fs::write( - dir.path().join("people.gq"), - "query find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n", - ) - .unwrap(); - fs::write( - dir.path().join("cluster.yaml"), - format!( - "version: 1\nstorage: {root}\ngraphs:\n knowledge:\n schema: people.pg\n queries:\n find_person:\n file: people.gq\n" - ), - ) - .unwrap(); - let import = omnigraph_cluster::import_config_dir(dir.path()).await; - assert!(import.ok, "{:?}", import.diagnostics); - let apply = omnigraph_cluster::apply_config_dir(dir.path()).await; - assert!(apply.ok && apply.converged, "{:?}", apply.diagnostics); - - let graph_uri = format!("{root}/graphs/knowledge.omni"); - let mut db = Omnigraph::open(&graph_uri).await.unwrap(); - load_jsonl( - &mut db, - "{\"type\":\"Person\",\"data\":{\"name\":\"Ada\"}}\n", - LoadMode::Overwrite, - ) - .await - .unwrap(); - } - - let settings = omnigraph_server::load_server_settings( - None, - Some(&std::path::PathBuf::from(&root)), - None, - None, - None, - true, - ) - .await - .unwrap(); - let omnigraph_server::ServerConfigMode::Multi { - graphs, - config_path, - server_policy, - } = settings.mode - else { - panic!("cluster boot must select multi-graph routing"); - }; - let state = omnigraph_server::open_multi_graph_state( - graphs, - Vec::new(), - server_policy.as_ref(), - config_path, - ) - .await - .unwrap(); - let app = build_app(state); - - let response = tower::ServiceExt::oneshot( - app, - Request::builder() - .method(Method::POST) - .uri("/graphs/knowledge/queries/find_person") - .header("content-type", "application/json") - .body(Body::from(json!({"params": {"name": "Ada"}}).to_string())) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::OK); - let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); - let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(value["rows"][0]["p.name"], "Ada", "{value}"); -} diff --git a/crates/omnigraph-server/tests/schema_routes.rs b/crates/omnigraph-server/tests/schema_routes.rs deleted file mode 100644 index d250d8a..0000000 --- a/crates/omnigraph-server/tests/schema_routes.rs +++ /dev/null @@ -1,830 +0,0 @@ -//! Schema read/apply routes: migrations over HTTP, drift, gating. -//! Moved verbatim from tests/server.rs in the modularization. - -use std::fs; - -use axum::body::Body; -use axum::http::{Method, Request, StatusCode}; -use lance::index::DatasetIndexExt; -use omnigraph::db::{Omnigraph, ReadTarget}; -use omnigraph::loader::LoadMode; -use omnigraph_server::api::{ - ChangeRequest, ErrorOutput, ReadRequest, SchemaApplyRequest, SchemaOutput, -}; -use omnigraph_server::{AppState, build_app}; -use serde_json::json; - - -mod support; -use support::*; - -#[tokio::test] -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, - ) - .await; - let schema = additive_schema_with_nickname(); - - 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: schema, - ..Default::default() - }) - .unwrap(), - )) - .unwrap(); - let (status, payload) = json_response(&app, request).await; - - assert_eq!(status, StatusCode::OK); - assert_eq!(payload["applied"], true); - let graph = graph_path(temp.path()); - let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - assert!( - reopened.catalog().node_types["Person"] - .properties - .contains_key("nickname") - ); -} - -#[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_graph_with_auth_tokens_and_policy( - &fs::read_to_string(fixture("test.pg")).unwrap(), - &[("act-ragnor", "admin-token")], - 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: additive_schema_with_nickname(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(); - let (status, payload) = json_response(&app, request).await; - - assert_eq!(status, StatusCode::FORBIDDEN); - assert_eq!( - payload["code"], - serde_json::to_value(omnigraph_server::api::ErrorCode::Forbidden).unwrap() - ); -} - -#[tokio::test] -async fn schema_apply_route_requires_bearer_token_when_policy_enabled() { - 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 request = Request::builder() - .method(Method::POST) - .uri("/schema/apply") - .header("content-type", "application/json") - .body(Body::from( - serde_json::to_vec(&SchemaApplyRequest { - schema_source: additive_schema_with_nickname(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(); - let (status, payload) = json_response(&app, request).await; - - assert_eq!(status, StatusCode::UNAUTHORIZED); - assert_eq!( - payload["code"], - serde_json::to_value(omnigraph_server::api::ErrorCode::Unauthorized).unwrap() - ); -} - -#[tokio::test] -async fn schema_apply_route_can_rename_type() { - 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 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_person_schema(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(); - let (status, payload) = json_response(&app, request).await; - - assert_eq!(status, StatusCode::OK); - assert_eq!(payload["applied"], true); - 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 - .unwrap(); - assert!(snapshot.entry("node:Human").is_some()); - assert!(snapshot.entry("node:Person").is_none()); -} - -#[tokio::test] -async fn schema_apply_route_can_rename_property() { - 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 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::OK); - assert_eq!(payload["applied"], true); - 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")); -} - -#[tokio::test] -async fn schema_apply_route_can_add_index() { - 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 graph = graph_path(temp.path()); - let before_index_count = { - 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() - }; - - 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: indexed_name_schema(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(); - let (status, payload) = json_response(&app, request).await; - - assert_eq!(status, StatusCode::OK); - assert_eq!(payload["applied"], true); - let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - let snapshot = reopened - .snapshot_of(ReadTarget::branch("main")) - .await - .unwrap(); - let dataset = snapshot.open("node:Person").await.unwrap(); - let after_index_count = dataset.load_indices().await.unwrap().len(); - assert!(after_index_count > before_index_count); -} - -#[tokio::test] -async fn schema_apply_route_rejects_unsupported_plan() { - 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 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: unsupported_schema_change(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(); - let (status, payload) = json_response(&app, request).await; - - assert_eq!(status, StatusCode::BAD_REQUEST); - assert_eq!( - payload["code"], - serde_json::to_value(omnigraph_server::api::ErrorCode::BadRequest).unwrap() - ); -} - -#[tokio::test] -async fn schema_apply_route_rejects_when_non_main_branch_exists() { - let temp = init_graph_with_schema(&fs::read_to_string(fixture("test.pg")).unwrap()).await; - let graph = graph_path(temp.path()); - let 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( - graph.to_string_lossy().to_string(), - vec![("act-ragnor".to_string(), "admin-token".to_string())], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - - 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: additive_schema_with_nickname(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(); - let (status, payload) = json_response(&app, request).await; - - assert_eq!(status, StatusCode::CONFLICT); - assert_eq!( - payload["code"], - serde_json::to_value(omnigraph_server::api::ErrorCode::Conflict).unwrap() - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_drift_returns_conflict_for_snapshot_read_and_change() { - 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, - Request::builder() - .uri("/snapshot?branch=main") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - let snapshot_error: ErrorOutput = serde_json::from_value(snapshot_body).unwrap(); - assert_eq!(snapshot_status, StatusCode::CONFLICT); - assert_eq!( - snapshot_error.code, - Some(omnigraph_server::api::ErrorCode::Conflict) - ); - assert!( - snapshot_error - .error - .contains("schema evolution is locked down in phase 1") - ); - - let read = 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 (read_status, read_body) = json_response( - &app, - Request::builder() - .uri("/read") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&read).unwrap())) - .unwrap(), - ) - .await; - let read_error: ErrorOutput = serde_json::from_value(read_body).unwrap(); - assert_eq!(read_status, StatusCode::CONFLICT); - assert_eq!( - read_error.code, - Some(omnigraph_server::api::ErrorCode::Conflict) - ); - assert!( - read_error - .error - .contains("schema evolution is locked down in phase 1") - ); - - let change = ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "Mina", "age": 28 })), - branch: Some("main".to_string()), - }; - let (change_status, change_body) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&change).unwrap())) - .unwrap(), - ) - .await; - let change_error: ErrorOutput = serde_json::from_value(change_body).unwrap(); - assert_eq!(change_status, StatusCode::CONFLICT); - assert_eq!( - change_error.code, - Some(omnigraph_server::api::ErrorCode::Conflict) - ); - assert!( - change_error - .error - .contains("schema evolution is locked down in phase 1") - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_route_returns_current_source() { - let (_temp, app) = app_for_loaded_graph().await; - let (status, body) = json_response( - &app, - Request::builder() - .uri("/schema") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - - assert_eq!(status, StatusCode::OK); - let output: SchemaOutput = serde_json::from_value(body).unwrap(); - assert!(output.schema_source.contains("node Person")); -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_route_requires_bearer_token_when_auth_configured() { - let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; - - let (missing_status, missing_body) = json_response( - &app, - Request::builder() - .uri("/schema") - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await; - let missing_error: ErrorOutput = serde_json::from_value(missing_body).unwrap(); - assert_eq!(missing_status, StatusCode::UNAUTHORIZED); - assert_eq!( - missing_error.code, - Some(omnigraph_server::api::ErrorCode::Unauthorized) - ); - - let (ok_status, ok_body) = json_response( - &app, - Request::builder() - .uri("/schema") - .method(Method::GET) - .header("authorization", "Bearer demo-token") - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(ok_status, StatusCode::OK); - let output: SchemaOutput = serde_json::from_value(ok_body).unwrap(); - assert!(!output.schema_source.is_empty()); -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_route_denied_when_actor_lacks_read_permission() { - 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( - graph.to_string_lossy().to_string(), - vec![("act-bruno".to_string(), "team-token".to_string())], - Some(&policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - - let (status, body) = json_response( - &app, - Request::builder() - .uri("/schema") - .method(Method::GET) - .header("authorization", "Bearer team-token") - .body(Body::empty()) - .unwrap(), - ) - .await; - let error: ErrorOutput = serde_json::from_value(body).unwrap(); - assert_eq!(status, StatusCode::FORBIDDEN); - assert_eq!( - error.code, - Some(omnigraph_server::api::ErrorCode::Forbidden) - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_apply_route_soft_drops_property_via_http() { - 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 graph = graph_path(temp.path()); - { - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.load( - "main", - r#"{"type":"Person","data":{"name":"PreDrop","age":42}}"#, - LoadMode::Append, - ) - .await - .unwrap(); - } - let pre_version = manifest_dataset_version(&graph).await; - - let (status, payload) = json_response( - &app, - 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: schema_without_age(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - assert_eq!(payload["applied"], true); - - // Catalog reflects the drop: `age` is gone from the live schema. - let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - assert!( - !reopened.catalog().node_types["Person"] - .properties - .contains_key("age"), - "catalog should not contain `age` after drop" - ); - - // Soft drop preserves the prior version β€” `age` is still readable - // via time travel to the pre-drop manifest version. Mirrors the - // SDK-side assertion in `apply_schema_drops_a_nullable_property_softly_preserves_prior_version`. - let pre_drop_snapshot = reopened.snapshot_at_version(pre_version).await.unwrap(); - let pre_drop_ds = pre_drop_snapshot.open("node:Person").await.unwrap(); - let pre_drop_fields = pre_drop_ds - .schema() - .fields - .iter() - .map(|f| f.name.clone()) - .collect::>(); - assert!( - pre_drop_fields.iter().any(|f| f == "age"), - "soft drop should leave the pre-drop dataset's `age` column \ - time-travel-reachable; got fields {pre_drop_fields:?}" - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_apply_route_soft_drops_node_type_via_http() { - 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 graph = graph_path(temp.path()); - - let (status, payload) = json_response( - &app, - 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: schema_without_company(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - assert_eq!(payload["applied"], true); - - 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" - ); - assert!( - !reopened.catalog().edge_types.contains_key("WorksAt"), - "catalog should not contain `WorksAt` after cascade" - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_apply_route_hard_drops_property_with_allow_data_loss() { - 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 graph = graph_path(temp.path()); - { - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.load( - "main", - r#"{"type":"Person","data":{"name":"PreDropHard","age":50}}"#, - LoadMode::Append, - ) - .await - .unwrap(); - } - - // Apply with allow_data_loss=true β†’ Hard mode promotion. - let (status, payload) = json_response( - &app, - 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: schema_without_age(), - allow_data_loss: true, - }) - .unwrap(), - )) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - assert_eq!(payload["applied"], true); - - // Catalog reflects the drop. - let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - assert!( - !reopened.catalog().node_types["Person"] - .properties - .contains_key("age"), - "catalog should not contain `age` after Hard drop" - ); - // Plan steps should show DropMode::Hard for property drops. - let steps = payload["steps"].as_array().expect("steps array"); - let drop_step = steps - .iter() - .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" - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_apply_route_keeps_drops_soft_without_flag() { - // Symmetric to the Hard test: same schema change, but no - // 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_graph_with_auth_tokens_and_policy( - &fs::read_to_string(fixture("test.pg")).unwrap(), - &[("act-ragnor", "admin-token")], - SCHEMA_APPLY_POLICY_YAML, - ) - .await; - let graph = graph_path(temp.path()); - - let (status, payload) = json_response( - &app, - 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: schema_without_age(), - allow_data_loss: false, - }) - .unwrap(), - )) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - assert_eq!(payload["applied"], true); - - let steps = payload["steps"].as_array().expect("steps array"); - let drop_step = steps - .iter() - .find(|s| s["kind"] == "drop_property") - .expect("plan should include drop_property step"); - let mode = &drop_step["mode"]; - assert_eq!(mode, "soft", "expected soft mode without allow_data_loss"); - let _ = graph; -} - -#[tokio::test(flavor = "multi_thread")] -async fn schema_apply_route_additive_property_preserves_existing_rows() { - // SDK suite covers rename and drop data preservation. Additive - // 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_graph_with_auth_tokens_and_policy( - &fs::read_to_string(fixture("test.pg")).unwrap(), - &[("act-ragnor", "admin-token")], - SCHEMA_APPLY_POLICY_YAML, - ) - .await; - let graph = graph_path(temp.path()); - - // Standard fixture data: 4 Persons + 1 Company. Load it. - let pre_count = { - let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); - db.load( - "main", - &fs::read_to_string(fixture("test.jsonl")).unwrap(), - LoadMode::Append, - ) - .await - .unwrap(); - let snap = db - .snapshot_of(omnigraph::db::ReadTarget::branch("main")) - .await - .unwrap(); - snap.entry("node:Person").expect("Person").row_count - }; - assert!(pre_count > 0, "fixture should have loaded Person rows"); - - let (status, payload) = json_response( - &app, - 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: additive_schema_with_nickname(), - ..Default::default() - }) - .unwrap(), - )) - .unwrap(), - ) - .await; - assert_eq!(status, StatusCode::OK); - assert_eq!(payload["applied"], true); - - // Row count preserved. - 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; - assert_eq!( - post_count, pre_count, - "AddProperty should preserve row count", - ); -} diff --git a/crates/omnigraph-server/tests/server.rs b/crates/omnigraph-server/tests/server.rs new file mode 100644 index 0000000..4a49a14 --- /dev/null +++ b/crates/omnigraph-server/tests/server.rs @@ -0,0 +1,6209 @@ +use std::env; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use axum::Router; +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}; +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, 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; +use tower::ServiceExt; + +const MUTATION_QUERIES: &str = r#" +query insert_person($name: String, $age: I32) { + insert Person { name: $name, age: $age } +} + +query set_age($name: String, $age: I32) { + update Person set { age: $age } where name = $name +} +"#; + +const POLICY_YAML: &str = r#" +version: 1 +groups: + team: [act-andrew, act-bruno, act-ragnor] + admins: [act-ragnor] +protected_branches: [main] +rules: + - id: team-read + allow: + actors: { group: team } + actions: [read] + branch_scope: any + - id: admins-export + allow: + actors: { group: admins } + actions: [export] + branch_scope: any + - id: team-write-unprotected + allow: + actors: { group: team } + actions: [change] + branch_scope: unprotected + - id: admins-merge + allow: + actors: { group: admins } + actions: [branch_delete, branch_merge] + target_branch_scope: protected +"#; + +const POLICY_PROTECTED_READ_YAML: &str = r#" +version: 1 +groups: + team: [act-bruno] +protected_branches: [main] +rules: + - id: protected-read + allow: + actors: { group: team } + actions: [read] + branch_scope: protected +"#; + +const INGEST_CREATE_ONLY_POLICY_YAML: &str = r#" +version: 1 +groups: + team: [act-bruno] +protected_branches: [main] +rules: + - id: team-branch-create + allow: + actors: { group: team } + actions: [branch_create] + target_branch_scope: unprotected +"#; + +const SCHEMA_APPLY_POLICY_YAML: &str = r#" +version: 1 +groups: + admins: [act-ragnor] +protected_branches: [main] +rules: + - id: admins-schema-apply + allow: + actors: { group: admins } + actions: [schema_apply] + target_branch_scope: protected +"#; + +fn fixture(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../omnigraph/tests/fixtures") + .join(name) +} + +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_graph_with_schema_and_data(schema: &str, data: &str) -> tempfile::TempDir { + let temp = tempfile::tempdir().unwrap(); + 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(graph.to_str().unwrap()).await.unwrap(); + load_jsonl(&mut db, data, LoadMode::Overwrite) + .await + .unwrap(); + temp +} + +async fn init_graph_with_schema(schema: &str) -> tempfile::TempDir { + let temp = tempfile::tempdir().unwrap(); + let graph = graph_path(temp.path()); + fs::create_dir_all(&graph).unwrap(); + Omnigraph::init(graph.to_str().unwrap(), schema) + .await + .unwrap(); + temp +} + +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(graph: &Path) -> u64 { + Omnigraph::open(graph.to_string_lossy().as_ref()) + .await + .unwrap() + .snapshot_of(ReadTarget::branch("main")) + .await + .unwrap() + .version() +} + +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() + .filter(|value| !value.trim().is_empty()) + .unwrap_or_else(|| "omnigraph-itests".to_string()); + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .ok()? + .as_nanos(); + Some(format!("s3://{}/{}/{}/{}", bucket, prefix, suite, unique)) +} + +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)) +} + +/// Build a permit-all policy YAML that grants every action used by the +/// HTTP-layer tests to the listed actor names. MR-723 default-deny +/// closed the "tokens but no policy" loophole; helpers that used to +/// represent "auth without policy" now install this permit-all policy +/// 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_graph_with_auth_tokens_only` instead. +fn permit_all_policy_yaml(actors: &[&str]) -> String { + let members = actors + .iter() + .map(|a| format!("\"{a}\"")) + .collect::>() + .join(", "); + format!( + r#" +version: 1 +groups: + permitted: [{members}] +protected_branches: [main] +rules: + - id: permit-data + allow: + actors: {{ group: permitted }} + actions: [read, change, export] + branch_scope: any + - id: permit-protected-target-actions + allow: + actors: {{ group: permitted }} + actions: [schema_apply, branch_create, branch_delete, branch_merge] + target_branch_scope: any +"# + ) +} + +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_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( + graph.to_string_lossy().to_string(), + vec![("default".to_string(), token.to_string())], + Some(&policy_path), + ) + .await + .unwrap(); + (temp, build_app(state)) +} + +async fn app_for_loaded_graph_with_auth_tokens( + tokens: &[(&str, &str)], +) -> (tempfile::TempDir, Router) { + 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( + graph.to_string_lossy().to_string(), + tokens + .iter() + .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) + .collect(), + Some(&policy_path), + ) + .await + .unwrap(); + (temp, build_app(state)) +} + +async fn app_for_loaded_graph_with_auth_tokens_and_policy( + 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 state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + tokens + .iter() + .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) + .collect(), + Some(&policy_path), + ) + .await + .unwrap(); + (temp, build_app(state)) +} + +async fn app_for_graph_with_auth_tokens_and_policy( + schema: &str, + tokens: &[(&str, &str)], + policy: &str, +) -> (tempfile::TempDir, Router) { + 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( + graph.to_string_lossy().to_string(), + tokens + .iter() + .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) + .collect(), + Some(&policy_path), + ) + .await + .unwrap(); + (temp, build_app(state)) +} + +/// MR-723 default-deny mode: bearer tokens configured, no policy file. +/// 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_graph_with_auth_tokens_only( + schema: &str, + tokens: &[(&str, &str)], +) -> (tempfile::TempDir, Router) { + let temp = init_graph_with_schema(schema).await; + let graph = graph_path(temp.path()); + let state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + tokens + .iter() + .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) + .collect(), + None, + ) + .await + .unwrap(); + (temp, build_app(state)) +} + +fn additive_schema_with_nickname() -> String { + fs::read_to_string(fixture("test.pg")).unwrap().replace( + " age: I32?\n}", + " age: I32?\n nickname: String?\n}", + ) +} + +fn schema_without_age() -> String { + // Drop the nullable `age` column from the test schema. Used by the + // HTTP soft/hard drop tests below. + fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace(" age: I32?\n", "") +} + +fn schema_without_company() -> String { + // Drop the `Company` node type and the edge referencing it. Used + // by the HTTP DropType test below. Hand-crafted (no template + // string replace) because the fixture interleaves the type and + // its edge. + r#"node Person { + name: String @key + age: I32? +} + +edge Knows: Person -> Person { + since: Date? +} +"# + .to_string() +} + +fn renamed_person_schema() -> String { + fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("node Person {\n", "node Human @rename_from(\"Person\") {\n") + .replace("edge Knows: Person -> Person", "edge Knows: Human -> Human") + .replace( + "edge WorksAt: Person -> Company", + "edge WorksAt: Human -> Company", + ) +} + +fn renamed_age_schema() -> String { + fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("age: I32?", "years: I32? @rename_from(\"age\")") +} + +fn indexed_name_schema() -> String { + fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("name: String @key", "name: String @key @index") +} + +fn unsupported_schema_change() -> String { + fs::read_to_string(fixture("test.pg")) + .unwrap() + .replace("age: I32?", "age: I64?") +} + +async fn json_response(app: &Router, request: Request) -> (StatusCode, Value) { + let response = app.clone().oneshot(request).await.unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let value = serde_json::from_slice(&body).unwrap(); + (status, value) +} + +#[tokio::test] +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, + ) + .await; + let schema = additive_schema_with_nickname(); + + 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: schema, + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(payload["applied"], true); + let graph = graph_path(temp.path()); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + assert!( + reopened.catalog().node_types["Person"] + .properties + .contains_key("nickname") + ); +} + +#[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_graph_with_auth_tokens_and_policy( + &fs::read_to_string(fixture("test.pg")).unwrap(), + &[("act-ragnor", "admin-token")], + 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: additive_schema_with_nickname(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!( + payload["code"], + serde_json::to_value(omnigraph_server::api::ErrorCode::Forbidden).unwrap() + ); +} + +#[tokio::test] +async fn schema_apply_route_requires_bearer_token_when_policy_enabled() { + 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 request = Request::builder() + .method(Method::POST) + .uri("/schema/apply") + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&SchemaApplyRequest { + schema_source: additive_schema_with_nickname(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!( + payload["code"], + serde_json::to_value(omnigraph_server::api::ErrorCode::Unauthorized).unwrap() + ); +} + +#[tokio::test] +async fn schema_apply_route_can_rename_type() { + 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 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_person_schema(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(payload["applied"], true); + 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 + .unwrap(); + assert!(snapshot.entry("node:Human").is_some()); + assert!(snapshot.entry("node:Person").is_none()); +} + +#[tokio::test] +async fn schema_apply_route_can_rename_property() { + 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 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::OK); + assert_eq!(payload["applied"], true); + 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")); +} + +#[tokio::test] +async fn schema_apply_route_can_add_index() { + 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 graph = graph_path(temp.path()); + let before_index_count = { + 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() + }; + + 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: indexed_name_schema(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(payload["applied"], true); + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + let snapshot = reopened + .snapshot_of(ReadTarget::branch("main")) + .await + .unwrap(); + let dataset = snapshot.open("node:Person").await.unwrap(); + let after_index_count = dataset.load_indices().await.unwrap().len(); + assert!(after_index_count > before_index_count); +} + +#[tokio::test] +async fn schema_apply_route_rejects_unsupported_plan() { + 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 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: unsupported_schema_change(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!( + payload["code"], + serde_json::to_value(omnigraph_server::api::ErrorCode::BadRequest).unwrap() + ); +} + +#[tokio::test] +async fn schema_apply_route_rejects_when_non_main_branch_exists() { + 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( + graph.to_string_lossy().to_string(), + vec![("act-ragnor".to_string(), "admin-token".to_string())], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + + 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: additive_schema_with_nickname(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(); + let (status, payload) = json_response(&app, request).await; + + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!( + payload["code"], + serde_json::to_value(omnigraph_server::api::ErrorCode::Conflict).unwrap() + ); +} + +struct EnvGuard { + saved: Vec<(&'static str, Option)>, +} + +impl EnvGuard { + fn set(vars: &[(&'static str, Option<&str>)]) -> Self { + let saved = vars + .iter() + .map(|(name, _)| (*name, env::var(name).ok())) + .collect::>(); + for (name, value) in vars { + unsafe { + match value { + Some(value) => env::set_var(name, value), + None => env::remove_var(name), + } + } + } + Self { saved } + } +} + +impl Drop for EnvGuard { + fn drop(&mut self) { + for (name, value) in self.saved.drain(..) { + unsafe { + match value { + Some(value) => env::set_var(name, value), + None => env::remove_var(name), + } + } + } + } +} + +fn format_vector(values: &[f32]) -> String { + values + .iter() + .map(|value| format!("{:.8}", value)) + .collect::>() + .join(", ") +} + +fn normalize_vector(mut values: Vec) -> Vec { + let norm = values + .iter() + .map(|value| (*value as f64) * (*value as f64)) + .sum::() + .sqrt() as f32; + if norm > f32::EPSILON { + for value in &mut values { + *value /= norm; + } + } + values +} + +fn fnv1a64(bytes: &[u8]) -> u64 { + let mut hash = 14695981039346656037u64; + for byte in bytes { + hash ^= *byte as u64; + hash = hash.wrapping_mul(1099511628211u64); + } + hash +} + +fn xorshift64(mut x: u64) -> u64 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x +} + +fn mock_embedding(input: &str, dim: usize) -> Vec { + let mut seed = fnv1a64(input.as_bytes()); + let mut out = Vec::with_capacity(dim); + for _ in 0..dim { + seed = xorshift64(seed); + let ratio = (seed as f64 / u64::MAX as f64) as f32; + out.push((ratio * 2.0) - 1.0); + } + normalize_vector(out) +} + +#[tokio::test(flavor = "multi_thread")] +async fn healthz_succeeds_after_startup() { + let (_temp, app) = app_for_loaded_graph().await; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/healthz") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(body["status"], "ok"); + assert_eq!(body["version"], env!("CARGO_PKG_VERSION")); + match option_env!("OMNIGRAPH_SOURCE_VERSION") { + Some(source_version) => assert_eq!(body["source_version"], source_version), + None => assert!(body.get("source_version").is_none()), + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_drift_returns_conflict_for_snapshot_read_and_change() { + 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, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + let snapshot_error: ErrorOutput = serde_json::from_value(snapshot_body).unwrap(); + assert_eq!(snapshot_status, StatusCode::CONFLICT); + assert_eq!( + snapshot_error.code, + Some(omnigraph_server::api::ErrorCode::Conflict) + ); + assert!( + snapshot_error + .error + .contains("schema evolution is locked down in phase 1") + ); + + let read = 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 (read_status, read_body) = json_response( + &app, + Request::builder() + .uri("/read") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&read).unwrap())) + .unwrap(), + ) + .await; + let read_error: ErrorOutput = serde_json::from_value(read_body).unwrap(); + assert_eq!(read_status, StatusCode::CONFLICT); + assert_eq!( + read_error.code, + Some(omnigraph_server::api::ErrorCode::Conflict) + ); + assert!( + read_error + .error + .contains("schema evolution is locked down in phase 1") + ); + + let change = ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "Mina", "age": 28 })), + branch: Some("main".to_string()), + }; + let (change_status, change_body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&change).unwrap())) + .unwrap(), + ) + .await; + let change_error: ErrorOutput = serde_json::from_value(change_body).unwrap(); + assert_eq!(change_status, StatusCode::CONFLICT); + assert_eq!( + change_error.code, + Some(omnigraph_server::api::ErrorCode::Conflict) + ); + assert!( + change_error + .error + .contains("schema evolution is locked down in phase 1") + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn protected_routes_require_bearer_token() { + let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/branches") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + + let error: ErrorOutput = serde_json::from_value(body).unwrap(); + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!( + error.code, + Some(omnigraph_server::api::ErrorCode::Unauthorized) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn protected_routes_accept_valid_bearer_token_while_healthz_stays_open() { + let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; + + let health = app + .clone() + .oneshot( + Request::builder() + .uri("/healthz") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(health.status(), StatusCode::OK); + + let (status, body) = json_response( + &app, + Request::builder() + .uri("/branches") + .method(Method::GET) + .header("authorization", "Bearer demo-token") + .body(Body::empty()) + .unwrap(), + ) + .await; + + assert_eq!(status, StatusCode::OK); + assert!(body["branches"].is_array()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn export_route_returns_jsonl_for_branch_snapshot() { + let token = "demo-token"; + 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(); + db.load( + "feature", + r#"{"type":"Person","data":{"name":"Eve","age":29}}"#, + LoadMode::Append, + ) + .await + .unwrap(); + let expected = db + .export_jsonl("feature", &["Person".to_string()], &[]) + .await + .unwrap(); + drop(db); + + // MR-723: tokens-without-policy is now default-deny. Install a + // permit-all policy alongside the bearer token so /export + // (action=Export) passes Cedar evaluation. The test is exercising + // export semantics, not policy β€” the policy is just enough to clear + // the State 3 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( + graph.to_string_lossy().to_string(), + vec![("default".to_string(), token.to_string())], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/export") + .method(Method::POST) + .header("content-type", "application/json") + .header("authorization", format!("Bearer {}", token)) + .body(Body::from( + serde_json::to_vec(&ExportRequest { + branch: Some("feature".to_string()), + type_names: vec!["Person".to_string()], + table_keys: Vec::new(), + }) + .unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers().get("content-type").unwrap(), + "application/x-ndjson; charset=utf-8" + ); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let text = String::from_utf8(body.to_vec()).unwrap(); + assert_eq!(text, expected); +} + +#[tokio::test(flavor = "multi_thread")] +async fn protected_routes_accept_any_configured_team_bearer_token() { + 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, + Request::builder() + .uri("/branches") + .method(Method::GET) + .header("authorization", "Bearer token-two") + .body(Body::empty()) + .unwrap(), + ) + .await; + + assert_eq!(status, StatusCode::OK); + assert!(body["branches"].is_array()); +} + +/// Verifies the hashed-token lookup correctly resolves each bearer to its +/// associated actor, and that the resolved actor β€” not the handler-supplied +/// default β€” is what the policy engine sees. Two tokens for two distinct +/// actors; policy grants read to actor-A only. Swapping tokens must swap +/// the policy outcome. +#[tokio::test(flavor = "multi_thread")] +async fn bearer_token_resolves_to_correct_actor_for_policy_decisions() { + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let policy_path = temp.path().join("policy.yaml"); + fs::write( + &policy_path, + r#" +version: 1 +groups: + readers: [act-a] + writers: [act-b] +protected_branches: [main] +rules: + - id: readers-only + allow: + actors: { group: readers } + actions: [read] + branch_scope: any +"#, + ) + .unwrap(); + let state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + vec![ + ("act-a".to_string(), "token-a".to_string()), + ("act-b".to_string(), "token-b".to_string()), + ], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + + // act-a is authenticated AND authorized. + let (ok_status, _) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .header("authorization", "Bearer token-a") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(ok_status, StatusCode::OK); + + // act-b is authenticated but policy rejects β€” proves the resolved actor + // (not some default) was the policy subject. + let (denied_status, denied_body) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .header("authorization", "Bearer token-b") + .body(Body::empty()) + .unwrap(), + ) + .await; + let denied_error: ErrorOutput = serde_json::from_value(denied_body).unwrap(); + assert_eq!(denied_status, StatusCode::FORBIDDEN); + assert_eq!( + denied_error.code, + Some(omnigraph_server::api::ErrorCode::Forbidden) + ); + + // Unknown token: 401, never reaches the policy engine. + let (bad_status, _) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .header("authorization", "Bearer wrong-token") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(bad_status, StatusCode::UNAUTHORIZED); +} + +/// Regression test for MR-731: actor identity comes from the matched +/// bearer token, never from a client-supplied request header. A future +/// "convenience" PR that lets clients override `actor_id` to spoof +/// another identity must break this test. The principle is named in +/// `docs/dev/invariants.md` Hard Invariant 11 and at the actor-resolution +/// site in `omnigraph-server/src/lib.rs::authorize_request`. +/// +/// Two assertions in one fixture: +/// 1. Spoof-up: bearer for a *denied* actor + X-Actor-Id naming an +/// *allowed* actor β€” policy still denies (proves the spoof header +/// doesn't promote the request). +/// 2. Spoof-down: bearer for an *allowed* actor + X-Actor-Id naming a +/// *denied* actor β€” policy still allows (proves the server-resolved +/// identity wins; the spoof can't trick the request into a denial +/// either, which would otherwise be a confusing UX trap). +/// +/// Cross-reference: MR-777 covers boundary cases like actor-id +/// *collision* (two distinct tokens minting the same actor_id) and +/// malformed bearer header parsing. See `auth_boundary_case_coverage` +/// suite when it lands; the two tests together pin the full bearer-token +/// β†’ actor identity contract. +#[tokio::test(flavor = "multi_thread")] +async fn actor_id_resolves_from_bearer_token_ignoring_client_supplied_headers() { + 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` β€” + // `act-a` can read main, `act-b` cannot. The asymmetry is what + // makes the spoof-up/spoof-down distinction observable. + fs::write( + &policy_path, + r#" +version: 1 +groups: + readers: [act-a] + writers: [act-b] +protected_branches: [main] +rules: + - id: readers-only + allow: + actors: { group: readers } + actions: [read] + branch_scope: any +"#, + ) + .unwrap(); + let state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + vec![ + ("act-a".to_string(), "token-a".to_string()), + ("act-b".to_string(), "token-b".to_string()), + ], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + + // (1) Spoof-up: bearer for act-b (denied) + X-Actor-Id: act-a (allowed). + // If the server were trusting the header, this would succeed as + // act-a. The contract is: the bearer wins. Expect 403 because + // act-b can't read. + let (spoof_up_status, spoof_up_body) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .header("authorization", "Bearer token-b") + .header("x-actor-id", "act-a") + .body(Body::empty()) + .unwrap(), + ) + .await; + let spoof_up_error: ErrorOutput = serde_json::from_value(spoof_up_body).unwrap(); + assert_eq!( + spoof_up_status, + StatusCode::FORBIDDEN, + "X-Actor-Id must not promote a denied bearer to an allowed actor", + ); + assert_eq!( + spoof_up_error.code, + Some(omnigraph_server::api::ErrorCode::Forbidden), + ); + + // (2) Spoof-down: bearer for act-a (allowed) + X-Actor-Id: act-b (denied). + // If the server were trusting the header, this would fail as act-b. + // The contract is: the bearer wins. Expect 200 because act-a can read. + let (spoof_down_status, _) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .header("authorization", "Bearer token-a") + .header("x-actor-id", "act-b") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!( + spoof_down_status, + StatusCode::OK, + "X-Actor-Id must not demote an allowed bearer to a denied actor", + ); + + // (3) Empty-string spoof attempt: an X-Actor-Id of "" must not + // leak through as the policy subject. Same expectation as (1): + // bearer for act-b is denied regardless of what the header tries. + let (empty_spoof_status, _) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .header("authorization", "Bearer token-b") + .header("x-actor-id", "") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!( + empty_spoof_status, + StatusCode::FORBIDDEN, + "empty X-Actor-Id must not clear the resolved actor", + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn policy_allows_read_but_distinguishes_401_from_403() { + let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( + &[("act-bruno", "team-token"), ("act-ragnor", "admin-token")], + POLICY_YAML, + ) + .await; + + let (missing_status, missing_body) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + let missing_error: ErrorOutput = serde_json::from_value(missing_body).unwrap(); + assert_eq!(missing_status, StatusCode::UNAUTHORIZED); + assert_eq!( + missing_error.code, + Some(omnigraph_server::api::ErrorCode::Unauthorized) + ); + + let (snapshot_status, snapshot_body) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .header("authorization", "Bearer team-token") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(snapshot_status, StatusCode::OK); + assert_eq!(snapshot_body["branch"], "main"); + + let export_request = ExportRequest { + branch: Some("main".to_string()), + type_names: Vec::new(), + table_keys: Vec::new(), + }; + let (forbidden_status, forbidden_body) = json_response( + &app, + Request::builder() + .uri("/export") + .method(Method::POST) + .header("authorization", "Bearer team-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&export_request).unwrap())) + .unwrap(), + ) + .await; + let forbidden_error: ErrorOutput = serde_json::from_value(forbidden_body).unwrap(); + assert_eq!(forbidden_status, StatusCode::FORBIDDEN); + assert_eq!( + forbidden_error.code, + Some(omnigraph_server::api::ErrorCode::Forbidden) + ); + + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/export") + .method(Method::POST) + .header("authorization", "Bearer admin-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&export_request).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); +} + +#[tokio::test(flavor = "multi_thread")] +async fn policy_uses_resolved_branch_for_snapshot_reads() { + let temp = init_loaded_graph().await; + let graph = graph_path(temp.path()); + let snapshot_id = { + 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( + graph.to_string_lossy().to_string(), + vec![("act-bruno".to_string(), "team-token".to_string())], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + + let read = ReadRequest { + query_source: fs::read_to_string(fixture("test.gq")).unwrap(), + query_name: Some("get_person".to_string()), + params: Some(json!({ "name": "Alice" })), + branch: None, + snapshot: Some(snapshot_id), + }; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/read") + .method(Method::POST) + .header("authorization", "Bearer team-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&read).unwrap())) + .unwrap(), + ) + .await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(body["target"]["branch"], Value::Null); + assert_eq!( + body["target"]["snapshot"].as_str(), + read.snapshot.as_deref() + ); + assert_eq!(body["row_count"], 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn snapshot_route_returns_manifest_dataset_version() { + 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, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + + assert_eq!(snapshot_status, StatusCode::OK); + assert_eq!(snapshot_body["branch"], "main"); + assert_eq!( + snapshot_body["manifest_version"].as_u64().unwrap(), + expected_manifest_version + ); + assert!(snapshot_body["tables"].is_array()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_route_returns_current_source() { + let (_temp, app) = app_for_loaded_graph().await; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/schema") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + + assert_eq!(status, StatusCode::OK); + let output: SchemaOutput = serde_json::from_value(body).unwrap(); + assert!(output.schema_source.contains("node Person")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_route_requires_bearer_token_when_auth_configured() { + let (_temp, app) = app_for_loaded_graph_with_auth("demo-token").await; + + let (missing_status, missing_body) = json_response( + &app, + Request::builder() + .uri("/schema") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + let missing_error: ErrorOutput = serde_json::from_value(missing_body).unwrap(); + assert_eq!(missing_status, StatusCode::UNAUTHORIZED); + assert_eq!( + missing_error.code, + Some(omnigraph_server::api::ErrorCode::Unauthorized) + ); + + let (ok_status, ok_body) = json_response( + &app, + Request::builder() + .uri("/schema") + .method(Method::GET) + .header("authorization", "Bearer demo-token") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(ok_status, StatusCode::OK); + let output: SchemaOutput = serde_json::from_value(ok_body).unwrap(); + assert!(!output.schema_source.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_route_denied_when_actor_lacks_read_permission() { + 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( + graph.to_string_lossy().to_string(), + vec![("act-bruno".to_string(), "team-token".to_string())], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + + let (status, body) = json_response( + &app, + Request::builder() + .uri("/schema") + .method(Method::GET) + .header("authorization", "Bearer team-token") + .body(Body::empty()) + .unwrap(), + ) + .await; + let error: ErrorOutput = serde_json::from_value(body).unwrap(); + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!( + error.code, + Some(omnigraph_server::api::ErrorCode::Forbidden) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn policy_blocks_change_on_protected_main_but_allows_unprotected_branch() { + 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(); + drop(db); + + let policy_path = temp.path().join("policy.yaml"); + fs::write(&policy_path, POLICY_YAML).unwrap(); + let state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + vec![("act-bruno".to_string(), "team-token".to_string())], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + + let main_change = ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "Mina", "age": 28 })), + branch: Some("main".to_string()), + }; + let (main_status, main_body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("authorization", "Bearer team-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&main_change).unwrap())) + .unwrap(), + ) + .await; + let main_error: ErrorOutput = serde_json::from_value(main_body).unwrap(); + assert_eq!(main_status, StatusCode::FORBIDDEN); + assert_eq!( + main_error.code, + Some(omnigraph_server::api::ErrorCode::Forbidden) + ); + + let feature_change = ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "Mina", "age": 28 })), + branch: Some("feature".to_string()), + }; + let (feature_status, feature_body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("authorization", "Bearer team-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&feature_change).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(feature_status, StatusCode::OK); + assert_eq!(feature_body["branch"], "feature"); + assert_eq!(feature_body["affected_nodes"], 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn policy_blocks_non_admin_merge_to_main_and_allows_admin() { + 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(); + db.load( + "feature", + r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#, + LoadMode::Append, + ) + .await + .unwrap(); + drop(db); + + let policy_path = temp.path().join("policy.yaml"); + fs::write(&policy_path, POLICY_YAML).unwrap(); + let state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + vec![ + ("act-bruno".to_string(), "team-token".to_string()), + ("act-ragnor".to_string(), "admin-token".to_string()), + ], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + + let merge = BranchMergeRequest { + source: "feature".to_string(), + target: Some("main".to_string()), + }; + let (deny_status, deny_body) = json_response( + &app, + Request::builder() + .uri("/branches/merge") + .method(Method::POST) + .header("authorization", "Bearer team-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&merge).unwrap())) + .unwrap(), + ) + .await; + let deny_error: ErrorOutput = serde_json::from_value(deny_body).unwrap(); + assert_eq!(deny_status, StatusCode::FORBIDDEN); + assert_eq!( + deny_error.code, + Some(omnigraph_server::api::ErrorCode::Forbidden) + ); + + let (allow_status, allow_body) = json_response( + &app, + Request::builder() + .uri("/branches/merge") + .method(Method::POST) + .header("authorization", "Bearer admin-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&merge).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(allow_status, StatusCode::OK); + assert_eq!(allow_body["actor_id"], "act-ragnor"); +} + +#[tokio::test(flavor = "multi_thread")] +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_graph_with_auth_tokens(&[("act-andrew", "token-one")]).await; + + let change = ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "Mina", "age": 28 })), + branch: Some("main".to_string()), + }; + let (change_status, change_body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("authorization", "Bearer token-one") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&change).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(change_status, StatusCode::OK); + assert_eq!(change_body["actor_id"], "act-andrew"); + + let (commits_status, commits_body) = json_response( + &app, + Request::builder() + .uri("/commits?branch=main") + .method(Method::GET) + .header("authorization", "Bearer token-one") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(commits_status, StatusCode::OK); + let head = commits_body["commits"] + .as_array() + .unwrap() + .last() + .expect("head commit should exist"); + assert_eq!(head["actor_id"], "act-andrew"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn ingest_creates_branch_returns_metadata_and_stamps_actor() { + 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()), + mode: Some(LoadMode::Merge), + data: r#"{"type":"Person","data":{"name":"Zoe","age":33}} +{"type":"Person","data":{"name":"Bob","age":26}}"# + .to_string(), + }; + + let (status, body) = json_response( + &app, + Request::builder() + .uri("/ingest") + .method(Method::POST) + .header("authorization", "Bearer token-one") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&ingest).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["branch"], "feature-ingest"); + assert_eq!(body["base_branch"], "main"); + assert_eq!(body["branch_created"], true); + assert_eq!(body["mode"], "merge"); + assert_eq!(body["actor_id"], "act-andrew"); + assert_eq!(body["tables"][0]["table_key"], "node:Person"); + assert_eq!(body["tables"][0]["rows_loaded"], 2); + + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + let snapshot = db + .snapshot_of(ReadTarget::branch("feature-ingest")) + .await + .unwrap(); + let person_ds = snapshot.open("node:Person").await.unwrap(); + assert_eq!(person_ds.count_rows(None).await.unwrap(), 5); + let head = db + .list_commits(Some("feature-ingest")) + .await + .unwrap() + .into_iter() + .last() + .unwrap(); + assert_eq!(head.actor_id.as_deref(), Some("act-andrew")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn ingest_existing_branch_skips_branch_create_policy_check() { + 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(); + } + let policy_path = temp.path().join("policy.yaml"); + fs::write(&policy_path, POLICY_YAML).unwrap(); + let state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + vec![("act-bruno".to_string(), "team-token".to_string())], + Some(&policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + let ingest = IngestRequest { + branch: Some("feature".to_string()), + from: Some("other-base".to_string()), + mode: Some(LoadMode::Merge), + data: r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#.to_string(), + }; + + let (status, body) = json_response( + &app, + Request::builder() + .uri("/ingest") + .method(Method::POST) + .header("authorization", "Bearer team-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&ingest).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["branch"], "feature"); + assert_eq!(body["branch_created"], false); + assert_eq!(body["base_branch"], "other-base"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn ingest_denies_missing_branch_without_branch_create_permission() { + let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( + &[("act-bruno", "team-token")], + POLICY_YAML, + ) + .await; + let ingest = IngestRequest { + branch: Some("feature".to_string()), + from: Some("main".to_string()), + mode: Some(LoadMode::Merge), + data: r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#.to_string(), + }; + + let (status, body) = json_response( + &app, + Request::builder() + .uri("/ingest") + .method(Method::POST) + .header("authorization", "Bearer team-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&ingest).unwrap())) + .unwrap(), + ) + .await; + let error: ErrorOutput = serde_json::from_value(body).unwrap(); + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!( + error.code, + Some(omnigraph_server::api::ErrorCode::Forbidden) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn ingest_denies_when_actor_lacks_change_permission() { + let (_temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( + &[("act-bruno", "team-token")], + INGEST_CREATE_ONLY_POLICY_YAML, + ) + .await; + let ingest = IngestRequest { + branch: Some("feature".to_string()), + from: Some("main".to_string()), + mode: Some(LoadMode::Merge), + data: r#"{"type":"Person","data":{"name":"Zoe","age":33}}"#.to_string(), + }; + + let (status, body) = json_response( + &app, + Request::builder() + .uri("/ingest") + .method(Method::POST) + .header("authorization", "Bearer team-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&ingest).unwrap())) + .unwrap(), + ) + .await; + let error: ErrorOutput = serde_json::from_value(body).unwrap(); + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!( + error.code, + Some(omnigraph_server::api::ErrorCode::Forbidden) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn ingest_rejects_payloads_over_32_mib() { + let (_temp, app) = app_for_loaded_graph().await; + let oversize = IngestRequest { + branch: Some("feature".to_string()), + from: Some("main".to_string()), + mode: Some(LoadMode::Merge), + data: "x".repeat(33 * 1024 * 1024), + }; + + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/ingest") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&oversize).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); +} + +#[tokio::test(flavor = "multi_thread")] +async fn authenticated_branch_merge_stamps_merge_actor_on_head_commit() { + let (_temp, app) = app_for_loaded_graph_with_auth_tokens(&[ + ("act-andrew", "token-one"), + ("act-ragnor", "token-two"), + ]) + .await; + + let create = BranchCreateRequest { + from: Some("main".to_string()), + name: "feature".to_string(), + }; + let (create_status, _) = json_response( + &app, + Request::builder() + .uri("/branches") + .method(Method::POST) + .header("authorization", "Bearer token-one") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&create).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(create_status, StatusCode::OK); + + let change = ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "Zoe", "age": 33 })), + branch: Some("feature".to_string()), + }; + let (change_status, _) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("authorization", "Bearer token-one") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&change).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(change_status, StatusCode::OK); + + let merge = BranchMergeRequest { + source: "feature".to_string(), + target: Some("main".to_string()), + }; + let (merge_status, merge_body) = json_response( + &app, + Request::builder() + .uri("/branches/merge") + .method(Method::POST) + .header("authorization", "Bearer token-two") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&merge).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(merge_status, StatusCode::OK); + assert_eq!(merge_body["actor_id"], "act-ragnor"); + + let (commit_status, commit_body) = json_response( + &app, + Request::builder() + .uri("/commits?branch=main") + .method(Method::GET) + .header("authorization", "Bearer token-two") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(commit_status, StatusCode::OK); + let head = commit_body["commits"] + .as_array() + .unwrap() + .last() + .expect("head commit should exist"); + assert_eq!(head["actor_id"], "act-ragnor"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn branch_merge_conflict_response_includes_structured_conflicts() { + 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(); + db.mutate( + "main", + MUTATION_QUERIES, + "set_age", + &omnigraph_compiler::json_params_to_param_map( + Some(&json!({"name": "Alice", "age": 31 })), + &omnigraph_compiler::find_named_query(MUTATION_QUERIES, "set_age") + .unwrap() + .params, + omnigraph_compiler::JsonParamMode::Standard, + ) + .unwrap(), + ) + .await + .unwrap(); + db.mutate( + "feature", + MUTATION_QUERIES, + "set_age", + &omnigraph_compiler::json_params_to_param_map( + Some(&json!({"name": "Alice", "age": 32 })), + &omnigraph_compiler::find_named_query(MUTATION_QUERIES, "set_age") + .unwrap() + .params, + omnigraph_compiler::JsonParamMode::Standard, + ) + .unwrap(), + ) + .await + .unwrap(); + drop(db); + + let state = AppState::open(graph.to_string_lossy().to_string()) + .await + .unwrap(); + let app = build_app(state); + let merge = BranchMergeRequest { + source: "feature".to_string(), + target: Some("main".to_string()), + }; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/branches/merge") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&merge).unwrap())) + .unwrap(), + ) + .await; + + let error: ErrorOutput = serde_json::from_value(body).unwrap(); + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(error.code, Some(omnigraph_server::api::ErrorCode::Conflict)); + assert!(error.error.contains("merge conflict")); + assert!(error.merge_conflicts.iter().any(|conflict| { + conflict.table_key == "node:Person" + && conflict.row_id.as_deref() == Some("Alice") + && conflict.kind == omnigraph_server::api::MergeConflictKindOutput::DivergentUpdate + })); +} + +#[tokio::test(flavor = "multi_thread")] +async fn repeated_read_after_change_sees_updated_state_from_same_app() { + let (_temp, app) = app_for_loaded_graph().await; + + let change = ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "Mina", "age": 28 })), + branch: Some("main".to_string()), + }; + let (change_status, change_body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&change).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(change_status, StatusCode::OK); + assert_eq!(change_body["affected_nodes"], 1); + + let read = ReadRequest { + query_source: fs::read_to_string(fixture("test.gq")).unwrap(), + query_name: Some("get_person".to_string()), + params: Some(json!({ "name": "Mina" })), + branch: Some("main".to_string()), + snapshot: None, + }; + let (read_status, read_body) = json_response( + &app, + Request::builder() + .uri("/read") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&read).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(read_status, StatusCode::OK); + assert_eq!(read_body["row_count"], 1); + 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_graph().await; + + let (list_status, list_body) = json_response( + &app, + Request::builder() + .uri("/branches") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(list_status, StatusCode::OK); + assert_eq!(list_body["branches"], json!(["main"])); + + let create = BranchCreateRequest { + from: Some("main".to_string()), + name: "feature".to_string(), + }; + let (create_status, create_body) = json_response( + &app, + Request::builder() + .uri("/branches") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&create).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(create_status, StatusCode::OK); + assert_eq!(create_body["from"], "main"); + assert_eq!(create_body["name"], "feature"); + + let (list_status, list_body) = json_response( + &app, + Request::builder() + .uri("/branches") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(list_status, StatusCode::OK); + assert_eq!(list_body["branches"], json!(["feature", "main"])); + + let change = ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "Zoe", "age": 33 })), + branch: Some("feature".to_string()), + }; + let (change_status, change_body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&change).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(change_status, StatusCode::OK); + assert_eq!(change_body["branch"], "feature"); + assert_eq!(change_body["affected_nodes"], 1); + + let read_main_before = ReadRequest { + query_source: fs::read_to_string(fixture("test.gq")).unwrap(), + query_name: Some("get_person".to_string()), + params: Some(json!({ "name": "Zoe" })), + branch: Some("main".to_string()), + snapshot: None, + }; + let (read_status, read_body) = json_response( + &app, + Request::builder() + .uri("/read") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&read_main_before).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(read_status, StatusCode::OK); + assert_eq!(read_body["row_count"], 0); + + let merge = BranchMergeRequest { + source: "feature".to_string(), + target: Some("main".to_string()), + }; + let (merge_status, merge_body) = json_response( + &app, + Request::builder() + .uri("/branches/merge") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&merge).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(merge_status, StatusCode::OK); + assert_eq!(merge_body["source"], "feature"); + assert_eq!(merge_body["target"], "main"); + assert_eq!(merge_body["outcome"], "fast_forward"); + + let read_main_after = ReadRequest { + query_source: fs::read_to_string(fixture("test.gq")).unwrap(), + query_name: Some("get_person".to_string()), + params: Some(json!({ "name": "Zoe" })), + branch: Some("main".to_string()), + snapshot: None, + }; + let (read_status, read_body) = json_response( + &app, + Request::builder() + .uri("/read") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&read_main_after).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(read_status, StatusCode::OK); + assert_eq!(read_body["row_count"], 1); + assert_eq!(read_body["rows"][0]["p.name"], "Zoe"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn remote_branch_delete_flow_works() { + let (_temp, app) = app_for_loaded_graph().await; + + let create = BranchCreateRequest { + from: Some("main".to_string()), + name: "feature".to_string(), + }; + let (create_status, _) = json_response( + &app, + Request::builder() + .uri("/branches") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&create).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(create_status, StatusCode::OK); + + let (delete_status, delete_body) = json_response( + &app, + Request::builder() + .uri("/branches/feature") + .method(Method::DELETE) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(delete_status, StatusCode::OK); + assert_eq!(delete_body["name"], "feature"); + + let (list_status, list_body) = json_response( + &app, + Request::builder() + .uri("/branches") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(list_status, StatusCode::OK); + assert_eq!(list_body["branches"], json!(["main"])); +} + +#[tokio::test(flavor = "multi_thread")] +async fn branch_delete_denies_without_policy_permission() { + let (temp, app) = app_for_loaded_graph_with_auth_tokens_and_policy( + &[("act-andrew", "token-admin"), ("act-bruno", "token-team")], + POLICY_YAML, + ) + .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(); + drop(db); + + let (status, body) = json_response( + &app, + Request::builder() + .uri("/branches/feature") + .method(Method::DELETE) + .header("authorization", "Bearer token-team") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert!( + body["error"] + .as_str() + .unwrap() + .contains("policy denied action 'branch_delete'") + ); +} + +#[tokio::test(flavor = "multi_thread")] +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; + }; + + Omnigraph::init(&uri, &fs::read_to_string(fixture("test.pg")).unwrap()) + .await + .unwrap(); + let mut db = Omnigraph::open(&uri).await.unwrap(); + load_jsonl( + &mut db, + &fs::read_to_string(fixture("test.jsonl")).unwrap(), + LoadMode::Overwrite, + ) + .await + .unwrap(); + + let app = build_app( + AppState::open_with_bearer_token(uri.clone(), Some("s3-token".to_string())) + .await + .unwrap(), + ); + + let (snapshot_status, snapshot_body) = json_response( + &app, + Request::builder() + .uri("/snapshot") + .method(Method::GET) + .header("authorization", "Bearer s3-token") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(snapshot_status, StatusCode::OK); + assert!(snapshot_body["tables"].is_array()); + + let read = 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 (read_status, read_body) = json_response( + &app, + Request::builder() + .uri("/read") + .method(Method::POST) + .header("authorization", "Bearer s3-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&read).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(read_status, StatusCode::OK); + assert_eq!(read_body["row_count"], 1); + assert_eq!(read_body["rows"][0]["p.name"], "Alice"); +} + +#[tokio::test(flavor = "multi_thread")] +#[serial] +async fn remote_read_embeds_string_nearest_queries_with_mock_runtime() { + const EMBED_SCHEMA: &str = r#" +node Doc { + slug: String @key + title: String @index + embedding: Vector(4) @index +} +"#; + const EMBED_QUERY: &str = r#" +query vector_search_string($q: String) { + match { $d: Doc } + return { $d.slug, $d.title } + order { nearest($d.embedding, $q) } + limit 3 +} +"#; + + let alpha = mock_embedding("alpha", 4); + let beta = mock_embedding("beta", 4); + let gamma = mock_embedding("gamma", 4); + let data = format!( + concat!( + r#"{{"type":"Doc","data":{{"slug":"alpha-doc","title":"alpha guide","embedding":[{}]}}}}"#, + "\n", + r#"{{"type":"Doc","data":{{"slug":"beta-doc","title":"beta guide","embedding":[{}]}}}}"#, + "\n", + r#"{{"type":"Doc","data":{{"slug":"gamma-doc","title":"gamma handbook","embedding":[{}]}}}}"# + ), + format_vector(&alpha), + format_vector(&beta), + format_vector(&gamma), + ); + + let _guard = EnvGuard::set(&[ + ("OMNIGRAPH_EMBEDDINGS_MOCK", Some("1")), + ("GEMINI_API_KEY", None), + ]); + 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); + + let read = ReadRequest { + query_source: EMBED_QUERY.to_string(), + query_name: Some("vector_search_string".to_string()), + params: Some(json!({ "q": "alpha" })), + branch: Some("main".to_string()), + snapshot: None, + }; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/read") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&read).unwrap())) + .unwrap(), + ) + .await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(body["row_count"], 3); + assert_eq!(body["rows"][0]["d.slug"], "alpha-doc"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn change_conflict_returns_manifest_conflict_409() { + // A write that races with another writer surfaces as HTTP 409 with + // a structured `manifest_conflict` body β€” `table_key`, `expected`, + // and `actual` β€” so clients can detect-and-retry without parsing + // the message. + 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(graph.to_string_lossy().to_string()) + .await + .unwrap(); + let app = build_app(state); + + { + let mut db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + db.mutate( + "main", + MUTATION_QUERIES, + "set_age", + &omnigraph_compiler::json_params_to_param_map( + Some(&json!({"name": "Alice", "age": 31 })), + &omnigraph_compiler::find_named_query(MUTATION_QUERIES, "set_age") + .unwrap() + .params, + omnigraph_compiler::JsonParamMode::Standard, + ) + .unwrap(), + ) + .await + .unwrap(); + } + + 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(&ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("set_age".to_string()), + params: Some(json!({ "name": "Alice", "age": 33 })), + branch: Some("main".to_string()), + }) + .unwrap(), + )) + .unwrap(), + ) + .await; + + assert_eq!(status, StatusCode::CONFLICT); + let error: ErrorOutput = serde_json::from_value(body).unwrap(); + assert_eq!(error.code, Some(omnigraph_server::api::ErrorCode::Conflict)); + let conflict = error + .manifest_conflict + .expect("publisher CAS rejection must populate manifest_conflict body"); + assert_eq!(conflict.table_key, "node:Person"); + assert!( + conflict.actual > conflict.expected, + "actual ({}) should be ahead of expected ({})", + conflict.actual, + conflict.expected, + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn change_concurrent_inserts_same_key_serialize_without_409() { + // PR 2 Phase 2 (MR-686): pin the design fix for the same-key + // concurrency hazard. Pre-fix, in-process concurrent inserts on + // the same `(table, branch)` rejected with 409 manifest_conflict + // because `ensure_expected_version` fired before the per-table + // queue was acquired and saw Lance HEAD already advanced by a + // peer writer. Post-fix, Insert/Merge skip the strict pre-stage + // check (see `MutationOpKind::strict_pre_stage_version_check`); + // the queue serializes commit_staged; Lance's natural rebase + // handles the in-flight stage; the publisher's CAS on a fresh + // per-branch snapshot under the queue catches genuine cross- + // process drift. + // + // This test spawns N concurrent /change inserts on a single + // 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_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); + + // test.jsonl seeds 4 Persons (Alice, Bob, Charlie, Diana). + const SEED_PERSON_ROWS: u64 = 4; + const N: usize = 12; + + let mut handles = Vec::with_capacity(N); + for i in 0..N { + let app = app.clone(); + handles.push(tokio::spawn(async move { + let body = serde_json::to_vec(&ChangeRequest { + 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()), + }) + .unwrap(); + let req = Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(); + let response = app.oneshot(req).await.unwrap(); + response.status() + })); + } + + let mut statuses = Vec::with_capacity(N); + for h in handles { + statuses.push(h.await.unwrap()); + } + + let bad: Vec<_> = statuses + .iter() + .enumerate() + .filter(|(_, s)| **s != StatusCode::OK) + .collect(); + assert!( + bad.is_empty(), + "expected every concurrent insert to return 200, got non-200 for: {:?}", + bad + ); + + // Verify the inserts actually landed. The status check above only proves + // the publisher CAS didn't reject; the row count proves none of the + // concurrent commits silently overwrote a peer. + let (snapshot_status, snapshot_body) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(snapshot_status, StatusCode::OK); + let person_rows = snapshot_body["tables"] + .as_array() + .and_then(|tables| { + tables + .iter() + .find(|t| t["table_key"].as_str() == Some("node:Person")) + }) + .and_then(|t| t["row_count"].as_u64()) + .expect("snapshot must include node:Person row_count"); + assert_eq!( + person_rows, + SEED_PERSON_ROWS + N as u64, + "expected {} seeded + {} concurrent inserts = {} Person rows; got {}", + SEED_PERSON_ROWS, + N, + SEED_PERSON_ROWS + N as u64, + person_rows, + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn change_concurrent_updates_same_key_serialize_via_publisher_cas() { + // Pin Update RYW semantics under in-process concurrency on the same + // `(table, branch)`. With per-table queue serialization and op-kind-aware + // drift detection at commit time, exactly one of N concurrent UPDATEs + // on the same row commits; the rest are rejected as 409 manifest_conflict. + // + // Pre-fix bug class: in `MutationStaging::commit_all`, after queue + // acquisition, the staged Lance transaction is handed straight to + // `commit_staged`. For a writer whose staged dataset is at V0 but + // Lance HEAD has advanced to V1 (because the queue's prior winner + // already published), Lance's transaction conflict resolver fires + // `RetryableCommitConflict` on Update vs Update on the same row. + // That error gets wrapped as `OmniError::Lance()` and the + // API surfaces it as **500 internal**, not 409. Users see "internal + // server error" instead of a retryable conflict, breaking the + // documented 409 contract for in-process drift. + // + // Post-fix invariant: `commit_all` does an op-kind-aware drift check + // before each `commit_staged`. For tables whose tracked op_kind has + // `strict_pre_stage_version_check() == true` (Update / Delete / + // SchemaRewrite), if the staged dataset's version doesn't match the + // fresh manifest pin, return `OmniError::manifest_expected_version_mismatch` + // β†’ 409 ExpectedVersionMismatch. The N-1 losers see a clean 409 + // before Lance's commit_staged ever runs. + // + // Why correct-by-design: closing the class "Lance internal conflict + // surfaces as 500 instead of 409" rather than mapping the specific + // 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_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); + + // Spawn N=8 concurrent UPDATEs on Alice (from test.jsonl, age=30 at V0) + // writing distinct ages. + const N: usize = 8; + let mut handles = Vec::with_capacity(N); + for i in 0..N { + let app = app.clone(); + let target_age = 100 + i as i32; + handles.push(tokio::spawn(async move { + let body = serde_json::to_vec(&ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("set_age".to_string()), + params: Some(json!({ "name": "Alice", "age": target_age })), + branch: Some("main".to_string()), + }) + .unwrap(); + let req = Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(); + let response = app.oneshot(req).await.unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + (status, body.to_vec()) + })); + } + + let mut results = Vec::with_capacity(N); + for h in handles { + results.push(h.await.unwrap()); + } + let statuses: Vec = results.iter().map(|(s, _)| *s).collect(); + + let ok_count = statuses.iter().filter(|s| **s == StatusCode::OK).count(); + let conflict_count = statuses + .iter() + .filter(|s| **s == StatusCode::CONFLICT) + .count(); + let other: Vec<_> = statuses + .iter() + .enumerate() + .filter(|(_, s)| **s != StatusCode::OK && **s != StatusCode::CONFLICT) + .collect(); + + let other_bodies: Vec<(usize, StatusCode, String)> = other + .iter() + .map(|(i, s)| { + let body_str = String::from_utf8_lossy(&results[*i].1).to_string(); + (*i, **s, body_str) + }) + .collect(); + assert!( + other.is_empty(), + "expected only 200 or 409 statuses, got non-200/409 entries: {:?}", + other_bodies + ); + assert_eq!( + ok_count + conflict_count, + N, + "all responses must be 200 or 409 to satisfy the RYW invariant; statuses: {:?}", + statuses + ); + assert_eq!( + 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. \ + Pre-fix symptom: 1 OK + (N-1) x 500 because Lance's RetryableCommitConflict for \ + Update vs Update on the same row bubbles up as `OmniError::Lance()` and \ + the API maps it to 500 internal, not 409. Statuses: {:?}", + ok_count, + conflict_count, + statuses.len() - ok_count - conflict_count, + statuses, + ); +} + +// ───────────────────────────────────────────────────────────────────────── +// Branch-ops morphological matrix +// +// Table-driven test covering all interesting (op_a, op_b, target_overlap) +// concurrent-pair cells with the C1-C6 invariants asserted uniformly: +// +// C1 β€” both complete (no deadlock, no hang) +// C2 β€” status: both 200, or exactly one clean conflict (409/429), no 500 +// C3 β€” per-target row count +// C4 β€” per-target row identity (present + absent named persons) +// C5 β€” engine state remains coherent (subsequent /snapshot is consistent) +// C6 β€” post-op /change on main succeeds (engine state isn't poisoned) +// +// Cell list (a-k) below. Each cell uses a fresh tempdir + AppState so a +// failure in one doesn't leak into the next. Within a cell, ops align at +// a tokio::sync::Barrier so both reach the engine close in time, and the +// pair is wrapped in tokio::time::timeout(15s) so a deadlock surfaces +// as a clean panic. +// +// Replaces the three narrow concurrent_branch_* tests below; their +// scenarios are folded into cells f, h, i (branch_create_from race), +// cell a (merge race with C4 identity assertions), and cell d +// (concurrent change-during-merge). +// ───────────────────────────────────────────────────────────────────────── + +mod matrix { + use super::*; + use std::time::Duration; + use tokio::sync::Barrier; + + #[derive(Debug)] + pub(super) struct OpStatus { + pub status: StatusCode, + pub body: Vec, + } + + pub(super) struct Harness { + pub _temp: tempfile::TempDir, + pub app: Router, + } + + impl Harness { + pub async fn new() -> Self { + 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 + // (`ingest_per_actor_admission_cap_returns_429`) sets + // OMNIGRAPH_PER_ACTOR_INFLIGHT_MAX=1 inside an EnvGuard while + // it runs. Process-wide env vars are visible to + // concurrently-running tests; if a matrix cell reads env at + // AppState construction time during that window it picks up + // cap=1 and the second concurrent merge in cell b surfaces + // 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(graph.to_str().unwrap()).await.unwrap(); + let workload = omnigraph_server::workload::WorkloadController::with_defaults(); + let state = AppState::new_with_workload( + graph.to_string_lossy().to_string(), + db, + Vec::new(), + workload, + ); + let app = build_app(state); + Self { _temp: temp, app } + } + + pub async fn create_branch(&self, from: &str, name: &str) { + let body = serde_json::to_vec(&BranchCreateRequest { + from: Some(from.to_string()), + name: name.to_string(), + }) + .unwrap(); + let r = self + .app + .clone() + .oneshot( + Request::builder() + .uri("/branches") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + r.status(), + StatusCode::OK, + "setup create_branch {} from {} failed", + name, + from + ); + } + + pub async fn insert_person(&self, branch: &str, name: &str, age: i32) { + let body = serde_json::to_vec(&ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": name, "age": age })), + branch: Some(branch.to_string()), + }) + .unwrap(); + let r = self + .app + .clone() + .oneshot( + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + r.status(), + StatusCode::OK, + "setup insert {} on {} failed", + name, + branch + ); + } + + /// Run two ops concurrently with barrier alignment + 15s deadlock + /// timeout. Returns `(op_a, op_b)`. Panics on timeout. + pub async fn run_pair( + &self, + op_a: impl FnOnce(Router, Arc) -> tokio::task::JoinHandle, + op_b: impl FnOnce(Router, Arc) -> tokio::task::JoinHandle, + ) -> (OpStatus, OpStatus) { + let barrier = Arc::new(Barrier::new(2)); + let h_a = op_a(self.app.clone(), Arc::clone(&barrier)); + let h_b = op_b(self.app.clone(), Arc::clone(&barrier)); + let result = tokio::time::timeout(Duration::from_secs(15), async { + let a = h_a.await.unwrap(); + let b = h_b.await.unwrap(); + (a, b) + }) + .await; + result.expect("concurrent op pair deadlocked (>15s)") + } + + pub async fn person_count(&self, branch: &str) -> u64 { + let r = self + .app + .clone() + .oneshot( + Request::builder() + .uri(format!("/snapshot?branch={}", branch)) + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + 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"] + .as_array() + .and_then(|tables| { + tables + .iter() + .find(|t| t["table_key"].as_str() == Some("node:Person")) + }) + .and_then(|t| t["row_count"].as_u64()) + .unwrap_or_else(|| panic!("snapshot {} missing node:Person", branch)) + } + + /// True iff the named Person exists on `branch`. Uses the + /// `get_person` query from `test.gq` for identity rather than + /// 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_name: Some("get_person".to_string()), + params: Some(json!({ "name": name })), + branch: Some(branch.to_string()), + snapshot: None, + }) + .unwrap(); + let r = self + .app + .clone() + .oneshot( + Request::builder() + .uri("/read") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + r.status(), + StatusCode::OK, + "person_exists query for {} on {} failed", + name, + branch + ); + let body = to_bytes(r.into_body(), usize::MAX).await.unwrap(); + let v: Value = serde_json::from_slice(&body).unwrap(); + v["row_count"].as_u64().unwrap_or(0) > 0 + } + + /// Asserts each name in `present` exists on `branch` and each in + /// `absent` does not. Identity-grade check that catches symmetric + /// swap races a row-count assertion would miss. + pub async fn assert_persons( + &self, + branch: &str, + cell: &str, + present: &[&str], + absent: &[&str], + ) { + for name in present { + assert!( + self.person_exists(branch, name).await, + "[{}] expected {} to be present on {}", + cell, + name, + branch + ); + } + for name in absent { + assert!( + !self.person_exists(branch, name).await, + "[{}] expected {} to be absent from {}", + cell, + name, + branch + ); + } + } + + /// C6: insert a uniquely-named sentinel on main and verify it + /// landed. Catches engine-state poisoning where a cell's + /// concurrent ops left the engine half-broken β€” subsequent + /// /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: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": sentinel, "age": 99 })), + branch: Some("main".to_string()), + }) + .unwrap(); + let r = self + .app + .clone() + .oneshot( + Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + r.status(), + StatusCode::OK, + "[{}] post-op sentinel /change on main failed (engine poisoned?)", + cell + ); + assert!( + self.person_exists("main", sentinel).await, + "[{}] sentinel {} did not land on main", + cell, + sentinel + ); + } + } + + // Helpers that build the closures for `run_pair`. Each takes a + // Router + Barrier and returns a JoinHandle yielding the status/body. + + pub(super) fn op_merge( + source: String, + target: String, + ) -> impl FnOnce(Router, Arc) -> tokio::task::JoinHandle { + move |app: Router, barrier: Arc| { + tokio::spawn(async move { + barrier.wait().await; + let body = serde_json::to_vec(&BranchMergeRequest { + source, + target: Some(target), + }) + .unwrap(); + let response = app + .oneshot( + Request::builder() + .uri("/branches/merge") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + OpStatus { + status, + body: body.to_vec(), + } + }) + } + } + + pub(super) fn op_change_insert( + branch: String, + name: String, + age: i32, + ) -> impl FnOnce(Router, Arc) -> tokio::task::JoinHandle { + move |app: Router, barrier: Arc| { + tokio::spawn(async move { + barrier.wait().await; + let body = serde_json::to_vec(&ChangeRequest { + 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(), + ) + .await + .unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + OpStatus { + status, + body: body.to_vec(), + } + }) + } + } + + pub(super) fn op_branch_create( + from: String, + name: String, + ) -> impl FnOnce(Router, Arc) -> tokio::task::JoinHandle { + move |app: Router, barrier: Arc| { + tokio::spawn(async move { + barrier.wait().await; + let body = serde_json::to_vec(&BranchCreateRequest { + from: Some(from), + name, + }) + .unwrap(); + let response = app + .oneshot( + Request::builder() + .uri("/branches") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + OpStatus { + status, + body: body.to_vec(), + } + }) + } + } + + pub(super) fn op_branch_delete( + name: String, + ) -> impl FnOnce(Router, Arc) -> tokio::task::JoinHandle { + move |app: Router, barrier: Arc| { + tokio::spawn(async move { + barrier.wait().await; + let response = app + .oneshot( + Request::builder() + .uri(format!("/branches/{}", name)) + .method(Method::DELETE) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + OpStatus { + status, + body: body.to_vec(), + } + }) + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn concurrent_branch_ops_morphological_matrix() { + // Cell a: Merge Γ— Merge, distinct targets. + // Pre-fix on b09a097/22d76db: branch_merge_impl's swap-restore race + // landed feature_a's content in target_b instead of target_a (and + // vice versa β€” symmetric swap). Identity asserts catch both + // asymmetric and symmetric variants. + { + let cell = "a:mergeΓ—merge:distinct-targets"; + let h = matrix::Harness::new().await; + h.create_branch("main", "feature-a-cella").await; + h.insert_person("feature-a-cella", "EveA-cella", 22).await; + h.create_branch("main", "feature-b-cella").await; + h.insert_person("feature-b-cella", "FrankB-cella", 33).await; + h.create_branch("main", "target-a-cella").await; + h.create_branch("main", "target-b-cella").await; + + 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()), + ) + .await; + assert_eq!(sa.status, StatusCode::OK, "[{}] merge a", cell); + assert_eq!(sb.status, StatusCode::OK, "[{}] merge b", cell); + h.assert_persons("target-a-cella", cell, &["EveA-cella"], &["FrankB-cella"]) + .await; + h.assert_persons("target-b-cella", cell, &["FrankB-cella"], &["EveA-cella"]) + .await; + h.assert_post_op_sentinel(cell, "sentinel-cella").await; + } + + // Cell b: Merge Γ— Merge, same target / distinct sources. + // Both want to land in main. merge_exclusive serializes; both should + // succeed and main should contain BOTH sources' contributions. + { + let cell = "b:mergeΓ—merge:same-target-distinct-sources"; + let h = matrix::Harness::new().await; + h.create_branch("main", "src-x-cellb").await; + h.insert_person("src-x-cellb", "Xavier-cellb", 41).await; + h.create_branch("main", "src-y-cellb").await; + h.insert_person("src-y-cellb", "Yvonne-cellb", 42).await; + + let (sa, sb) = h + .run_pair( + matrix::op_merge("src-x-cellb".to_string(), "main".to_string()), + matrix::op_merge("src-y-cellb".to_string(), "main".to_string()), + ) + .await; + assert_eq!(sa.status, StatusCode::OK, "[{}] merge x", cell); + assert_eq!(sb.status, StatusCode::OK, "[{}] merge y", cell); + h.assert_persons("main", cell, &["Xavier-cellb", "Yvonne-cellb"], &[]) + .await; + h.assert_post_op_sentinel(cell, "sentinel-cellb").await; + } + + // Cell c: Merge Γ— Merge, same source / distinct targets (fanout). + // One source merged into two targets simultaneously. merge_exclusive + // serializes; both targets should reflect the source's content. + { + 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.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()), + ) + .await; + assert_eq!(sa.status, StatusCode::OK, "[{}] merge into tgt-1", cell); + assert_eq!(sb.status, StatusCode::OK, "[{}] merge into tgt-2", cell); + h.assert_persons("tgt-1-cellc", cell, &["Sharon-cellc"], &[]) + .await; + h.assert_persons("tgt-2-cellc", cell, &["Sharon-cellc"], &[]) + .await; + h.assert_post_op_sentinel(cell, "sentinel-cellc").await; + } + + // Cell d: Merge Γ— Change, both touching main. C2 permits both + // succeed, or exactly one clean 409 if the merge detects target + // movement after planning but before acquiring the queue. + { + let cell = "d:mergeΓ—change:into-target"; + let h = matrix::Harness::new().await; + h.create_branch("main", "feature-celld").await; + h.insert_person("feature-celld", "EveD-celld", 22).await; + + let (sa, sb) = h + .run_pair( + matrix::op_merge("feature-celld".to_string(), "main".to_string()), + matrix::op_change_insert("main".to_string(), "FrankD-celld".to_string(), 33), + ) + .await; + assert_eq!(sb.status, StatusCode::OK, "[{}] change", cell); + assert!( + sa.status == StatusCode::OK || sa.status == StatusCode::CONFLICT, + "[{}] merge must be 200 or clean 409, got {}", + cell, + sa.status + ); + if sa.status == StatusCode::OK { + h.assert_persons("main", cell, &["EveD-celld", "FrankD-celld"], &[]) + .await; + } else { + let error: ErrorOutput = serde_json::from_slice(&sa.body).unwrap(); + let conflict = error + .manifest_conflict + .expect("merge 409 must include manifest_conflict"); + assert_eq!( + conflict.table_key, "node:Person", + "[{}] conflict table", + cell + ); + h.assert_persons("main", cell, &["FrankD-celld"], &["EveD-celld"]) + .await; + } + h.assert_post_op_sentinel(cell, "sentinel-celld").await; + } + + // Cell e: Merge Γ— BranchCreateFrom-target. Concurrent fork off the + // merge target while the merge runs. Both should succeed; the new + // branch should have a coherent view (either pre- or post-merge, + // both valid). After both, target = main has the merged content. + { + let cell = "e:mergeΓ—branch_create_from:target"; + let h = matrix::Harness::new().await; + h.create_branch("main", "src-celle").await; + h.insert_person("src-celle", "Eve-celle", 22).await; + + let (sa, sb) = h + .run_pair( + matrix::op_merge("src-celle".to_string(), "main".to_string()), + matrix::op_branch_create("main".to_string(), "fork-celle".to_string()), + ) + .await; + assert_eq!(sa.status, StatusCode::OK, "[{}] merge", cell); + assert_eq!(sb.status, StatusCode::OK, "[{}] branch_create_from", cell); + // Main definitely has Eve. + h.assert_persons("main", cell, &["Eve-celle"], &[]).await; + // fork-celle was forked off main at SOME version; main's current + // count is 5 (4 seeded + Eve). fork-celle has either 4 (pre-merge + // snapshot) or 5 (post-merge snapshot); both are valid timings. + let fork_count = h.person_count("fork-celle").await; + assert!( + fork_count == 4 || fork_count == 5, + "[{}] fork-celle row count must be pre- or post-merge view (4 or 5), got {}", + cell, + fork_count + ); + h.assert_post_op_sentinel(cell, "sentinel-celle").await; + } + + // Cell f: BranchCreateFrom Γ— BranchCreateFrom, distinct parents. + // Pre-fix on f925ad1: swap-restore race in branch_create_from_impl + // forked the new branch off the wrong parent. Identity asserts pin + // that fork-from-A inherits A's content, fork-from-B inherits B's. + { + let cell = "f:branch_create_fromΓ—branch_create_from:distinct-parents"; + let h = matrix::Harness::new().await; + h.create_branch("main", "alpha-cellf").await; + h.insert_person("alpha-cellf", "Eve-cellf", 22).await; + h.create_branch("main", "beta-cellf").await; + + 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()), + ) + .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; + // delta forks off beta β†’ must NOT contain Eve. + h.assert_persons("delta-cellf", cell, &[], &["Eve-cellf"]) + .await; + h.assert_post_op_sentinel(cell, "sentinel-cellf").await; + } + + // Cell g: BranchCreateFrom Γ— BranchDelete, unrelated branches. + // Disjoint branches; both should complete cleanly without + // interference. + { + let cell = "g:branch_create_fromΓ—branch_delete:unrelated"; + let h = matrix::Harness::new().await; + h.create_branch("main", "doomed-cellg").await; + + let (sa, sb) = h + .run_pair( + matrix::op_branch_create("main".to_string(), "newborn-cellg".to_string()), + matrix::op_branch_delete("doomed-cellg".to_string()), + ) + .await; + 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_post_op_sentinel(cell, "sentinel-cellg").await; + } + + // Cell h: BranchDelete Γ— BranchDelete, distinct branches. Both call + // refresh() internally; verify no deadlock and both deletes land. + { + let cell = "h:branch_deleteΓ—branch_delete:distinct"; + let h = matrix::Harness::new().await; + h.create_branch("main", "doomed1-cellh").await; + h.create_branch("main", "doomed2-cellh").await; + + let (sa, sb) = h + .run_pair( + matrix::op_branch_delete("doomed1-cellh".to_string()), + matrix::op_branch_delete("doomed2-cellh".to_string()), + ) + .await; + assert_eq!(sa.status, StatusCode::OK, "[{}] delete 1", cell); + assert_eq!(sb.status, StatusCode::OK, "[{}] delete 2", cell); + // Verify both gone via /branches list (snapshot would still work + // for a deleted branch via parent fallback in some paths, so we + // use the explicit list). + let r = h + .app + .clone() + .oneshot( + Request::builder() + .uri("/branches") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::OK); + let body = to_bytes(r.into_body(), usize::MAX).await.unwrap(); + let list_body: Value = serde_json::from_slice(&body).unwrap(); + let branches: Vec<&str> = list_body["branches"] + .as_array() + .unwrap() + .iter() + .filter_map(|v| v.as_str()) + .collect(); + assert!( + !branches.contains(&"doomed1-cellh"), + "[{}] doomed1 still in branch list: {:?}", + cell, + branches + ); + assert!( + !branches.contains(&"doomed2-cellh"), + "[{}] doomed2 still in branch list: {:?}", + cell, + branches + ); + h.assert_post_op_sentinel(cell, "sentinel-cellh").await; + } + + // Cell i: BranchDelete Γ— Change, on a different branch. Delete one + // branch while a /change runs on main. Both should succeed. + { + let cell = "i:branch_deleteΓ—change:distinct-branch"; + let h = matrix::Harness::new().await; + h.create_branch("main", "doomed-celli").await; + + let (sa, sb) = h + .run_pair( + matrix::op_branch_delete("doomed-celli".to_string()), + matrix::op_change_insert("main".to_string(), "Pat-celli".to_string(), 44), + ) + .await; + assert_eq!(sa.status, StatusCode::OK, "[{}] delete", cell); + assert_eq!(sb.status, StatusCode::OK, "[{}] change", cell); + h.assert_persons("main", cell, &["Pat-celli"], &[]).await; + h.assert_post_op_sentinel(cell, "sentinel-celli").await; + } + + // Cell j: BranchCreateFrom Γ— Change, both on main. The fork timing + // determines whether the new branch sees the change (pre or post). + // Both valid. Main must contain the inserted row. + { + let cell = "j:branch_create_fromΓ—change:on-source"; + let h = matrix::Harness::new().await; + + let (sa, sb) = h + .run_pair( + matrix::op_branch_create("main".to_string(), "twin-cellj".to_string()), + matrix::op_change_insert("main".to_string(), "Quincy-cellj".to_string(), 55), + ) + .await; + assert_eq!(sa.status, StatusCode::OK, "[{}] branch_create", cell); + assert_eq!(sb.status, StatusCode::OK, "[{}] change", cell); + h.assert_persons("main", cell, &["Quincy-cellj"], &[]).await; + // twin-cellj has either pre-change view (no Quincy) or + // post-change view (with Quincy); either is valid. + let twin_has_quincy = h.person_exists("twin-cellj", "Quincy-cellj").await; + let _ = twin_has_quincy; // either valid timing β€” just ensure no panic + h.assert_post_op_sentinel(cell, "sentinel-cellj").await; + } + + // Cell k: reopen consistency. Run a representative concurrent pair, + // drop the engine, reopen on a separate handle, verify state matches. + { + let cell = "k:reopen-after-pair"; + let h = matrix::Harness::new().await; + h.create_branch("main", "src-cellk").await; + h.insert_person("src-cellk", "Rita-cellk", 36).await; + + let (sa, sb) = h + .run_pair( + matrix::op_merge("src-cellk".to_string(), "main".to_string()), + matrix::op_change_insert("main".to_string(), "Steve-cellk".to_string(), 37), + ) + .await; + assert_eq!(sb.status, StatusCode::OK, "[{}] change", cell); + assert!( + sa.status == StatusCode::OK || sa.status == StatusCode::CONFLICT, + "[{}] merge must be 200 or clean 409, got {}", + cell, + sa.status + ); + if sa.status == StatusCode::OK { + h.assert_persons("main", cell, &["Rita-cellk", "Steve-cellk"], &[]) + .await; + } else { + let error: ErrorOutput = serde_json::from_slice(&sa.body).unwrap(); + let conflict = error + .manifest_conflict + .expect("merge 409 must include manifest_conflict"); + 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 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. + let r = app2 + .clone() + .oneshot( + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::OK, "[{}] reopen snapshot", cell); + let body = to_bytes(r.into_body(), usize::MAX).await.unwrap(); + let v: Value = serde_json::from_slice(&body).unwrap(); + let person_rows = v["tables"] + .as_array() + .and_then(|tables| { + tables + .iter() + .find(|t| t["table_key"].as_str() == Some("node:Person")) + }) + .and_then(|t| t["row_count"].as_u64()) + .expect("reopen snapshot must include node:Person row_count"); + let expected_rows = if sa.status == StatusCode::OK { 6 } else { 5 }; + assert_eq!( + person_rows, expected_rows, + "[{}] reopened main should include seed (4) + committed concurrent writes", + cell, + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn change_disjoint_table_concurrency_succeeds_at_http_level() { + // HTTP-level pin for MR-686's disjoint-table promise: concurrent /change + // requests touching different node types must coexist without admission + // rejection or publisher-CAS conflict. The bench harness measures + // throughput; this test is the regression sentinel that catches a + // future change which accidentally re-introduces graph-wide + // serialization on the disjoint path. + // + // Setup: test.jsonl seeds 4 Persons + 2 Companies. Spawn N=4 concurrent + // /change inserts on `node:Person` and N=4 concurrent inserts on + // `node:Company`. All 8 must return 200, and the post-test row counts + // must reflect every insert. + const PERSON_QUERY: &str = r#" +query insert_p($name: String, $age: I32) { + insert Person { name: $name, age: $age } +} +"#; + const COMPANY_QUERY: &str = r#" +query insert_c($name: String) { + insert Company { name: $name } +} +"#; + const SEED_PERSONS: u64 = 4; + const SEED_COMPANIES: u64 = 2; + const PER_TYPE: usize = 4; + + 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 mut handles = Vec::with_capacity(PER_TYPE * 2); + for i in 0..PER_TYPE { + let app_p = app.clone(); + handles.push(tokio::spawn(async move { + let body = serde_json::to_vec(&ChangeRequest { + 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()), + }) + .unwrap(); + let req = Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(); + app_p.oneshot(req).await.unwrap().status() + })); + let app_c = app.clone(); + handles.push(tokio::spawn(async move { + let body = serde_json::to_vec(&ChangeRequest { + query: COMPANY_QUERY.to_string(), + name: Some("insert_c".to_string()), + params: Some(json!({ "name": format!("c-{i}") })), + branch: Some("main".to_string()), + }) + .unwrap(); + let req = Request::builder() + .uri("/change") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(); + app_c.oneshot(req).await.unwrap().status() + })); + } + + let mut statuses = Vec::with_capacity(PER_TYPE * 2); + for h in handles { + statuses.push(h.await.unwrap()); + } + + let bad: Vec<_> = statuses + .iter() + .enumerate() + .filter(|(_, s)| **s != StatusCode::OK) + .collect(); + assert!( + bad.is_empty(), + "expected every disjoint /change insert to return 200, got non-200 for: {:?}", + bad, + ); + + // Verify both tables landed every insert. + let (status, body) = json_response( + &app, + Request::builder() + .uri("/snapshot?branch=main") + .method(Method::GET) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + 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(|t| t["row_count"].as_u64()) + .unwrap_or_else(|| panic!("snapshot missing {}", table_key)) + }; + assert_eq!( + lookup_count("node:Person"), + SEED_PERSONS + PER_TYPE as u64, + "Person row count after concurrent inserts", + ); + assert_eq!( + lookup_count("node:Company"), + SEED_COMPANIES + PER_TYPE as u64, + "Company row count after concurrent inserts", + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn ingest_per_actor_admission_cap_returns_429() { + // Pin the admission gate on `/ingest`. With per-actor in-flight cap of 1 + // and 8 concurrent requests from the same actor, at least one request + // must be rejected with HTTP 429 and `code: too_many_requests`. + // + // Pre-fix bug class: the admission pattern at `server_change` + // (`crates/omnigraph-server/src/lib.rs:932`) was the only handler + // that called `WorkloadController::try_admit`. A heavy actor sending + // bulk-ingest traffic would exhaust shared engine capacity (Lance I/O + // threads, manifest churn) without ever hitting an admission cap. + // Pinned at the HTTP boundary so future refactors that drop the + // try_admit call from a mutating handler turn this red. + // + // Post-fix invariant: `/ingest`, `/branches/create`, `/branches/delete`, + // `/branches/merge`, and `/schema/apply` all gate on + // `state.workload.try_admit(&actor_arc, est_bytes)` after Cedar + // authorization and before the engine call. Cap exhaustion surfaces as + // 429 with `code: too_many_requests`. + // + // Construct the WorkloadController directly with cap=1 instead of + // mutating `OMNIGRAPH_PER_ACTOR_INFLIGHT_MAX` via EnvGuard. Process-wide + // env vars are visible to concurrently-running tests; the previous + // `EnvGuard + #[serial]` pair leaked the override into any other test + // that called `AppState::open` during the guard's window + // (matrix CI failure on commit 99b0941). Using the explicit + // `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_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 + ); + // MR-723: install a permit-all policy alongside the bearer token so + // /ingest (action=Change) passes Cedar evaluation. The test is + // exercising the admission cap, not policy β€” the policy is just + // 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_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, + ); + let app = build_app(state); + let _temp = temp; + + // Eight concurrent ingests, all from act-flooder. Only one fits in a + // cap=1 in-flight semaphore; the others must 429. + const N: usize = 8; + let barrier = Arc::new(tokio::sync::Barrier::new(N)); + let mut handles = Vec::with_capacity(N); + for i in 0..N { + let app = app.clone(); + let barrier = Arc::clone(&barrier); + handles.push(tokio::spawn(async move { + // Align the 8 tasks at the barrier so they all attempt + // try_admit close in time. + barrier.wait().await; + + let body = serde_json::to_vec(&IngestRequest { + data: format!( + "{{\"type\":\"Person\",\"data\":{{\"name\":\"flooder-{i}\",\"age\":{i}}}}}\n" + ), + branch: Some("main".to_string()), + from: Some("main".to_string()), + mode: Some(omnigraph::loader::LoadMode::Merge), + }) + .unwrap(); + let req = Request::builder() + .uri("/ingest") + .method(Method::POST) + .header("authorization", "Bearer flooder-token") + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(); + let response = app.oneshot(req).await.unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + (status, headers, body.to_vec()) + })); + } + + let mut results = Vec::with_capacity(N); + for h in handles { + results.push(h.await.unwrap()); + } + let statuses: Vec = results.iter().map(|(s, _, _)| *s).collect(); + + let too_many: Vec = statuses + .iter() + .enumerate() + .filter(|(_, s)| **s == StatusCode::TOO_MANY_REQUESTS) + .map(|(i, _)| i) + .collect(); + assert!( + !too_many.is_empty(), + "expected at least one /ingest under cap=1 to return 429; got statuses: {:?}", + statuses, + ); + + // Validate the structured error body for each 429 (body must carry + // the `too_many_requests` code so clients can distinguish it from + // generic conflicts). + for i in &too_many { + let body_value: Value = serde_json::from_slice(&results[*i].2).unwrap(); + let error: ErrorOutput = serde_json::from_value(body_value).unwrap(); + assert_eq!( + error.code, + Some(omnigraph_server::api::ErrorCode::TooManyRequests), + "429 body must carry code=too_many_requests; idx {} got {:?}", + i, + error.code, + ); + } + + // Validate the `Retry-After` header is set on every 429. Pinned by + // the same test so a future refactor that drops the header from + // `IntoResponse for ApiError` turns this red. The constant + // matches `crates/omnigraph-server/src/lib.rs::ApiError::into_response`. + for i in &too_many { + let retry_after = results[*i] + .1 + .get(axum::http::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + assert!( + retry_after.is_some(), + "429 response must include a Retry-After header; idx {} headers were: {:?}", + i, + results[*i].1, + ); + } +} + +/// 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_graph().await; + let oversized = "x".repeat(1_100_000); + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/read") + .method(Method::POST) + .header("content-type", "application/json") + .body(Body::from(oversized)) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); +} + +// ─── MR-723 default-deny mode (State 2: tokens without policy) ────────── +// +// `authorize_request` returns 403 for every action except `Read` when a +// PolicyEngine is not installed but bearer tokens are configured. Pinned +// by the three tests below β€” Read allowed, Change/SchemaApply denied β€” +// to prevent regressing back to the pre-MR-723 "tokens configured but +// no policy = fully open" trap. + +#[tokio::test(flavor = "multi_thread")] +async fn default_deny_mode_allows_read_for_authenticated_actor() { + let (_temp, app) = app_for_graph_with_auth_tokens_only( + &fs::read_to_string(fixture("test.pg")).unwrap(), + &[("act-andrew", "demo-token")], + ) + .await; + + let (status, _body) = json_response( + &app, + Request::builder() + .uri("/snapshot") + .method(Method::GET) + .header(AUTHORIZATION, "Bearer demo-token") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); +} + +#[tokio::test(flavor = "multi_thread")] +async fn default_deny_mode_rejects_change_with_forbidden() { + 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: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "DefaultDeny", "age": 1 })), + branch: Some("main".to_string()), + }; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header(AUTHORIZATION, "Bearer demo-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&change).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + let error: ErrorOutput = serde_json::from_value(body).unwrap(); + assert!( + error.error.contains("default-deny"), + "expected default-deny in error message, got: {}", + error.error + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn default_deny_mode_rejects_schema_apply_with_forbidden() { + let (_temp, app) = app_for_graph_with_auth_tokens_only( + &fs::read_to_string(fixture("test.pg")).unwrap(), + &[("act-andrew", "demo-token")], + ) + .await; + + let req = SchemaApplyRequest { + schema_source: additive_schema_with_nickname(), + ..Default::default() + }; + let (status, body) = json_response( + &app, + Request::builder() + .uri("/schema/apply") + .method(Method::POST) + .header(AUTHORIZATION, "Bearer demo-token") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&req).unwrap())) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + let error: ErrorOutput = serde_json::from_value(body).unwrap(); + assert!( + error.error.contains("default-deny"), + "expected default-deny in error message, got: {}", + error.error + ); +} + +// ─── SDK ↔ HTTP decision parity (MR-722 PR A) ───────────────────────────── +// +// Engine and HTTP both consult Cedar via `PolicyChecker::check()`; by +// construction they cannot disagree on a decision. These tests pin that +// property explicitly so a future refactor that introduces a separate +// auth path (or copy-pastes Cedar evaluation logic) turns red. +// +// Four cases cover the per-action scope shapes: +// * Change on a protected branch via `mutate_as` / POST /change +// * Change with an actor that has no permit +// * BranchMerge to a protected target via `branch_merge_as` / POST /branches/merge +// * BranchMerge with an actor that has no permit + +const PARITY_POLICY_YAML: &str = r#" +version: 1 +groups: + team: [act-bruno] + admins: [act-ragnor] +protected_branches: [main] +rules: + - id: admins-change-anywhere + allow: + actors: { group: admins } + actions: [change] + branch_scope: any + - id: admins-merge-to-protected + allow: + actors: { group: admins } + actions: [branch_merge] + target_branch_scope: protected +"#; + +#[derive(Clone, Copy, Debug)] +enum ParityDecision { + Allow, + Deny, +} + +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(graph.to_str().unwrap()).await.unwrap(); + db.branch_create_from(ReadTarget::branch("main"), "feature") + .await + .unwrap(); + db.load_as( + "feature", + r#"{"type":"Person","data":{"name":"ParityEve","age":29}}"#, + LoadMode::Append, + None, + ) + .await + .unwrap(); + } + let policy_path = temp.path().join("policy.yaml"); + fs::write(&policy_path, PARITY_POLICY_YAML).unwrap(); + (temp, graph, policy_path) +} + +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); + let mut params: omnigraph_compiler::ParamMap = Default::default(); + // Parameter keys are bare names (no `$` prefix); the runtime resolves + // `$name` references in the query body to `params["name"]`. + params.insert( + "name".to_string(), + omnigraph_compiler::Literal::String("ParityCharlie".to_string()), + ); + params.insert("age".to_string(), omnigraph_compiler::Literal::Integer(30)); + let result = db + .mutate_as( + "main", + MUTATION_QUERIES, + "insert_person", + ¶ms, + Some(actor), + ) + .await; + match result { + Ok(_) => ParityDecision::Allow, + Err(OmniError::Policy(_)) => ParityDecision::Deny, + Err(other) => panic!("unexpected SDK error for change: {other:?}"), + } +} + +async fn http_change_decision( + graph: &Path, + policy_path: &PathBuf, + actor: &str, + token: &str, +) -> ParityDecision { + let state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + vec![(actor.to_string(), token.to_string())], + Some(policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + let req = ChangeRequest { + query: MUTATION_QUERIES.to_string(), + name: Some("insert_person".to_string()), + params: Some(json!({ "name": "ParityCharlie", "age": 30 })), + branch: Some("main".to_string()), + }; + let (status, _body) = json_response( + &app, + Request::builder() + .uri("/change") + .method(Method::POST) + .header(AUTHORIZATION, format!("Bearer {token}")) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&req).unwrap())) + .unwrap(), + ) + .await; + match status { + StatusCode::OK => ParityDecision::Allow, + StatusCode::FORBIDDEN => ParityDecision::Deny, + other => panic!("unexpected HTTP status for change: {other}"), + } +} + +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); + let result = db.branch_merge_as("feature", "main", Some(actor)).await; + match result { + Ok(_) => ParityDecision::Allow, + Err(OmniError::Policy(_)) => ParityDecision::Deny, + Err(other) => panic!("unexpected SDK error for branch_merge: {other:?}"), + } +} + +async fn http_merge_decision( + graph: &Path, + policy_path: &PathBuf, + actor: &str, + token: &str, +) -> ParityDecision { + let state = AppState::open_with_bearer_tokens_and_policy( + graph.to_string_lossy().to_string(), + vec![(actor.to_string(), token.to_string())], + Some(policy_path), + ) + .await + .unwrap(); + let app = build_app(state); + let req = BranchMergeRequest { + source: "feature".to_string(), + target: Some("main".to_string()), + }; + let (status, _body) = json_response( + &app, + Request::builder() + .uri("/branches/merge") + .method(Method::POST) + .header(AUTHORIZATION, format!("Bearer {token}")) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&req).unwrap())) + .unwrap(), + ) + .await; + match status { + StatusCode::OK => ParityDecision::Allow, + StatusCode::FORBIDDEN => ParityDecision::Deny, + other => panic!("unexpected HTTP status for branch_merge: {other}"), + } +} + +#[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 graph + // because allowβ†’side-effects. + 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", + ); +} + +#[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 graph is reusable + // because denyβ†’no side-effects. + 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", + ); +} + +#[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 graph β€” + // a successful merge consumes the feature branch's commit on main. + 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", + ); +} + +#[tokio::test(flavor = "multi_thread")] +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, 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", + ); +} + +// ─── MR-694 PR B: HTTP soft + hard drop semantics + data preservation ──── +// +// SDK-level drop semantics are pinned in `crates/omnigraph/tests/schema_apply.rs`. +// These HTTP-side tests mirror the assertions through POST /schema/apply +// and exercise the new `allow_data_loss` field (closes the gap where +// the schema-lint chassis v1.2 shipped Hard mode on the CLI but the +// HTTP request struct had no equivalent field). + +#[tokio::test(flavor = "multi_thread")] +async fn schema_apply_route_soft_drops_property_via_http() { + 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 graph = graph_path(temp.path()); + { + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + db.load( + "main", + r#"{"type":"Person","data":{"name":"PreDrop","age":42}}"#, + LoadMode::Append, + ) + .await + .unwrap(); + } + let pre_version = manifest_dataset_version(&graph).await; + + let (status, payload) = json_response( + &app, + 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: schema_without_age(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(payload["applied"], true); + + // Catalog reflects the drop: `age` is gone from the live schema. + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + assert!( + !reopened.catalog().node_types["Person"] + .properties + .contains_key("age"), + "catalog should not contain `age` after drop" + ); + + // Soft drop preserves the prior version β€” `age` is still readable + // via time travel to the pre-drop manifest version. Mirrors the + // SDK-side assertion in `apply_schema_drops_a_nullable_property_softly_preserves_prior_version`. + let pre_drop_snapshot = reopened.snapshot_at_version(pre_version).await.unwrap(); + let pre_drop_ds = pre_drop_snapshot.open("node:Person").await.unwrap(); + let pre_drop_fields = pre_drop_ds + .schema() + .fields + .iter() + .map(|f| f.name.clone()) + .collect::>(); + assert!( + pre_drop_fields.iter().any(|f| f == "age"), + "soft drop should leave the pre-drop dataset's `age` column \ + time-travel-reachable; got fields {pre_drop_fields:?}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_apply_route_soft_drops_node_type_via_http() { + 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 graph = graph_path(temp.path()); + + let (status, payload) = json_response( + &app, + 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: schema_without_company(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(payload["applied"], true); + + 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" + ); + assert!( + !reopened.catalog().edge_types.contains_key("WorksAt"), + "catalog should not contain `WorksAt` after cascade" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_apply_route_hard_drops_property_with_allow_data_loss() { + 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 graph = graph_path(temp.path()); + { + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + db.load( + "main", + r#"{"type":"Person","data":{"name":"PreDropHard","age":50}}"#, + LoadMode::Append, + ) + .await + .unwrap(); + } + + // Apply with allow_data_loss=true β†’ Hard mode promotion. + let (status, payload) = json_response( + &app, + 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: schema_without_age(), + allow_data_loss: true, + }) + .unwrap(), + )) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(payload["applied"], true); + + // Catalog reflects the drop. + let reopened = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + assert!( + !reopened.catalog().node_types["Person"] + .properties + .contains_key("age"), + "catalog should not contain `age` after Hard drop" + ); + // Plan steps should show DropMode::Hard for property drops. + let steps = payload["steps"].as_array().expect("steps array"); + let drop_step = steps + .iter() + .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" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_apply_route_keeps_drops_soft_without_flag() { + // Symmetric to the Hard test: same schema change, but no + // 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_graph_with_auth_tokens_and_policy( + &fs::read_to_string(fixture("test.pg")).unwrap(), + &[("act-ragnor", "admin-token")], + SCHEMA_APPLY_POLICY_YAML, + ) + .await; + let graph = graph_path(temp.path()); + + let (status, payload) = json_response( + &app, + 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: schema_without_age(), + allow_data_loss: false, + }) + .unwrap(), + )) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(payload["applied"], true); + + let steps = payload["steps"].as_array().expect("steps array"); + let drop_step = steps + .iter() + .find(|s| s["kind"] == "drop_property") + .expect("plan should include drop_property step"); + let mode = &drop_step["mode"]; + assert_eq!(mode, "soft", "expected soft mode without allow_data_loss"); + let _ = graph; +} + +#[tokio::test(flavor = "multi_thread")] +async fn schema_apply_route_additive_property_preserves_existing_rows() { + // SDK suite covers rename and drop data preservation. Additive + // 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_graph_with_auth_tokens_and_policy( + &fs::read_to_string(fixture("test.pg")).unwrap(), + &[("act-ragnor", "admin-token")], + SCHEMA_APPLY_POLICY_YAML, + ) + .await; + let graph = graph_path(temp.path()); + + // Standard fixture data: 4 Persons + 1 Company. Load it. + let pre_count = { + let db = Omnigraph::open(graph.to_str().unwrap()).await.unwrap(); + db.load( + "main", + &fs::read_to_string(fixture("test.jsonl")).unwrap(), + LoadMode::Append, + ) + .await + .unwrap(); + let snap = db + .snapshot_of(omnigraph::db::ReadTarget::branch("main")) + .await + .unwrap(); + snap.entry("node:Person").expect("Person").row_count + }; + assert!(pre_count > 0, "fixture should have loaded Person rows"); + + let (status, payload) = json_response( + &app, + 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: additive_schema_with_nickname(), + ..Default::default() + }) + .unwrap(), + )) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(payload["applied"], true); + + // Row count preserved. + 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; + assert_eq!( + post_count, pre_count, + "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-server/tests/stored_queries.rs b/crates/omnigraph-server/tests/stored_queries.rs deleted file mode 100644 index e4da1d3..0000000 --- a/crates/omnigraph-server/tests/stored_queries.rs +++ /dev/null @@ -1,329 +0,0 @@ -//! Stored-query registry boot, /queries listing, and invocation routes. -//! Moved verbatim from tests/server.rs in the modularization. - - -use axum::body::Body; -use axum::http::StatusCode; -use omnigraph_server::AppState; -use serde_json::json; - - -mod support; -use support::*; - -#[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}" - ); -} - -#[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"); -} - -#[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" - ); -} diff --git a/crates/omnigraph-server/tests/support/mod.rs b/crates/omnigraph-server/tests/support/mod.rs deleted file mode 100644 index 0e32410..0000000 --- a/crates/omnigraph-server/tests/support/mod.rs +++ /dev/null @@ -1,1195 +0,0 @@ -//! Shared helpers for the server integration suites (moved verbatim -//! from the monolithic tests/server.rs in the modularization). -#![allow(dead_code)] - -use std::env; -use std::fs; -use std::path::{Path, PathBuf}; -use std::sync::Arc; - -use axum::Router; -use axum::body::{Body, to_bytes}; -use axum::http::header::AUTHORIZATION; -use axum::http::{Method, Request, StatusCode}; -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, ReadRequest, -}; -use omnigraph_server::queries::{QueryRegistry, RegistrySpec}; -use omnigraph_server::{AppState, build_app}; -use serde_json::{Value, json}; -use tower::ServiceExt; - - -pub const MUTATION_QUERIES: &str = r#" -query insert_person($name: String, $age: I32) { - insert Person { name: $name, age: $age } -} - -query set_age($name: String, $age: I32) { - update Person set { age: $age } where name = $name -} -"#; - -pub const POLICY_YAML: &str = r#" -version: 1 -groups: - team: [act-andrew, act-bruno, act-ragnor] - admins: [act-ragnor] -protected_branches: [main] -rules: - - id: team-read - allow: - actors: { group: team } - actions: [read] - branch_scope: any - - id: admins-export - allow: - actors: { group: admins } - actions: [export] - branch_scope: any - - id: team-write-unprotected - allow: - actors: { group: team } - actions: [change] - branch_scope: unprotected - - id: admins-merge - allow: - actors: { group: admins } - actions: [branch_delete, branch_merge] - target_branch_scope: protected -"#; - -pub const POLICY_PROTECTED_READ_YAML: &str = r#" -version: 1 -groups: - team: [act-bruno] -protected_branches: [main] -rules: - - id: protected-read - allow: - actors: { group: team } - actions: [read] - branch_scope: protected -"#; - -pub const INGEST_CREATE_ONLY_POLICY_YAML: &str = r#" -version: 1 -groups: - team: [act-bruno] -protected_branches: [main] -rules: - - id: team-branch-create - allow: - actors: { group: team } - actions: [branch_create] - target_branch_scope: unprotected -"#; - -pub const SCHEMA_APPLY_POLICY_YAML: &str = r#" -version: 1 -groups: - admins: [act-ragnor] -protected_branches: [main] -rules: - - id: admins-schema-apply - allow: - actors: { group: admins } - actions: [schema_apply] - target_branch_scope: protected -"#; - -pub fn fixture(name: &str) -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../omnigraph/tests/fixtures") - .join(name) -} - -pub 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 -} - -pub async fn init_graph_with_schema_and_data(schema: &str, data: &str) -> tempfile::TempDir { - let temp = tempfile::tempdir().unwrap(); - 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(graph.to_str().unwrap()).await.unwrap(); - load_jsonl(&mut db, data, LoadMode::Overwrite) - .await - .unwrap(); - temp -} - -pub async fn init_graph_with_schema(schema: &str) -> tempfile::TempDir { - let temp = tempfile::tempdir().unwrap(); - let graph = graph_path(temp.path()); - fs::create_dir_all(&graph).unwrap(); - Omnigraph::init(graph.to_str().unwrap(), schema) - .await - .unwrap(); - temp -} - -pub fn graph_path(root: &Path) -> PathBuf { - root.join("server.omni") -} - -pub 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") -} - -pub 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)) -} - -pub 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 -"#; - -pub 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 -"#; - -pub const FIND_PERSON_GQ: &str = - "query find_person($name: String) { match { $p: Person { name: $name } } return { $p.age } }"; - -pub 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() -} - -pub 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() -} - -pub fn get_request(uri: &str, token: &str) -> Request { - Request::builder() - .uri(uri) - .method(Method::GET) - .header("authorization", format!("Bearer {token}")) - .body(Body::empty()) - .unwrap() -} - -pub fn drifted_test_schema() -> String { - fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("age: I32?", "age: I64?") -} - -pub async fn manifest_dataset_version(graph: &Path) -> u64 { - Omnigraph::open(graph.to_string_lossy().as_ref()) - .await - .unwrap() - .snapshot_of(ReadTarget::branch("main")) - .await - .unwrap() - .version() -} - -pub 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() - .filter(|value| !value.trim().is_empty()) - .unwrap_or_else(|| "omnigraph-itests".to_string()); - let unique = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .ok()? - .as_nanos(); - Some(format!("s3://{}/{}/{}/{}", bucket, prefix, suite, unique)) -} - -pub 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)) -} - -pub fn permit_all_policy_yaml(actors: &[&str]) -> String { - let members = actors - .iter() - .map(|a| format!("\"{a}\"")) - .collect::>() - .join(", "); - format!( - r#" -version: 1 -groups: - permitted: [{members}] -protected_branches: [main] -rules: - - id: permit-data - allow: - actors: {{ group: permitted }} - actions: [read, change, export] - branch_scope: any - - id: permit-protected-target-actions - allow: - actors: {{ group: permitted }} - actions: [schema_apply, branch_create, branch_delete, branch_merge] - target_branch_scope: any -"# - ) -} - -pub 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_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( - graph.to_string_lossy().to_string(), - vec![("default".to_string(), token.to_string())], - Some(&policy_path), - ) - .await - .unwrap(); - (temp, build_app(state)) -} - -pub async fn app_for_loaded_graph_with_auth_tokens( - tokens: &[(&str, &str)], -) -> (tempfile::TempDir, Router) { - 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( - graph.to_string_lossy().to_string(), - tokens - .iter() - .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) - .collect(), - Some(&policy_path), - ) - .await - .unwrap(); - (temp, build_app(state)) -} - -pub async fn app_for_loaded_graph_with_auth_tokens_and_policy( - 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 state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - tokens - .iter() - .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) - .collect(), - Some(&policy_path), - ) - .await - .unwrap(); - (temp, build_app(state)) -} - -pub async fn app_for_graph_with_auth_tokens_and_policy( - schema: &str, - tokens: &[(&str, &str)], - policy: &str, -) -> (tempfile::TempDir, Router) { - 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( - graph.to_string_lossy().to_string(), - tokens - .iter() - .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) - .collect(), - Some(&policy_path), - ) - .await - .unwrap(); - (temp, build_app(state)) -} - -pub async fn app_for_graph_with_auth_tokens_only( - schema: &str, - tokens: &[(&str, &str)], -) -> (tempfile::TempDir, Router) { - let temp = init_graph_with_schema(schema).await; - let graph = graph_path(temp.path()); - let state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - tokens - .iter() - .map(|(actor, token)| ((*actor).to_string(), (*token).to_string())) - .collect(), - None, - ) - .await - .unwrap(); - (temp, build_app(state)) -} - -pub fn additive_schema_with_nickname() -> String { - fs::read_to_string(fixture("test.pg")).unwrap().replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ) -} - -pub fn schema_without_age() -> String { - // Drop the nullable `age` column from the test schema. Used by the - // HTTP soft/hard drop tests below. - fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace(" age: I32?\n", "") -} - -pub fn schema_without_company() -> String { - // Drop the `Company` node type and the edge referencing it. Used - // by the HTTP DropType test below. Hand-crafted (no template - // string replace) because the fixture interleaves the type and - // its edge. - r#"node Person { - name: String @key - age: I32? -} - -edge Knows: Person -> Person { - since: Date? -} -"# - .to_string() -} - -pub fn renamed_person_schema() -> String { - fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("node Person {\n", "node Human @rename_from(\"Person\") {\n") - .replace("edge Knows: Person -> Person", "edge Knows: Human -> Human") - .replace( - "edge WorksAt: Person -> Company", - "edge WorksAt: Human -> Company", - ) -} - -pub fn renamed_age_schema() -> String { - fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("age: I32?", "years: I32? @rename_from(\"age\")") -} - -pub fn indexed_name_schema() -> String { - fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("name: String @key", "name: String @key @index") -} - -pub fn unsupported_schema_change() -> String { - fs::read_to_string(fixture("test.pg")) - .unwrap() - .replace("age: I32?", "age: I64?") -} - -pub async fn json_response(app: &Router, request: Request) -> (StatusCode, Value) { - let response = app.clone().oneshot(request).await.unwrap(); - let status = response.status(); - let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - let value = serde_json::from_slice(&body).unwrap(); - (status, value) -} - -pub struct EnvGuard { - saved: Vec<(&'static str, Option)>, -} - -impl EnvGuard { - pub fn set(vars: &[(&'static str, Option<&str>)]) -> Self { - let saved = vars - .iter() - .map(|(name, _)| (*name, env::var(name).ok())) - .collect::>(); - for (name, value) in vars { - unsafe { - match value { - Some(value) => env::set_var(name, value), - None => env::remove_var(name), - } - } - } - Self { saved } - } -} - -impl Drop for EnvGuard { - fn drop(&mut self) { - for (name, value) in self.saved.drain(..) { - unsafe { - match value { - Some(value) => env::set_var(name, value), - None => env::remove_var(name), - } - } - } - } -} - -pub fn format_vector(values: &[f32]) -> String { - values - .iter() - .map(|value| format!("{:.8}", value)) - .collect::>() - .join(", ") -} - -pub fn normalize_vector(mut values: Vec) -> Vec { - let norm = values - .iter() - .map(|value| (*value as f64) * (*value as f64)) - .sum::() - .sqrt() as f32; - if norm > f32::EPSILON { - for value in &mut values { - *value /= norm; - } - } - values -} - -pub fn fnv1a64(bytes: &[u8]) -> u64 { - let mut hash = 14695981039346656037u64; - for byte in bytes { - hash ^= *byte as u64; - hash = hash.wrapping_mul(1099511628211u64); - } - hash -} - -pub fn xorshift64(mut x: u64) -> u64 { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x -} - -pub fn mock_embedding(input: &str, dim: usize) -> Vec { - let mut seed = fnv1a64(input.as_bytes()); - let mut out = Vec::with_capacity(dim); - for _ in 0..dim { - seed = xorshift64(seed); - let ratio = (seed as f64 / u64::MAX as f64) as f32; - out.push((ratio * 2.0) - 1.0); - } - normalize_vector(out) -} - -pub mod matrix { - use super::*; - use std::time::Duration; - use tokio::sync::Barrier; - - #[derive(Debug)] - pub struct OpStatus { - pub status: StatusCode, - pub body: Vec, - } - - pub struct Harness { - pub _temp: tempfile::TempDir, - pub app: Router, - } - - impl Harness { - pub async fn new() -> Self { - 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 - // (`ingest_per_actor_admission_cap_returns_429`) sets - // OMNIGRAPH_PER_ACTOR_INFLIGHT_MAX=1 inside an EnvGuard while - // it runs. Process-wide env vars are visible to - // concurrently-running tests; if a matrix cell reads env at - // AppState construction time during that window it picks up - // cap=1 and the second concurrent merge in cell b surfaces - // 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(graph.to_str().unwrap()).await.unwrap(); - let workload = omnigraph_server::workload::WorkloadController::with_defaults(); - let state = AppState::new_with_workload( - graph.to_string_lossy().to_string(), - db, - Vec::new(), - workload, - ); - let app = build_app(state); - Self { _temp: temp, app } - } - - pub async fn create_branch(&self, from: &str, name: &str) { - let body = serde_json::to_vec(&BranchCreateRequest { - from: Some(from.to_string()), - name: name.to_string(), - }) - .unwrap(); - let r = self - .app - .clone() - .oneshot( - Request::builder() - .uri("/branches") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!( - r.status(), - StatusCode::OK, - "setup create_branch {} from {} failed", - name, - from - ); - } - - pub async fn insert_person(&self, branch: &str, name: &str, age: i32) { - let body = serde_json::to_vec(&ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": name, "age": age })), - branch: Some(branch.to_string()), - }) - .unwrap(); - let r = self - .app - .clone() - .oneshot( - Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!( - r.status(), - StatusCode::OK, - "setup insert {} on {} failed", - name, - branch - ); - } - - /// Run two ops concurrently with barrier alignment + 15s deadlock - /// timeout. Returns `(op_a, op_b)`. Panics on timeout. - pub async fn run_pair( - &self, - op_a: impl FnOnce(Router, Arc) -> tokio::task::JoinHandle, - op_b: impl FnOnce(Router, Arc) -> tokio::task::JoinHandle, - ) -> (OpStatus, OpStatus) { - let barrier = Arc::new(Barrier::new(2)); - let h_a = op_a(self.app.clone(), Arc::clone(&barrier)); - let h_b = op_b(self.app.clone(), Arc::clone(&barrier)); - let result = tokio::time::timeout(Duration::from_secs(15), async { - let a = h_a.await.unwrap(); - let b = h_b.await.unwrap(); - (a, b) - }) - .await; - result.expect("concurrent op pair deadlocked (>15s)") - } - - pub async fn person_count(&self, branch: &str) -> u64 { - let r = self - .app - .clone() - .oneshot( - Request::builder() - .uri(format!("/snapshot?branch={}", branch)) - .method(Method::GET) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - 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"] - .as_array() - .and_then(|tables| { - tables - .iter() - .find(|t| t["table_key"].as_str() == Some("node:Person")) - }) - .and_then(|t| t["row_count"].as_u64()) - .unwrap_or_else(|| panic!("snapshot {} missing node:Person", branch)) - } - - /// True iff the named Person exists on `branch`. Uses the - /// `get_person` query from `test.gq` for identity rather than - /// 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_name: Some("get_person".to_string()), - params: Some(json!({ "name": name })), - branch: Some(branch.to_string()), - snapshot: None, - }) - .unwrap(); - let r = self - .app - .clone() - .oneshot( - Request::builder() - .uri("/read") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!( - r.status(), - StatusCode::OK, - "person_exists query for {} on {} failed", - name, - branch - ); - let body = to_bytes(r.into_body(), usize::MAX).await.unwrap(); - let v: Value = serde_json::from_slice(&body).unwrap(); - v["row_count"].as_u64().unwrap_or(0) > 0 - } - - /// Asserts each name in `present` exists on `branch` and each in - /// `absent` does not. Identity-grade check that catches symmetric - /// swap races a row-count assertion would miss. - pub async fn assert_persons( - &self, - branch: &str, - cell: &str, - present: &[&str], - absent: &[&str], - ) { - for name in present { - assert!( - self.person_exists(branch, name).await, - "[{}] expected {} to be present on {}", - cell, - name, - branch - ); - } - for name in absent { - assert!( - !self.person_exists(branch, name).await, - "[{}] expected {} to be absent from {}", - cell, - name, - branch - ); - } - } - - /// C6: insert a uniquely-named sentinel on main and verify it - /// landed. Catches engine-state poisoning where a cell's - /// concurrent ops left the engine half-broken β€” subsequent - /// /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: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": sentinel, "age": 99 })), - branch: Some("main".to_string()), - }) - .unwrap(); - let r = self - .app - .clone() - .oneshot( - Request::builder() - .uri("/change") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!( - r.status(), - StatusCode::OK, - "[{}] post-op sentinel /change on main failed (engine poisoned?)", - cell - ); - assert!( - self.person_exists("main", sentinel).await, - "[{}] sentinel {} did not land on main", - cell, - sentinel - ); - } - } - - // Helpers that build the closures for `run_pair`. Each takes a - // Router + Barrier and returns a JoinHandle yielding the status/body. - - pub fn op_merge( - source: String, - target: String, - ) -> impl FnOnce(Router, Arc) -> tokio::task::JoinHandle { - move |app: Router, barrier: Arc| { - tokio::spawn(async move { - barrier.wait().await; - let body = serde_json::to_vec(&BranchMergeRequest { - source, - target: Some(target), - }) - .unwrap(); - let response = app - .oneshot( - Request::builder() - .uri("/branches/merge") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - OpStatus { - status, - body: body.to_vec(), - } - }) - } - } - - pub fn op_change_insert( - branch: String, - name: String, - age: i32, - ) -> impl FnOnce(Router, Arc) -> tokio::task::JoinHandle { - move |app: Router, barrier: Arc| { - tokio::spawn(async move { - barrier.wait().await; - let body = serde_json::to_vec(&ChangeRequest { - 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(), - ) - .await - .unwrap(); - let status = response.status(); - let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - OpStatus { - status, - body: body.to_vec(), - } - }) - } - } - - pub fn op_branch_create( - from: String, - name: String, - ) -> impl FnOnce(Router, Arc) -> tokio::task::JoinHandle { - move |app: Router, barrier: Arc| { - tokio::spawn(async move { - barrier.wait().await; - let body = serde_json::to_vec(&BranchCreateRequest { - from: Some(from), - name, - }) - .unwrap(); - let response = app - .oneshot( - Request::builder() - .uri("/branches") - .method(Method::POST) - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - OpStatus { - status, - body: body.to_vec(), - } - }) - } - } - - pub fn op_branch_delete( - name: String, - ) -> impl FnOnce(Router, Arc) -> tokio::task::JoinHandle { - move |app: Router, barrier: Arc| { - tokio::spawn(async move { - barrier.wait().await; - let response = app - .oneshot( - Request::builder() - .uri(format!("/branches/{}", name)) - .method(Method::DELETE) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - OpStatus { - status, - body: body.to_vec(), - } - }) - } - } -} - -pub const PARITY_POLICY_YAML: &str = r#" -version: 1 -groups: - team: [act-bruno] - admins: [act-ragnor] -protected_branches: [main] -rules: - - id: admins-change-anywhere - allow: - actors: { group: admins } - actions: [change] - branch_scope: any - - id: admins-merge-to-protected - allow: - actors: { group: admins } - actions: [branch_merge] - target_branch_scope: protected -"#; - -#[derive(Clone, Copy, Debug)] -pub enum ParityDecision { - Allow, - Deny, -} - -pub 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(graph.to_str().unwrap()).await.unwrap(); - db.branch_create_from(ReadTarget::branch("main"), "feature") - .await - .unwrap(); - db.load_as( - "feature", - None, - r#"{"type":"Person","data":{"name":"ParityEve","age":29}}"#, - LoadMode::Append, - None, - ) - .await - .unwrap(); - } - let policy_path = temp.path().join("policy.yaml"); - fs::write(&policy_path, PARITY_POLICY_YAML).unwrap(); - (temp, graph, policy_path) -} - -pub 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); - let mut params: omnigraph_compiler::ParamMap = Default::default(); - // Parameter keys are bare names (no `$` prefix); the runtime resolves - // `$name` references in the query body to `params["name"]`. - params.insert( - "name".to_string(), - omnigraph_compiler::Literal::String("ParityCharlie".to_string()), - ); - params.insert("age".to_string(), omnigraph_compiler::Literal::Integer(30)); - let result = db - .mutate_as( - "main", - MUTATION_QUERIES, - "insert_person", - ¶ms, - Some(actor), - ) - .await; - match result { - Ok(_) => ParityDecision::Allow, - Err(OmniError::Policy(_)) => ParityDecision::Deny, - Err(other) => panic!("unexpected SDK error for change: {other:?}"), - } -} - -pub async fn http_change_decision( - graph: &Path, - policy_path: &PathBuf, - actor: &str, - token: &str, -) -> ParityDecision { - let state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - vec![(actor.to_string(), token.to_string())], - Some(policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - let req = ChangeRequest { - query: MUTATION_QUERIES.to_string(), - name: Some("insert_person".to_string()), - params: Some(json!({ "name": "ParityCharlie", "age": 30 })), - branch: Some("main".to_string()), - }; - let (status, _body) = json_response( - &app, - Request::builder() - .uri("/change") - .method(Method::POST) - .header(AUTHORIZATION, format!("Bearer {token}")) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&req).unwrap())) - .unwrap(), - ) - .await; - match status { - StatusCode::OK => ParityDecision::Allow, - StatusCode::FORBIDDEN => ParityDecision::Deny, - other => panic!("unexpected HTTP status for change: {other}"), - } -} - -pub 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); - let result = db.branch_merge_as("feature", "main", Some(actor)).await; - match result { - Ok(_) => ParityDecision::Allow, - Err(OmniError::Policy(_)) => ParityDecision::Deny, - Err(other) => panic!("unexpected SDK error for branch_merge: {other:?}"), - } -} - -pub async fn http_merge_decision( - graph: &Path, - policy_path: &PathBuf, - actor: &str, - token: &str, -) -> ParityDecision { - let state = AppState::open_with_bearer_tokens_and_policy( - graph.to_string_lossy().to_string(), - vec![(actor.to_string(), token.to_string())], - Some(policy_path), - ) - .await - .unwrap(); - let app = build_app(state); - let req = BranchMergeRequest { - source: "feature".to_string(), - target: Some("main".to_string()), - }; - let (status, _body) = json_response( - &app, - Request::builder() - .uri("/branches/merge") - .method(Method::POST) - .header(AUTHORIZATION, format!("Bearer {token}")) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&req).unwrap())) - .unwrap(), - ) - .await; - match status { - StatusCode::OK => ParityDecision::Allow, - StatusCode::FORBIDDEN => ParityDecision::Deny, - other => panic!("unexpected HTTP status for branch_merge: {other}"), - } -} - -pub async fn converged_cluster_dir(policies_yaml: &str) -> tempfile::TempDir { - let temp = tempfile::tempdir().unwrap(); - fs::write( - temp.path().join("people.pg"), - "\nnode Person {\n name: String @key\n}\n", - ) - .unwrap(); - fs::write( - temp.path().join("people.gq"), - "\nquery find_person($name: String) {\n match { $p: Person { name: $name } }\n return { $p.name }\n}\n", - ) - .unwrap(); - fs::write( - temp.path().join("cluster.yaml"), - format!( - r#" -version: 1 -graphs: - knowledge: - schema: ./people.pg - queries: - find_person: - file: ./people.gq -{policies_yaml}"# - ), - ) - .unwrap(); - let import = omnigraph_cluster::import_config_dir(temp.path()).await; - assert!(import.ok, "{:?}", import.diagnostics); - let apply = omnigraph_cluster::apply_config_dir(temp.path()).await; - assert!(apply.ok && apply.converged, "{:?}", apply.diagnostics); - temp -} - -pub async fn cluster_settings(dir: &Path) -> color_eyre::eyre::Result { - omnigraph_server::load_server_settings(None, Some(&dir.to_path_buf()), None, None, None, true).await -} diff --git a/crates/omnigraph/Cargo.toml b/crates/omnigraph/Cargo.toml index a4a2fe0..70f51d8 100644 --- a/crates/omnigraph/Cargo.toml +++ b/crates/omnigraph/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omnigraph-engine" -version = "0.6.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.6.2" } -omnigraph-policy = { path = "../omnigraph-policy", version = "0.6.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 } @@ -37,7 +37,6 @@ serde_json = { workspace = true } reqwest = { workspace = true } object_store = { workspace = true } ulid = { workspace = true } -sha2 = { workspace = true } base64 = { workspace = true } futures = { workspace = true } tracing = { workspace = true } @@ -52,8 +51,7 @@ chrono = { workspace = true } arc-swap = { workspace = true } [dev-dependencies] -omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.2" } +omnigraph-compiler = { path = "../omnigraph-compiler", version = "0.6.1" } tokio = { workspace = true } lance-namespace-impls = { workspace = true } serial_test = "3" -proptest = "1" diff --git a/crates/omnigraph/examples/bench_expand.rs b/crates/omnigraph/examples/bench_expand.rs index bb904a0..c723b24 100644 --- a/crates/omnigraph/examples/bench_expand.rs +++ b/crates/omnigraph/examples/bench_expand.rs @@ -221,65 +221,6 @@ fn microbench_dedup() { ); } -/// Selective single-source traversal, timed cold in CSR vs indexed mode across -/// growing |E|. The win of the indexed path: a small fixed frontier should be -/// ~flat in |E| (one BTREE scan per hop), whereas CSR pays an O(|E|) adjacency -/// build on the first (cold) query. Also asserts both modes return the same -/// rows β€” a guard against the scalar-index `physical_rows` silent fallback -/// dropping unindexed-fragment rows. -async fn bench_selective_modes() { - println!("\n── Selective traversal: indexed vs CSR (cold, single-source knows{{1,2}}) ──"); - let sel = r#" -query sel($name: String) { - match { - $a: Person { name: $name } - $a knows{1,2} $b - } - return { $b.name } -} -"#; - for &(n, avg_deg) in &[(1_000usize, 8usize), (10_000, 8), (30_000, 8)] { - let jsonl = generate_jsonl(n, avg_deg, 42); - let mut params = ParamMap::new(); - params.insert( - "name".to_string(), - omnigraph_compiler::query::ast::Literal::String("p0".to_string()), - ); - - let mut rows_by_mode: Vec<(&str, usize)> = Vec::new(); - for mode in ["csr", "indexed"] { - // Fresh db per measurement so the query is cold (CSR pays its build). - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let mut db = Omnigraph::init(uri, SCHEMA).await.unwrap(); - load_jsonl(&mut db, &jsonl, LoadMode::Overwrite).await.unwrap(); - // SAFE: example main drives queries sequentially; no concurrent env reader. - unsafe { std::env::set_var("OMNIGRAPH_TRAVERSAL_MODE", mode) }; - - let t = Instant::now(); - let r = db - .query(ReadTarget::branch("main"), sel, "sel", ¶ms) - .await - .expect("sel query"); - let elapsed = t.elapsed(); - let rows = r.num_rows(); - rows_by_mode.push((mode, rows)); - println!( - " |E|β‰ˆ{:>7} {:<8} cold={:>9.2?} rows={}", - n * avg_deg, - mode, - elapsed, - rows - ); - } - unsafe { std::env::remove_var("OMNIGRAPH_TRAVERSAL_MODE") }; - assert_eq!( - rows_by_mode[0].1, rows_by_mode[1].1, - "indexed and CSR must return identical rows (no silent drop under partial index coverage)" - ); - } -} - #[tokio::main(flavor = "multi_thread")] async fn main() { println!("── End-to-end query latency ──"); @@ -321,7 +262,5 @@ async fn main() { } } - bench_selective_modes().await; - microbench_dedup(); } diff --git a/crates/omnigraph/src/changes/mod.rs b/crates/omnigraph/src/changes/mod.rs index d4a3fe7..7c9e8ea 100644 --- a/crates/omnigraph/src/changes/mod.rs +++ b/crates/omnigraph/src/changes/mod.rs @@ -7,7 +7,6 @@ use lance::dataset::scanner::ColumnOrdering; use crate::db::SubTableEntry; use crate::db::manifest::Snapshot; use crate::error::Result; -use crate::storage_layer::{SnapshotHandle, TableStorage}; use crate::table_store::TableStore; // ─── Types ────────────────────────────────────────────────────────────────── @@ -230,8 +229,7 @@ async fn diff_table_same_lineage( ) -> Result> { let vf = from_entry.table_version; let vt = to_entry.table_version; - let storage: &dyn TableStorage = table_store; - let to_ds = storage.open_snapshot_at_entry(to_entry).await?; + let to_ds = table_store.open_at_entry(to_entry).await?; let cols: Vec<&str> = if is_edge { vec!["id", "src", "dst", "_row_last_updated_at_version"] @@ -259,12 +257,12 @@ async fn diff_table_same_lineage( "_row_last_updated_at_version > {} AND _row_last_updated_at_version <= {}", vf, vt ); - let changed_rows = scan_with_filter(storage, &to_ds, &cols, &filter_sql).await?; + let changed_rows = scan_with_filter(table_store, &to_ds, &cols, &filter_sql).await?; if !changed_rows.is_empty() { // Build the set of IDs that existed at the from version - let from_ds = storage.open_snapshot_at_entry(from_entry).await?; - let from_ids: HashSet = scan_id_set(storage, &from_ds, &["id"]) + let from_ds = table_store.open_at_entry(from_entry).await?; + let from_ids: HashSet = scan_id_set(table_store, &from_ds, &["id"]) .await? .into_iter() .map(|r| r.id) @@ -284,8 +282,8 @@ async fn diff_table_same_lineage( // Deletes: ID set-difference if wants_deletes { - let from_ds = storage.open_snapshot_at_entry(from_entry).await?; - let deleted = deleted_ids_by_set_diff(storage, &from_ds, &to_ds, is_edge).await?; + let from_ds = table_store.open_at_entry(from_entry).await?; + let deleted = deleted_ids_by_set_diff(table_store, &from_ds, &to_ds, is_edge).await?; changes.extend(deleted); } @@ -302,14 +300,13 @@ async fn diff_table_cross_branch( is_edge: bool, filter: &ChangeFilter, ) -> Result> { - let storage: &dyn TableStorage = table_store; - let from_ds = storage - .open_snapshot_at_table(from_snap, table_key) + let from_ds = table_store + .open_snapshot_table(from_snap, table_key) .await?; - let to_ds = storage.open_snapshot_at_table(to_snap, table_key).await?; + let to_ds = table_store.open_snapshot_table(to_snap, table_key).await?; - let from_rows = scan_all_rows_ordered(storage, &from_ds, is_edge).await?; - let to_rows = scan_all_rows_ordered(storage, &to_ds, is_edge).await?; + let from_rows = scan_all_rows_ordered(table_store, &from_ds, is_edge).await?; + let to_rows = scan_all_rows_ordered(table_store, &to_ds, is_edge).await?; let mut changes = Vec::new(); let mut fi = 0; @@ -395,9 +392,8 @@ async fn diff_table_added( if !filter.wants_op(ChangeOp::Insert) { return Ok(Vec::new()); } - let storage: &dyn TableStorage = table_store; - let ds = storage.open_snapshot_at_table(to_snap, table_key).await?; - let rows = scan_all_rows_ordered(storage, &ds, is_edge).await?; + let ds = table_store.open_snapshot_table(to_snap, table_key).await?; + let rows = scan_all_rows_ordered(table_store, &ds, is_edge).await?; Ok(rows .into_iter() .map(|r| entity_change_from_row(&r, ChangeOp::Insert, is_edge)) @@ -414,11 +410,10 @@ async fn diff_table_removed( if !filter.wants_op(ChangeOp::Delete) { return Ok(Vec::new()); } - let storage: &dyn TableStorage = table_store; - let ds = storage - .open_snapshot_at_table(from_snap, table_key) + let ds = table_store + .open_snapshot_table(from_snap, table_key) .await?; - let rows = scan_all_rows_ordered(storage, &ds, is_edge).await?; + let rows = scan_all_rows_ordered(table_store, &ds, is_edge).await?; Ok(rows .into_iter() .map(|r| entity_change_from_row(&r, ChangeOp::Delete, is_edge)) @@ -429,12 +424,12 @@ async fn diff_table_removed( /// Scan with a SQL filter, projecting specific columns. async fn scan_with_filter( - storage: &dyn TableStorage, - ds: &SnapshotHandle, + table_store: &TableStore, + ds: &lance::Dataset, cols: &[&str], filter_sql: &str, ) -> Result> { - let batches = storage + let batches = table_store .scan(ds, Some(cols), Some(filter_sql), None) .await?; Ok(extract_rows(&batches)) @@ -442,11 +437,11 @@ async fn scan_with_filter( /// Scan all rows ordered by id, projecting id (+ src/dst for edges) + all columns for signature. async fn scan_all_rows_ordered( - storage: &dyn TableStorage, - ds: &SnapshotHandle, + table_store: &TableStore, + ds: &lance::Dataset, is_edge: bool, ) -> Result> { - let batches = storage + let batches = table_store .scan( ds, None, @@ -459,9 +454,9 @@ async fn scan_all_rows_ordered( /// Compute deleted IDs: scan id at from and to, set-difference. async fn deleted_ids_by_set_diff( - storage: &dyn TableStorage, - from_ds: &SnapshotHandle, - to_ds: &SnapshotHandle, + table_store: &TableStore, + from_ds: &lance::Dataset, + to_ds: &lance::Dataset, is_edge: bool, ) -> Result> { let cols: Vec<&str> = if is_edge { @@ -470,8 +465,8 @@ async fn deleted_ids_by_set_diff( vec!["id"] }; - let from_rows = scan_id_set(storage, from_ds, &cols).await?; - let to_ids: HashSet = scan_id_set(storage, to_ds, &["id"]) + let from_rows = scan_id_set(table_store, from_ds, &cols).await?; + let to_ids: HashSet = scan_id_set(table_store, to_ds, &["id"]) .await? .into_iter() .map(|r| r.id) @@ -485,11 +480,11 @@ async fn deleted_ids_by_set_diff( } async fn scan_id_set( - storage: &dyn TableStorage, - ds: &SnapshotHandle, + table_store: &TableStore, + ds: &lance::Dataset, cols: &[&str], ) -> Result> { - let batches = storage.scan(ds, Some(cols), None, None).await?; + let batches = table_store.scan(ds, Some(cols), None, None).await?; Ok(extract_rows(&batches)) } diff --git a/crates/omnigraph/src/db/manifest.rs b/crates/omnigraph/src/db/manifest.rs index 5bf1f87..7fcf7de 100644 --- a/crates/omnigraph/src/db/manifest.rs +++ b/crates/omnigraph/src/db/manifest.rs @@ -36,7 +36,7 @@ use publisher::{GraphNamespacePublisher, ManifestBatchPublisher}; pub(crate) use recovery::{ RecoveryMode, RecoverySidecar, RecoverySidecarHandle, SidecarKind, SidecarTablePin, SidecarTableRegistration, SidecarTombstone, delete_sidecar, has_schema_apply_sidecar, - list_sidecars, new_sidecar, recover_manifest_drift, write_sidecar, + new_sidecar, recover_manifest_drift, write_sidecar, }; pub use state::SubTableEntry; #[cfg(test)] @@ -48,22 +48,6 @@ const OBJECT_TYPE_TABLE_VERSION: &str = "table_version"; const OBJECT_TYPE_TABLE_TOMBSTONE: &str = "table_tombstone"; const TABLE_VERSION_MANAGEMENT_KEY: &str = "table_version_management"; -/// Apply pending internal-schema migrations against `__manifest` on the -/// open-for-write path, independent of a publish. -/// -/// `Omnigraph::open(ReadWrite)` calls this before the coordinator reads branch -/// state, so branch-observing code (`branch_list`, the schema-apply -/// blocking-branch checks) sees the post-migration graph. In particular the -/// v2β†’v3 step sweeps legacy `__run__*` staging branches off `__manifest` -/// (MR-770); running it here closes the window where those branches would -/// otherwise block schema apply before the first publish runs the migration. -/// -/// Idempotent: a no-op stamp read when the on-disk version already matches. -pub(crate) async fn migrate_on_open(root_uri: &str) -> Result<()> { - let mut dataset = open_manifest_dataset(root_uri, None).await?; - migrations::migrate_internal_schema(&mut dataset).await -} - /// Immutable point-in-time view of the database. /// /// Cheap to create (no storage I/O). All reads within a query go through one diff --git a/crates/omnigraph/src/db/manifest/migrations.rs b/crates/omnigraph/src/db/manifest/migrations.rs index e2801fe..bbb7995 100644 --- a/crates/omnigraph/src/db/manifest/migrations.rs +++ b/crates/omnigraph/src/db/manifest/migrations.rs @@ -46,11 +46,7 @@ use crate::error::{OmniError, Result}; /// - v2 β€” `__manifest.object_id` carries the unenforced-PK annotation, /// engaging Lance's bloom-filter conflict resolver at commit time. Added /// alongside `expected_table_versions` OCC on `ManifestBatchPublisher::publish`. -/// - v3 β€” one-time sweep of legacy `__run__` staging branches left on the -/// `__manifest` dataset by the pre-v0.4.0 Run state machine (removed in -/// MR-771). Once swept, the `is_internal_run_branch` defense-in-depth guard -/// is no longer needed (MR-770). -pub(super) const INTERNAL_MANIFEST_SCHEMA_VERSION: u32 = 3; +pub(super) const INTERNAL_MANIFEST_SCHEMA_VERSION: u32 = 2; const INTERNAL_SCHEMA_VERSION_KEY: &str = "omnigraph:internal_schema_version"; const OBJECT_ID_PK_KEY: &str = "lance-schema:unenforced-primary-key"; @@ -93,10 +89,6 @@ pub(super) async fn migrate_internal_schema(dataset: &mut Dataset) -> Result<()> migrate_v1_to_v2(dataset).await?; current = 2; } - 2 => { - migrate_v2_to_v3(dataset).await?; - current = 3; - } other => { return Err(OmniError::manifest_internal(format!( "no internal-schema migration registered for v{} β†’ v{}", @@ -130,51 +122,6 @@ async fn migrate_v1_to_v2(dataset: &mut Dataset) -> Result<()> { set_stamp(dataset, 2).await } -/// v2 β†’ v3: sweep legacy `__run__` staging branches off the `__manifest` -/// dataset, then bump the stamp. -/// -/// The pre-v0.4.0 Run state machine (removed in MR-771) created graph-level -/// staging branches named `__run__` on `__manifest`. MR-771 stopped -/// creating them but left any pre-existing ones in place; Lance's -/// `list_branches` still enumerates them, so they leak into `branch_list()` -/// and count as blocking branches at schema-apply time. This one-time sweep -/// removes them so the `is_internal_run_branch` guard can retire (MR-770). -/// -/// The `"__run__"` prefix is inlined here on purpose: this migration must keep -/// working after the `run_registry` module (the guard) is deleted, so it does -/// not depend on it. -/// -/// Idempotent under both sequential retry and concurrent runners: each run -/// re-enumerates `list_branches` fresh, and `force_delete_branch` tolerates a -/// branch that is already gone β€” so a crash before the stamp bump, or a second -/// process opening the same legacy graph at the same time, never errors out. -async fn migrate_v2_to_v3(dataset: &mut Dataset) -> Result<()> { - const LEGACY_RUN_BRANCH_PREFIX: &str = "__run__"; - let branches = dataset - .list_branches() - .await - .map_err(|e| OmniError::Lance(e.to_string()))?; - let run_branches: Vec = branches - .into_keys() - .filter(|name| { - name.trim_start_matches('/') - .starts_with(LEGACY_RUN_BRANCH_PREFIX) - }) - .collect(); - for name in run_branches { - // `force_delete_branch` deletes even when the `BranchContents` is - // already gone. Plain `delete_branch` errors "BranchContents not - // found", which would fail a second concurrent open (or a retry that - // raced another runner) after the first one swept the branch. Force is - // exactly Lance's documented path for cleaning up zombie branches. - dataset - .force_delete_branch(&name) - .await - .map_err(|e| OmniError::Lance(e.to_string()))?; - } - set_stamp(dataset, 3).await -} - async fn set_stamp(dataset: &mut Dataset, version: u32) -> Result<()> { dataset .update_schema_metadata([(INTERNAL_SCHEMA_VERSION_KEY.to_string(), version.to_string())]) diff --git a/crates/omnigraph/src/db/manifest/recovery.rs b/crates/omnigraph/src/db/manifest/recovery.rs index 3b0f147..4c1b987 100644 --- a/crates/omnigraph/src/db/manifest/recovery.rs +++ b/crates/omnigraph/src/db/manifest/recovery.rs @@ -25,7 +25,7 @@ //! version. Pinned by //! `tests/staged_writes.rs::lance_restore_appends_one_commit_with_checked_out_content`. //! - `Dataset::restore` "wins" against concurrent Append/Update/Delete/ -//! CreateIndex/Merge β€” see `check_restore_txn` at lance-6.0.1 +//! CreateIndex/Merge β€” see `check_restore_txn` at lance-4.0.0 //! `src/io/commit/conflict_resolver.rs:986`. The hazard is documented //! by `tests/staged_writes.rs::lance_restore_loses_to_concurrent_append_via_orphaning`. //! This module sidesteps the hazard by running recovery only at @@ -106,12 +106,6 @@ pub(crate) enum SidecarKind { BranchMerge, /// `ensure_indices_for_branch` β€” index lifecycle commits. EnsureIndices, - /// `optimize_all_tables` β€” Lance `compact_files` (reserve-fragments + - /// rewrite commits) followed by a manifest publish of the compacted - /// version. Loose-match like the other multi-commit writers; roll-forward - /// is always safe because compaction is content-preserving (Lance - /// `Operation::Rewrite` "reorganizes data without semantic modification"). - Optimize, } /// One table's contribution to a sidecar's intended commit. The classifier @@ -418,13 +412,11 @@ pub(crate) fn parse_sidecar(sidecar_uri: &str, body: &str) -> Result manifest_pinned` as `RolledPastExpected` when /// `pin.expected_version == manifest_pinned` (the writer's CAS /// target matches what the manifest currently shows). The risk this @@ -502,12 +494,9 @@ pub(crate) fn decide(classifications: &[TableClassification]) -> SidecarDecision /// Skipping the restore in those cases would leave Lance HEAD ahead of /// the manifest with no recovery artifact left. /// -/// Cost: a successful roll-back appends one restore commit and then publishes -/// the manifest to match (`roll_back_sidecar`), so the table converges -/// (`manifest == HEAD`) in one pass. Only repeated crashes *between* the restore -/// and that publish (rare) accumulate extra restore commits; each re-classified -/// roll-back restores again and `omnigraph cleanup` reclaims the surplus. -/// Bounded by the number of interrupted recovery iterations β€” typically 0. +/// Cost: under repeated mid-rollback crashes (rare), Lance HEAD +/// accumulates extra restore commits that `omnigraph cleanup` reclaims. +/// Bounded by the number of recovery iterations β€” typically 1. pub(crate) async fn restore_table_to_version( table_path: &str, branch: Option<&str>, @@ -812,24 +801,13 @@ async fn roll_back_sidecar( sidecar: &RecoverySidecar, states: &[ClassifiedTable], ) -> Result<()> { - // Restore every drifted table (RolledPastExpected / UnexpectedAtP1 / - // UnexpectedMultistep) to its manifest-pinned content, then PUBLISH so - // `manifest == Lance HEAD` for each β€” symmetric with roll-forward. The - // restore commit's content equals the manifest-pinned version, so re-pinning - // the manifest to the new (restored) HEAD is content-correct and closes the - // orphaned-drift class (`HEAD > manifest` with no covering sidecar). This is - // what makes a failed-then-retried schema_apply converge: after one - // roll-back `manifest == HEAD`, so the retry's precondition passes instead of - // failing one version higher each iteration. - // - // NoMovement tables are already at the pin β€” excluded from both the restore - // and the publish. The audit `to_version` stays the *logical* rolled-back-to - // version (`manifest_pinned`), while the manifest is published at - // `manifest_pinned + 1` (the restore commit, same content) β€” keep that - // asymmetry so the audit records the drift (`from_version > to_version`). + // Restore every table whose Lance HEAD has drifted from the + // manifest pin (RolledPastExpected, UnexpectedAtP1, + // UnexpectedMultistep). NoMovement tables are already at the + // manifest pin β€” no action. Restore is unconditional; repeated + // mid-rollback crashes accumulate a few extra Lance commits that + // `omnigraph cleanup` reclaims. let mut outcomes = Vec::with_capacity(sidecar.tables.len()); - let mut updates: Vec = Vec::with_capacity(sidecar.tables.len()); - let mut expected: HashMap = HashMap::with_capacity(sidecar.tables.len()); for (pin, state) in sidecar.tables.iter().zip(states.iter()) { if matches!( state.classification, @@ -843,20 +821,10 @@ async fn roll_back_sidecar( state.manifest_pinned, ) .await?; - // Publish the post-restore HEAD, CAS against the current (unmoved) - // manifest pin β€” the same helper roll-forward uses. - push_table_update_at_head( - root_uri, - &pin.table_key, - &pin.table_path, - pin.table_branch.as_deref(), - state.manifest_pinned, - &mut updates, - &mut expected, - ) - .await?; - // `from_version` records the Lance HEAD observed BEFORE the restore - // (the actual drift); `to_version` the logical pin we rolled back to. + // `from_version` records the Lance HEAD observed BEFORE the + // restore (the actual drift), not the manifest pin. Operators + // reading `_graph_commit_recoveries.lance` see "rolled back + // from v7 to v5" rather than "v5 β†’ v5". outcomes.push(TableOutcome { table_key: pin.table_key.clone(), from_version: state.lance_head, @@ -864,23 +832,13 @@ async fn roll_back_sidecar( }); } } - // Publish the restored HEADs so manifest == HEAD. A degenerate all-NoMovement - // roll-back restores nothing β€” there's nothing to publish, and the audit - // records the unchanged snapshot version. - let manifest_version = if updates.is_empty() { - snapshot.version() - } else { - let publisher = GraphNamespacePublisher::new(root_uri, sidecar.branch.as_deref()); - publisher - .publish(&updates, &expected) - .await? - .version() - .version - }; + // Manifest pin doesn't move on rollback; record an audit-only + // commit at the existing version so operators can correlate via + // `omnigraph commit list --filter actor=omnigraph:recovery`. record_audit( root_uri, sidecar, - manifest_version, + snapshot.version(), RecoveryKind::RolledBack, outcomes, ) @@ -961,20 +919,44 @@ async fn roll_forward_all( HashMap::with_capacity(sidecar.tables.len() + sidecar.additional_registrations.len()); for pin in &sidecar.tables { - // Publish to the table's CURRENT Lance HEAD on the pin's branch (not the - // sidecar's `post_commit_pin`, a lower bound for loose-match writers that - // run multiple commit_staged calls per table). CAS against the pin's - // pre-write `expected_version`. - let head_version = push_table_update_at_head( + // Open the dataset at its CURRENT Lance HEAD on the pin's branch + // (not at the sidecar's post_commit_pin). For strict-match writers + // (Mutation/Load) HEAD == post_commit_pin by construction. For + // loose-match writers (SchemaApply/EnsureIndices/BranchMerge) HEAD + // may be higher than post_commit_pin (multiple commit_staged + // calls per table); we want to publish to the actual current HEAD. + let head_ds = Dataset::open(&pin.table_path) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + let head_ds = match pin.table_branch.as_deref() { + Some(b) if b != "main" => head_ds + .checkout_branch(b) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?, + _ => head_ds, + }; + let head_version = head_ds.version().version; + + let row_count = head_ds + .count_rows(None) + .await + .map_err(|e| OmniError::Lance(e.to_string()))? as u64; + + let table_relative_path = super::table_path_for_table_key(&pin.table_key)?; + let version_metadata = super::metadata::TableVersionMetadata::from_dataset( root_uri, - &pin.table_key, - &pin.table_path, - pin.table_branch.as_deref(), - pin.expected_version, - &mut updates, - &mut expected, - ) - .await?; + &table_relative_path, + &head_ds, + )?; + + updates.push(ManifestChange::Update(SubTableUpdate { + table_key: pin.table_key.clone(), + table_version: head_version, + table_branch: pin.table_branch.clone(), + row_count, + version_metadata, + })); + expected.insert(pin.table_key.clone(), pin.expected_version); published_versions.insert(pin.table_key.clone(), head_version); } @@ -1065,57 +1047,6 @@ async fn roll_forward_all( Ok((new_dataset.version().version, published_versions)) } -/// Open `table_path` at its branch HEAD, read the current Lance HEAD version, -/// row count, and version metadata, and push a `ManifestChange::Update` (plus -/// its CAS `expected` entry) that re-pins the manifest to that HEAD. Returns the -/// published HEAD version. -/// -/// Shared by `roll_forward_all` (where `expected_version` is the sidecar's -/// pre-write pin) and `roll_back_sidecar` (where it is the manifest-pinned -/// version the table was just restored to). The HEAD is read AFTER any restore -/// in the same single-threaded sweep, so no concurrent writer can have advanced -/// it. -async fn push_table_update_at_head( - root_uri: &str, - table_key: &str, - table_path: &str, - branch: Option<&str>, - expected_version: u64, - updates: &mut Vec, - expected: &mut HashMap, -) -> Result { - let head_ds = Dataset::open(table_path) - .await - .map_err(|e| OmniError::Lance(e.to_string()))?; - let head_ds = match branch { - Some(b) if b != "main" => head_ds - .checkout_branch(b) - .await - .map_err(|e| OmniError::Lance(e.to_string()))?, - _ => head_ds, - }; - let head_version = head_ds.version().version; - let row_count = head_ds - .count_rows(None) - .await - .map_err(|e| OmniError::Lance(e.to_string()))? as u64; - let table_relative_path = super::table_path_for_table_key(table_key)?; - let version_metadata = super::metadata::TableVersionMetadata::from_dataset( - root_uri, - &table_relative_path, - &head_ds, - )?; - updates.push(ManifestChange::Update(SubTableUpdate { - table_key: table_key.to_string(), - table_version: head_version, - table_branch: branch.map(str::to_string), - row_count, - version_metadata, - })); - expected.insert(table_key.to_string(), expected_version); - Ok(head_version) -} - /// Append the audit row describing this recovery action. /// /// Two-part write: (a) `_graph_commits.lance` row anchored on the recovery diff --git a/crates/omnigraph/src/db/manifest/tests.rs b/crates/omnigraph/src/db/manifest/tests.rs index 885a2a8..effa0b5 100644 --- a/crates/omnigraph/src/db/manifest/tests.rs +++ b/crates/omnigraph/src/db/manifest/tests.rs @@ -1461,80 +1461,6 @@ async fn test_publish_migrates_pre_stamp_manifest_to_current_version() { assert!(reopened.snapshot().entry("node:Person").is_some()); } -#[tokio::test] -async fn test_v2_to_v3_sweeps_legacy_run_branches_on_write_open() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let catalog = build_test_catalog(); - let mut mc = ManifestCoordinator::init(uri, &catalog).await.unwrap(); - - // Synthesize a pre-MR-770 graph: several stale `__run__` staging branches - // left on `__manifest` (a real legacy graph accumulates one per run), plus - // a real user branch that must survive the sweep. Multiple run branches - // exercise the migration's delete loop on a single reused dataset handle. - mc.create_branch("__run__01J9LEGACY").await.unwrap(); - mc.create_branch("__run__01J9SECOND").await.unwrap(); - mc.create_branch("__run__01J9THIRD").await.unwrap(); - mc.create_branch("feature").await.unwrap(); - let before = mc.list_branches().await.unwrap(); - assert_eq!( - before.iter().filter(|b| b.starts_with("__run__")).count(), - 3, - "precondition: three legacy run branches exist on __manifest; got {before:?}", - ); - - // Rewind the internal-schema stamp to v2 so the next write-open runs the - // v2 β†’ v3 sweep arm (init stamps at the current version, which is past it). - { - let mut ds = open_manifest_dataset(uri, None).await.unwrap(); - ds.update_schema_metadata([( - "omnigraph:internal_schema_version".to_string(), - Some("2".to_string()), - )]) - .await - .unwrap(); - let post = open_manifest_dataset(uri, None).await.unwrap(); - assert_eq!(super::migrations::read_stamp(&post), 2, "stamp rewound to v2"); - } - - // A no-op publish forces the open-for-write path, which runs the migration. - let mut expected = HashMap::new(); - expected.insert("node:Person".to_string(), 1); - GraphNamespacePublisher::new(uri, None) - .publish(&[], &expected) - .await - .unwrap(); - - // Stamp advanced to current; the legacy run branch is physically gone from - // `__manifest` (checked via the raw, unfiltered manifest list β€” not the - // guard-filtered `branch_list`), and the real branch + `main` survive. - let post = open_manifest_dataset(uri, None).await.unwrap(); - assert_eq!( - super::migrations::read_stamp(&post), - super::migrations::INTERNAL_MANIFEST_SCHEMA_VERSION, - ); - let reopened = ManifestCoordinator::open(uri).await.unwrap(); - let after = reopened.list_branches().await.unwrap(); - assert!( - !after.iter().any(|b| b.starts_with("__run__")), - "legacy run branch must be swept; got {after:?}", - ); - assert!(after.iter().any(|b| b == "feature"), "user branch must survive"); - assert!(after.iter().any(|b| b == "main"), "main must survive"); - - // Idempotent: a second write-open finds the stamp at current and does not - // re-run the sweep or error. - GraphNamespacePublisher::new(uri, None) - .publish(&[], &expected) - .await - .unwrap(); - let final_ds = open_manifest_dataset(uri, None).await.unwrap(); - assert_eq!( - super::migrations::read_stamp(&final_ds), - super::migrations::INTERNAL_MANIFEST_SCHEMA_VERSION, - ); -} - #[tokio::test] async fn test_publish_rejects_manifest_stamped_at_future_version() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/omnigraph/src/db/mod.rs b/crates/omnigraph/src/db/mod.rs index 000602a..8702f88 100644 --- a/crates/omnigraph/src/db/mod.rs +++ b/crates/omnigraph/src/db/mod.rs @@ -3,6 +3,7 @@ pub mod graph_coordinator; pub mod manifest; mod omnigraph; mod recovery_audit; +mod run_registry; mod schema_state; pub(crate) mod write_queue; @@ -11,10 +12,10 @@ pub use graph_coordinator::{GraphCoordinator, ReadTarget, ResolvedTarget, Snapsh pub use manifest::{Snapshot, SubTableEntry, SubTableUpdate}; pub(crate) use omnigraph::ensure_public_branch_ref; pub use omnigraph::{ - CleanupPolicyOptions, InitOptions, MergeOutcome, Omnigraph, OpenMode, RepairAction, - RepairClassification, RepairOptions, RepairStats, SchemaApplyOptions, SchemaApplyResult, - SkipReason, TableCleanupStats, TableOptimizeStats, TableRepairStats, + 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__"; @@ -68,8 +69,5 @@ pub(crate) fn is_schema_apply_lock_branch(name: &str) -> bool { } pub(crate) fn is_internal_system_branch(name: &str) -> bool { - // Legacy `__run__*` staging branches (Run state machine, removed MR-771) - // are swept off `__manifest` by the v2β†’v3 internal-schema migration, so the - // only internal branch the engine still creates is the schema-apply lock. - is_schema_apply_lock_branch(name) + is_internal_run_branch(name) || is_schema_apply_lock_branch(name) } diff --git a/crates/omnigraph/src/db/omnigraph.rs b/crates/omnigraph/src/db/omnigraph.rs index 50f5d34..7b8a3f6 100644 --- a/crates/omnigraph/src/db/omnigraph.rs +++ b/crates/omnigraph/src/db/omnigraph.rs @@ -26,19 +26,14 @@ use crate::db::graph_coordinator::{GraphCoordinator, PublishedSnapshot}; use crate::error::{OmniError, Result}; use crate::runtime_cache::RuntimeCache; use crate::storage::{StorageAdapter, join_uri, normalize_root_uri, storage_for_uri}; -use crate::storage_layer::SnapshotHandle; use crate::table_store::TableStore; mod export; mod optimize; -mod repair; mod schema_apply; mod table_ops; pub use optimize::{CleanupPolicyOptions, SkipReason, TableCleanupStats, TableOptimizeStats}; -pub use repair::{ - RepairAction, RepairClassification, RepairOptions, RepairStats, TableRepairStats, -}; pub use schema_apply::SchemaApplyOptions; use super::commit_graph::GraphCommit; @@ -351,16 +346,6 @@ impl Omnigraph { mode: OpenMode, ) -> Result { let root = normalize_root_uri(uri)?; - // Apply pending internal-schema migrations before the coordinator reads - // branch state, so `branch_list` and the schema-apply blocking-branch - // checks observe the post-migration graph β€” notably the v2β†’v3 sweep of - // legacy `__run__*` staging branches (MR-770). ReadWrite only: a - // read-only open must not trigger object-store writes, so a read-only - // open of an unmigrated legacy graph still lists `__run__*` until its - // first read-write open (an accepted, documented limitation). - if matches!(mode, OpenMode::ReadWrite) { - crate::db::manifest::migrate_on_open(&root).await?; - } // Open the coordinator first so the schema-staging recovery sweep can // compare its snapshot against any leftover staging files. let mut coordinator = GraphCoordinator::open(&root, Arc::clone(&storage)).await?; @@ -584,30 +569,19 @@ impl Omnigraph { schema_apply::ensure_schema_apply_not_locked(self, operation).await } - /// Engine-facing trait surface around `TableStore`. - /// - /// This is the **only** accessor for engine code reaching into the - /// storage layer. The trait's signatures use opaque `SnapshotHandle` - /// / `StagedHandle` instead of leaking `lance::Dataset` / - /// `lance::dataset::transaction::Transaction`, so newly-added engine - /// call sites cannot drift the staged-write invariant by mistake - /// (the trait's `stage_*` + `commit_staged` pair is the only way to - /// land a write). - pub(crate) fn storage(&self) -> &dyn crate::storage_layer::TableStorage { + pub(crate) fn table_store(&self) -> &TableStore { &self.table_store } - /// Inline-commit residual surface (`delete_where`, - /// `create_vector_index`) β€” the writes Lance cannot yet express as a - /// stage-then-commit pair. Deliberately separate from [`Self::storage`] so - /// the default storage surface is staged-only and a new writer cannot couple - /// "write bytes" with "advance HEAD" by reaching for `db.storage()`. Only - /// the handful of documented residual call sites (mutation/merge deletes, - /// vector-index build) use this accessor. See - /// `crate::storage_layer::InlineCommitResidual` for the per-method blocker. - pub(crate) fn storage_inline_residual( - &self, - ) -> &dyn crate::storage_layer::InlineCommitResidual { + /// Engine-facing trait surface around `TableStore`. + /// + /// This is the canonical accessor for newly-written engine code. The + /// trait's signatures use opaque `SnapshotHandle` / `StagedHandle` + /// instead of leaking `lance::Dataset` / + /// `lance::dataset::transaction::Transaction`. Existing call sites + /// that still use `db.table_store.X(...)` (the inherent struct + /// methods) are migrated incrementally. + pub(crate) fn storage(&self) -> &dyn crate::storage_layer::TableStorage { &self.table_store } @@ -698,16 +672,6 @@ impl Omnigraph { .map(|resolved| resolved.snapshot) } - pub(crate) async fn fresh_snapshot_for_branch(&self, branch: Option<&str>) -> Result { - self.ensure_schema_state_valid().await?; - let requested = ReadTarget::Branch(branch.unwrap_or("main").to_string()); - let coord = self.coordinator.read().await; - coord - .resolve_target(&requested) - .await - .map(|resolved| resolved.snapshot) - } - pub(crate) async fn version(&self) -> u64 { self.coordinator.read().await.version() } @@ -1025,13 +989,6 @@ impl Omnigraph { optimize::optimize_all_tables(self).await } - /// Classify and explicitly repair uncovered manifest/head drift. See - /// [`repair`] for the distinction between safe maintenance drift and - /// suspicious/unverifiable drift. - pub async fn repair(&self, options: repair::RepairOptions) -> Result { - repair::repair_all_tables(self, options).await - } - /// Remove Lance manifests (and the fragments they uniquely own) per the /// given [`optimize::CleanupPolicyOptions`]. Destructive to version /// history. See [`optimize`] for details. @@ -1067,24 +1024,19 @@ impl Omnigraph { let snapshot = self.snapshot().await; let table_key = format!("node:{}", type_name); - let handle = self - .storage() - .open_snapshot_at_table(&snapshot, &table_key) - .await?; + let ds = snapshot.open(&table_key).await?; let filter_sql = format!("id = '{}'", id.replace('\'', "''")); let row_id = self - .storage() - .first_row_id_for_filter(&handle, &filter_sql) + .table_store + .first_row_id_for_filter(&ds, &filter_sql) .await? .ok_or_else(|| { OmniError::manifest(format!("no {} with id '{}' found", type_name, id)) })?; - // `take_blobs` is a Lance-specific blob accessor not surfaced - // through the `TableStorage` trait β€” reach the inner `Arc` - // via the `pub(crate)` accessor for this read-only call. - let ds = handle.into_arc(); + // Use take_blobs to get the BlobFile handle + let ds = Arc::new(ds); let mut blobs = ds .take_blobs(&[row_id], property) .await @@ -1158,14 +1110,10 @@ impl Omnigraph { cleanup_targets.sort_by(|left, right| left.0.cmp(&right.0)); for (table_key, table_path) in cleanup_targets { - let dataset_uri = self.storage().dataset_uri(&table_path); + let dataset_uri = self.table_store.dataset_uri(&table_path); let outcome = match crate::failpoints::maybe_fail("branch_delete.before_table_cleanup") { - Ok(()) => { - self.storage() - .force_delete_branch(&dataset_uri, branch) - .await - } + Ok(()) => self.table_store.force_delete_branch(&dataset_uri, branch).await, Err(injected) => Err(injected), }; if let Err(err) = outcome { @@ -1391,7 +1339,7 @@ impl Omnigraph { &self, table_key: &str, op_kind: crate::db::MutationOpKind, - ) -> Result<(SnapshotHandle, String, Option)> { + ) -> Result<(Dataset, String, Option)> { table_ops::open_for_mutation(self, table_key, op_kind).await } @@ -1400,7 +1348,7 @@ impl Omnigraph { branch: Option<&str>, table_key: &str, op_kind: crate::db::MutationOpKind, - ) -> Result<(SnapshotHandle, String, Option)> { + ) -> Result<(Dataset, String, Option)> { table_ops::open_for_mutation_on_branch(self, branch, table_key, op_kind).await } @@ -1411,7 +1359,7 @@ impl Omnigraph { source_branch: Option<&str>, source_version: u64, active_branch: &str, - ) -> Result { + ) -> Result { table_ops::fork_dataset_from_entry_state( self, table_key, @@ -1430,7 +1378,7 @@ impl Omnigraph { table_branch: Option<&str>, expected_version: u64, op_kind: crate::db::MutationOpKind, - ) -> Result { + ) -> Result { table_ops::reopen_for_mutation( self, table_key, @@ -1447,14 +1395,14 @@ impl Omnigraph { table_path: &str, table_branch: Option<&str>, table_version: u64, - ) -> Result { + ) -> Result { table_ops::open_dataset_at_state(self, table_path, table_branch, table_version).await } pub(crate) async fn build_indices_on_dataset( &self, table_key: &str, - ds: &mut SnapshotHandle, + ds: &mut Dataset, ) -> Result<()> { table_ops::build_indices_on_dataset(self, table_key, ds).await } @@ -1463,7 +1411,7 @@ impl Omnigraph { &self, catalog: &Catalog, table_key: &str, - ds: &mut SnapshotHandle, + ds: &mut Dataset, ) -> Result<()> { table_ops::build_indices_on_dataset_for_catalog(self, catalog, table_key, ds).await } @@ -1543,6 +1491,12 @@ pub(crate) fn normalize_branch_name(branch: &str) -> Result> { } pub(crate) fn ensure_public_branch_ref(branch: &str, operation: &str) -> Result<()> { + if super::is_internal_run_branch(branch) { + return Err(OmniError::manifest(format!( + "{} does not allow internal run ref '{}'", + operation, branch + ))); + } if is_internal_system_branch(branch) { return Err(OmniError::manifest(format!( "{} does not allow internal system ref '{}'", @@ -1946,6 +1900,7 @@ fn json_value_from_array(array: &dyn Array, row: usize) -> Result Company async fn list_dir(&self, dir_uri: &str) -> Result> { self.inner.list_dir(dir_uri).await } - - async fn read_text_versioned(&self, uri: &str) -> Result<(String, String)> { - self.inner.read_text_versioned(uri).await - } - - async fn write_text_if_match( - &self, - uri: &str, - contents: &str, - expected_version: &str, - ) -> Result> { - self.inner - .write_text_if_match(uri, contents, expected_version) - .await - } - - async fn delete_prefix(&self, prefix_uri: &str) -> Result<()> { - self.inner.delete_prefix(prefix_uri).await - } } #[derive(Debug)] @@ -2090,25 +2026,6 @@ edge WorksAt: Person -> Company async fn list_dir(&self, dir_uri: &str) -> Result> { self.inner.list_dir(dir_uri).await } - - async fn read_text_versioned(&self, uri: &str) -> Result<(String, String)> { - self.inner.read_text_versioned(uri).await - } - - async fn write_text_if_match( - &self, - uri: &str, - contents: &str, - expected_version: &str, - ) -> Result> { - self.inner - .write_text_if_match(uri, contents, expected_version) - .await - } - - async fn delete_prefix(&self, prefix_uri: &str) -> Result<()> { - self.inner.delete_prefix(prefix_uri).await - } } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -2198,12 +2115,8 @@ edge WorksAt: Person -> Company async fn table_rows_json(db: &Omnigraph, table_key: &str) -> Vec { let snapshot = db.snapshot().await; - let ds = db - .storage() - .open_snapshot_at_table(&snapshot, table_key) - .await - .unwrap(); - let batches = db.storage().scan_batches(&ds).await.unwrap(); + let ds = snapshot.open(table_key).await.unwrap(); + let batches = db.table_store().scan_batches(&ds).await.unwrap(); batches .into_iter() .flat_map(|batch| { @@ -2215,11 +2128,11 @@ edge WorksAt: Person -> Company } async fn seed_person_row(db: &mut Omnigraph, name: &str, age: Option) { - let (ds, full_path, table_branch) = db + let (mut ds, full_path, table_branch) = db .open_for_mutation("node:Person", crate::db::MutationOpKind::Insert) .await .unwrap(); - let schema: Arc = Arc::new(ds.dataset().schema().into()); + let schema: Arc = Arc::new(ds.schema().into()); let columns: Vec> = schema .fields() .iter() @@ -2231,11 +2144,9 @@ edge WorksAt: Person -> Company }) .collect(); let batch = RecordBatch::try_new(Arc::clone(&schema), columns).unwrap(); - let staged = db.storage().stage_append(&ds, batch, &[]).await.unwrap(); - let committed = db.storage().commit_staged(ds, staged).await.unwrap(); let state = db - .storage() - .table_state(&full_path, &committed) + .table_store() + .append_batch(&full_path, &mut ds, batch) .await .unwrap(); db.commit_updates(&[crate::db::SubTableUpdate { @@ -2327,11 +2238,11 @@ edge WorksAt: Person -> Company #[tokio::test] async fn test_apply_schema_succeeds_after_load() { // Historical: schema apply used to be blocked by leftover - // `__run__` branches. The Run state machine was removed in - // MR-771, so a fresh graph never creates a `__run__` branch; - // legacy ones are swept by the v2β†’v3 manifest migration. This - // asserts the invariant a current graph upholds: publish leaves - // no `__run__` branch behind, so schema apply proceeds. + // `__run__` branches. A defense-in-depth filter now skips + // internal system branches, and run branches were made + // ephemeral on every terminal state β€” so in practice no + // `__run__` branch survives publish. The filter still guards + // the invariant. let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); @@ -2346,8 +2257,8 @@ edge WorksAt: Person -> Company let all_branches = db.coordinator.read().await.all_branches().await.unwrap(); assert!( - !all_branches.iter().any(|b| b.starts_with("__run__")), - "no __run__ branch should exist after publish, got: {:?}", + !all_branches.iter().any(|b| is_internal_run_branch(b)), + "run branch should be deleted after publish, got: {:?}", all_branches ); @@ -2359,56 +2270,6 @@ edge WorksAt: Person -> Company assert!(result.applied, "schema apply should have applied"); } - /// Regression (MR-770): a pre-v0.4.0 graph that still carries a stale - /// `__run__*` branch on `__manifest` must not block schema apply. The - /// v2β†’v3 sweep runs in `Omnigraph::open(ReadWrite)` β€” before the - /// schema-apply blocking-branch check β€” so apply succeeds with no - /// intervening publish. - /// - /// Confirmed to fail before the open-time migration landed: the reopened - /// graph still listed `__run__legacy`, and `apply_schema` returned - /// "found non-main branches: __run__legacy". - #[tokio::test] - async fn legacy_run_branch_is_swept_on_open_and_does_not_block_schema_apply() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - - // Synthesize a legacy graph: a stale `__run__` branch on `__manifest` - // plus the manifest stamp rewound to v2 (pre-sweep). - db.branch_create("__run__legacy").await.unwrap(); - drop(db); - { - let mut ds = lance::Dataset::open(&format!("{}/__manifest", uri)) - .await - .unwrap(); - ds.update_schema_metadata([( - "omnigraph:internal_schema_version".to_string(), - Some("2".to_string()), - )]) - .await - .unwrap(); - } - - // Reopen (ReadWrite): the open-time migration must sweep `__run__legacy` - // before any branch-observing code runs. - let db = Omnigraph::open(uri).await.unwrap(); - let branches = db.branch_list().await.unwrap(); - assert!( - !branches.iter().any(|b| b.starts_with("__run__")), - "open-time migration must sweep legacy __run__ branches; got {branches:?}", - ); - - // Schema apply must proceed with no intervening publish β€” the - // blocking-branch check no longer sees `__run__legacy`. - let desired = TEST_SCHEMA.replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ); - let result = db.apply_schema(&desired).await.unwrap(); - assert!(result.applied, "schema apply should have applied"); - } - #[tokio::test] async fn test_apply_schema_adds_index_for_existing_property() { let dir = tempfile::tempdir().unwrap(); @@ -2419,12 +2280,8 @@ edge WorksAt: Person -> Company db.apply_schema(&desired).await.unwrap(); let snapshot = db.snapshot().await; - let ds = db - .storage() - .open_snapshot_at_table(&snapshot, "node:Person") - .await - .unwrap(); - assert!(db.storage().has_fts_index(&ds, "name").await.unwrap()); + let ds = snapshot.open("node:Person").await.unwrap(); + assert!(db.table_store().has_fts_index(&ds, "name").await.unwrap()); } #[tokio::test] @@ -2442,13 +2299,9 @@ edge WorksAt: Person -> Company db.apply_schema(&desired).await.unwrap(); let snapshot = db.snapshot().await; - let ds = db - .storage() - .open_snapshot_at_table(&snapshot, "node:Person") - .await - .unwrap(); - assert!(db.storage().has_btree_index(&ds, "id").await.unwrap()); - assert!(db.storage().has_fts_index(&ds, "name").await.unwrap()); + let ds = snapshot.open("node:Person").await.unwrap(); + assert!(db.table_store().has_btree_index(&ds, "id").await.unwrap()); + assert!(db.table_store().has_fts_index(&ds, "name").await.unwrap()); } #[tokio::test] diff --git a/crates/omnigraph/src/db/omnigraph/export.rs b/crates/omnigraph/src/db/omnigraph/export.rs index 7696056..366f50a 100644 --- a/crates/omnigraph/src/db/omnigraph/export.rs +++ b/crates/omnigraph/src/db/omnigraph/export.rs @@ -60,12 +60,12 @@ async fn entity_from_snapshot( } let ds = db - .storage() - .open_snapshot_at_table(snapshot, table_key) + .table_store + .open_snapshot_table(snapshot, table_key) .await?; let filter_sql = format!("id = '{}'", id.replace('\'', "''")); let batches = db - .storage() + .table_store .scan(&ds, None, Some(&filter_sql), None) .await?; let Some(batch) = batches.iter().find(|batch| batch.num_rows() > 0) else { @@ -143,23 +143,23 @@ async fn export_table_to_writer( writer: &mut W, ) -> Result<()> { let ds = db - .storage() - .open_snapshot_at_table(snapshot, table_key) + .table_store + .open_snapshot_table(snapshot, table_key) .await?; let ordering = Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())]); let catalog = db.catalog(); let blob_properties = blob_properties_for_table_key(&catalog, table_key)?; if blob_properties.is_empty() { - for batch in db.storage().scan(&ds, None, None, ordering).await? { + for batch in db.table_store.scan(&ds, None, None, ordering).await? { write_export_rows_from_batch(db, table_key, &batch, None, writer)?; } return Ok(()); } let batches = db - .storage() - .scan_with_row_id(&ds, None, None, ordering, true) + .table_store + .scan_with(&ds, None, None, ordering, true, |_| Ok(())) .await?; for batch in batches { let row_ids = batch @@ -175,13 +175,7 @@ async fn export_table_to_writer( .iter() .copied() .collect::>(); - // Blob materialization reaches through to the inner Lance - // `Dataset` because `take_blobs` is a Lance-only API not lifted - // onto the `TableStorage` trait surface (the trait covers - // staged-write and snapshot-scan primitives; blob descriptor - // materialization sits outside that surface). - let blob_values = - export_blob_values(ds.dataset(), &batch, &row_ids, blob_properties).await?; + let blob_values = export_blob_values(&ds, &batch, &row_ids, blob_properties).await?; write_export_rows_from_batch(db, table_key, &batch, Some(&blob_values), writer)?; } Ok(()) diff --git a/crates/omnigraph/src/db/omnigraph/optimize.rs b/crates/omnigraph/src/db/omnigraph/optimize.rs index 21629a8..fff3f54 100644 --- a/crates/omnigraph/src/db/omnigraph/optimize.rs +++ b/crates/omnigraph/src/db/omnigraph/optimize.rs @@ -8,14 +8,8 @@ //! Two dials: //! //! * `optimize_all_tables` β€” Lance `compact_files` on every table. Rewrites -//! small fragments into fewer large ones, then **publishes the compacted -//! version to the `__manifest`** so the manifest's `table_version` tracks the -//! compacted Lance HEAD (reads pin the manifest version, so without the -//! publish compaction would be invisible to readers and would break the -//! HEAD-vs-manifest precondition of schema apply / strict writes). Compaction -//! is content-preserving (Lance `Operation::Rewrite` "reorganizes data -//! without semantic modification"), so old fragments remain reachable via -//! older manifest versions until `cleanup` runs. +//! small fragments into fewer large ones. Non-destructive (creates a new +//! version; old fragments remain reachable via older manifest versions). //! * `cleanup_all_tables` β€” Lance `cleanup_old_versions` on every table. //! Removes manifests (and their unique fragments) older than the configured //! retention. Destructive to version history β€” callers should gate this @@ -29,9 +23,7 @@ use std::time::Duration; use chrono::Utc; use futures::stream::StreamExt; use lance::dataset::cleanup::{CleanupPolicy, RemovalStats}; -use lance::dataset::optimize::{ - CompactionMetrics, CompactionOptions, compact_files, plan_compaction, -}; +use lance::dataset::optimize::{CompactionMetrics, CompactionOptions, compact_files}; use super::*; @@ -75,7 +67,8 @@ pub struct CleanupPolicyOptions { } /// Why `optimize` did not compact a table. Typed so callers branch on the -/// reason rather than sniffing a string. +/// 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 { @@ -83,12 +76,6 @@ pub enum SkipReason { /// `BlobHandling::AllBinary`, which mis-decodes blob-v2 columns; see /// [`LANCE_SUPPORTS_BLOB_COMPACTION`] and `docs/dev/lance.md`. BlobColumnsUnsupportedByLance, - /// The Lance dataset HEAD is ahead of the version recorded in - /// `__manifest`, and no recovery sidecar covers that movement. `optimize` - /// cannot infer whether the drift is benign maintenance or an external - /// semantic write, so it leaves the table untouched and points operators at - /// explicit `repair`. - DriftNeedsRepair, } impl SkipReason { @@ -97,7 +84,6 @@ impl SkipReason { pub fn as_str(&self) -> &'static str { match self { SkipReason::BlobColumnsUnsupportedByLance => "blob_columns_unsupported_by_lance", - SkipReason::DriftNeedsRepair => "drift_needs_repair", } } } @@ -109,7 +95,6 @@ impl std::fmt::Display for SkipReason { SkipReason::BlobColumnsUnsupportedByLance => { "blob columns β€” Lance compaction unsupported" } - SkipReason::DriftNeedsRepair => "manifest/head drift β€” run omnigraph repair", }; f.write_str(msg) } @@ -126,18 +111,11 @@ pub struct TableOptimizeStats { pub fragments_removed: usize, /// Number of new, larger fragments Lance produced. pub fragments_added: usize, - /// Did this table get a new manifest version from the compaction? True when - /// compaction ran and its compacted version was published to `__manifest`. + /// 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, - /// Manifest table version observed by optimize for drift skips. `None` for - /// normal compaction/no-op/blob skips. - pub manifest_version: Option, - /// Lance HEAD version observed by optimize for drift skips. `None` for - /// normal compaction/no-op/blob skips. - pub lance_head_version: Option, } impl TableOptimizeStats { @@ -149,8 +127,6 @@ impl TableOptimizeStats { fragments_added: metrics.fragments_added, committed, skipped: None, - manifest_version: None, - lance_head_version: None, } } @@ -162,25 +138,6 @@ impl TableOptimizeStats { fragments_added: 0, committed: false, skipped: Some(reason), - manifest_version: None, - lance_head_version: None, - } - } - - /// Stat for a table skipped because the manifest and Lance HEAD disagree. - fn skipped_for_drift( - table_key: String, - manifest_version: u64, - lance_head_version: u64, - ) -> Self { - Self { - table_key, - fragments_removed: 0, - fragments_added: 0, - committed: false, - skipped: Some(SkipReason::DriftNeedsRepair), - manifest_version: Some(manifest_version), - lance_head_version: Some(lance_head_version), } } } @@ -196,30 +153,14 @@ pub struct TableCleanupStats { pub error: Option, } -/// Run Lance `compact_files` on every node + edge table on `main`, publishing -/// each compacted table's new version to the `__manifest`. Tables run in -/// parallel (bounded concurrency); each is fault-isolated only at the Lance -/// level β€” a publish error is propagated (the recovery sidecar covers it). +/// Run Lance `compact_files` on every node + edge table on `main`. +/// Tables run in parallel (bounded concurrency). pub async fn optimize_all_tables(db: &Omnigraph) -> Result> { db.ensure_schema_state_valid().await?; db.ensure_schema_apply_idle("optimize").await?; - // Refuse on an unrecovered graph. A pending recovery sidecar means a failed - // write left partial state that the open-time sweep must resolve (roll - // forward/back) first; compacting + publishing a table covered by such a - // sidecar could commit a partial write the sweep would roll back. Reopen the - // graph to run recovery, then re-run optimize. - if !crate::db::manifest::list_sidecars(db.root_uri(), db.storage_adapter()) - .await? - .is_empty() - { - return Err(OmniError::manifest_conflict( - "optimize requires a clean recovery state; reopen the graph to run the \ - recovery sweep before optimizing", - )); - } - - let snapshot = db.fresh_snapshot_for_branch(None).await?; + let resolved = db.resolved_branch_target(None).await?; + let snapshot = resolved.snapshot; // 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. @@ -242,210 +183,49 @@ pub async fn optimize_all_tables(db: &Omnigraph) -> Result> = futures::stream::iter(table_tasks.into_iter()) - .map(move |(table_key, full_path, has_blob)| async move { - optimize_one_table(db, table_key, full_path, has_blob).await + .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?; + let version_before = ds.version().version; + let metrics: CompactionMetrics = + compact_files(&mut ds, CompactionOptions::default(), None) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + let version_after = ds.version().version; + Ok(TableOptimizeStats::compacted( + table_key, + &metrics, + version_after != version_before, + )) }) .buffer_unordered(concurrency) .collect() .await; - // Invalidate caches for any table that published a compaction β€” done BEFORE - // propagating a sibling table's error, since the published versions are - // durable and reads must observe the new fragment layout (Lance invalidates - // the original row addresses on rewrite). The CSR/CSC graph topology index - // is rebuilt only when an edge table moved. Mirrors schema_apply's - // post-publish invalidation. - let any_committed = stats - .iter() - .any(|s| matches!(s, Ok(st) if st.committed)); - let edge_committed = stats - .iter() - .any(|s| matches!(s, Ok(st) if st.committed && st.table_key.starts_with("edge:"))); - if any_committed { - db.runtime_cache.invalidate_all().await; - if edge_committed { - db.invalidate_graph_index().await; - } - } - stats.into_iter().collect() } -/// Compact one table and publish the compacted version to the `__manifest`. -/// -/// Compaction (`compact_files`) advances the *dataset's* Lance HEAD via a -/// reserve-fragments + rewrite commit, but Lance knows nothing about the -/// `__manifest`. To keep the manifest the single authority for each table's -/// visible version (invariant 2), optimize must publish the compacted version. -/// The Lance-HEAD-before-manifest-publish gap is unavoidable (Lance has no -/// staged/uncommitted compaction), so it is covered by a recovery sidecar like -/// the other multi-commit writers; roll-forward is always safe because -/// compaction is content-preserving. -async fn optimize_one_table( - db: &Omnigraph, - table_key: String, - full_path: String, - has_blob: bool, -) -> Result { - // Lance `compact_files` mis-decodes blob-v2 columns under the forced - // `BlobHandling::AllBinary` read (see LANCE_SUPPORTS_BLOB_COMPACTION). Skip - // blob-bearing tables before acquiring the write queue; `repair` is the - // operator tool for full manifest/head drift classification. - 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, - )); - } - - // Serialize the whole compactβ†’publish against concurrent mutations on this - // (table, main): compaction is a Rewrite op that retryable-conflicts with a - // concurrent Merge/Update/Delete on overlapping fragments, and an - // interleaved write would also move the manifest version out from under the - // CAS below. Holding the queue makes the CAS baseline read under it exact. - let _guard = db - .write_queue() - .acquire_many(&[(table_key.clone(), None)]) - .await; - - // `compact_files` is a Lance-only maintenance API that needs `&mut Dataset`. - // The `TableStorage` trait deliberately does not surface it (the staged-write - // invariant covers writes; compaction is a separate concern). Unwrap the - // opaque `SnapshotHandle` via `into_dataset()` (`pub(crate)`, gated to the - // maintenance path). - let handle = db - .storage() - .open_dataset_head_for_write(&table_key, &full_path, None) - .await?; - let mut ds = handle.into_dataset(); - - // CAS baseline: the table's current manifest version, read under the queue - // (in-memory coordinator snapshot, no storage I/O β€” stable for this section). - let expected_version = db - .fresh_snapshot_for_branch(None) - .await? - .entry(&table_key) - .map(|e| e.table_version) - .ok_or_else(|| OmniError::manifest(format!("no manifest entry for {}", table_key)))?; - - let lance_head_version = ds.version().version; - if lance_head_version < expected_version { - return Err(OmniError::manifest_internal(format!( - "table '{}' Lance HEAD version {} is behind manifest version {}", - table_key, lance_head_version, expected_version - ))); - } - if lance_head_version > expected_version { - tracing::warn!( - target: "omnigraph::optimize", - table = %table_key, - manifest_version = expected_version, - lance_head_version, - "skipping compaction: Lance HEAD is ahead of the manifest; run `omnigraph repair` \ - to classify and publish covered maintenance drift explicitly", - ); - return Ok(TableOptimizeStats::skipped_for_drift( - table_key, - expected_version, - lance_head_version, - )); - } - - // Precise "will it compact?" check β€” `plan_compaction` also accounts for - // deletion materialization (which can rewrite even a single fragment). A - // steady-state already-compacted table yields an empty plan and is never - // pinned in a sidecar (a zero-commit pin would classify NoMovement on - // recovery and force an all-or-nothing rollback). Uncovered pre-existing - // drift is skipped above and must go through explicit repair. - let options = CompactionOptions::default(); - let plan = plan_compaction(&ds, &options) - .await - .map_err(|e| OmniError::Lance(e.to_string()))?; - if plan.num_tasks() == 0 { - return Ok(TableOptimizeStats::compacted( - table_key, - &CompactionMetrics::default(), - false, - )); - } - - // Phase A: recovery sidecar BEFORE compaction advances the Lance HEAD, so a - // crash before the manifest publish rolls forward on next open. - let sidecar = crate::db::manifest::new_sidecar( - crate::db::manifest::SidecarKind::Optimize, - None, - // optimize is system-attributed (no `optimize_as` actor API today). - None, - vec![crate::db::manifest::SidecarTablePin { - table_key: table_key.clone(), - table_path: full_path.clone(), - expected_version, - // Lower bound β€” compaction commits Nβ‰₯1 versions (reserve + rewrite); - // the classifier loose-matches SidecarKind::Optimize. - post_commit_pin: expected_version + 1, - table_branch: None, - }], - ); - let handle = - crate::db::manifest::write_sidecar(db.root_uri(), db.storage_adapter(), &sidecar).await?; - - // Phase B: compaction (reserve-fragments + rewrite commits advance HEAD). - let version_before = ds.version().version; - let metrics: CompactionMetrics = compact_files(&mut ds, options, None) - .await - .map_err(|e| OmniError::Lance(e.to_string()))?; - let version_after = ds.version().version; - let committed = version_after != version_before; - - // Pin the per-writer Phase B β†’ Phase C residual for optimize: Lance HEAD has - // advanced but the manifest publish below hasn't run. - crate::failpoints::maybe_fail("optimize.post_phase_b_pre_manifest_commit")?; - - // Phase C: publish the compacted version to the manifest (one CAS commit, - // expected = the version observed under the queue). On failure the sidecar - // is intentionally left for the open-time recovery sweep to roll forward. - if committed { - // Re-wrap the post-compaction dataset to read its state through the - // trait surface (`table_state` is a read; no HEAD advance). - let snapshot = crate::storage_layer::SnapshotHandle::new(ds); - let state = db.storage().table_state(&full_path, &snapshot).await?; - let update = crate::db::SubTableUpdate { - table_key: table_key.clone(), - table_version: state.version, - table_branch: None, - row_count: state.row_count, - version_metadata: state.version_metadata, - }; - let mut expected = std::collections::HashMap::new(); - expected.insert(table_key.clone(), expected_version); - db.coordinator - .write() - .await - .commit_updates_with_actor_with_expected(&[update], &expected, None) - .await?; - } - - // Phase D: delete the sidecar (best-effort; recovery resolves a leftover). - if let Err(err) = crate::db::manifest::delete_sidecar(&handle, db.storage_adapter()).await { - tracing::warn!( - error = %err, - operation_id = handle.operation_id.as_str(), - "optimize recovery sidecar cleanup failed; next open's recovery sweep will resolve it" - ); - } - - Ok(TableOptimizeStats::compacted(table_key, &metrics, committed)) -} - /// Run Lance `cleanup_old_versions` on every node + edge table on `main`, /// using [`CleanupPolicyOptions`]. The latest manifest is always preserved /// regardless (Lance invariant). @@ -502,7 +282,7 @@ pub async fn cleanup_all_tables( } let concurrency = maint_concurrency().min(table_tasks.len()).max(1); - let storage = db.storage(); + let table_store = &db.table_store; // 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. @@ -512,13 +292,9 @@ pub async fn cleanup_all_tables( .map(|(table_key, full_path)| async move { let outcome: Result = async { crate::failpoints::maybe_fail("cleanup.table_gc")?; - // `cleanup_old_versions` is a Lance-only maintenance API not - // surfaced through `TableStorage` β€” see the optimize path - // above for the same rationale. Unwrap via `into_dataset()`. - let handle = storage + let ds = table_store .open_dataset_head_for_write(&table_key, &full_path, None) .await?; - let ds = handle.into_dataset(); let before_version = keep_versions .map(|n| ds.version().version.saturating_sub(n as u64)) .filter(|v| *v > 0); @@ -619,9 +395,8 @@ pub async fn reconcile_orphaned_branches(db: &Omnigraph) -> Result listed, Err(err) => { tracing::warn!( @@ -636,7 +411,7 @@ pub async fn reconcile_orphaned_branches(db: &Omnigraph) -> Result storage.force_delete_branch(&full_path, &branch).await, + Ok(()) => db.table_store.force_delete_branch(&full_path, &branch).await, Err(injected) => Err(injected), }; match outcome { @@ -710,7 +485,7 @@ fn orphan_branches(present: Vec, keep: &std::collections::HashSet Vec { +fn all_table_keys(catalog: &omnigraph_compiler::catalog::Catalog) -> Vec { let mut keys: Vec = catalog .node_types .keys() diff --git a/crates/omnigraph/src/db/omnigraph/repair.rs b/crates/omnigraph/src/db/omnigraph/repair.rs deleted file mode 100644 index 8e7146a..0000000 --- a/crates/omnigraph/src/db/omnigraph/repair.rs +++ /dev/null @@ -1,340 +0,0 @@ -//! Explicit repair for uncovered manifest/head drift. -//! -//! Recovery sidecars handle deterministic crash residuals automatically. This -//! module is for the different case: a table's Lance HEAD is ahead of the -//! version recorded in `__manifest` and there is no sidecar encoding writer -//! intent. `repair` classifies that uncovered drift from Lance transactions and -//! only auto-publishes maintenance-only drift when the operator confirms. - -use std::collections::HashMap; - -use lance::Dataset; -use lance::dataset::transaction::Operation; - -use super::*; - -/// Options for [`Omnigraph::repair`]. -#[derive(Debug, Clone, Copy, Default)] -pub struct RepairOptions { - /// Preview by default. With `confirm`, verified maintenance drift is - /// published to `__manifest`. - pub confirm: bool, - /// Also publish suspicious/unverifiable drift. Requires `confirm`. - pub force: bool, -} - -/// Classification of a table's manifest/head state. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum RepairClassification { - /// Lance HEAD equals the manifest pin. - NoDrift, - /// Every uncovered Lance transaction is maintenance-only (`Rewrite` or - /// `ReserveFragments`), so publishing the HEAD is content-preserving. - VerifiedMaintenance, - /// At least one uncovered transaction is semantic (`Append`, `Delete`, - /// `Update`, etc.). - Suspicious, - /// A needed transaction could not be read, so the drift cannot be judged. - Unverifiable, -} - -impl RepairClassification { - /// Stable machine-readable token for serialized output. - pub fn as_str(&self) -> &'static str { - match self { - Self::NoDrift => "no_drift", - Self::VerifiedMaintenance => "verified_maintenance", - Self::Suspicious => "suspicious", - Self::Unverifiable => "unverifiable", - } - } -} - -impl std::fmt::Display for RepairClassification { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(self.as_str()) - } -} - -/// What repair did for a table. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum RepairAction { - /// Nothing to do. - NoOp, - /// Drift was reported but not published because this was a preview. - Preview, - /// Verified maintenance drift was published to `__manifest`. - Healed, - /// Suspicious/unverifiable drift was published because `force` was set. - Forced, - /// Drift was left untouched because it was not safe to publish without - /// `force`. - Refused, -} - -impl RepairAction { - /// Stable machine-readable token for serialized output. - pub fn as_str(&self) -> &'static str { - match self { - Self::NoOp => "no_op", - Self::Preview => "preview", - Self::Healed => "healed", - Self::Forced => "forced", - Self::Refused => "refused", - } - } -} - -impl std::fmt::Display for RepairAction { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(self.as_str()) - } -} - -/// Per-table repair outcome. -#[derive(Debug, Clone)] -#[non_exhaustive] -pub struct TableRepairStats { - pub table_key: String, - pub manifest_version: u64, - pub lance_head_version: u64, - pub classification: RepairClassification, - pub action: RepairAction, - pub operations: Vec, - pub error: Option, -} - -/// Whole-graph repair outcome. -#[derive(Debug, Clone)] -#[non_exhaustive] -pub struct RepairStats { - pub tables: Vec, - /// New graph manifest version if repair published any table pins. - pub manifest_version: Option, -} - -struct ClassificationResult { - classification: RepairClassification, - operations: Vec, - error: Option, -} - -pub async fn repair_all_tables(db: &Omnigraph, options: RepairOptions) -> Result { - if options.force && !options.confirm { - return Err(OmniError::manifest("repair --force requires --confirm")); - } - - db.ensure_schema_state_valid().await?; - db.ensure_schema_apply_idle("repair").await?; - ensure_no_pending_recovery_sidecars(db, "repair").await?; - - let snapshot = db.fresh_snapshot_for_branch(None).await?; - let table_tasks: Vec<(String, String)> = { - let catalog = db.catalog(); - let mut tasks = Vec::new(); - for table_key in optimize::all_table_keys(&catalog) { - let Some(entry) = snapshot.entry(&table_key) else { - continue; - }; - let full_path = format!("{}/{}", db.root_uri, entry.table_path); - tasks.push((table_key, full_path)); - } - tasks - }; - - if table_tasks.is_empty() { - return Ok(RepairStats { - tables: Vec::new(), - manifest_version: None, - }); - } - - let queue_keys: Vec<(String, Option)> = table_tasks - .iter() - .map(|(table_key, _)| (table_key.clone(), None)) - .collect(); - let _guards = db.write_queue().acquire_many(&queue_keys).await; - ensure_no_pending_recovery_sidecars(db, "repair").await?; - - let snapshot = db.fresh_snapshot_for_branch(None).await?; - let mut tables = Vec::with_capacity(table_tasks.len()); - let mut updates = Vec::new(); - let mut expected = HashMap::new(); - let mut any_forced = false; - - for (table_key, full_path) in table_tasks { - // `classify_drift` inspects raw Lance transaction history - // (`read_transaction_by_version`), a Lance-only maintenance read the - // staged-write trait does not surface. Open via `db.storage()` and - // unwrap the opaque handle (mirrors optimize / cleanup). - let ds = db - .storage() - .open_dataset_head_for_write(&table_key, &full_path, None) - .await? - .into_dataset(); - let manifest_version = snapshot - .entry(&table_key) - .map(|e| e.table_version) - .ok_or_else(|| OmniError::manifest(format!("no manifest entry for {}", table_key)))?; - let lance_head_version = ds.version().version; - - if lance_head_version < manifest_version { - return Err(OmniError::manifest_internal(format!( - "table '{}' Lance HEAD version {} is behind manifest version {}", - table_key, lance_head_version, manifest_version - ))); - } - - if lance_head_version == manifest_version { - tables.push(TableRepairStats { - table_key, - manifest_version, - lance_head_version, - classification: RepairClassification::NoDrift, - action: RepairAction::NoOp, - operations: Vec::new(), - error: None, - }); - continue; - } - - let classification = classify_drift(&ds, manifest_version, lance_head_version).await; - let action = match ( - options.confirm, - options.force, - classification.classification, - ) { - (false, _, _) => RepairAction::Preview, - (true, _, RepairClassification::VerifiedMaintenance) => RepairAction::Healed, - (true, true, RepairClassification::Suspicious | RepairClassification::Unverifiable) => { - any_forced = true; - RepairAction::Forced - } - (true, _, RepairClassification::Suspicious | RepairClassification::Unverifiable) => { - RepairAction::Refused - } - (true, _, RepairClassification::NoDrift) => RepairAction::NoOp, - }; - - if matches!(action, RepairAction::Healed | RepairAction::Forced) { - // Re-wrap the opened dataset to read its state through the trait - // surface (`table_state` is a read; no HEAD advance). - let snapshot = crate::storage_layer::SnapshotHandle::new(ds); - let state = db.storage().table_state(&full_path, &snapshot).await?; - updates.push(crate::db::SubTableUpdate { - table_key: table_key.clone(), - table_version: state.version, - table_branch: None, - row_count: state.row_count, - version_metadata: state.version_metadata, - }); - expected.insert(table_key.clone(), manifest_version); - } - - tables.push(TableRepairStats { - table_key, - manifest_version, - lance_head_version, - classification: classification.classification, - action, - operations: classification.operations, - error: classification.error, - }); - } - - let manifest_version = if updates.is_empty() { - None - } else { - let actor = if any_forced { - Some("omnigraph:repair:force") - } else { - Some("omnigraph:repair") - }; - let PublishedSnapshot { - manifest_version, - _snapshot_id: _, - } = db - .coordinator - .write() - .await - .commit_updates_with_actor_with_expected(&updates, &expected, actor) - .await?; - db.runtime_cache.invalidate_all().await; - if updates - .iter() - .any(|update| update.table_key.starts_with("edge:")) - { - db.invalidate_graph_index().await; - } - Some(manifest_version) - }; - - Ok(RepairStats { - tables, - manifest_version, - }) -} - -async fn ensure_no_pending_recovery_sidecars(db: &Omnigraph, operation: &str) -> Result<()> { - if !crate::db::manifest::list_sidecars(db.root_uri(), db.storage_adapter()) - .await? - .is_empty() - { - return Err(OmniError::manifest_conflict(format!( - "{operation} requires a clean recovery state; reopen the graph to run the \ - recovery sweep before repairing" - ))); - } - Ok(()) -} - -async fn classify_drift( - ds: &Dataset, - manifest_version: u64, - lance_head_version: u64, -) -> ClassificationResult { - let mut operations = Vec::new(); - let mut saw_suspicious = false; - let mut error = None; - - for version in manifest_version.saturating_add(1)..=lance_head_version { - match ds.read_transaction_by_version(version).await { - Ok(Some(transaction)) => { - let operation = transaction.operation; - operations.push(operation.name().to_string()); - if !matches!( - operation, - Operation::Rewrite { .. } | Operation::ReserveFragments { .. } - ) { - saw_suspicious = true; - } - } - Ok(None) => { - error = Some(format!("missing Lance transaction for version {version}")); - break; - } - Err(err) => { - error = Some(format!( - "failed to read Lance transaction for version {version}: {err}" - )); - break; - } - } - } - - let classification = if error.is_some() { - RepairClassification::Unverifiable - } else if saw_suspicious { - RepairClassification::Suspicious - } else { - RepairClassification::VerifiedMaintenance - }; - - ClassificationResult { - classification, - operations, - error, - } -} diff --git a/crates/omnigraph/src/db/omnigraph/schema_apply.rs b/crates/omnigraph/src/db/omnigraph/schema_apply.rs index 506db36..35fe161 100644 --- a/crates/omnigraph/src/db/omnigraph/schema_apply.rs +++ b/crates/omnigraph/src/db/omnigraph/schema_apply.rs @@ -61,11 +61,11 @@ async fn plan_schema_for_apply( ) -> 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, - // the cluster-wide schema-apply serializer). Legacy `__run__*` staging - // branches were swept off `__manifest` by the v2β†’v3 migration that runs in - // `Omnigraph::open(ReadWrite)` before this check (MR-770), so they no - // longer appear here. + // 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)) @@ -355,7 +355,7 @@ where let entry = snapshot.entry(table_key)?; Some(crate::db::manifest::SidecarTablePin { table_key: table_key.clone(), - table_path: db.storage().dataset_uri(&entry.table_path), + table_path: db.table_store.dataset_uri(&entry.table_path), expected_version: entry.table_version, post_commit_pin: entry.table_version + 1, table_branch: entry.table_branch.clone(), @@ -469,13 +469,12 @@ where for table_key in &added_tables { let table_path = table_path_for_table_key(table_key)?; - let dataset_uri = db.storage().dataset_uri(&table_path); + let dataset_uri = db.table_store.dataset_uri(&table_path); let schema = schema_for_table_key(&desired_catalog, table_key)?; - let mut ds = - SnapshotHandle::new(TableStore::create_empty_dataset(&dataset_uri, &schema).await?); + let mut ds = TableStore::create_empty_dataset(&dataset_uri, &schema).await?; db.build_indices_on_dataset_for_catalog(&desired_catalog, table_key, &mut ds) .await?; - let state = db.storage().table_state(&dataset_uri, &ds).await?; + let state = db.table_store.table_state(&dataset_uri, &ds).await?; table_registrations.insert(table_key.clone(), table_path); table_updates.insert( table_key.clone(), @@ -497,10 +496,7 @@ where )) })?; ensure_snapshot_entry_head_matches(db, source_entry).await?; - let source_ds = db - .storage() - .open_snapshot_at_table(&snapshot, source_table_key) - .await?; + let source_ds = snapshot.open(source_table_key).await?; let current_catalog = db.catalog(); let batch = batch_for_schema_apply_rewrite( db, @@ -513,12 +509,11 @@ where ) .await?; let table_path = table_path_for_table_key(target_table_key)?; - let dataset_uri = db.storage().dataset_uri(&table_path); - let mut target_ds = - SnapshotHandle::new(TableStore::write_dataset(&dataset_uri, batch).await?); + let dataset_uri = db.table_store.dataset_uri(&table_path); + let mut target_ds = TableStore::write_dataset(&dataset_uri, batch).await?; db.build_indices_on_dataset_for_catalog(&desired_catalog, target_table_key, &mut target_ds) .await?; - let state = db.storage().table_state(&dataset_uri, &target_ds).await?; + let state = db.table_store.table_state(&dataset_uri, &target_ds).await?; table_registrations.insert(target_table_key.clone(), table_path); table_updates.insert( target_table_key.clone(), @@ -547,10 +542,7 @@ where )) })?; ensure_snapshot_entry_head_matches(db, entry).await?; - let source_ds = db - .storage() - .open_snapshot_at_table(&snapshot, table_key) - .await?; + let source_ds = snapshot.open(table_key).await?; let current_catalog = db.catalog(); let batch = batch_for_schema_apply_rewrite( db, @@ -562,22 +554,37 @@ where property_renames.get(table_key), ) .await?; - let dataset_uri = db.storage().dataset_uri(&entry.table_path); - // Pass `entry.table_branch.as_deref()` (not `None`) for - // consistency with the indexed_tables block below. Schema - // apply runs under `__schema_apply_lock__` which today rejects - // non-main branches, so `entry.table_branch` is expected to be - // `None`. But the defensive passthrough means a future relaxation - // of the lock-check can't quietly open the wrong HEAD here. - let existing = db - .storage() - .open_dataset_head_for_write(table_key, &dataset_uri, entry.table_branch.as_deref()) - .await?; - let staged = db.storage().stage_overwrite(&existing, batch).await?; - let mut target_ds = db.storage().commit_staged(existing, staged).await?; + let dataset_uri = db.table_store.dataset_uri(&entry.table_path); + // Route through stage_overwrite + commit_staged for non-empty + // batches. Lance's `InsertBuilder::execute_uncommitted` + // errors on empty data (lance-4.0.0 `src/dataset/write/insert.rs:144`), + // so the empty-rewrite case stays on `overwrite_dataset` (which + // accepts empty input). The empty case is rare in schema_apply + // β€” it only fires when the source table itself was already empty + // β€” and schema_apply runs under `__schema_apply_lock__` so the + // narrow inline-commit residual is bounded. + let mut target_ds = if batch.num_rows() == 0 { + TableStore::overwrite_dataset(&dataset_uri, batch).await? + } else { + // Pass `entry.table_branch.as_deref()` (not `None`) for + // consistency with the indexed_tables block below. Schema + // apply runs under `__schema_apply_lock__` which today + // rejects non-main branches, so `entry.table_branch` is + // expected to be `None`. But the defensive passthrough + // means a future relaxation of the lock-check can't quietly + // open the wrong HEAD here. + let existing = db + .table_store + .open_dataset_head_for_write(table_key, &dataset_uri, entry.table_branch.as_deref()) + .await?; + let staged = db.table_store.stage_overwrite(&existing, batch).await?; + db.table_store + .commit_staged(Arc::new(existing), staged.transaction) + .await? + }; db.build_indices_on_dataset_for_catalog(&desired_catalog, table_key, &mut target_ds) .await?; - let state = db.storage().table_state(&dataset_uri, &target_ds).await?; + let state = db.table_store.table_state(&dataset_uri, &target_ds).await?; table_updates.insert( table_key.clone(), crate::db::SubTableUpdate { @@ -604,16 +611,16 @@ where )) })?; ensure_snapshot_entry_head_matches(db, entry).await?; - let dataset_uri = db.storage().dataset_uri(&entry.table_path); + let dataset_uri = db.table_store.dataset_uri(&entry.table_path); let mut ds = db - .storage() + .table_store .open_dataset_head_for_write(table_key, &dataset_uri, entry.table_branch.as_deref()) .await?; - db.storage() + db.table_store .ensure_expected_version(&ds, table_key, entry.table_version)?; db.build_indices_on_dataset_for_catalog(&desired_catalog, table_key, &mut ds) .await?; - let state = db.storage().table_state(&dataset_uri, &ds).await?; + let state = db.table_store.table_state(&dataset_uri, &ds).await?; table_updates.insert( table_key.clone(), crate::db::SubTableUpdate { @@ -862,22 +869,22 @@ pub(super) async fn ensure_snapshot_entry_head_matches( db: &Omnigraph, entry: &SubTableEntry, ) -> Result<()> { - let dataset_uri = db.storage().dataset_uri(&entry.table_path); + let dataset_uri = db.table_store.dataset_uri(&entry.table_path); let ds = db - .storage() + .table_store .open_dataset_head_for_write( &entry.table_key, &dataset_uri, entry.table_branch.as_deref(), ) .await?; - db.storage() + db.table_store .ensure_expected_version(&ds, &entry.table_key, entry.table_version) } pub(super) async fn batch_for_schema_apply_rewrite( db: &Omnigraph, - source_ds: &SnapshotHandle, + source_ds: &Dataset, source_table_key: &str, source_catalog: &Catalog, target_table_key: &str, @@ -889,11 +896,11 @@ pub(super) async fn batch_for_schema_apply_rewrite( let target_blob_properties = blob_properties_for_table_key(target_catalog, target_table_key)?; let needs_row_ids = !source_blob_properties.is_empty() || !target_blob_properties.is_empty(); let batches = if needs_row_ids { - db.storage() - .scan_with_row_id(source_ds, None, None, None, true) + db.table_store() + .scan_with(source_ds, None, None, None, true, |_| Ok(())) .await? } else { - db.storage().scan_batches(source_ds).await? + db.table_store().scan_batches(source_ds).await? }; if batches.is_empty() { return Ok(RecordBatch::new_empty(target_schema)); @@ -963,7 +970,7 @@ pub(super) async fn batch_for_schema_apply_rewrite( async fn rebuild_blob_column( _db: &Omnigraph, - source_ds: &SnapshotHandle, + source_ds: &Dataset, column_name: &str, descriptions: &StructArray, row_ids: &[u64], @@ -983,7 +990,7 @@ async fn rebuild_blob_column( let blob_files = if non_null_row_ids.is_empty() { Vec::new() } else { - Arc::new(source_ds.dataset().clone()) + Arc::new(source_ds.clone()) .take_blobs(&non_null_row_ids, column_name) .await .map_err(|e| OmniError::Lance(e.to_string()))? diff --git a/crates/omnigraph/src/db/omnigraph/table_ops.rs b/crates/omnigraph/src/db/omnigraph/table_ops.rs index f7a365a..3ed9c43 100644 --- a/crates/omnigraph/src/db/omnigraph/table_ops.rs +++ b/crates/omnigraph/src/db/omnigraph/table_ops.rs @@ -50,10 +50,10 @@ pub(super) async fn failpoint_publish_table_head_without_index_rebuild_for_test( .ok_or_else(|| OmniError::manifest(format!("no manifest entry for {}", table_key)))?; let full_path = format!("{}/{}", db.root_uri, entry.table_path); let ds = db - .storage() + .table_store .open_dataset_head_for_write(table_key, &full_path, table_branch) .await?; - let state = db.storage().table_state(&full_path, &ds).await?; + let state = db.table_store.table_state(&full_path, &ds).await?; let update = crate::db::SubTableUpdate { table_key: table_key.to_string(), table_version: state.version, @@ -209,18 +209,18 @@ pub(super) async fn ensure_indices_for_branch(db: &Omnigraph, branch: Option<&st } }, None => ( - db.storage() + db.table_store .open_dataset_head_for_write(&table_key, &full_path, None) .await?, None, ), }; - let row_count = db.storage().count_rows(&ds, None).await.unwrap_or(0); + let row_count = db.table_store.count_rows(&ds, None).await.unwrap_or(0); if row_count > 0 { build_indices_on_dataset(db, &table_key, &mut ds).await?; } - let state = db.storage().table_state(&full_path, &ds).await?; + let state = db.table_store.table_state(&full_path, &ds).await?; if state.version != entry.table_version || resolved_branch.as_deref() != entry.table_branch.as_deref() { @@ -257,18 +257,18 @@ pub(super) async fn ensure_indices_for_branch(db: &Omnigraph, branch: Option<&st } }, None => ( - db.storage() + db.table_store .open_dataset_head_for_write(&table_key, &full_path, None) .await?, None, ), }; - let row_count = db.storage().count_rows(&ds, None).await.unwrap_or(0); + let row_count = db.table_store.count_rows(&ds, None).await.unwrap_or(0); if row_count > 0 { build_indices_on_dataset(db, &table_key, &mut ds).await?; } - let state = db.storage().table_state(&full_path, &ds).await?; + let state = db.table_store.table_state(&full_path, &ds).await?; if state.version != entry.table_version || resolved_branch.as_deref() != entry.table_branch.as_deref() { @@ -331,7 +331,7 @@ async fn needs_index_work_node( table_branch: Option<&str>, ) -> Result { let ds = db - .storage() + .table_store .open_dataset_head_for_write(table_key, full_path, table_branch) .await?; // Empty tables are skipped by the ensure_indices loop, so they must @@ -341,10 +341,10 @@ async fn needs_index_work_node( // Errors from count_rows are propagated: silently treating them as // "0 rows" risks skipping a table that is actually about to be // modified. - if db.storage().count_rows(&ds, None).await? == 0 { + if db.table_store.count_rows(&ds, None).await? == 0 { return Ok(false); } - if !db.storage().has_btree_index(&ds, "id").await? { + if !db.table_store.has_btree_index(&ds, "id").await? { return Ok(true); } let catalog = db.catalog(); @@ -360,11 +360,11 @@ async fn needs_index_work_node( continue; }; if matches!(prop_type.scalar, ScalarType::String) && !prop_type.list { - if !db.storage().has_fts_index(&ds, prop_name).await? { + if !db.table_store.has_fts_index(&ds, prop_name).await? { return Ok(true); } } else if matches!(prop_type.scalar, ScalarType::Vector(_)) && !prop_type.list { - if !db.storage().has_vector_index(&ds, prop_name).await? { + if !db.table_store.has_vector_index(&ds, prop_name).await? { return Ok(true); } } @@ -389,22 +389,22 @@ async fn needs_index_work_edge( table_branch: Option<&str>, ) -> Result { let ds = db - .storage() + .table_store .open_dataset_head_for_write(table_key, full_path, table_branch) .await?; - if db.storage().count_rows(&ds, None).await? == 0 { + if db.table_store.count_rows(&ds, None).await? == 0 { return Ok(false); } - Ok(!db.storage().has_btree_index(&ds, "id").await? - || !db.storage().has_btree_index(&ds, "src").await? - || !db.storage().has_btree_index(&ds, "dst").await?) + Ok(!db.table_store.has_btree_index(&ds, "id").await? + || !db.table_store.has_btree_index(&ds, "src").await? + || !db.table_store.has_btree_index(&ds, "dst").await?) } pub(super) async fn open_for_mutation( db: &Omnigraph, table_key: &str, op_kind: crate::db::MutationOpKind, -) -> Result<(SnapshotHandle, String, Option)> { +) -> Result<(Dataset, String, Option)> { let current_branch = db .coordinator .read() @@ -425,7 +425,7 @@ pub(super) async fn open_for_mutation_on_branch( branch: Option<&str>, table_key: &str, op_kind: crate::db::MutationOpKind, -) -> Result<(SnapshotHandle, String, Option)> { +) -> Result<(Dataset, String, Option)> { db.ensure_schema_apply_not_locked("write").await?; let resolved = db.resolved_branch_target(branch).await?; let entry = resolved @@ -436,11 +436,11 @@ pub(super) async fn open_for_mutation_on_branch( match resolved.branch.as_deref() { None => { let ds = db - .storage() + .table_store .open_dataset_head_for_write(table_key, &full_path, None) .await?; if op_kind.strict_pre_stage_version_check() { - db.storage() + db.table_store .ensure_expected_version(&ds, table_key, entry.table_version)?; } Ok((ds, full_path, None)) @@ -469,15 +469,15 @@ pub(super) async fn open_owned_dataset_for_branch_write( entry_version: u64, active_branch: &str, op_kind: crate::db::MutationOpKind, -) -> Result<(SnapshotHandle, Option)> { +) -> Result<(Dataset, Option)> { match entry_branch { Some(branch) if branch == active_branch => { let ds = db - .storage() + .table_store .open_dataset_head_for_write(table_key, full_path, Some(active_branch)) .await?; if op_kind.strict_pre_stage_version_check() { - db.storage() + db.table_store .ensure_expected_version(&ds, table_key, entry_version)?; } Ok((ds, Some(active_branch.to_string()))) @@ -509,11 +509,11 @@ pub(super) async fn open_owned_dataset_for_branch_write( ) .await?; let ds = db - .storage() + .table_store .open_dataset_head_for_write(table_key, full_path, Some(active_branch)) .await?; if op_kind.strict_pre_stage_version_check() { - db.storage() + db.table_store .ensure_expected_version(&ds, table_key, entry_version)?; } Ok((ds, Some(active_branch.to_string()))) @@ -528,8 +528,8 @@ pub(super) async fn fork_dataset_from_entry_state( source_branch: Option<&str>, source_version: u64, active_branch: &str, -) -> Result { - db.storage() +) -> Result { + db.table_store .fork_branch_from_state( full_path, source_branch, @@ -547,10 +547,10 @@ pub(super) async fn reopen_for_mutation( table_branch: Option<&str>, expected_version: u64, op_kind: crate::db::MutationOpKind, -) -> Result { +) -> Result { db.ensure_schema_apply_not_locked("write").await?; if op_kind.strict_pre_stage_version_check() { - db.storage() + db.table_store .reopen_for_mutation(full_path, table_branch, table_key, expected_version) .await } else { @@ -563,7 +563,7 @@ pub(super) async fn reopen_for_mutation( // genuine cross-process drift as 409. See // [`crate::db::MutationOpKind`] for the policy rationale. let _ = expected_version; - db.storage() + db.table_store .open_dataset_head_for_write(table_key, full_path, table_branch) .await } @@ -574,8 +574,8 @@ pub(super) async fn open_dataset_at_state( table_path: &str, table_branch: Option<&str>, table_version: u64, -) -> Result { - db.storage() +) -> Result { + db.table_store .open_dataset_at_state(table_path, table_branch, table_version) .await } @@ -583,7 +583,7 @@ pub(super) async fn open_dataset_at_state( pub(super) async fn build_indices_on_dataset( db: &Omnigraph, table_key: &str, - ds: &mut SnapshotHandle, + ds: &mut Dataset, ) -> Result<()> { let catalog = db.catalog(); build_indices_on_dataset_for_catalog(db, &catalog, table_key, ds).await @@ -593,10 +593,10 @@ pub(super) async fn build_indices_on_dataset_for_catalog( db: &Omnigraph, catalog: &Catalog, table_key: &str, - ds: &mut SnapshotHandle, + ds: &mut Dataset, ) -> Result<()> { if let Some(type_name) = table_key.strip_prefix("node:") { - if !db.storage().has_btree_index(ds, "id").await? { + if !db.table_store.has_btree_index(ds, "id").await? { stage_and_commit_btree(db, table_key, ds, &["id"]).await?; } @@ -616,20 +616,19 @@ pub(super) async fn build_indices_on_dataset_for_catalog( let prop_name = &index_cols[0]; if let Some(prop_type) = node_type.properties.get(prop_name) { if matches!(prop_type.scalar, ScalarType::String) && !prop_type.list { - if !db.storage().has_fts_index(ds, prop_name).await? { + if !db.table_store.has_fts_index(ds, prop_name).await? { stage_and_commit_inverted(db, table_key, ds, prop_name.as_str()) .await?; } } else if matches!(prop_type.scalar, ScalarType::Vector(_)) && !prop_type.list { - if !db.storage().has_vector_index(ds, prop_name).await? { - // Inline-commit residual: lance-6.0.1 does not + if !db.table_store.has_vector_index(ds, prop_name).await? { + // Inline-commit residual: lance-4.0.0 does not // expose `build_index_metadata_from_segments` as // `pub`, so vector indices cannot be staged from // outside the lance crate. Document at the call // site; companion ticket to lance-format/lance#6658. - let new_snap = db - .storage_inline_residual() - .create_vector_index(ds.clone(), prop_name.as_str()) + db.table_store + .create_vector_index(ds, prop_name.as_str()) .await .map_err(|e| { OmniError::Lance(format!( @@ -637,7 +636,6 @@ pub(super) async fn build_indices_on_dataset_for_catalog( table_key, prop_name, e )) })?; - *ds = new_snap; } } } @@ -647,13 +645,13 @@ pub(super) async fn build_indices_on_dataset_for_catalog( } if table_key.starts_with("edge:") { - if !db.storage().has_btree_index(ds, "id").await? { + if !db.table_store.has_btree_index(ds, "id").await? { stage_and_commit_btree(db, table_key, ds, &["id"]).await?; } - if !db.storage().has_btree_index(ds, "src").await? { + if !db.table_store.has_btree_index(ds, "src").await? { stage_and_commit_btree(db, table_key, ds, &["src"]).await?; } - if !db.storage().has_btree_index(ds, "dst").await? { + if !db.table_store.has_btree_index(ds, "dst").await? { stage_and_commit_btree(db, table_key, ds, &["dst"]).await?; } return Ok(()); @@ -676,11 +674,11 @@ pub(super) async fn build_indices_on_dataset_for_catalog( async fn stage_and_commit_btree( db: &Omnigraph, table_key: &str, - ds: &mut SnapshotHandle, + ds: &mut Dataset, columns: &[&str], ) -> Result<()> { let staged = db - .storage() + .table_store .stage_create_btree_index(ds, columns) .await .map_err(|e| { @@ -695,8 +693,8 @@ async fn stage_and_commit_btree( // yet called) leaves no Lance-HEAD drift on the touched table. crate::failpoints::maybe_fail("ensure_indices.post_stage_pre_commit_btree")?; let new_ds = db - .storage() - .commit_staged(ds.clone(), staged) + .table_store + .commit_staged(Arc::new(ds.clone()), staged.transaction) .await .map_err(|e| { OmniError::Lance(format!( @@ -713,11 +711,11 @@ async fn stage_and_commit_btree( async fn stage_and_commit_inverted( db: &Omnigraph, table_key: &str, - ds: &mut SnapshotHandle, + ds: &mut Dataset, column: &str, ) -> Result<()> { let staged = db - .storage() + .table_store .stage_create_inverted_index(ds, column) .await .map_err(|e| { @@ -727,8 +725,8 @@ async fn stage_and_commit_inverted( )) })?; let new_ds = db - .storage() - .commit_staged(ds.clone(), staged) + .table_store + .commit_staged(Arc::new(ds.clone()), staged.transaction) .await .map_err(|e| { OmniError::Lance(format!( @@ -779,7 +777,7 @@ async fn prepare_updates_for_commit( ) .await?; build_indices_on_dataset(db, &prepared_update.table_key, &mut ds).await?; - let state = db.storage().table_state(&full_path, &ds).await?; + let state = db.table_store.table_state(&full_path, &ds).await?; prepared_update.table_version = state.version; prepared_update.row_count = state.row_count; prepared_update.version_metadata = state.version_metadata; diff --git a/crates/omnigraph/src/db/run_registry.rs b/crates/omnigraph/src/db/run_registry.rs new file mode 100644 index 0000000..ee3d336 --- /dev/null +++ b/crates/omnigraph/src/db/run_registry.rs @@ -0,0 +1,16 @@ +// The Run state machine has been removed. Mutations now write directly +// to target tables and use the publisher's `expected_table_versions` +// CAS for cross-table OCC; `__run__` staging branches and the +// `_graph_runs.lance` state machine no longer exist. +// +// What remains is the branch-name predicate, kept as a defense-in-depth +// guard against users naming a public branch `__run__*`. A future +// production sweep of legacy `_graph_runs.lance` rows and stale +// `__run__*` branches will let this predicate (and this file) go too. + +pub(crate) const INTERNAL_RUN_BRANCH_PREFIX: &str = "__run__"; + +pub(crate) fn is_internal_run_branch(name: &str) -> bool { + name.trim_start_matches('/') + .starts_with(INTERNAL_RUN_BRANCH_PREFIX) +} diff --git a/crates/omnigraph/src/exec/merge.rs b/crates/omnigraph/src/exec/merge.rs index f245d15..2e5f32e 100644 --- a/crates/omnigraph/src/exec/merge.rs +++ b/crates/omnigraph/src/exec/merge.rs @@ -670,34 +670,36 @@ fn update_unique_constraints( table_key: &str, batch: &RecordBatch, constraints: &[Vec], - seen: &mut [HashMap, String>], + seen: &mut [HashMap], conflicts: &mut Vec, ) -> Result<()> { for (constraint_idx, columns) in constraints.iter().enumerate() { let seen = &mut seen[constraint_idx]; - // Resolve the group's columns once. The candidate dataset always - // carries the full table schema, so a missing column is an internal - // error rather than a skip. - let group_columns = columns - .iter() - .map(|column_name| { - batch.column_by_name(column_name).cloned().ok_or_else(|| { + for row in 0..batch.num_rows() { + let mut parts = Vec::with_capacity(columns.len()); + let mut any_null = false; + for column_name in columns { + let column = batch.column_by_name(column_name).ok_or_else(|| { OmniError::manifest(format!( "table {} missing unique column '{}'", table_key, column_name )) - }) - }) - .collect::>>()?; - for row in 0..batch.num_rows() { - // Same tuple key as the intake path β€” one shared derivation in - // `crate::loader::composite_unique_key`, so the two cannot drift on - // separator or scalar conversion. Null rows are exempt. - let Some(key) = crate::loader::composite_unique_key(&group_columns, row)? else { + })?; + if column.is_null(row) { + any_null = true; + break; + } + parts.push( + array_value_to_string(column.as_ref(), row) + .map_err(|e| OmniError::Lance(e.to_string()))?, + ); + } + if any_null { continue; - }; + } + let value = parts.join("|"); let row_id = row_id_at(batch, row)?; - if let Some(first_row_id) = seen.insert(key, row_id.clone()) { + if let Some(first_row_id) = seen.insert(value.clone(), row_id.clone()) { conflicts.push(MergeConflict { table_key: table_key.to_string(), row_id: Some(row_id.clone()), @@ -926,7 +928,7 @@ async fn publish_adopted_source_state( target_branch, ) .await?; - let state = target_db.storage().table_state(&full_path, &ds).await?; + let state = target_db.table_store().table_state(&full_path, &ds).await?; Ok(crate::db::SubTableUpdate { table_key: table_key.to_string(), table_version: state.version, @@ -963,13 +965,9 @@ async fn publish_rewritten_merge_table( // commit point, narrowed from the previous "merge_insert + delete + // index" multi-step inline-commit chain. if let Some(delta) = &staged.delta_staged { - // The staged delta dataset is a temp-dir Lance dataset used only - // to collect the rewrite batches; wrap it in a `SnapshotHandle` - // so we can route through the trait's `scan_batches_for_rewrite`. - let delta_snapshot = SnapshotHandle::new(delta.dataset.clone()); let batches: Vec = target_db - .storage() - .scan_batches_for_rewrite(&delta_snapshot) + .table_store() + .scan_batches_for_rewrite(&delta.dataset) .await? .into_iter() .filter(|batch| batch.num_rows() > 0) @@ -984,7 +982,7 @@ async fn publish_rewritten_merge_table( .map_err(|e| OmniError::Lance(e.to_string()))? }; let staged_merge = target_db - .storage() + .table_store() .stage_merge_insert( current_ds.clone(), combined, @@ -994,15 +992,15 @@ async fn publish_rewritten_merge_table( ) .await?; current_ds = target_db - .storage() - .commit_staged(current_ds, staged_merge) + .table_store() + .commit_staged(Arc::new(current_ds), staged_merge.transaction) .await?; } } // Phase 2: delete removed rows via deletion vectors. // - // INLINE-COMMIT RESIDUAL: lance-6.0.1 does not expose a public + // INLINE-COMMIT RESIDUAL: lance-4.0.0 does not expose a public // two-phase delete API (DeleteJob is `pub(crate)` β€” // lance-format/lance#6658 is open with no PRs). We deliberately do // NOT introduce a `stage_delete` wrapper that would secretly @@ -1016,11 +1014,10 @@ async fn publish_rewritten_merge_table( .map(|id| format!("'{}'", id.replace('\'', "''"))) .collect(); let filter = format!("id IN ({})", escaped.join(", ")); - let (new_ds, _) = target_db - .storage_inline_residual() - .delete_where(&full_path, current_ds, &filter) + target_db + .table_store() + .delete_where(&full_path, &mut current_ds, &filter) .await?; - current_ds = new_ds; } // Phase 3: rebuild indices. @@ -1029,9 +1026,9 @@ async fn publish_rewritten_merge_table( // `stage_create_inverted_index` + `commit_staged` for scalar // indices. Vector indices remain inline-commit // (`build_index_metadata_from_segments` is `pub(crate)` in lance- - // 6.0.1 β€” companion ticket to lance-format/lance#6666). + // 4.0.0 β€” companion ticket to lance-format/lance#6658). let row_count = target_db - .storage() + .table_store() .table_state(&full_path, ¤t_ds) .await? .row_count; @@ -1041,7 +1038,7 @@ async fn publish_rewritten_merge_table( .await?; } let final_state = target_db - .storage() + .table_store() .table_state(&full_path, ¤t_ds) .await?; @@ -1090,9 +1087,9 @@ impl Omnigraph { target: &str, actor_id: Option<&str>, ) -> Result { - if is_internal_system_branch(source) || is_internal_system_branch(target) { + if is_internal_run_branch(source) || is_internal_run_branch(target) { return Err(OmniError::manifest(format!( - "branch_merge does not allow internal system refs ('{}' -> '{}')", + "branch_merge does not allow internal run refs ('{}' -> '{}')", source, target ))); } @@ -1367,7 +1364,7 @@ impl Omnigraph { let entry = target_snapshot.entry(table_key)?; Some(crate::db::manifest::SidecarTablePin { table_key: table_key.clone(), - table_path: self.storage().dataset_uri(&entry.table_path), + table_path: self.table_store().dataset_uri(&entry.table_path), expected_version: entry.table_version, post_commit_pin: entry.table_version + 1, // Use the merge target branch (where commits actually diff --git a/crates/omnigraph/src/exec/mod.rs b/crates/omnigraph/src/exec/mod.rs index 4076414..33a7e41 100644 --- a/crates/omnigraph/src/exec/mod.rs +++ b/crates/omnigraph/src/exec/mod.rs @@ -35,12 +35,11 @@ use time::format_description::well_known::Rfc3339; use crate::db::commit_graph::CommitGraph; use crate::db::manifest::ManifestCoordinator; -use crate::db::{MergeOutcome, Omnigraph, is_internal_system_branch}; +use crate::db::{MergeOutcome, Omnigraph, is_internal_run_branch}; use crate::db::{ReadTarget, Snapshot}; use crate::embedding::EmbeddingClient; use crate::error::{MergeConflict, MergeConflictKind, OmniError, Result}; use crate::graph_index::GraphIndex; -use crate::storage_layer::SnapshotHandle; use tempfile::{Builder as TempDirBuilder, TempDir}; mod merge; diff --git a/crates/omnigraph/src/exec/mutation.rs b/crates/omnigraph/src/exec/mutation.rs index e537d0d..02b2a21 100644 --- a/crates/omnigraph/src/exec/mutation.rs +++ b/crates/omnigraph/src/exec/mutation.rs @@ -428,11 +428,12 @@ async fn ensure_node_id_exists( let filter = format!("id = '{}'", id.replace('\'', "''")); let snapshot = db.snapshot_for_branch(branch).await?; - let ds = db - .storage() - .open_snapshot_at_table(&snapshot, &table_key) - .await?; - let exists = db.storage().count_rows(&ds, Some(filter)).await? > 0; + let ds = snapshot.open(&table_key).await?; + let exists = ds + .count_rows(Some(filter)) + .await + .map_err(|e| OmniError::Lance(e.to_string()))? + > 0; if exists { Ok(()) @@ -568,8 +569,7 @@ use super::staging::{MutationStaging, PendingMode}; /// via `open_for_mutation_on_branch`, which compares Lance HEAD against /// the manifest's pinned version β€” that fence is the engine's /// publisher-style OCC catching cross-writer drift before we make any -/// changes. For delete-only queries, this strict open is also the uncovered -/// drift guard that runs before `delete_where` can inline-commit. +/// changes. /// /// On subsequent touches *within the same query*, behavior depends on /// whether the table has already been inline-committed by a delete op: @@ -601,7 +601,7 @@ async fn open_table_for_mutation( branch: Option<&str>, table_key: &str, op_kind: crate::db::MutationOpKind, -) -> Result<(SnapshotHandle, String, Option)> { +) -> Result<(Dataset, String, Option)> { if let Some(prior) = staging.inline_committed.get(table_key) { let path = staging.paths.get(table_key).ok_or_else(|| { OmniError::manifest_internal(format!( @@ -623,7 +623,7 @@ async fn open_table_for_mutation( let (ds, full_path, table_branch) = db .open_for_mutation_on_branch(branch, table_key, op_kind) .await?; - let expected_version = ds.version(); + let expected_version = ds.version().version; staging.ensure_path( table_key, full_path.clone(), @@ -639,7 +639,7 @@ async fn open_table_for_mutation( /// /// Reason: under the staged-write writer, inserts and updates /// accumulate in memory and commit at end-of-query, while deletes still -/// inline-commit (Lance lacks a public two-phase delete in 6.0.1). +/// inline-commit (Lance lacks a public two-phase delete in 4.0.0). /// 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). @@ -904,12 +904,12 @@ impl Omnigraph { let batch = build_insert_batch(&schema, &id, &resolved, &blob_props)?; crate::loader::validate_value_constraints(&batch, node_type)?; crate::loader::validate_enum_constraints(&batch, &node_type.properties, type_name)?; - let unique_groups = crate::loader::unique_constraint_groups_for_node(node_type); - if !unique_groups.is_empty() { + let unique_props = crate::loader::unique_property_names_for_node(node_type); + if !unique_props.is_empty() { crate::loader::enforce_unique_constraints_intra_batch( &batch, type_name, - &unique_groups, + &unique_props, )?; } let has_key = node_type.key_property().is_some(); @@ -945,12 +945,12 @@ impl Omnigraph { let batch = build_insert_batch(&schema, &id, &resolved, &blob_props)?; validate_edge_insert_endpoints(self, staging, branch, type_name, &resolved).await?; crate::loader::validate_enum_constraints(&batch, &edge_type.properties, type_name)?; - let unique_groups = crate::loader::unique_constraint_groups_for_edge(edge_type); - if !unique_groups.is_empty() { + let unique_props = crate::loader::unique_property_names_for_edge(edge_type); + if !unique_props.is_empty() { crate::loader::enforce_unique_constraints_intra_batch( &batch, type_name, - &unique_groups, + &unique_props, )?; } let table_key = format!("edge:{}", type_name); @@ -1055,7 +1055,7 @@ impl Omnigraph { // and a chained `update where ` can match a row whose // pending value no longer satisfies . let batches = self - .storage() + .table_store() .scan_with_pending( &ds, pending_batches, @@ -1093,12 +1093,12 @@ impl Omnigraph { let node_type = &self.catalog().node_types[type_name]; crate::loader::validate_value_constraints(&updated, node_type)?; crate::loader::validate_enum_constraints(&updated, &node_type.properties, type_name)?; - let unique_groups = crate::loader::unique_constraint_groups_for_node(node_type); - if !unique_groups.is_empty() { + let unique_props = crate::loader::unique_property_names_for_node(node_type); + if !unique_props.is_empty() { crate::loader::enforce_unique_constraints_intra_batch( &updated, type_name, - &unique_groups, + &unique_props, )?; } @@ -1153,13 +1153,13 @@ impl Omnigraph { crate::db::MutationOpKind::Delete, ) .await?; - let initial_version = ds.version(); + let initial_version = ds.version().version; // Scan matching IDs for cascade. Per Dβ‚‚ this never overlaps with // staged inserts (mixed insert/delete in one query is rejected at // parse time), so we scan committed only. let batches = self - .storage() + .table_store() .scan(&ds, Some(&["id"]), Some(&pred_sql), None) .await?; @@ -1187,11 +1187,11 @@ impl Omnigraph { let affected_nodes = deleted_ids.len(); // Delete nodes β€” still inline-commit (Lance's `Dataset::delete` is - // not exposed as a two-phase op in 6.0.1). Dβ‚‚ keeps inserts and + // not exposed as a two-phase op in 4.0.0). Dβ‚‚ keeps inserts and // deletes from coexisting in one query, so this advance of Lance // HEAD is the only HEAD movement during the query and the // publisher's CAS captures it intact. - let ds = self + let mut ds = self .reopen_for_mutation( &table_key, &full_path, @@ -1201,9 +1201,9 @@ impl Omnigraph { ) .await?; crate::failpoints::maybe_fail("mutation.delete_node_pre_primary_delete")?; - let (_new_ds, delete_state) = self - .storage_inline_residual() - .delete_where(&full_path, ds, &pred_sql) + let delete_state = self + .table_store() + .delete_where(&full_path, &mut ds, &pred_sql) .await?; staging.record_inline(crate::db::SubTableUpdate { @@ -1242,7 +1242,7 @@ impl Omnigraph { let edge_table_key = format!("edge:{}", edge_name); let cascade_filter = cascade_filters.join(" OR "); - let (edge_ds, edge_full_path, edge_table_branch) = open_table_for_mutation( + let (mut edge_ds, edge_full_path, edge_table_branch) = open_table_for_mutation( self, staging, branch, @@ -1251,9 +1251,9 @@ impl Omnigraph { ) .await?; - let (_new_edge_ds, edge_delete) = self - .storage_inline_residual() - .delete_where(&edge_full_path, edge_ds, &cascade_filter) + let edge_delete = self + .table_store() + .delete_where(&edge_full_path, &mut edge_ds, &cascade_filter) .await?; affected_edges += edge_delete.deleted_rows; @@ -1290,7 +1290,7 @@ impl Omnigraph { let pred_sql = predicate_to_sql(predicate, params, true)?; let table_key = format!("edge:{}", type_name); - let (ds, full_path, table_branch) = open_table_for_mutation( + let (mut ds, full_path, table_branch) = open_table_for_mutation( self, staging, branch, @@ -1299,9 +1299,9 @@ impl Omnigraph { ) .await?; - let (_new_ds, delete_state) = self - .storage_inline_residual() - .delete_where(&full_path, ds, &pred_sql) + let delete_state = self + .table_store() + .delete_where(&full_path, &mut ds, &pred_sql) .await?; let affected = delete_state.deleted_rows; @@ -1355,7 +1355,7 @@ fn concat_match_batches_to_schema( /// dedup needed (`dedupe_key_column = None`). async fn validate_edge_cardinality_with_pending( db: &Omnigraph, - committed_ds: &SnapshotHandle, + committed_ds: &Dataset, staging: &MutationStaging, table_key: &str, edge_type: &omnigraph_compiler::catalog::EdgeType, diff --git a/crates/omnigraph/src/exec/projection.rs b/crates/omnigraph/src/exec/projection.rs index 7280ec5..dec13a8 100644 --- a/crates/omnigraph/src/exec/projection.rs +++ b/crates/omnigraph/src/exec/projection.rs @@ -422,35 +422,6 @@ pub(super) fn apply_ordering( }); } - // Deterministic tie-break for a TOTAL order. `lexsort_to_indices` is unstable - // and the input row order is not guaranteed (scan parallelism, upstream - // hashing), so equal user-sort keys would otherwise come out run-dependent β€” - // making `ORDER ... LIMIT` non-deterministic. Append the bound entities' key - // columns (`.id`, unique per row) in canonical (name-sorted) order as - // ascending tie-breaks. The combination of all bound keys uniquely identifies - // a result row, so the order is total and reproducible. (Aggregate results - // have no `.id` columns; their group rows are already distinct on the - // projected group keys.) - let mut tiebreak_cols: Vec = source - .schema() - .fields() - .iter() - .map(|f| f.name().to_string()) - .filter(|name| name.ends_with(".id")) - .collect(); - tiebreak_cols.sort(); - for name in &tiebreak_cols { - if let Some(col) = source.column_by_name(name) { - sort_columns.push(SortColumn { - values: col.clone(), - options: Some(arrow_schema::SortOptions { - descending: false, - nulls_first: true, - }), - }); - } - } - let indices = lexsort_to_indices(&sort_columns, None).map_err(|e| OmniError::Lance(e.to_string()))?; diff --git a/crates/omnigraph/src/exec/query.rs b/crates/omnigraph/src/exec/query.rs index 5bc18f2..7590512 100644 --- a/crates/omnigraph/src/exec/query.rs +++ b/crates/omnigraph/src/exec/query.rs @@ -24,14 +24,20 @@ impl Omnigraph { .pipeline .iter() .any(|op| matches!(op, IROp::Expand { .. } | IROp::AntiJoin { .. })); - // Lazy: an index-served query with no AntiJoin never builds the CSR. let graph_index = if needs_graph { - GraphIndexHandle::cached(self, &resolved) + Some(self.graph_index_for_resolved(&resolved).await?) } else { - GraphIndexHandle::none() + None }; - execute_query(&ir, params, &resolved.snapshot, &graph_index, &catalog).await + execute_query( + &ir, + params, + &resolved.snapshot, + graph_index.as_deref(), + &catalog, + ) + .await } /// Run a named query against the graph as it existed at a prior manifest version. @@ -58,21 +64,18 @@ impl Omnigraph { .pipeline .iter() .any(|op| matches!(op, IROp::Expand { .. } | IROp::AntiJoin { .. })); - // Lazy build against this historical snapshot (not the RuntimeCache, - // which is keyed to live branch targets); only a CSR-path Expand or an - // AntiJoin triggers it. let graph_index = if needs_graph { let edge_types = catalog .edge_types .iter() .map(|(name, et)| (name.clone(), (et.from_type.clone(), et.to_type.clone()))) .collect(); - GraphIndexHandle::direct(&snapshot, edge_types) + Some(Arc::new(GraphIndex::build(&snapshot, &edge_types).await?)) } else { - GraphIndexHandle::none() + None }; - execute_query(&ir, params, &snapshot, &graph_index, &catalog).await + execute_query(&ir, params, &snapshot, graph_index.as_deref(), &catalog).await } } @@ -339,7 +342,7 @@ pub async fn execute_query( ir: &QueryIR, params: &ParamMap, snapshot: &Snapshot, - graph_index: &GraphIndexHandle<'_>, + graph_index: Option<&GraphIndex>, catalog: &Catalog, ) -> Result { let search_mode = extract_search_mode(ir, params, catalog).await?; @@ -397,7 +400,7 @@ async fn execute_rrf_query( ir: &QueryIR, params: &ParamMap, snapshot: &Snapshot, - graph_index: &GraphIndexHandle<'_>, + graph_index: Option<&GraphIndex>, catalog: &Catalog, rrf: &RrfMode, ) -> Result { @@ -580,7 +583,7 @@ fn execute_pipeline<'a>( pipeline: &'a [IROp], params: &'a ParamMap, snapshot: &'a Snapshot, - graph_index: &'a GraphIndexHandle<'a>, + graph_index: Option<&'a GraphIndex>, catalog: &'a Catalog, wide: &'a mut Option, search_mode: &'a SearchMode, @@ -650,10 +653,13 @@ fn execute_pipeline<'a>( max_hops, dst_filters, } => { + let gi = graph_index.ok_or_else(|| { + OmniError::manifest("graph index required for traversal".to_string()) + })?; if let Some(batch) = wide.as_mut() { execute_expand( batch, - graph_index, + gi, snapshot, catalog, src_var, @@ -682,671 +688,8 @@ fn execute_pipeline<'a>( }) } -/// Lazily provides the in-memory CSR graph index, building it on first use and -/// memoizing for the rest of the query. Indexed-mode Expand never asks for it, -/// so a query that is entirely index-served and has no AntiJoin never pays the -/// O(|E|) CSR build (the whole point of the indexed path). The `Cached` builder -/// also reuses the cross-query `RuntimeCache` entry; `Direct` builds against an -/// arbitrary snapshot (time-travel reads); `None` is for queries with no -/// traversal at all. -pub struct GraphIndexHandle<'a> { - cell: tokio::sync::OnceCell>>, - builder: GraphIndexBuilder<'a>, -} - -enum GraphIndexBuilder<'a> { - None, - Cached(&'a Omnigraph, &'a crate::db::ResolvedTarget), - Direct(&'a Snapshot, HashMap), -} - -impl<'a> GraphIndexHandle<'a> { - fn none() -> Self { - Self { - cell: tokio::sync::OnceCell::new(), - builder: GraphIndexBuilder::None, - } - } - - fn cached(db: &'a Omnigraph, resolved: &'a crate::db::ResolvedTarget) -> Self { - Self { - cell: tokio::sync::OnceCell::new(), - builder: GraphIndexBuilder::Cached(db, resolved), - } - } - - fn direct(snapshot: &'a Snapshot, edge_types: HashMap) -> Self { - Self { - cell: tokio::sync::OnceCell::new(), - builder: GraphIndexBuilder::Direct(snapshot, edge_types), - } - } - - /// The CSR index, built on first call. `None` only when the query needs no - /// traversal (the `None` builder). - async fn get(&self) -> Result> { - let built = self - .cell - .get_or_try_init(|| async { - match &self.builder { - GraphIndexBuilder::None => Ok::>, OmniError>(None), - GraphIndexBuilder::Cached(db, resolved) => { - Ok(Some(db.graph_index_for_resolved(resolved).await?)) - } - GraphIndexBuilder::Direct(snapshot, edge_types) => { - Ok(Some(Arc::new(GraphIndex::build(snapshot, edge_types).await?))) - } - } - }) - .await?; - Ok(built.as_deref()) - } - - /// Whether the in-memory CSR is already materialized for this query (a prior - /// Expand or bulk AntiJoin realized it), so reusing it is ~free. Lets the - /// cost chooser prefer the warm CSR over per-hop indexed scans. - fn is_built(&self) -> bool { - matches!(self.cell.get(), Some(Some(_))) - } -} - -/// Explicit traversal-mode override. `OMNIGRAPH_TRAVERSAL_MODE=indexed|csr` -/// forces the path (ops escape hatch + test hook). Both modes are semantically -/// identical, so the override only changes which path runs, never the result. -fn traversal_indexed_override() -> Option { - match std::env::var("OMNIGRAPH_TRAVERSAL_MODE").ok().as_deref() { - Some("indexed") => Some(true), - Some("csr") => Some(false), - _ => None, - } -} - -/// Max source-row frontier for which Expand uses the BTREE-indexed path. -/// Larger frontiers fall back to the in-memory CSR (dense / whole-graph). See -/// `docs/user/constants.md`. -const DEFAULT_EXPAND_INDEXED_MAX_FRONTIER: usize = 1024; -/// Max hop count for the indexed path (each hop is one indexed scan; very deep -/// traversals fan out toward whole-graph and are better served by CSR). -const DEFAULT_EXPAND_INDEXED_MAX_HOPS: u32 = 6; - -fn expand_indexed_max_frontier() -> usize { - std::env::var("OMNIGRAPH_EXPAND_INDEXED_MAX_FRONTIER") - .ok() - .and_then(|v| v.parse::().ok()) - .unwrap_or(DEFAULT_EXPAND_INDEXED_MAX_FRONTIER) -} - -fn expand_indexed_max_hops() -> u32 { - std::env::var("OMNIGRAPH_EXPAND_INDEXED_MAX_HOPS") - .ok() - .and_then(|v| v.parse::().ok()) - .filter(|&v| v > 0) - .unwrap_or(DEFAULT_EXPAND_INDEXED_MAX_HOPS) -} - -/// The two Expand execution paths the chooser dispatches between. Extensible: -/// a future persisted-adjacency artifact would become a third variant here, and -/// `choose_expand_mode` would learn to prefer it when covered. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ExpandMode { - /// Per-hop neighbor lookup via the persisted src/dst BTREE. Work scales - /// with the frontier, not |E| β€” best for selective traversals. - IndexedScan, - /// Whole-graph in-memory CSR (built once, reused). Best for dense / deep / - /// large-frontier traversals, or when the index is degraded and a full - /// scan would be paid per hop anyway. - Csr, -} - -/// Building the in-memory CSR costs more than a bare edge scan: it scans every -/// edge AND allocates + groups the adjacency. This factor expresses that -/// overhead so a one-off degraded single-hop scan can still edge out a full CSR -/// build. The crossover is insensitive to its exact value. -const CSR_BUILD_FACTOR: f64 = 1.5; - -/// Cardinality inputs for the (pure, IO-free) traversal-mode cost model. Every -/// field is a cheap manifest-resident count or an already-in-hand value β€” the -/// chooser performs no scans. -#[derive(Debug, Clone)] -struct ExpandCostInputs { - /// Current frontier size (`wide.num_rows()`). - frontier_rows: usize, - /// |E| for the edge type (manifest `row_count`). - edge_count: u64, - /// |V_src| β€” node count of the keyed endpoint type (manifest `row_count`). - src_node_count: u64, - /// Effective max hop count for this Expand. - effective_max_hops: u32, - /// Hard ceiling above which the indexed path is never used (resolved - /// `OMNIGRAPH_EXPAND_INDEXED_MAX_HOPS`). - max_hops_cap: u32, - /// Hard ceiling above which the indexed path is never used (resolved - /// `OMNIGRAPH_EXPAND_INDEXED_MAX_FRONTIER`). - max_frontier_cap: usize, - /// Whether `scan_edges_by_endpoint`'s `key_col IN (...)` is served by the - /// BTREE (`Indexed`) or silently falls back to a full scan (`Degraded`). - coverage: crate::table_store::IndexCoverage, - /// Whether the cross-query CSR for this snapshot+edge-version is already - /// built (making the CSR path β‰ˆ free). Conservatively `false` until the - /// cache-peek is wired (the plan's optional refinement). - csr_cached: bool, -} - -/// Pure cost-based traversal-mode chooser. Compares an estimate of the indexed -/// path's frontier-relative work against the cost of building (or reusing) the -/// whole-graph CSR, and picks the cheaper. Deterministic and IO-free so it is -/// unit-tested at the crossover; the caller supplies the manifest counts and the -/// (optionally degraded) index coverage. -/// -/// Under `Indexed` coverage and a cold CSR the decision reduces to a clean -/// selectivity ratio β€” indexed wins when `hops * frontier < BUILD_FACTOR * -/// |V_src|`, i.e. when the frontier is a small fraction of the source vertex -/// set β€” which is independent of |E| (the flat-in-|E| property PR #149 shipped). -fn choose_expand_mode(i: &ExpandCostInputs) -> ExpandMode { - // Hard ceilings: very deep or very large frontiers fan out toward - // whole-graph and are always better served by CSR, regardless of the cost - // estimate. These preserve the documented semantics of the two cap flags. - if i.effective_max_hops > i.max_hops_cap || i.frontier_rows > i.max_frontier_cap { - return ExpandMode::Csr; - } - - let hops = i.effective_max_hops.max(1) as f64; - let frontier = i.frontier_rows as f64; - let edges = i.edge_count as f64; - let src = i.src_node_count.max(1) as f64; - let fanout = edges / src; - - // Indexed work scales with the frontier when the BTREE serves the IN-list; - // a degraded scan is a full edge scan per hop instead (the C6 perf cliff). - let indexed_cost = match i.coverage { - crate::table_store::IndexCoverage::Indexed => hops * frontier * fanout, - crate::table_store::IndexCoverage::Degraded { .. } => hops * edges, - }; - // A warm CSR is ~free to reuse; a cold one costs a build over all edges. - let csr_cost = if i.csr_cached { - 0.0 - } else { - CSR_BUILD_FACTOR * edges - }; - - if indexed_cost < csr_cost { - ExpandMode::IndexedScan - } else { - ExpandMode::Csr - } -} - -/// Hops the indexed path will actually run, for cost-model purposes. A cross-type -/// edge cannot chain, so `execute_expand_indexed` caps it at one hop regardless of -/// the requested range; the cost model must use that, or it over-estimates the -/// indexed cost of a cross-type variable-length expand and skews toward CSR. -fn cost_effective_hops(requested_max_hops: u32, same_type: bool) -> u32 { - if same_type { - requested_max_hops - } else { - requested_max_hops.min(1) - } -} - -/// Gather the cost-model inputs from cheap manifest counts. `None` when the -/// edge type, its source node type, or their manifest entries are absent (e.g. -/// a not-yet-materialized table) β€” the caller then falls back to the legacy -/// frontier/hop ceiling so the decision is always defined. -fn gather_cost_inputs( - snapshot: &Snapshot, - catalog: &Catalog, - edge_type: &str, - direction: Direction, - frontier_rows: usize, - effective_max_hops: u32, - coverage: crate::table_store::IndexCoverage, - csr_cached: bool, -) -> Option { - let edge_entry = snapshot.entry(&format!("edge:{}", edge_type))?; - let edge_def = catalog.edge_types.get(edge_type)?; - // Match the indexed path's cross-type one-hop cap so the cost estimate - // reflects what actually runs (see `cost_effective_hops`). - let effective_max_hops = - cost_effective_hops(effective_max_hops, edge_def.from_type == edge_def.to_type); - // The frontier source vertices are the keyed endpoint's type: `from` for an - // Out traversal (keyed on `src`), `to` for In (keyed on `dst`). - let src_type = match direction { - Direction::Out => &edge_def.from_type, - Direction::In => &edge_def.to_type, - }; - let src_entry = snapshot.entry(&format!("node:{}", src_type))?; - Some(ExpandCostInputs { - frontier_rows, - edge_count: edge_entry.row_count, - src_node_count: src_entry.row_count, - effective_max_hops, - max_hops_cap: expand_indexed_max_hops(), - max_frontier_cap: expand_indexed_max_frontier(), - coverage, - csr_cached, - }) -} - -/// Coverage value to feed the cost decision. A failed coverage probe is treated -/// as `Degraded` (conservative: don't over-favor the indexed path when we can't -/// confirm the BTREE will serve the scan). -fn coverage_for_decision( - coverage: &Result, -) -> crate::table_store::IndexCoverage { - match coverage { - Ok(c) => c.clone(), - Err(_) => crate::table_store::IndexCoverage::Degraded { - reason: "coverage check failed".to_string(), - }, - } -} - -/// Surface the C6 silent scalar-index fallback (commit `5a7ab6d`): warn when the -/// per-hop `key_col IN (...)` won't route through the BTREE. Detection-only; -/// never fails the query. Behavior-identical to the inline check it replaced. -fn warn_on_degraded_coverage( - coverage: &Result, - key_col: &str, - edge_type: &str, -) { - match coverage { - Ok(crate::table_store::IndexCoverage::Degraded { reason }) => tracing::warn!( - target: "omnigraph::traverse", - edge = %edge_type, - key_col = key_col, - reason = %reason, - "indexed traversal falls back to a full edge scan (results correct, perf degraded)" - ), - Ok(crate::table_store::IndexCoverage::Indexed) => {} - Err(e) => tracing::debug!( - target: "omnigraph::traverse", - error = %e, - "index-coverage check failed; proceeding with traversal" - ), - } -} - -/// The (key, opposite) endpoint columns for a traversal direction. Out follows -/// src -> dst (key on src); In follows the reverse. The persisted BTREE exists -/// on both columns. -fn endpoint_columns(direction: Direction) -> (&'static str, &'static str) { - match direction { - Direction::Out => ("src", "dst"), - Direction::In => ("dst", "src"), - } -} - -/// Execute a graph traversal (Expand). Dispatches to the BTREE-indexed path -/// (selective traversals β€” neighbor lookups via the persisted src/dst index) or -/// the in-memory CSR path (dense / whole-graph traversals). The CSR index is -/// built lazily and only the CSR path requests it. +/// Execute a graph traversal (Expand). async fn execute_expand( - wide: &mut RecordBatch, - graph_index: &GraphIndexHandle<'_>, - snapshot: &Snapshot, - catalog: &Catalog, - src_var: &str, - dst_var: &str, - edge_type: &str, - direction: Direction, - dst_type: &str, - min_hops: u32, - max_hops: Option, - dst_filters: &[IRFilter], - params: &ParamMap, -) -> Result<()> { - let frontier_rows = wide.num_rows(); - let effective_max_hops = max_hops.unwrap_or(min_hops.max(1)); - let (key_col, _) = endpoint_columns(direction); - let edge_table_key = format!("edge:{}", edge_type); - - // Cardinality-first preliminary decision (no IO). The override wins; else the - // cost model decides under *optimistic* coverage. Optimistic is what lets us - // skip the dataset open on a clearly-CSR traversal: real coverage can only - // make the indexed path costlier, so if even a perfectly-indexed scan loses - // to CSR here, it loses for real. - let forced = traversal_indexed_override(); - let lean_indexed = match forced { - Some(v) => v, - None => match gather_cost_inputs( - snapshot, - catalog, - edge_type, - direction, - frontier_rows, - effective_max_hops, - crate::table_store::IndexCoverage::Indexed, - graph_index.is_built(), - ) { - Some(inputs) => choose_expand_mode(&inputs) == ExpandMode::IndexedScan, - // Manifest counts absent (e.g. not-yet-materialized table): fall back - // to the legacy frontier/hop ceiling so the decision is defined. - None => { - frontier_rows <= expand_indexed_max_frontier() - && effective_max_hops <= expand_indexed_max_hops() - } - }, - }; - - if !lean_indexed { - tracing::debug!( - target: "omnigraph::traverse", - edge = %edge_type, - frontier = frontier_rows, - hops = effective_max_hops, - mode = "csr", - "expand mode chosen", - ); - let gi = graph_index.get().await?.ok_or_else(|| { - OmniError::manifest("graph index required for CSR traversal".to_string()) - })?; - return execute_expand_csr( - wide, gi, snapshot, catalog, src_var, dst_var, edge_type, direction, dst_type, - min_hops, max_hops, dst_filters, params, - ) - .await; - } - - // Leaning indexed: open the edge dataset once, confirm real coverage, and - // (unless forced) re-decide with it. The opened dataset is threaded into the - // indexed path so it is never opened twice. - let edge_ds = snapshot.open(&edge_table_key).await?; - let coverage = - crate::table_store::TableStore::key_column_index_coverage(&edge_ds, key_col).await; - - if forced.is_none() { - if let Some(inputs) = gather_cost_inputs( - snapshot, - catalog, - edge_type, - direction, - frontier_rows, - effective_max_hops, - coverage_for_decision(&coverage), - graph_index.is_built(), - ) { - if choose_expand_mode(&inputs) == ExpandMode::Csr { - tracing::debug!( - target: "omnigraph::traverse", - edge = %edge_type, - frontier = frontier_rows, - hops = effective_max_hops, - mode = "csr", - reason = "index coverage degraded", - "expand mode chosen", - ); - let gi = graph_index.get().await?.ok_or_else(|| { - OmniError::manifest("graph index required for CSR traversal".to_string()) - })?; - return execute_expand_csr( - wide, gi, snapshot, catalog, src_var, dst_var, edge_type, direction, dst_type, - min_hops, max_hops, dst_filters, params, - ) - .await; - } - } - } - - tracing::debug!( - target: "omnigraph::traverse", - edge = %edge_type, - frontier = frontier_rows, - hops = effective_max_hops, - mode = "indexed", - "expand mode chosen", - ); - // Surface the C6 silent scalar-index fallback once, now that coverage is known. - warn_on_degraded_coverage(&coverage, key_col, edge_type); - execute_expand_indexed( - wide, snapshot, catalog, src_var, dst_var, edge_type, direction, dst_type, min_hops, - max_hops, dst_filters, params, edge_ds, - ) - .await -} - -/// BTREE-indexed graph traversal: per hop, batch the current frontier into one -/// `scan_edges_by_endpoint` call against the persisted src/dst index, then fan -/// out per source row. Cost scales with the frontier, not |E|. Produces the -/// same `(src_row, dst_id)` pairs as the CSR path and shares its hydrate+align -/// tail. Multi-hop only advances for same-type edges; cross-type frontiers go -/// empty after one hop (no edges key off the destination type), matching CSR. -async fn execute_expand_indexed( - wide: &mut RecordBatch, - snapshot: &Snapshot, - catalog: &Catalog, - src_var: &str, - dst_var: &str, - edge_type: &str, - direction: Direction, - dst_type: &str, - min_hops: u32, - max_hops: Option, - dst_filters: &[IRFilter], - params: &ParamMap, - edge_ds: Dataset, -) -> Result<()> { - 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)) - })? - .as_any() - .downcast_ref::() - .ok_or_else(|| OmniError::manifest(format!("'{}' column is not Utf8", src_id_col_name)))? - .clone(); - - let edge_def = catalog - .edge_types - .get(edge_type) - .ok_or_else(|| OmniError::manifest(format!("unknown edge type '{}'", edge_type)))?; - let same_type = edge_def.from_type == edge_def.to_type; - // The keyed/opposite endpoint columns for this direction. The edge dataset - // and the C6 coverage warn are owned by the caller (`execute_expand`), which - // opens the dataset once and threads it in. - let (key_col, opp_col) = endpoint_columns(direction); - - let max = max_hops.unwrap_or(min_hops.max(1)); - // Cross-type edges cannot chain (a Company is not a `WorksAt` source), so a - // variable-length traversal over one is structurally single-hop. Enforce it - // here instead of relying on the hop-2 scan returning empty: this BFS interns - // every endpoint string into ONE dense id space, so a cross-type id-string - // collision (a Person and a Company sharing an id) would otherwise let hop 2 - // de-intern a destination id back to the colliding source-type id and match - // its edges, emitting rows the CSR path never produces. - let max = if same_type { max } else { max.min(1) }; - - // Per-source BFS state in DENSE id space: intern node ids to u32 once via a - // per-traversal interner so visited/seen/frontier/neighbor-map avoid string - // hashing + cloning in the hot loop (mirrors the CSR path's TypeIndex). The - // GraphIndex/CSR is NOT built β€” only a local id↔u32 dictionary. Strings - // survive at the substrate edges only: the per-hop IN-list to Lance, and the - // emitted dst ids handed to the string-keyed hydrate+align tail. - let mut interner = crate::graph_index::TypeIndex::new(); - let n = src_ids.len(); - let mut frontiers: Vec> = Vec::with_capacity(n); - let mut visited: Vec> = Vec::with_capacity(n); - let mut seen_dst: Vec> = Vec::with_capacity(n); - for i in 0..n { - let sid = interner.get_or_insert(src_ids.value(i)); - let mut v = HashSet::new(); - if same_type { - v.insert(sid); - } - frontiers.push(vec![sid]); - visited.push(v); - seen_dst.push(HashSet::new()); - } - - let mut src_indices: Vec = Vec::new(); - let mut dst_dense: Vec = Vec::new(); - - for hop in 1..=max { - // Union of all live frontiers (dense), de-interned once for the IN-list. - let mut union_dense: Vec = Vec::new(); - { - let mut seen: HashSet = HashSet::new(); - for f in &frontiers { - for &node in f { - if seen.insert(node) { - union_dense.push(node); - } - } - } - } - if union_dense.is_empty() { - break; - } - let union_keys: Vec = union_dense - .iter() - .map(|&u| { - interner - .to_id(u) - .expect("interned frontier id must resolve") - .to_string() - }) - .collect(); - - let batches = crate::table_store::TableStore::scan_edges_by_endpoint( - &edge_ds, key_col, opp_col, &union_keys, - ) - .await?; - - // dense key -> dense neighbors (scan order; duplicates preserved, like CSR multi-edges). - let mut neighbor_map: HashMap> = HashMap::new(); - for batch in &batches { - let keys = batch - .column_by_name(key_col) - .ok_or_else(|| OmniError::manifest(format!("edge batch missing '{}'", key_col)))? - .as_any() - .downcast_ref::() - .ok_or_else(|| OmniError::manifest(format!("edge '{}' is not Utf8", key_col)))?; - let opps = batch - .column_by_name(opp_col) - .ok_or_else(|| OmniError::manifest(format!("edge batch missing '{}'", opp_col)))? - .as_any() - .downcast_ref::() - .ok_or_else(|| OmniError::manifest(format!("edge '{}' is not Utf8", opp_col)))?; - for r in 0..batch.num_rows() { - let k = interner.get_or_insert(keys.value(r)); - let o = interner.get_or_insert(opps.value(r)); - neighbor_map.entry(k).or_default().push(o); - } - } - - // Advance each source row's frontier independently (dense ids). - for i in 0..n { - let cur = std::mem::take(&mut frontiers[i]); - let mut next: Vec = Vec::new(); - for &node in &cur { - let Some(neighbors) = neighbor_map.get(&node) else { - continue; - }; - for &neighbor in neighbors { - if !same_type || visited[i].insert(neighbor) { - next.push(neighbor); - if hop >= min_hops && seen_dst[i].insert(neighbor) { - src_indices.push(i as u32); - dst_dense.push(neighbor); - } - } - } - } - frontiers[i] = next; - } - } - - // De-intern emitted destination ids (parallel to src_indices) for the - // string-keyed hydrate+align tail, exactly as the CSR path does. - let dst_ids: Vec = dst_dense - .iter() - .map(|&d| { - interner - .to_id(d) - .expect("interned dst id must resolve") - .to_string() - }) - .collect(); - - expand_hydrate_and_align( - wide, src_indices, dst_ids, snapshot, catalog, dst_type, dst_var, dst_filters, params, - ) - .await -} - -/// Shared tail for both Expand modes: hydrate the unique destination ids, align -/// the `(src_row, dst_id)` pairs back onto `wide`, hconcat, and apply -/// non-pushable destination filters in memory. -async fn expand_hydrate_and_align( - wide: &mut RecordBatch, - src_indices: Vec, - dst_ids: Vec, - snapshot: &Snapshot, - catalog: &Catalog, - dst_type: &str, - dst_var: &str, - dst_filters: &[IRFilter], - params: &ParamMap, -) -> Result<()> { - // Pushable destination filters are applied by `hydrate_nodes`; the rest - // (`ir_filter_to_expr` β†’ None) are applied in memory after hconcat. - let non_pushable: Vec<&IRFilter> = dst_filters - .iter() - .filter(|f| ir_filter_to_expr(f, params).is_none()) - .collect(); - - // Unique destination ids (first-seen order) for one batched hydration. - let mut unique_dst_list: Vec = Vec::new(); - { - let mut seen: HashSet<&str> = HashSet::with_capacity(dst_ids.len()); - for id in &dst_ids { - if seen.insert(id.as_str()) { - unique_dst_list.push(id.clone()); - } - } - } - let dst_batch = - hydrate_nodes(snapshot, catalog, dst_type, &unique_dst_list, dst_filters, params).await?; - - // id -> row index in the hydrated batch. - let dst_batch_id_col = dst_batch - .column_by_name("id") - .ok_or_else(|| OmniError::manifest("hydrated batch missing 'id' column".to_string()))? - .as_any() - .downcast_ref::() - .ok_or_else(|| OmniError::manifest("hydrated 'id' column is not Utf8".to_string()))?; - let mut id_to_row: HashMap<&str, u32> = HashMap::with_capacity(dst_batch_id_col.len()); - for row in 0..dst_batch_id_col.len() { - id_to_row.insert(dst_batch_id_col.value(row), row as u32); - } - - // Align pairs to (src_row, hydrated_dst_row), dropping ids hydration filtered out. - let mut final_src_indices: Vec = Vec::with_capacity(src_indices.len()); - let mut dst_indices: Vec = Vec::with_capacity(src_indices.len()); - for (&src_idx, dst_id) in src_indices.iter().zip(dst_ids.iter()) { - if let Some(&dst_row) = id_to_row.get(dst_id.as_str()) { - final_src_indices.push(src_idx); - dst_indices.push(dst_row); - } - } - - let src_take = UInt32Array::from(final_src_indices); - let dst_take = UInt32Array::from(dst_indices); - let expanded_wide = take_batch(wide, &src_take)?; - let dst_prefixed = prefix_batch(&dst_batch, dst_var)?; - let aligned_dst = take_batch(&dst_prefixed, &dst_take)?; - *wide = hconcat_batches(&expanded_wide, &aligned_dst)?; - - for f in &non_pushable { - apply_filter(wide, f, params)?; - } - Ok(()) -} - -/// CSR-backed graph traversal: BFS over the in-memory adjacency index. Used for -/// dense / whole-graph traversals; selective traversals use -/// `execute_expand_indexed`. Both share `expand_hydrate_and_align`. -async fn execute_expand_csr( wide: &mut RecordBatch, graph_index: &GraphIndex, snapshot: &Snapshot, @@ -1399,9 +742,6 @@ async fn execute_expand_csr( let max = max_hops.unwrap_or(min_hops.max(1)); let same_type = src_type_name == dst_type_name; - // Cross-type edges cannot chain; a variable-length traversal over one is - // structurally single-hop (mirrors the indexed path's guarantee). - let max = if same_type { max } else { max.min(1) }; // BFS to collect (src_row_idx, dst_dense) pairs with per-source dedup. // Dense u32 ids stay in hand through BFS, dedup, and align β€” we only @@ -1445,52 +785,88 @@ async fn execute_expand_csr( } } - // Map BFS-produced dense destination ids to string ids for the shared - // hydrate+align tail. Dense ids always resolve (they came from the index); - // drop any that don't, keeping the (src, dst) arrays parallel. - let mut tail_src_indices: Vec = Vec::with_capacity(src_indices.len()); - let mut dst_ids: Vec = Vec::with_capacity(dst_dense_list.len()); - for (&s, &d) in src_indices.iter().zip(dst_dense_list.iter()) { - if let Some(id) = dst_type_idx.to_id(d) { - tail_src_indices.push(s); - dst_ids.push(id.to_string()); + // Split dst_filters: SQL-pushable go to Lance, the rest applied post-hconcat + let pushdown_sql = build_lance_filter(dst_filters, params); + let non_pushable: Vec<&IRFilter> = dst_filters + .iter() + .filter(|f| ir_filter_to_sql(f, params).is_none()) + .collect(); + + // Dedup dst dense ids globally across source rows, then stringify once + // for the Lance IN-list. The post-hydrate alignment fans rows back out to + // the original (src, dst) pairs via a dense-indexed lookup below. + let mut unique_dst_list: Vec = Vec::new(); + { + let mut seen: HashSet = HashSet::with_capacity(dst_dense_list.len()); + for &d in &dst_dense_list { + if seen.insert(d) { + if let Some(id) = dst_type_idx.to_id(d) { + unique_dst_list.push(id.to_string()); + } + } } } - - expand_hydrate_and_align( - wide, - tail_src_indices, - dst_ids, + let dst_batch = hydrate_nodes( snapshot, catalog, dst_type, - dst_var, - dst_filters, - params, + &unique_dst_list, + pushdown_sql.as_deref(), ) - .await + .await?; + + // Build dense β†’ row-in-hydrated-batch via a direct-indexed array. + let dst_batch_id_col = dst_batch + .column_by_name("id") + .ok_or_else(|| OmniError::manifest("hydrated batch missing 'id' column".to_string()))? + .as_any() + .downcast_ref::() + .ok_or_else(|| OmniError::manifest("hydrated 'id' column is not Utf8".to_string()))?; + let mut dense_to_row: Vec> = vec![None; dst_type_idx.len()]; + for row in 0..dst_batch_id_col.len() { + let id_str = dst_batch_id_col.value(row); + if let Some(dense) = dst_type_idx.to_dense(id_str) { + dense_to_row[dense as usize] = Some(row as u32); + } + } + + // Build aligned src/dst index arrays (only for ids that exist in hydrated batch) + let mut final_src_indices: Vec = Vec::new(); + let mut dst_indices: Vec = Vec::new(); + for (src_idx, dst_dense) in src_indices.iter().zip(dst_dense_list.iter()) { + if let Some(dst_row) = dense_to_row[*dst_dense as usize] { + final_src_indices.push(*src_idx); + dst_indices.push(dst_row); + } + } + + let src_take = UInt32Array::from(final_src_indices); + let dst_take = UInt32Array::from(dst_indices); + let expanded_wide = take_batch(wide, &src_take)?; + let dst_prefixed = prefix_batch(&dst_batch, dst_var)?; + let aligned_dst = take_batch(&dst_prefixed, &dst_take)?; + *wide = hconcat_batches(&expanded_wide, &aligned_dst)?; + + // Apply any non-pushable destination filters (e.g. list-contains) in memory + for f in &non_pushable { + apply_filter(wide, f, params)?; + } + + Ok(()) } /// Load full node rows for a set of IDs from a snapshot. /// -/// The `id IN (...)` predicate is built as a structured DataFusion `Expr` and -/// AND'd with any pushable `dst_filters` (destination-binding filters), then -/// applied via `Scanner::filter_expr`. The structured form routes the id -/// IN-list through the `id` BTREE scalar index (index-search β†’ take) rather -/// than evaluating a string filter via DataFusion `InListEval`, which is -/// O(NΓ—M) and was measured at 72Γ— the indexed cost on a 100k-node hop -/// (MR-376). Non-pushable `dst_filters` (`ir_filter_to_expr` β†’ None) are -/// applied in memory by the caller after hydration. +/// When `extra_filter_sql` is provided (from deferred destination-binding +/// filters), it is ANDed with the `id IN (...)` clause so that Lance can +/// skip non-matching rows at the storage level. async fn hydrate_nodes( snapshot: &Snapshot, catalog: &Catalog, type_name: &str, ids: &[String], - dst_filters: &[IRFilter], - params: &ParamMap, + extra_filter_sql: Option<&str>, ) -> Result { - use datafusion::prelude::{col, lit}; - let node_type = catalog .node_types .get(type_name) @@ -1503,13 +879,15 @@ async fn hydrate_nodes( let table_key = format!("node:{}", type_name); let ds = snapshot.open(&table_key).await?; - // `id IN (ids)` AND any pushable destination filters, as a structured Expr. - let id_list: Vec = ids.iter().map(|id| lit(id.clone())).collect(); - let mut filter_expr = col("id").in_list(id_list, false); - if let Some(dst_expr) = build_lance_filter_expr(dst_filters, params) { - filter_expr = filter_expr.and(dst_expr); + // Build filter: id IN ('a', 'b', 'c') + let escaped: Vec = ids + .iter() + .map(|id| format!("'{}'", id.replace('\'', "''"))) + .collect(); + let mut filter_sql = format!("id IN ({})", escaped.join(", ")); + if let Some(extra) = extra_filter_sql { + filter_sql = format!("({}) AND ({})", filter_sql, extra); } - let has_blobs = !node_type.blob_properties.is_empty(); let non_blob_cols: Vec<&str> = node_type .arrow_schema @@ -1519,16 +897,12 @@ async fn hydrate_nodes( .map(|f| f.name().as_str()) .collect(); let projection = has_blobs.then_some(non_blob_cols.as_slice()); - let batches = crate::table_store::TableStore::scan_stream_with( + let batches = crate::table_store::TableStore::scan_stream( &ds, projection, - None, + Some(&filter_sql), None, false, - |scanner| { - scanner.filter_expr(filter_expr); - Ok(()) - }, ) .await? .try_collect::>() @@ -1551,25 +925,6 @@ async fn hydrate_nodes( Ok(scan_result) } -/// Whether the inner pipeline is the bulk-anti-join shape: a single Expand from -/// the outer var with no destination filters (the only shape the CSR -/// `has_neighbors` fast path can serve). Pure β€” it does not touch the CSR β€” so -/// the caller can decide whether to realize the O(|E|) graph index at all. -fn bulk_anti_join_applies(inner_pipeline: &[IROp], outer_var: &str) -> bool { - matches!( - inner_pipeline, - [IROp::Expand { src_var, dst_filters, min_hops, max_hops, .. }] - if src_var == outer_var - && dst_filters.is_empty() - // `has_neighbors` is a ONE-hop existence test, so the fast path - // is valid only for a single-hop expand. Multi-hop negations - // (e.g. `not { $p knows{2,2} $x }`) fall to the slow path, whose - // inner Expand runs the real bounded traversal. - && *min_hops == 1 - && (*max_hops).unwrap_or(1) == 1 - ) -} - /// Try bulk anti-join via CSR existence check. Returns Some(mask) if the inner /// pipeline is a single Expand from outer_var (the common negation pattern). fn try_bulk_anti_join_mask( @@ -1579,17 +934,27 @@ fn try_bulk_anti_join_mask( catalog: &Catalog, outer_var: &str, ) -> Option { - if !bulk_anti_join_applies(inner_pipeline, outer_var) { + if inner_pipeline.len() != 1 { return None; } let IROp::Expand { + src_var, edge_type, direction, + dst_filters, .. } = &inner_pipeline[0] else { return None; }; + if src_var != outer_var { + return None; + } + // Bulk CSR check only tests neighbor existence, not destination + // properties. Fall back to the slow path when dst_filters are present. + if !dst_filters.is_empty() { + return None; + } let gi = graph_index?; let edge_def = catalog.edge_types.get(edge_type.as_str())?; @@ -1628,106 +993,49 @@ async fn execute_anti_join( inner_pipeline: &[IROp], params: &ParamMap, snapshot: &Snapshot, - graph_index: &GraphIndexHandle<'_>, + graph_index: Option<&GraphIndex>, catalog: &Catalog, outer_var: &str, ) -> Result<()> { - // Only the bulk fast path consumes the CSR; the slow path's inner Expand - // chooses its own access path. Realize the O(|E|) graph index ONLY when the - // inner-pipeline shape qualifies for the bulk check β€” a filtered/nested - // anti-join over a large graph must not pay a whole-graph build it won't use. - let gi = if bulk_anti_join_applies(inner_pipeline, outer_var) { - graph_index.get().await? - } else { - None - }; // Fast path: bulk CSR existence check (O(N), zero Lance I/O) - if let Some(mask) = try_bulk_anti_join_mask(wide, inner_pipeline, gi, catalog, outer_var) { + if let Some(mask) = + try_bulk_anti_join_mask(wide, inner_pipeline, graph_index, catalog, outer_var) + { *wide = arrow_select::filter::filter_record_batch(wide, &mask) .map_err(|e| OmniError::Lance(e.to_string()))?; return Ok(()); } - // Slow path (filtered / non-bulk inner): run the inner pipeline ONCE over the - // whole frontier β€” a set-oriented anti-semi-join β€” instead of row-by-row. - // Each outer row is tagged with a synthetic index; an outer row matches iff - // it produced at least one surviving inner row. No per-row dispatch, so the - // inner Expand runs as a single set-at-a-time traversal over the full - // frontier (its own chooser picks indexed vs CSR) rather than one Lance scan - // per outer row. + // Slow path: per-row inner pipeline execution let num_rows = wide.num_rows(); - if num_rows == 0 { - return Ok(()); - } + let mut keep_mask = vec![true; num_rows]; - // The tag rides through the inner pipeline: Expand's hconcat preserves - // existing columns and Filter only drops rows, so each surviving row carries - // its originating outer-row index. Correlating on the row index (not - // `outer_var.id`) stays correct even if a dst-filter references other outer - // bindings. Nested anti-joins reuse this slow path and an enclosing tag rides - // through too; Arrow allows duplicate field names and `column_by_name` - // returns the FIRST match, so choose a tag name not already present (each - // nesting level then reads its own) instead of a fixed one. - let tag_col: String = { - let mut n = 0usize; - loop { - let candidate = format!("__antijoin_outer_row_{n}"); - if wide.schema().column_with_name(&candidate).is_none() { - break candidate; - } - n += 1; - } - }; - let mut fields: Vec = wide - .schema() - .fields() - .iter() - .map(|f| f.as_ref().clone()) - .collect(); - fields.push(Field::new(tag_col.as_str(), DataType::UInt32, false)); - let mut columns: Vec = wide.columns().to_vec(); - columns.push(Arc::new(UInt32Array::from_iter_values(0..num_rows as u32))); - let tagged = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns) - .map_err(|e| OmniError::Lance(e.to_string()))?; + for i in 0..num_rows { + let single_row = wide.slice(i, 1); + let mut inner_wide: Option = Some(single_row); - let mut inner_wide: Option = Some(tagged); - let no_search = SearchMode::default(); - execute_pipeline( - inner_pipeline, - params, - snapshot, - graph_index, - catalog, - &mut inner_wide, - &no_search, - ) - .await?; + let no_search = SearchMode::default(); + execute_pipeline( + inner_pipeline, + params, + snapshot, + graph_index, + catalog, + &mut inner_wide, + &no_search, + ) + .await?; - // Outer rows whose tag survived have >= 1 match. A produced-but-untagged - // batch means the inner pipeline dropped the correlation column β€” fail loudly - // rather than silently keeping every row (which would corrupt the anti-join). - let mut matched: HashSet = HashSet::new(); - if let Some(batch) = inner_wide { - if batch.num_rows() > 0 { - let tags = batch - .column_by_name(tag_col.as_str()) - .ok_or_else(|| { - OmniError::manifest( - "anti-join inner pipeline dropped the correlation column".to_string(), - ) - })? - .as_any() - .downcast_ref::() - .ok_or_else(|| { - OmniError::manifest(format!("'{}' column is not UInt32", tag_col)) - })?; - for i in 0..tags.len() { - matched.insert(tags.value(i)); - } + let has_match = inner_wide + .as_ref() + .map(|batch| batch.num_rows() > 0) + .unwrap_or(false); + + if has_match { + keep_mask[i] = false; } } - let keep_mask: Vec = (0..num_rows as u32).map(|i| !matched.contains(&i)).collect(); let mask = BooleanArray::from(keep_mask); *wide = arrow_select::filter::filter_record_batch(wide, &mask) .map_err(|e| OmniError::Lance(e.to_string()))?; @@ -1878,6 +1186,45 @@ fn add_null_blob_columns( .map_err(|e| OmniError::Lance(e.to_string())) } +/// Convert IR filters to a Lance SQL filter string. +fn build_lance_filter(filters: &[IRFilter], params: &ParamMap) -> Option { + if filters.is_empty() { + return None; + } + + let parts: Vec = filters + .iter() + .filter_map(|f| ir_filter_to_sql(f, params)) + .collect(); + + if parts.is_empty() { + return None; + } + + Some(parts.join(" AND ")) +} + +fn ir_filter_to_sql(filter: &IRFilter, params: &ParamMap) -> Option { + // Search predicates (search/fuzzy/match_text = true) are NOT converted to SQL. + // They are handled via scanner.full_text_search() in execute_node_scan. + if is_search_filter(filter) { + return None; + } + + let left = ir_expr_to_sql(&filter.left, params)?; + let right = ir_expr_to_sql(&filter.right, params)?; + let op = match filter.op { + CompOp::Eq => "=", + CompOp::Ne => "!=", + CompOp::Gt => ">", + CompOp::Lt => "<", + CompOp::Ge => ">=", + CompOp::Le => "<=", + CompOp::Contains => return None, // Can't pushdown list contains + }; + Some(format!("{} {} {}", left, op, right)) +} + /// Build a FullTextSearchQuery from a search IR expression. fn build_fts_query( expr: &IRExpr, @@ -1950,6 +1297,15 @@ fn resolve_to_int(expr: &IRExpr, params: &ParamMap) -> Option { } } +fn ir_expr_to_sql(expr: &IRExpr, params: &ParamMap) -> Option { + match expr { + IRExpr::PropAccess { property, .. } => Some(property.clone()), + IRExpr::Literal(lit) => Some(literal_to_sql(lit)), + IRExpr::Param(name) => params.get(name).map(literal_to_sql), + _ => None, + } +} + pub(super) fn literal_to_sql(lit: &Literal) -> String { match lit { Literal::Null => "NULL".to_string(), @@ -1980,10 +1336,10 @@ pub(super) fn literal_to_sql(lit: &Literal) -> String { // // Search predicates (`is_search_filter`) are still handled separately via // `scanner.full_text_search(...)`, not via filter_expr β€” they stay None -// here (search predicates are never lowered to a scalar filter). The -// `literal_to_sql` path remains because the mutation/update layer -// (`exec/mutation.rs`) still produces SQL strings for `Dataset::delete(&str)`; -// that migration is MR-A's territory (Lance #6658 + delete two-phase). +// here just like in `ir_filter_to_sql`. The `literal_to_sql` path remains +// because the mutation/update layer (`exec/mutation.rs`) still produces +// SQL strings for `Dataset::delete(&str)`; that migration is MR-A's +// territory (Lance #6658 + delete two-phase). /// Convert IR filters to a single DataFusion `Expr` (AND-joined), or /// `None` if no filter is pushable. @@ -2025,8 +1381,8 @@ pub(super) fn ir_filter_to_expr( } // List-contains: `prop CONTAINS value` lowers to `array_has(prop, value)`. - // This is the case the old SQL-string pushdown had to return None for - // ("Can't pushdown list contains"); with structured Expr it pushes down fine. + // This is the case `ir_filter_to_sql` had to return None for ("Can't + // pushdown list contains"); with structured Expr it pushes down fine. if matches!(filter.op, CompOp::Contains) { let left = ir_expr_to_expr(&filter.left, params)?; let right = ir_expr_to_expr(&filter.right, params)?; @@ -2161,127 +1517,3 @@ fn take_batch(batch: &RecordBatch, indices: &UInt32Array) -> Result .map_err(|e| OmniError::Lance(e.to_string()))?; RecordBatch::try_new(batch.schema(), columns).map_err(|e| OmniError::Lance(e.to_string())) } - -#[cfg(test)] -mod expand_chooser_tests { - use super::*; - use crate::table_store::IndexCoverage; - - /// Build cost inputs with generous hard caps, so the cost comparison (not a - /// ceiling) is what the assertions exercise unless a test sets one on purpose. - fn inputs( - frontier_rows: usize, - edge_count: u64, - src_node_count: u64, - effective_max_hops: u32, - coverage: IndexCoverage, - ) -> ExpandCostInputs { - ExpandCostInputs { - frontier_rows, - edge_count, - src_node_count, - effective_max_hops, - max_hops_cap: 6, - max_frontier_cap: 1024, - coverage, - csr_cached: false, - } - } - - #[test] - fn selective_frontier_on_large_graph_picks_indexed() { - // 50 source rows against 1M source vertices, one hop: tiny selectivity β€” - // the PR #149 win the chooser must preserve. - let m = choose_expand_mode(&inputs(50, 10_000_000, 1_000_000, 1, IndexCoverage::Indexed)); - assert_eq!(m, ExpandMode::IndexedScan); - } - - #[test] - fn flat_in_edge_count_same_selectivity_same_choice() { - // Same selectivity (frontier/|V_src|), 1000Γ— difference in |E|. Indexed - // cost is independent of |E|, so the choice must not flip. - let small = choose_expand_mode(&inputs(50, 100_000, 1_000_000, 1, IndexCoverage::Indexed)); - let huge = - choose_expand_mode(&inputs(50, 100_000_000, 1_000_000, 1, IndexCoverage::Indexed)); - assert_eq!(small, ExpandMode::IndexedScan); - assert_eq!(huge, ExpandMode::IndexedScan); - } - - #[test] - fn frontier_large_fraction_of_source_picks_csr() { - // hops*frontier (200) exceeds BUILD_FACTOR*|V_src| (1.5*100=150) β†’ CSR, - // and 200 is below the frontier cap, so it is the cost model deciding. - let m = choose_expand_mode(&inputs(200, 1_000, 100, 1, IndexCoverage::Indexed)); - assert_eq!(m, ExpandMode::Csr); - } - - #[test] - fn frontier_over_hard_cap_picks_csr() { - // 2000 > 1024 ceiling, even though the selectivity is tiny. - let m = choose_expand_mode(&inputs(2000, 10_000_000, 1_000_000, 1, IndexCoverage::Indexed)); - assert_eq!(m, ExpandMode::Csr); - } - - #[test] - fn hops_over_hard_cap_picks_csr() { - let m = choose_expand_mode(&inputs(10, 10_000_000, 1_000_000, 8, IndexCoverage::Indexed)); - assert_eq!(m, ExpandMode::Csr); - } - - #[test] - fn degraded_single_hop_tiny_frontier_stays_indexed() { - // One full degraded scan (1*|E|) still edges out a full CSR build - // (1.5*|E|) for a one-off single hop. - let m = choose_expand_mode(&inputs( - 5, - 10_000, - 10_000, - 1, - IndexCoverage::Degraded { - reason: "no btree".into(), - }, - )); - assert_eq!(m, ExpandMode::IndexedScan); - } - - #[test] - fn degraded_multi_hop_picks_csr() { - // Two degraded scans (2*|E|) lose to one CSR build (1.5*|E|). - let m = choose_expand_mode(&inputs( - 5, - 10_000, - 10_000, - 2, - IndexCoverage::Degraded { - reason: "no btree".into(), - }, - )); - assert_eq!(m, ExpandMode::Csr); - } - - #[test] - fn warm_csr_is_always_reused() { - // A maximally selective traversal still prefers an already-built CSR - // (cost ~0) over re-scanning per hop. - let mut i = inputs(1, 10_000_000, 1_000_000, 1, IndexCoverage::Indexed); - i.csr_cached = true; - assert_eq!(choose_expand_mode(&i), ExpandMode::Csr); - } - - #[test] - fn cost_model_caps_cross_type_hops() { - // Same-type passes the requested range through; cross-type caps at 1, - // matching execute_expand_indexed. - assert_eq!(cost_effective_hops(5, true), 5); - assert_eq!(cost_effective_hops(5, false), 1); - assert_eq!(cost_effective_hops(1, false), 1); - - // Consequence: a selective frontier where the requested 5 hops would - // (wrongly) flip cross-type to CSR, but the capped 1 hop β€” what actually - // runs β€” keeps it indexed. - let mut i = inputs(50, 10_000, 100, cost_effective_hops(5, false), IndexCoverage::Indexed); - assert_eq!(choose_expand_mode(&i), ExpandMode::IndexedScan); - i.effective_max_hops = 5; // as if the cross-type cap were not applied - assert_eq!(choose_expand_mode(&i), ExpandMode::Csr); - } -} diff --git a/crates/omnigraph/src/exec/staging.rs b/crates/omnigraph/src/exec/staging.rs index a3932b0..0d26fd3 100644 --- a/crates/omnigraph/src/exec/staging.rs +++ b/crates/omnigraph/src/exec/staging.rs @@ -21,10 +21,9 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use crate::storage_layer::{SnapshotHandle, StagedHandle}; use arrow_array::{Array, RecordBatch, StringArray, UInt32Array}; use arrow_schema::SchemaRef; -use futures::stream::StreamExt; +use lance::Dataset; use omnigraph_compiler::catalog::EdgeType; use crate::db::manifest::{ @@ -33,13 +32,15 @@ use crate::db::manifest::{ use crate::db::{MutationOpKind, SubTableUpdate}; use crate::error::{OmniError, Result}; -/// Whether the per-table accumulator should commit via `stage_append`, -/// `stage_merge_insert`, or `stage_overwrite`. +/// Whether the per-table accumulator should commit via `stage_append` +/// (no @key inserts, edge inserts) or `stage_merge_insert` (any @key insert +/// or update). Once set to `Merge` for a table within a query, subsequent +/// inserts on that table are rolled into the same merge β€” a `WhenNotMatched +/// = InsertAll` merge is correct for both cases. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum PendingMode { Append, Merge, - Overwrite, } /// Per-table accumulator. Each insert/update op pushes a `RecordBatch` into @@ -157,9 +158,9 @@ impl MutationStaging { mode: PendingMode, batch: RecordBatch, ) -> Result<()> { - if batch.num_rows() == 0 && mode != PendingMode::Overwrite { - // No-op for additive modes. For Overwrite, an empty batch is - // observable: it means "replace this table with zero rows". + if batch.num_rows() == 0 { + // No-op β€” staging is purely additive; an empty batch should not + // be appended. return Ok(()); } // If we've already accumulated a batch on this table, the new @@ -173,14 +174,6 @@ impl MutationStaging { // caller a clearer point of failure attached to the specific // op that introduced the drift. if let Some(existing) = self.pending.get(table_key) { - if existing.mode == PendingMode::Overwrite || mode == PendingMode::Overwrite { - if existing.mode != mode { - return Err(OmniError::manifest_internal(format!( - "table '{}' cannot mix overwrite staging with append/merge staging", - table_key - ))); - } - } if !schemas_compatible(&existing.schema, &batch.schema()) { return Err(OmniError::manifest(format!( "table '{}' accumulated mutation batches with mismatched schemas: \ @@ -201,9 +194,8 @@ impl MutationStaging { .pending .entry(table_key.to_string()) .or_insert_with(|| PendingTable::new(schema.clone(), mode)); - // Upgrade Append -> Merge if any op needs merge semantics. Overwrite - // is never mixed with additive modes (guarded above). - if mode == PendingMode::Merge && entry.mode == PendingMode::Append { + // Upgrade Append -> Merge if any op needs merge semantics. + if mode == PendingMode::Merge { entry.mode = PendingMode::Merge; } entry.batches.push(batch); @@ -225,11 +217,6 @@ impl MutationStaging { .unwrap_or(&[]) } - /// Accumulator mode for `table_key`, if this query has touched it. - pub(crate) fn pending_mode(&self, table_key: &str) -> Option { - self.pending.get(table_key).map(|p| p.mode) - } - /// Schema of the accumulated batches for `table_key`, or `None` if no /// op has touched the table. Used by `scan_with_pending` to construct /// the in-memory `MemTable`. @@ -262,21 +249,9 @@ impl MutationStaging { /// Lance datasets is a perf follow-up; same loop structure as the /// pre-split `finalize`. pub(crate) async fn stage_all( - self, - db: &crate::db::Omnigraph, - branch: Option<&str>, - ) -> Result { - self.stage_all_with_concurrency(db, branch, 1).await - } - - /// Loader-facing variant of [`stage_all`] that preserves - /// `OMNIGRAPH_LOAD_CONCURRENCY` for the fragment-writing stage while - /// still leaving all Lance HEAD movement to [`StagedMutation::commit_all`]. - pub(crate) async fn stage_all_with_concurrency( self, db: &crate::db::Omnigraph, _branch: Option<&str>, - concurrency: usize, ) -> Result { let MutationStaging { expected_versions, @@ -286,8 +261,7 @@ impl MutationStaging { op_kinds, } = self; - let mut stage_inputs: Vec<(String, PendingTable, StagedTablePath, u64)> = - Vec::with_capacity(pending.len()); + let mut staged_entries: Vec = Vec::with_capacity(pending.len()); for (table_key, table) in pending { let path = paths.get(&table_key).cloned().ok_or_else(|| { OmniError::manifest_internal(format!( @@ -301,22 +275,77 @@ impl MutationStaging { table_key )) })?; - stage_inputs.push((table_key, table, path, expected)); + + // Reopen the dataset for staging. The op_kind reflects the + // accumulated PendingTable's mode: Append-mode batches are + // INSERT-shaped (no key-based dedup at commit_staged); Merge- + // mode batches are MERGE-shaped (key-dedup at commit_staged). + // Both skip the strict pre-stage version check under the + // [`MutationOpKind`] policy: Lance's natural rebase + the + // per-(table, branch) queue + the publisher CAS in + // `commit_all` handle drift; the strict check would + // over-reject in-process concurrent inserts (PR 2 / MR-686 + // Phase 2). + let stage_kind = match table.mode { + PendingMode::Append => crate::db::MutationOpKind::Insert, + PendingMode::Merge => crate::db::MutationOpKind::Merge, + }; + let ds = db + .reopen_for_mutation( + &table_key, + &path.full_path, + path.table_branch.as_deref(), + expected, + stage_kind, + ) + .await?; + + if table.batches.is_empty() { + continue; + } + + // For Merge mode, dedupe accumulated batches by `id`, keeping + // the LAST occurrence (last-write-wins for the query). This + // is required because Lance's `MergeInsertBuilder` produces + // arbitrary results on duplicate keys in the source. Append + // 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::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()))? + } + } + }; + + // 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::Merge => { + db.table_store() + .stage_merge_insert( + ds.clone(), + combined, + vec!["id".to_string()], + lance::dataset::WhenMatched::UpdateAll, + lance::dataset::WhenNotMatched::InsertAll, + ) + .await? + } + }; + staged_entries.push(StagedTableEntry { + table_key, + path, + expected_version: expected, + dataset: ds, + staged_write: staged, + }); } - let concurrency = concurrency.min(stage_inputs.len()).max(1); - let staged_entries = futures::stream::iter(stage_inputs.into_iter().map( - |(table_key, table, path, expected)| async move { - stage_pending_table(db, table_key, table, path, expected).await - }, - )) - .buffered(concurrency) - .collect::>>>() - .await - .into_iter() - .collect::>>()? - .into_iter() - .flatten() - .collect(); Ok(StagedMutation { inline_committed, @@ -328,73 +357,6 @@ impl MutationStaging { } } -async fn stage_pending_table( - db: &crate::db::Omnigraph, - table_key: String, - table: PendingTable, - path: StagedTablePath, - expected: u64, -) -> Result> { - // Reopen the dataset for staging. Append/Merge can be rebased later by - // Lance + publisher CAS; Overwrite is a strict replacement and uses the - // same SchemaRewrite policy as schema apply. - let stage_kind = match table.mode { - PendingMode::Append => crate::db::MutationOpKind::Insert, - PendingMode::Merge => crate::db::MutationOpKind::Merge, - PendingMode::Overwrite => crate::db::MutationOpKind::SchemaRewrite, - }; - let ds = db - .reopen_for_mutation( - &table_key, - &path.full_path, - path.table_branch.as_deref(), - expected, - stage_kind, - ) - .await?; - - if table.batches.is_empty() { - return Ok(None); - } - - let combined = match table.mode { - PendingMode::Merge => dedupe_merge_batches_by_id(&table.schema, table.batches)?, - PendingMode::Append | PendingMode::Overwrite => { - 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()))? - } - } - }; - - // Stage produces uncommitted fragments + transaction. No Lance HEAD - // advance until `commit_all` runs `commit_staged`. - let staged = match table.mode { - PendingMode::Append => db.storage().stage_append(&ds, combined, &[]).await?, - PendingMode::Merge => { - db.storage() - .stage_merge_insert( - ds.clone(), - combined, - vec!["id".to_string()], - lance::dataset::WhenMatched::UpdateAll, - lance::dataset::WhenNotMatched::InsertAll, - ) - .await? - } - PendingMode::Overwrite => db.storage().stage_overwrite(&ds, combined).await?, - }; - Ok(Some(StagedTableEntry { - table_key, - path, - expected_version: expected, - dataset: ds, - staged_write: staged, - })) -} - /// Output of [`MutationStaging::stage_all`]. Carries the staged Lance /// transactions (Phase A complete; uncommitted fragments written) plus /// the per-table metadata needed to write the recovery sidecar, run @@ -427,17 +389,15 @@ pub(crate) struct StagedMutation { } /// Per-table state captured during `stage_all` and consumed by -/// `commit_all`. Holds the opened snapshot (so `commit_staged` doesn't -/// re-open) plus the staged Lance transaction that `commit_staged` -/// will execute. Both held as opaque `TableStorage` handles per MR-793 -/// Β§III.9 β€” the inner `lance::Dataset` / `StagedWrite` are not visible -/// to engine code outside the storage layer. +/// `commit_all`. Holds the opened `Dataset` so `commit_staged` doesn't +/// re-open, and the `StagedWrite` whose `transaction` `commit_staged` +/// will execute. struct StagedTableEntry { table_key: String, path: StagedTablePath, expected_version: u64, - dataset: SnapshotHandle, - staged_write: StagedHandle, + dataset: lance::Dataset, + staged_write: crate::table_store::StagedWrite, } impl StagedMutation { @@ -535,21 +495,25 @@ impl StagedMutation { // until `ensure_path` learns how to bump expected_version on // op-kind upgrade. // - // Why a fresh per-branch snapshot (and not the bound-branch - // `db.snapshot()` / `snapshot_for_branch()` fast path): a stale - // engine handle may be bound to the same branch it is writing. For - // non-strict Insert/Merge, that stale local view is allowed to rebase - // to the live manifest pin under the queue; only uncovered Lance - // HEAD>manifest drift is refused. For writes targeting a branch other - // than the engine's bound branch (e.g., feature-branch ingest from a - // server handle bound to main), the same helper also resolves the - // correct branch pin. The cost is one fresh manifest read per mutation - // plus one Lance HEAD open per staged table for the drift guard below. + // Why per-branch (and not the bound-branch `db.snapshot()`): + // when the caller mutates a branch other than the engine's + // bound branch (e.g., feature-branch ingest from a server + // handle bound to main), `db.snapshot()` returns the bound + // branch's view of each table β€” which is the wrong pin for + // the publisher's CAS on a different branch. Using + // `snapshot_for_branch(branch)` resolves the per-branch + // entries correctly. The cost is one fresh manifest read per + // mutation; PR 1b's regression came from this same read, but + // that read is now strictly necessary for cross-branch + // correctness. Single-table same-branch mutations could still + // skip this read (queue exclusivity makes the publisher CAS a + // no-op), but the conditional adds complexity for marginal + // gain β€” left as a follow-up perf optimization. // // Multi-coordinator deployments (Β§VI.27 aspirational) get // genuine cross-process drift detection from this read for // free. - let snapshot = db.fresh_snapshot_for_branch(branch).await?; + let snapshot = db.snapshot_for_branch(branch).await?; for entry in staged.iter_mut() { let current = snapshot .entry(&entry.table_key) @@ -577,34 +541,6 @@ impl StagedMutation { )); } - // Separate manifest-visible concurrency from uncovered Lance drift. - // Non-strict inserts/merges are allowed to rebase from their staged - // read version to the fresh manifest pin above, but only if the - // live Lance HEAD still equals that manifest pin. If an external - // raw Lance write or a pre-fix maintenance path moved HEAD without - // publishing `__manifest`, this write must not silently fold it. - let head = db - .storage() - .open_dataset_head_for_write( - &entry.table_key, - &entry.path.full_path, - entry.path.table_branch.as_deref(), - ) - .await? - .version(); - if head < current { - return Err(OmniError::manifest_internal(format!( - "table '{}' Lance HEAD version {} is behind manifest version {}", - entry.table_key, head, current - ))); - } - if head > current { - return Err(OmniError::manifest_conflict(format!( - "table '{}' has Lance HEAD version {} ahead of manifest version {}; run `omnigraph repair` before writing", - entry.table_key, head, current - ))); - } - entry.expected_version = current; expected_versions.insert(entry.table_key.clone(), current); } @@ -711,8 +647,14 @@ impl StagedMutation { staged_write, } = entry; - let new_ds = db.storage().commit_staged(dataset, staged_write).await?; - let state = db.storage().table_state(&path.full_path, &new_ds).await?; + let new_ds = db + .table_store() + .commit_staged(Arc::new(dataset), staged_write.transaction) + .await?; + let state = db + .table_store() + .table_state(&path.full_path, &new_ds) + .await?; updates.push(SubTableUpdate { table_key, table_version: state.version, @@ -846,9 +788,7 @@ fn dedupe_merge_batches_by_id( /// Count edges per `src` value across committed (Lance scan) + pending /// (in-memory). Caller supplies an opened committed dataset so the /// mutation path (which already has one) and the loader path (which -/// opens via snapshot) share the same body. For overwrite staging, the -/// pending batches are the replacement table image, so committed rows are -/// intentionally skipped. +/// opens via snapshot) share the same body. /// /// `dedupe_key_column` controls whether committed rows are shadowed by /// pending: @@ -863,7 +803,7 @@ fn dedupe_merge_batches_by_id( /// `LoadMode::Merge` double-counts. pub(crate) async fn count_src_per_edge( db: &crate::db::Omnigraph, - committed_ds: &SnapshotHandle, + committed_ds: &Dataset, table_key: &str, staging: &MutationStaging, dedupe_key_column: Option<&str>, @@ -894,44 +834,41 @@ pub(crate) async fn count_src_per_edge( _ => None, }; - let replace_committed = staging.pending_mode(table_key) == Some(PendingMode::Overwrite); - if !replace_committed { - // Committed side: scan `src` plus the dedupe key column when set, so - // we can both count and shadow in one pass. - let projection: Vec<&str> = match dedupe_key_column { - Some(col) if pending_keys.as_ref().is_some_and(|s| !s.is_empty()) => vec!["src", col], - _ => vec!["src"], + // Committed side: scan `src` plus the dedupe key column when set, so + // we can both count and shadow in one pass. + let projection: Vec<&str> = match dedupe_key_column { + Some(col) if pending_keys.as_ref().is_some_and(|s| !s.is_empty()) => vec!["src", col], + _ => vec!["src"], + }; + let committed = db + .table_store() + .scan(committed_ds, Some(&projection), None, None) + .await?; + for batch in &committed { + let srcs = batch + .column_by_name("src") + .ok_or_else(|| OmniError::Lance("missing 'src' column on edge table".into()))? + .as_any() + .downcast_ref::() + .ok_or_else(|| OmniError::Lance("'src' column is not Utf8".into()))?; + // Optional shadow-key column (only present when dedupe is on). + let key_arr = match (&pending_keys, dedupe_key_column) { + (Some(set), Some(col)) if !set.is_empty() => batch + .column_by_name(col) + .and_then(|c| c.as_any().downcast_ref::()), + _ => None, }; - let committed = db - .storage() - .scan(committed_ds, Some(&projection), None, None) - .await?; - for batch in &committed { - let srcs = batch - .column_by_name("src") - .ok_or_else(|| OmniError::Lance("missing 'src' column on edge table".into()))? - .as_any() - .downcast_ref::() - .ok_or_else(|| OmniError::Lance("'src' column is not Utf8".into()))?; - // Optional shadow-key column (only present when dedupe is on). - let key_arr = match (&pending_keys, dedupe_key_column) { - (Some(set), Some(col)) if !set.is_empty() => batch - .column_by_name(col) - .and_then(|c| c.as_any().downcast_ref::()), - _ => None, - }; - for i in 0..srcs.len() { - if !srcs.is_valid(i) { + for i in 0..srcs.len() { + if !srcs.is_valid(i) { + continue; + } + // Shadow this committed row if its key is in pending. + if let (Some(arr), Some(set)) = (key_arr, pending_keys.as_ref()) { + if arr.is_valid(i) && set.contains(arr.value(i)) { continue; } - // Shadow this committed row if its key is in pending. - if let (Some(arr), Some(set)) = (key_arr, pending_keys.as_ref()) { - if arr.is_valid(i) && set.contains(arr.value(i)) { - continue; - } - } - *counts.entry(srcs.value(i).to_string()).or_insert(0) += 1; } + *counts.entry(srcs.value(i).to_string()).or_insert(0) += 1; } } diff --git a/crates/omnigraph/src/loader/mod.rs b/crates/omnigraph/src/loader/mod.rs index 09c2f7c..46a46e2 100644 --- a/crates/omnigraph/src/loader/mod.rs +++ b/crates/omnigraph/src/loader/mod.rs @@ -26,14 +26,6 @@ use crate::exec::staging::{MutationStaging, PendingMode}; /// Result of a load operation. #[derive(Debug, Clone, Default)] pub struct LoadResult { - /// Branch the load landed on (`"main"` when no branch was given). - pub branch: String, - /// Base branch a fork was requested from (the `base` parameter of - /// `load_as`), recorded verbatim even when the target branch already - /// existed and no fork happened. - pub base_branch: Option, - /// True when this load created `branch` by forking it from `base_branch`. - pub branch_created: bool, pub nodes_loaded: HashMap, pub edges_loaded: HashMap, } @@ -65,27 +57,21 @@ pub enum LoadMode { Merge, } -/// Convenience: load JSONL data onto the database handle's *active branch* -/// (`main` when unbound). Equivalent to `db.load(active_branch, data, mode)`; -/// use `Omnigraph::load`/`load_as` directly when targeting an explicit branch -/// or when fork-from-base semantics are needed. -pub async fn load_jsonl(db: &Omnigraph, data: &str, mode: LoadMode) -> Result { +/// Load JSONL data into an Omnigraph database. +pub async fn load_jsonl(db: &mut Omnigraph, data: &str, mode: LoadMode) -> Result { let current_branch = db.active_branch().await; let branch = current_branch.as_deref().unwrap_or("main"); db.load(branch, data, mode).await } -/// Convenience: like [`load_jsonl`] but reading from a file path. -pub async fn load_jsonl_file(db: &Omnigraph, path: &str, mode: LoadMode) -> Result { +/// Load JSONL data from a file path. +pub async fn load_jsonl_file(db: &mut Omnigraph, path: &str, mode: LoadMode) -> Result { let current_branch = db.active_branch().await; let branch = current_branch.as_deref().unwrap_or("main"); db.load_file(branch, path, mode).await } impl Omnigraph { - #[deprecated( - note = "use `load_as` with an explicit `base` instead; the ingest family will be removed in a future release" - )] pub async fn ingest( &self, branch: &str, @@ -93,17 +79,9 @@ impl Omnigraph { data: &str, mode: LoadMode, ) -> Result { - #[allow(deprecated)] self.ingest_as(branch, from, data, mode, None).await } - /// Deprecated shim over the unified `load_as`. Preserves the historical - /// ingest contract exactly: `from: None` means fork from `main`, and the - /// base branch is recorded in the result even when the target branch - /// already existed (no fork happened). - #[deprecated( - note = "use `load_as` with an explicit `base` instead; the ingest family will be removed in a future release" - )] pub async fn ingest_as( &self, branch: &str, @@ -112,24 +90,22 @@ impl Omnigraph { mode: LoadMode, actor_id: Option<&str>, ) -> Result { - let result = self - .load_as(branch, Some(from.unwrap_or("main")), data, mode, actor_id) - .await?; - Ok(IngestResult { - branch: result.branch.clone(), - base_branch: result - .base_branch - .clone() - .unwrap_or_else(|| "main".to_string()), - branch_created: result.branch_created, - mode, - tables: result.to_ingest_tables(), - }) + // Engine-layer policy gate (MR-722 fan-out / PR #3). Scope is + // `Branch(branch)` for the data-write portion. If ingest creates + // a new branch as a side-effect (target branch doesn't exist), + // the inner `branch_create_from_as` call below additionally + // checks `BranchCreate` β€” both authorities are genuinely needed + // for "ingest into a fresh branch", so the layered check is + // correct, not redundant. + self.enforce( + omnigraph_policy::PolicyAction::Change, + &omnigraph_policy::ResourceScope::Branch(branch.to_string()), + actor_id, + )?; + self.ingest_with_current_actor(branch, from, data, mode, actor_id) + .await } - #[deprecated( - note = "use `load_file_as` with an explicit `base` instead; the ingest family will be removed in a future release" - )] pub async fn ingest_file( &self, branch: &str, @@ -137,13 +113,9 @@ impl Omnigraph { path: &str, mode: LoadMode, ) -> Result { - #[allow(deprecated)] self.ingest_file_as(branch, from, path, mode, None).await } - #[deprecated( - note = "use `load_file_as` with an explicit `base` instead; the ingest family will be removed in a future release" - )] pub async fn ingest_file_as( &self, branch: &str, @@ -153,35 +125,69 @@ impl Omnigraph { actor_id: Option<&str>, ) -> Result { let data = std::fs::read_to_string(path).map_err(OmniError::Io)?; - #[allow(deprecated)] self.ingest_as(branch, from, &data, mode, actor_id).await } - pub async fn load(&self, branch: &str, data: &str, mode: LoadMode) -> Result { - self.load_as(branch, None, data, mode, None).await + async fn ingest_with_current_actor( + &self, + branch: &str, + from: Option<&str>, + data: &str, + mode: LoadMode, + actor_id: Option<&str>, + ) -> Result { + self.ensure_schema_state_valid().await?; + let target_branch = + Self::normalize_branch_name(branch)?.unwrap_or_else(|| "main".to_string()); + let base_branch = Self::normalize_branch_name(from.unwrap_or("main"))? + .unwrap_or_else(|| "main".to_string()); + let branch_created = !self + .branch_list() + .await? + .iter() + .any(|name| name == &target_branch); + if branch_created { + // Thread the actor through to the implicit BranchCreate so + // policy decisions match what an explicit `branch_create_from_as` + // call would see. Calling the no-actor variant here would + // bypass BranchCreate enforcement when policy is installed β€” + // the footgun guard catches that case too, but threading is + // the correct fix. + self.branch_create_from_as( + crate::db::ReadTarget::branch(&base_branch), + &target_branch, + actor_id, + ) + .await?; + } + + let result = self.load_as(&target_branch, data, mode, actor_id).await?; + Ok(IngestResult { + branch: target_branch, + base_branch, + branch_created, + mode, + tables: result.to_ingest_tables(), + }) + } + + pub async fn load(&self, branch: &str, data: &str, mode: LoadMode) -> Result { + self.load_as(branch, data, mode, None).await } - /// Load JSONL data onto `branch`. - /// - /// `base` selects the branch-creation behavior: with `Some(base)`, a - /// missing target branch is forked from `base` first (the former - /// `ingest` semantics); with `None`, the target branch must already - /// exist β€” staging fails on an unknown branch when it resolves the - /// manifest snapshot, so a typo'd branch name can never create one. pub async fn load_as( &self, branch: &str, - base: Option<&str>, data: &str, mode: LoadMode, actor_id: Option<&str>, ) -> Result { // Engine-layer policy gate (MR-722 fan-out / PR #3). Scope is // `Branch(branch)` to match the HTTP-layer Change convention. - // When a fork happens below, `branch_create_from_as` additionally - // checks `BranchCreate` β€” both authorities are genuinely needed - // for "load into a fresh branch", so the layered check is - // correct, not redundant. + // `ingest_as` also calls `load_as` after enforcing its own + // Change gate β€” that double-check is fine because both gates + // resolve to identical Cedar decisions for the same actor + + // branch (the second check is a structurally-correct no-op). self.enforce( omnigraph_policy::PolicyAction::Change, &omnigraph_policy::ResourceScope::Branch(branch.to_string()), @@ -199,47 +205,15 @@ impl Omnigraph { // `commit_prepared_updates_on_branch_with_expected`) and leave // `self.coordinator` with a stale manifest snapshot. let requested = Self::normalize_branch_name(branch)?; - let base_branch = match base { - Some(base) => { - Some(Self::normalize_branch_name(base)?.unwrap_or_else(|| "main".to_string())) - } - None => None, - }; - // Fork-if-missing only when a base branch was explicitly given. - // `requested == None` is `main`, which always exists. - let mut branch_created = false; - if let (Some(target), Some(base_name)) = (requested.as_deref(), base_branch.as_deref()) { - let exists = self.branch_list().await?.iter().any(|name| name == target); - if !exists { - // Thread the actor through to the implicit BranchCreate so - // policy decisions match what an explicit `branch_create_from_as` - // call would see. Calling the no-actor variant here would - // bypass BranchCreate enforcement when policy is installed β€” - // the footgun guard catches that case too, but threading is - // the correct fix. - self.branch_create_from_as( - crate::db::ReadTarget::branch(base_name), - target, - actor_id, - ) - .await?; - branch_created = true; - } - } // Direct-to-target writes: no Run state machine, no `__run__` staging // branch. Cross-table OCC is enforced by the publisher's // `expected_table_versions` CAS inside `load_jsonl_reader`. - let mut result = self - .load_direct_on_branch(requested.as_deref(), data, mode, actor_id) - .await?; - result.branch = requested.unwrap_or_else(|| "main".to_string()); - result.base_branch = base_branch; - result.branch_created = branch_created; - Ok(result) + self.load_direct_on_branch(requested.as_deref(), data, mode, actor_id) + .await } pub async fn load_file(&self, branch: &str, path: &str, mode: LoadMode) -> Result { - self.load_file_as(branch, None, path, mode, None).await + self.load_file_as(branch, path, mode, None).await } /// Read a file into memory and delegate to `load_as`. Used by the @@ -248,13 +222,12 @@ impl Omnigraph { pub async fn load_file_as( &self, branch: &str, - base: Option<&str>, path: &str, mode: LoadMode, actor_id: Option<&str>, ) -> Result { - let data = std::fs::read_to_string(path).map_err(OmniError::Io)?; - self.load_as(branch, base, &data, mode, actor_id).await + let data = std::fs::read_to_string(path).map_err(|e| OmniError::Io(e))?; + self.load_as(branch, &data, mode, actor_id).await } async fn load_direct_on_branch( @@ -315,24 +288,22 @@ async fn load_jsonl_reader( let mut node_rows: HashMap> = HashMap::new(); let mut edge_rows: HashMap> = HashMap::new(); - // Parse a stream of JSON values. Accepts both compact JSONL (one object - // per line) and pretty-printed JSON where a single object spans multiple - // lines β€” serde's streaming deserializer treats any whitespace (including - // newlines) between top-level values as a separator. - for (idx, parsed) in serde_json::Deserializer::from_reader(reader) - .into_iter::() - .enumerate() - { - let record_num = idx + 1; - let value: JsonValue = parsed.map_err(|e| { - OmniError::manifest(format!("invalid JSON at record {}: {}", record_num, e)) + for (line_num, line) in reader.lines().enumerate() { + let line = line?; + let line = line.trim(); + if line.is_empty() { + continue; + } + let value: JsonValue = serde_json::from_str(line).map_err(|e| { + OmniError::manifest(format!("invalid JSON on line {}: {}", line_num + 1, e)) })?; if let Some(type_name) = value.get("type").and_then(|v| v.as_str()) { if !catalog.node_types.contains_key(type_name) { return Err(OmniError::manifest(format!( - "record {}: unknown node type '{}'", - record_num, type_name + "line {}: unknown node type '{}'", + line_num + 1, + type_name ))); } let data = value @@ -346,22 +317,23 @@ async fn load_jsonl_reader( } else if let Some(edge_name) = value.get("edge").and_then(|v| v.as_str()) { if catalog.lookup_edge_by_name(edge_name).is_none() { return Err(OmniError::manifest(format!( - "record {}: unknown edge type '{}'", - record_num, edge_name + "line {}: unknown edge type '{}'", + line_num + 1, + edge_name ))); } let from = value .get("from") .and_then(|v| v.as_str()) .ok_or_else(|| { - OmniError::manifest(format!("record {}: edge missing 'from'", record_num)) + OmniError::manifest(format!("line {}: edge missing 'from'", line_num + 1)) })? .to_string(); let to = value .get("to") .and_then(|v| v.as_str()) .ok_or_else(|| { - OmniError::manifest(format!("record {}: edge missing 'to'", record_num)) + OmniError::manifest(format!("line {}: edge missing 'to'", line_num + 1)) })? .to_string(); let data = value @@ -375,30 +347,34 @@ async fn load_jsonl_reader( .push((from, to, data)); } else { return Err(OmniError::manifest(format!( - "record {}: expected 'type' or 'edge' field", - record_num + "line {}: expected 'type' or 'edge' field", + line_num + 1 ))); } } // Phase 2: Build per-type RecordBatches and accumulate into the - // staging pipeline. Batches go into an in-memory accumulator and a - // single `stage_*` + `commit_staged` per touched table runs at - // end-of-load β€” a mid-load failure (RI / cardinality violation) leaves - // Lance HEAD untouched. `LoadMode::Overwrite` uses Lance's staged - // `Overwrite` transaction rather than the former truncate-then-append - // inline path. + // staging pipeline. For Append/Merge, batches go into an in-memory + // accumulator and a single `stage_*` + `commit_staged` per touched + // table runs at end-of-load β€” a mid-load failure (RI / cardinality + // violation) leaves Lance HEAD untouched. For Overwrite, the legacy + // inline-commit path is preserved (truncate+append doesn't fit the + // staged shape cleanly, and overwrite has no in-flight read-your-writes + // requirement). let mut result = LoadResult::default(); let snapshot = db.snapshot_for_branch(branch).await?; + let use_staging = !matches!(mode, LoadMode::Overwrite); let mut staging = MutationStaging::default(); + let mut overwrite_updates: Vec = Vec::new(); + let mut overwrite_expected: HashMap = HashMap::new(); let pending_mode = match mode { LoadMode::Merge => PendingMode::Merge, // Append-mode loads accumulate as Append. Edge tables (no @key) // and no-key node tables stay safe on the stage_append path. The // Merge mode applies dedupe-by-id; Append assumes unique inputs. LoadMode::Append => PendingMode::Append, - LoadMode::Overwrite => PendingMode::Overwrite, + LoadMode::Overwrite => PendingMode::Append, // unused }; // Map LoadMode to MutationOpKind for the version-check policy. // Append/Merge skip the strict pre-stage check (concurrency-safe @@ -420,49 +396,87 @@ async fn load_jsonl_reader( let batch = build_node_batch(node_type, rows)?; validate_value_constraints(&batch, node_type)?; validate_enum_constraints(&batch, &node_type.properties, type_name)?; - let unique_groups = unique_constraint_groups_for_node(node_type); - if !unique_groups.is_empty() { - enforce_unique_constraints_intra_batch(&batch, type_name, &unique_groups)?; + let unique_props = unique_property_names_for_node(node_type); + if !unique_props.is_empty() { + enforce_unique_constraints_intra_batch(&batch, type_name, &unique_props)?; } let loaded_count = batch.num_rows(); let table_key = format!("node:{}", type_name); - let _entry = snapshot + let entry = snapshot .entry(&table_key) .ok_or_else(|| OmniError::manifest(format!("no manifest entry for {}", table_key)))?; + if !use_staging { + overwrite_expected.insert(table_key.clone(), entry.table_version); + } prepared_nodes.push((type_name.clone(), table_key, batch, loaded_count)); } - // Phase 2b: accumulate every node type in memory. Fragment writes are - // delayed until after all validation succeeds. - for (type_name, table_key, batch, loaded_count) in prepared_nodes { - let (ds, full_path, table_branch) = db - .open_for_mutation_on_branch(branch, &table_key, load_op_kind) - .await?; - let expected_version = ds.version(); - staging.ensure_path( - &table_key, - full_path, - table_branch, - expected_version, - load_op_kind, - ); - let schema = batch.schema(); - staging.append_batch(&table_key, schema, pending_mode, batch)?; - result.nodes_loaded.insert(type_name, loaded_count); + // Phase 2b: write every node type. Append/Merge β†’ in-memory + // accumulator. Overwrite β†’ concurrent inline-commit (legacy path). + if use_staging { + for (type_name, table_key, batch, loaded_count) in prepared_nodes { + let (ds, full_path, table_branch) = db + .open_for_mutation_on_branch(branch, &table_key, load_op_kind) + .await?; + let expected_version = ds.version().version; + staging.ensure_path( + &table_key, + full_path, + table_branch, + expected_version, + load_op_kind, + ); + let schema = batch.schema(); + staging.append_batch(&table_key, schema, pending_mode, batch)?; + result.nodes_loaded.insert(type_name, loaded_count); + } + } else { + let node_write_results = + write_batches_concurrently(db, branch, mode, prepared_nodes).await?; + for (type_name, table_key, loaded_count, state, table_branch) in node_write_results { + overwrite_updates.push(crate::db::SubTableUpdate { + table_key, + table_version: state.version, + table_branch, + row_count: state.row_count, + version_metadata: state.version_metadata, + }); + result.nodes_loaded.insert(type_name, loaded_count); + } } // Phase 2c: Validate edge referential integrity β€” every src/dst must - // reference an existing node ID in the appropriate type. For - // Append/Merge the lookup unions snapshot-committed IDs with the - // in-memory pending batches. For Overwrite, a touched node table's - // pending batch is the replacement image, so committed rows are not - // included for that table. + // reference an existing node ID in the appropriate type. For staged + // loads, the lookup unions snapshot-committed IDs with the in-memory + // pending batches (which carry the just-staged node inserts). for (edge_name, rows) in &edge_rows { let edge_type = &catalog.edge_types[edge_name]; - let from_ids = - collect_node_ids_with_pending(db, branch, &edge_type.from_type, &staging).await?; - let to_ids = - collect_node_ids_with_pending(db, branch, &edge_type.to_type, &staging).await?; + let from_ids = if use_staging { + collect_node_ids_with_pending(db, branch, &edge_type.from_type, &staging).await? + } else { + collect_node_ids( + db, + branch, + &edge_type.from_type, + &node_rows, + &catalog, + &overwrite_updates, + ) + .await? + }; + let to_ids = if use_staging { + collect_node_ids_with_pending(db, branch, &edge_type.to_type, &staging).await? + } else { + collect_node_ids( + db, + branch, + &edge_type.to_type, + &node_rows, + &catalog, + &overwrite_updates, + ) + .await? + }; for (i, (src, dst, _)) in rows.iter().enumerate() { if !from_ids.contains(src.as_str()) { @@ -493,78 +507,124 @@ async fn load_jsonl_reader( let edge_type = &catalog.edge_types[edge_name]; let batch = build_edge_batch(edge_type, rows)?; validate_enum_constraints(&batch, &edge_type.properties, edge_name)?; - let unique_groups = unique_constraint_groups_for_edge(edge_type); - if !unique_groups.is_empty() { - enforce_unique_constraints_intra_batch(&batch, edge_name, &unique_groups)?; + let unique_props = unique_property_names_for_edge(edge_type); + if !unique_props.is_empty() { + enforce_unique_constraints_intra_batch(&batch, edge_name, &unique_props)?; } let loaded_count = batch.num_rows(); let table_key = format!("edge:{}", edge_name); - let _entry = snapshot + let entry = snapshot .entry(&table_key) .ok_or_else(|| OmniError::manifest(format!("no manifest entry for {}", table_key)))?; + if !use_staging { + overwrite_expected.insert(table_key.clone(), entry.table_version); + } prepared_edges.push((edge_name.clone(), table_key, batch, loaded_count)); } - // Phase 2e: accumulate every edge type. Same dispatch as Phase 2b. - for (edge_name, table_key, batch, loaded_count) in prepared_edges { - let (ds, full_path, table_branch) = db - .open_for_mutation_on_branch(branch, &table_key, load_op_kind) - .await?; - let expected_version = ds.version(); - staging.ensure_path( - &table_key, - full_path, - table_branch, - expected_version, - load_op_kind, - ); - let schema = batch.schema(); - staging.append_batch(&table_key, schema, pending_mode, batch)?; - result.edges_loaded.insert(edge_name, loaded_count); + // Phase 2e: write every edge type. Same dispatch as Phase 2b. + if use_staging { + for (edge_name, table_key, batch, loaded_count) in prepared_edges { + let (ds, full_path, table_branch) = db + .open_for_mutation_on_branch(branch, &table_key, load_op_kind) + .await?; + let expected_version = ds.version().version; + staging.ensure_path( + &table_key, + full_path, + table_branch, + expected_version, + load_op_kind, + ); + let schema = batch.schema(); + staging.append_batch(&table_key, schema, pending_mode, batch)?; + result.edges_loaded.insert(edge_name, loaded_count); + } + } else { + let edge_write_results = + write_batches_concurrently(db, branch, mode, prepared_edges).await?; + for (edge_name, table_key, loaded_count, state, table_branch) in edge_write_results { + overwrite_updates.push(crate::db::SubTableUpdate { + table_key, + table_version: state.version, + table_branch, + row_count: state.row_count, + version_metadata: state.version_metadata, + }); + result.edges_loaded.insert(edge_name, loaded_count); + } } // Phase 3: Validate edge cardinality constraints (before commit β€” - // invalid data must not be committed). The helper scans committed - // edges via Lance + iterates pending edges in-memory; for Overwrite it - // treats the pending edge batches as the replacement table image. + // invalid data must not be committed). Staged path scans committed + // edges via Lance + iterates pending edges in-memory. Overwrite path + // opens the just-written version (legacy behavior). for (edge_name, _) in &edge_rows { let edge_type = &catalog.edge_types[edge_name]; let table_key = format!("edge:{}", edge_name); - validate_edge_cardinality_with_pending_loader( - db, branch, edge_type, &table_key, &staging, mode, - ) - .await?; + if use_staging { + validate_edge_cardinality_with_pending_loader( + db, branch, edge_type, &table_key, &staging, mode, + ) + .await?; + } else if let Some(update) = overwrite_updates.iter().find(|u| u.table_key == table_key) { + validate_edge_cardinality( + db, + branch, + edge_name, + update.table_version, + update.table_branch.as_deref(), + ) + .await?; + } } // Phase 4: Atomic manifest commit with publisher-level OCC. - let staged = staging - .stage_all_with_concurrency(db, branch, load_write_concurrency()) - .await?; - // `_queue_guards` holds per-(table_key, branch) write queues - // across the manifest publish below β€” see exec/mutation.rs for - // the rationale (interleaving prevention). - let (updates, expected_versions, sidecar_handle, _queue_guards) = staged - .commit_all(db, branch, crate::db::manifest::SidecarKind::Load, actor_id) - .await?; - // Same finalize β†’ publisher residual as mutations: per-table - // staged commits have advanced Lance HEAD, but the manifest - // publish has not run yet. Reuse the mutation failpoint name so - // one failpoint pins the shared `MutationStaging` boundary. - crate::failpoints::maybe_fail("mutation.post_finalize_pre_publisher")?; - db.commit_updates_on_branch_with_expected(branch, &updates, &expected_versions, actor_id) - .await?; - // The recovery sidecar protects the per-table commit_staged β†’ - // manifest publish window. Phase C succeeded β€” clean up - // best-effort: failing the user here would error out a write - // that already landed durably. - if let Some(handle) = sidecar_handle { - if let Err(err) = crate::db::manifest::delete_sidecar(&handle, db.storage_adapter()).await { - tracing::warn!( - error = %err, - operation_id = handle.operation_id.as_str(), - "recovery sidecar cleanup failed; the next open's recovery sweep will resolve it" - ); + if use_staging { + let staged = staging.stage_all(db, branch).await?; + // `_queue_guards` holds per-(table_key, branch) write queues + // across the manifest publish below β€” see exec/mutation.rs for + // the rationale (interleaving prevention). + let (updates, expected_versions, sidecar_handle, _queue_guards) = staged + .commit_all(db, branch, crate::db::manifest::SidecarKind::Load, actor_id) + .await?; + // Same finalize β†’ publisher residual as mutations: per-table + // staged commits have advanced Lance HEAD, but the manifest + // publish has not run yet. Reuse the mutation failpoint name so + // one failpoint pins the shared `MutationStaging` boundary. + crate::failpoints::maybe_fail("mutation.post_finalize_pre_publisher")?; + db.commit_updates_on_branch_with_expected(branch, &updates, &expected_versions, actor_id) + .await?; + // The recovery sidecar protects the per-table commit_staged β†’ + // manifest publish window. Phase C succeeded β€” clean up + // best-effort: failing the user here would error out a write + // that already landed durably. + if let Some(handle) = sidecar_handle { + if let Err(err) = + crate::db::manifest::delete_sidecar(&handle, db.storage_adapter()).await + { + tracing::warn!( + error = %err, + operation_id = handle.operation_id.as_str(), + "recovery sidecar cleanup failed; the next open's recovery sweep will resolve it" + ); + } } + } else { + // LoadMode::Overwrite keeps the legacy inline-commit path β€” + // truncate-then-append doesn't fit the staged shape (see + // `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 + // operator workflow (re-run overwrite to recover). + db.commit_updates_on_branch_with_expected( + branch, + &overwrite_updates, + &overwrite_expected, + actor_id, + ) + .await?; } Ok(result) @@ -1094,6 +1154,89 @@ fn load_write_concurrency() -> usize { .unwrap_or(DEFAULT_LOAD_WRITE_CONCURRENCY) } +/// Write a set of prepared `(type_name, table_key, batch, row_count)` tuples +/// concurrently. Returns results in original iteration order so callers can +/// zip them back to per-type metadata. +async fn write_batches_concurrently( + db: &Omnigraph, + branch: Option<&str>, + mode: LoadMode, + prepared: Vec<(String, String, RecordBatch, usize)>, +) -> Result< + Vec<( + String, + String, + usize, + crate::table_store::TableState, + Option, + )>, +> { + use futures::stream::StreamExt; + + if prepared.is_empty() { + return Ok(Vec::new()); + } + + let concurrency = load_write_concurrency().min(prepared.len()).max(1); + + futures::stream::iter(prepared.into_iter().map( + |(type_name, table_key, batch, loaded_count)| async move { + let (state, table_branch) = + write_batch_to_dataset(db, branch, &table_key, batch, mode).await?; + Ok::<_, OmniError>((type_name, table_key, loaded_count, state, table_branch)) + }, + )) + .buffered(concurrency) + .collect::>>() + .await + .into_iter() + .collect() +} + +async fn write_batch_to_dataset( + db: &Omnigraph, + branch: Option<&str>, + table_key: &str, + batch: RecordBatch, + mode: LoadMode, +) -> Result<(crate::table_store::TableState, Option)> { + let op_kind = match mode { + LoadMode::Append => crate::db::MutationOpKind::Insert, + LoadMode::Merge => crate::db::MutationOpKind::Merge, + LoadMode::Overwrite => crate::db::MutationOpKind::SchemaRewrite, + }; + let (mut ds, full_path, table_branch) = db + .open_for_mutation_on_branch(branch, table_key, op_kind) + .await?; + let table_store = db.table_store(); + + match mode { + LoadMode::Overwrite => { + let state = table_store + .overwrite_batch(&full_path, &mut ds, batch) + .await?; + Ok((state, table_branch)) + } + LoadMode::Append => { + let state = table_store.append_batch(&full_path, &mut ds, batch).await?; + Ok((state, table_branch)) + } + LoadMode::Merge => { + let state = table_store + .merge_insert_batch( + &full_path, + ds, + batch, + vec!["id".to_string()], + lance::dataset::WhenMatched::UpdateAll, + lance::dataset::WhenNotMatched::InsertAll, + ) + .await?; + Ok((state, table_branch)) + } + } +} + fn generate_id() -> String { ulid::Ulid::new().to_string() } @@ -1279,16 +1422,8 @@ pub(crate) fn validate_enum_constraints( Ok(()) } -/// Detect duplicate values within a single `RecordBatch` for any of the -/// `unique_constraints` groups. Each group is a list of one or more columns -/// that together form a uniqueness key: a violation occurs when two rows share -/// the same tuple of values across *all* columns in a group, so a composite -/// `@unique(a, b)` only conflicts when both `a` and `b` match. Returns an -/// error on the first duplicate found. -/// -/// Rows where any column in a group is null are exempt (standard SQL semantics -/// for uniqueness over nullable columns), as is any group whose columns are -/// not all present in the batch (e.g. a partial-schema load). +/// Detect duplicate values within a single `RecordBatch` for any of the named +/// `unique_properties`. Returns an error on the first duplicate found. /// /// Note: this only catches duplicates *within* the batch. Cross-batch /// uniqueness against already-committed rows is not enforced here β€” that @@ -1296,37 +1431,22 @@ pub(crate) fn validate_enum_constraints( pub(crate) fn enforce_unique_constraints_intra_batch( batch: &RecordBatch, type_name: &str, - unique_constraints: &[Vec], + unique_properties: &[String], ) -> Result<()> { - for columns in unique_constraints { - // Resolve the group's columns once. A group whose columns aren't all - // present in this batch is skipped (e.g. a partial-schema load). - let Some(group_columns) = columns - .iter() - .map(|name| { - batch - .schema() - .index_of(name) - .ok() - .map(|i| batch.column(i).clone()) - }) - .collect::>>() - else { + for property in unique_properties { + let Some(col_idx) = batch.schema().index_of(property).ok() else { continue; }; - let mut seen: HashMap, usize> = HashMap::new(); + let arr = batch.column(col_idx); + let mut seen: HashMap = HashMap::new(); for row in 0..batch.num_rows() { - let Some(key) = composite_unique_key(&group_columns, row)? else { + let Some(value) = scalar_to_string(arr, row) else { continue; }; - if let Some(prev_row) = seen.insert(key.clone(), row) { + if let Some(prev_row) = seen.insert(value.clone(), row) { return Err(OmniError::manifest(format!( "@unique violation on {}.{}: value '{}' appears in rows {} and {}", - type_name, - format_tuple(columns), - format_tuple(&key), - prev_row, - row + type_name, property, value, prev_row, row ))); } } @@ -1334,131 +1454,80 @@ pub(crate) fn enforce_unique_constraints_intra_batch( Ok(()) } -/// Build the composite uniqueness key for `row` over a constraint group's -/// already-resolved columns (in declaration order). -/// -/// The key is the *tuple* of per-column scalar strings (`Vec`), keyed -/// directly in the dedup map β€” there is no separator, so no data value can -/// forge a collision (an earlier version joined on `U+001F`, which a value -/// containing that control char could still defeat). -/// -/// - `Ok(None)` if any column is null: the row is exempt (a partial tuple -/// can't violate uniqueness under SQL null semantics). -/// - `Ok(Some(tuple))` otherwise. -/// - `Err(..)` propagated from [`unique_key_scalar`] on an un-keyable value. -/// -/// Shared by the intake path (`enforce_unique_constraints_intra_batch`) and the -/// branch-merge path (`exec/merge.rs::update_unique_constraints`) so the two -/// derive identical keys and cannot drift on separator or scalar conversion. -pub(crate) fn composite_unique_key( - group_columns: &[ArrayRef], - row: usize, -) -> Result>> { - let mut parts = Vec::with_capacity(group_columns.len()); - for column in group_columns { - match unique_key_scalar(column, row)? { - Some(value) => parts.push(value), - None => return Ok(None), - } - } - Ok(Some(parts)) -} - -/// Render a constraint's column tuple for error messages: a single item as -/// `col`, a composite as `(a, b)`. Used for both the column list and the -/// offending value tuple, which share the same shape. -fn format_tuple(items: &[String]) -> String { - match items { - [single] => single.clone(), - _ => format!("({})", items.join(", ")), - } -} - -/// Reduce a single Arrow scalar at (`array`, `row`) to its uniqueness-key -/// string. -/// -/// - `Ok(None)` for a null value: nulls are exempt from uniqueness (standard -/// SQL semantics over nullable columns). -/// - `Ok(Some(s))` for every scalar type a `@unique` / `@key` column can hold. -/// Strings are covered in all three physical Arrow encodings (`Utf8`, -/// `LargeUtf8`, `Utf8View`), so a legal string column is always keyable -/// regardless of how Lance materializes it on read-back. -/// - `Err(..)` for a non-null value whose Arrow type can't be reduced to a key -/// (a list, blob, or vector column). This fails loudly rather than silently -/// exempting the row, and because every legal scalar encoding is handled -/// above, the error fires only for a genuinely un-keyable column type β€” never -/// for a legal value that merely arrived in an unenumerated encoding. -fn unique_key_scalar(array: &ArrayRef, row: usize) -> Result> { - use arrow_array::{Array, LargeStringArray, StringViewArray}; +/// Reduce a single Arrow scalar at (`array`, `row`) to a `String` for +/// uniqueness comparison. Returns `None` for null values (nulls are exempt +/// from uniqueness in standard SQL semantics). +fn scalar_to_string(array: &ArrayRef, row: usize) -> Option { + use arrow_array::Array; if array.is_null(row) { - return Ok(None); + return None; } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); - } - if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); - } - if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } if let Some(a) = array.as_any().downcast_ref::() { - return Ok(Some(a.value(row).to_string())); + return Some(a.value(row).to_string()); } - Err(OmniError::manifest(format!( - "uniqueness key: unsupported column type {:?} for @unique/@key enforcement", - array.data_type() - ))) + None } -/// Build the list of uniqueness constraint groups to enforce on a node type. -/// Each group is the column tuple of one constraint. Includes every -/// `@unique(...)` constraint (from `NodeType.unique_constraints`) and the -/// `@key` (which implies uniqueness over its column tuple). Grouping is -/// preserved so a composite `@unique(a, b)` is enforced as a composite key -/// rather than degraded into independent single-field checks. -pub(crate) fn unique_constraint_groups_for_node( +/// Build the flat list of property names that must be checked for uniqueness +/// on a node type. Includes both `@unique` properties (from +/// `NodeType.unique_constraints`) and the `@key` (which implies uniqueness). +pub(crate) fn unique_property_names_for_node( node_type: &omnigraph_compiler::catalog::NodeType, -) -> Vec> { - let mut groups: Vec> = node_type.unique_constraints.clone(); - if let Some(key) = &node_type.key - && !groups.contains(key) - { - groups.push(key.clone()); +) -> Vec { + let mut props: Vec = node_type + .unique_constraints + .iter() + .flatten() + .cloned() + .collect(); + if let Some(key) = &node_type.key { + props.extend(key.iter().cloned()); } - groups + props.sort(); + props.dedup(); + props } -/// Same as [`unique_constraint_groups_for_node`] but for an edge type (edges -/// have no `@key`). -pub(crate) fn unique_constraint_groups_for_edge( +/// Same as [`unique_property_names_for_node`] but for an edge type. +pub(crate) fn unique_property_names_for_edge( edge_type: &omnigraph_compiler::catalog::EdgeType, -) -> Vec> { - edge_type.unique_constraints.clone() +) -> Vec { + let mut props: Vec = edge_type + .unique_constraints + .iter() + .flatten() + .cloned() + .collect(); + props.sort(); + props.dedup(); + props } fn extract_numeric_value(col: &ArrayRef, row: usize) -> Option { @@ -1526,7 +1595,10 @@ pub(crate) async fn validate_edge_cardinality( .await?; // Scan src column, count per source - let batches = db.storage().scan(&ds, Some(&["src"]), None, None).await?; + let batches = db + .table_store() + .scan(&ds, Some(&["src"]), None, None) + .await?; let mut counts: HashMap = HashMap::new(); for batch in &batches { @@ -1617,11 +1689,6 @@ async fn validate_edge_cardinality_with_pending_loader( /// - IDs from the staged loader's pending batches (in-memory; just-staged /// inserts of this type) /// - IDs from the committed sub-table at the pre-load snapshot version -/// -/// For `LoadMode::Overwrite`, if the node table is touched then the pending -/// batches are the replacement image. In that case committed IDs are not -/// included, so edge RI is validated against exactly what the overwrite will -/// publish. async fn collect_node_ids_with_pending( db: &Omnigraph, branch: Option<&str>, @@ -1644,10 +1711,6 @@ async fn collect_node_ids_with_pending( } } - if staging.pending_mode(&table_key) == Some(PendingMode::Overwrite) { - return Ok(ids); - } - // From the committed Lance sub-table at the pre-load snapshot version. let snapshot = db.snapshot_for_branch(branch).await?; let Some(entry) = snapshot.entry(&table_key) else { @@ -1661,7 +1724,10 @@ async fn collect_node_ids_with_pending( ) .await?; - let batches = db.storage().scan(&ds, Some(&["id"]), None, None).await?; + let batches = db + .table_store() + .scan(&ds, Some(&["id"]), None, None) + .await?; for batch in &batches { let id_col = batch @@ -1684,6 +1750,72 @@ async fn collect_node_ids_with_pending( Ok(ids) } +/// Collect all valid node IDs for a given type. Union of: +/// - IDs from the just-loaded batch (in memory, from node_rows) +/// - IDs from the sub-table at the just-written version (if it was updated) +/// - IDs from the sub-table at the snapshot-pinned version (if it was not updated) +async fn collect_node_ids( + db: &Omnigraph, + branch: Option<&str>, + type_name: &str, + node_rows: &HashMap>, + catalog: &omnigraph_compiler::catalog::Catalog, + updates: &[crate::db::SubTableUpdate], +) -> Result> { + let mut ids = HashSet::new(); + + // IDs from the in-memory batch (just loaded in this operation) + if let Some(rows) = node_rows.get(type_name) { + if let Some(node_type) = catalog.node_types.get(type_name) { + if let Some(key_prop) = node_type.key_property() { + for row in rows { + if let Some(id) = row.get(key_prop).and_then(|v| v.as_str()) { + ids.insert(id.to_string()); + } + } + } + } + } + + // IDs from the Lance sub-table + let table_key = format!("node:{}", type_name); + let snapshot = db.snapshot_for_branch(branch).await?; + let Some(entry) = snapshot.entry(&table_key) else { + return Ok(ids); + }; + // Use the just-written version if this type was updated, else snapshot version + let updated = updates + .iter() + .find(|u| u.table_key == table_key) + .map(|u| (u.table_version, u.table_branch.as_deref())); + let (version, branch) = updated.unwrap_or((entry.table_version, entry.table_branch.as_deref())); + let ds = db + .open_dataset_at_state(&entry.table_path, branch, version) + .await?; + + let batches = db + .table_store() + .scan(&ds, Some(&["id"]), None, None) + .await?; + + for batch in &batches { + let id_col = batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..batch.num_rows() { + if !id_col.is_valid(i) { + continue; + } + ids.insert(id_col.value(i).to_string()); + } + } + + Ok(ids) +} + #[cfg(test)] mod tests { use super::*; @@ -1851,7 +1983,6 @@ edge WorksAt: Person -> Company } #[tokio::test] - #[allow(deprecated)] async fn test_ingest_creates_branch_and_reports_tables() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -1896,7 +2027,6 @@ edge WorksAt: Person -> Company } #[tokio::test] - #[allow(deprecated)] async fn test_ingest_existing_branch_ignores_from_and_merges_data() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -1971,7 +2101,6 @@ edge WorksAt: Person -> Company } #[tokio::test] - #[allow(deprecated)] async fn test_ingest_as_stamps_actor_on_branch_head_commit() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -1997,68 +2126,6 @@ edge WorksAt: Person -> Company assert_eq!(head.actor_id.as_deref(), Some("act-andrew")); } - #[tokio::test] - async fn test_load_as_with_base_forks_missing_branch_and_stamps_metadata() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - - let result = db - .load_as("feature", Some("main"), TEST_DATA, LoadMode::Merge, None) - .await - .unwrap(); - - assert_eq!(result.branch, "feature"); - assert_eq!(result.base_branch.as_deref(), Some("main")); - assert!(result.branch_created); - assert!( - db.branch_list() - .await - .unwrap() - .contains(&"feature".to_string()) - ); - - // Re-loading onto the now-existing branch records the base but - // performs no fork. - let again = db - .load_as( - "feature", - Some("main"), - r#"{"type":"Person","data":{"name":"Bob","age":26}}"#, - LoadMode::Merge, - None, - ) - .await - .unwrap(); - assert!(!again.branch_created); - assert_eq!(again.base_branch.as_deref(), Some("main")); - } - - #[tokio::test] - async fn test_load_as_without_base_errors_on_missing_branch() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - - let result = db - .load_as("nonexistent", None, TEST_DATA, LoadMode::Merge, None) - .await; - assert!(result.is_err(), "load without base must not create branches"); - assert!( - !db.branch_list() - .await - .unwrap() - .contains(&"nonexistent".to_string()), - "failed load must not leave a branch behind" - ); - - // Loads to main carry the default branch metadata. - let main_load = db.load("main", TEST_DATA, LoadMode::Overwrite).await.unwrap(); - assert_eq!(main_load.branch, "main"); - assert_eq!(main_load.base_branch, None); - assert!(!main_load.branch_created); - } - #[test] fn test_range_constraint_rejects_nan() { use arrow_array::{Float64Array, RecordBatch, StringArray}; @@ -2102,66 +2169,4 @@ edge WorksAt: Person -> Company let err = result.unwrap_err().to_string(); assert!(err.contains("NaN"), "error should mention NaN: {}", err); } - - #[test] - fn composite_unique_key_builds_tuple_and_exempts_null() { - let a: ArrayRef = Arc::new(StringArray::from(vec![Some("x|y"), Some("x"), None])); - let b: ArrayRef = Arc::new(StringArray::from(vec![Some("z"), Some("y|z"), Some("q")])); - let cols = [a, b]; - - // Tuple key, so `("x|y", "z")` and `("x", "y|z")` stay distinct β€” - // a separator-joined key (the old `|` join) would collapse both to - // `x|y|z`. - assert_eq!( - composite_unique_key(&cols, 0).unwrap(), - Some(vec!["x|y".to_string(), "z".to_string()]) - ); - assert_eq!( - composite_unique_key(&cols, 1).unwrap(), - Some(vec!["x".to_string(), "y|z".to_string()]) - ); - assert_ne!( - composite_unique_key(&cols, 0).unwrap(), - composite_unique_key(&cols, 1).unwrap() - ); - - // Any null column β†’ the whole row is exempt (SQL null semantics). - assert_eq!(composite_unique_key(&cols, 2).unwrap(), None); - } - - #[test] - fn unique_key_scalar_errors_loudly_on_unkeyable_type() { - use arrow_array::LargeBinaryArray; - // A binary/blob column can't be reduced to a uniqueness key. Before the - // hardening this returned `None`, so a `@unique` on such a column was - // silently un-enforced; now it errors instead of weakening the - // constraint in silence. - let blob: ArrayRef = Arc::new(LargeBinaryArray::from(vec![Some(&b"abc"[..])])); - let err = unique_key_scalar(&blob, 0).unwrap_err(); - assert!( - err.to_string().contains("unsupported column type"), - "un-keyable type must fail loudly (got: {err})" - ); - } - - #[test] - fn unique_key_scalar_handles_all_string_encodings() { - use arrow_array::{LargeStringArray, StringViewArray}; - // A legal string column is keyable in every physical Arrow encoding - // Lance might hand back (Utf8 / LargeUtf8 / Utf8View). None of these may - // fall through to the loud `Err` path β€” that branch is reserved for - // genuinely un-keyable column types, not a legal value in an - // unenumerated encoding. - let utf8: ArrayRef = Arc::new(StringArray::from(vec![Some("v")])); - let large: ArrayRef = Arc::new(LargeStringArray::from(vec![Some("v")])); - let view: ArrayRef = Arc::new(StringViewArray::from(vec![Some("v")])); - for array in [&utf8, &large, &view] { - assert_eq!( - unique_key_scalar(array, 0).unwrap(), - Some("v".to_string()), - "string array {:?} must render, not error", - array.data_type() - ); - } - } } diff --git a/crates/omnigraph/src/storage.rs b/crates/omnigraph/src/storage.rs index 978d1ce..564b577 100644 --- a/crates/omnigraph/src/storage.rs +++ b/crates/omnigraph/src/storage.rs @@ -39,39 +39,6 @@ pub trait StorageAdapter: Debug + Send + Sync { /// Returns full URIs (same scheme as `dir_uri`). The result is unordered. /// Returns Ok(empty) if the directory does not exist or is empty. async fn list_dir(&self, dir_uri: &str) -> Result>; - /// Read a text object together with its backend version token (S3: the - /// object's ETag; local: sha256 of the content). The token is opaque β€” - /// valid only for `write_text_if_match` against the same adapter. - async fn read_text_versioned(&self, uri: &str) -> Result<(String, String)>; - /// Replace the object at `uri` only if its current version still matches - /// `expected_version` (obtained from a prior versioned read/write on this - /// adapter). Returns `Ok(Some(new_version))` on success and `Ok(None)` - /// when the precondition failed (a concurrent writer won β€” the CAS-lost - /// case callers must surface, never swallow). S3 uses a conditional put - /// (If-Match); local compares content then replaces via temp + rename β€” - /// the same single-machine semantics the callers had before this trait, - /// safe under the callers' own lock protocol but not a cross-process - /// barrier by itself. - async fn write_text_if_match( - &self, - uri: &str, - contents: &str, - expected_version: &str, - ) -> Result>; - /// Recursively delete every object under `prefix_uri`. Returns Ok(()) - /// when nothing exists there (idempotent). Local: `remove_dir_all`; - /// S3: list + delete (NOT atomic β€” callers must tolerate partial - /// prefixes on crash, which the cluster delete protocol does by retry). - async fn delete_prefix(&self, prefix_uri: &str) -> Result<()>; -} - -/// Version token for local files: content identity. ETags are unavailable -/// on the filesystem; sha256 is stable, cheap at these object sizes, and -/// already the cluster ledger's CAS vocabulary. -fn local_version_token(bytes: &[u8]) -> String { - use sha2::{Digest, Sha256}; - let digest = Sha256::digest(bytes); - digest.iter().map(|byte| format!("{byte:02x}")).collect() } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -182,49 +149,6 @@ impl StorageAdapter for LocalStorageAdapter { } Ok(out) } - - async fn read_text_versioned(&self, uri: &str) -> Result<(String, String)> { - let path = local_path_from_uri(uri)?; - let bytes = tokio::fs::read(&path).await?; - let version = local_version_token(&bytes); - let text = String::from_utf8(bytes).map_err(|err| { - OmniError::manifest_internal(format!("storage read failed for '{}': {}", uri, err)) - })?; - Ok((text, version)) - } - - async fn write_text_if_match( - &self, - uri: &str, - contents: &str, - expected_version: &str, - ) -> Result> { - let path = local_path_from_uri(uri)?; - let current = match tokio::fs::read(&path).await { - Ok(bytes) => bytes, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(err) => return Err(err.into()), - }; - if local_version_token(¤t) != expected_version { - return Ok(None); - } - let tmp = path.with_extension(format!("tmp.{}", ulid::Ulid::new())); - tokio::fs::write(&tmp, contents.as_bytes()).await?; - if let Err(err) = tokio::fs::rename(&tmp, &path).await { - let _ = tokio::fs::remove_file(&tmp).await; - return Err(err.into()); - } - Ok(Some(local_version_token(contents.as_bytes()))) - } - - async fn delete_prefix(&self, prefix_uri: &str) -> Result<()> { - let path = local_path_from_uri(prefix_uri)?; - match tokio::fs::remove_dir_all(&path).await { - Ok(()) => Ok(()), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(err) => Err(err.into()), - } - } } #[async_trait] @@ -352,84 +276,6 @@ impl StorageAdapter for S3StorageAdapter { } Ok(out) } - - async fn read_text_versioned(&self, uri: &str) -> Result<(String, String)> { - let location = self.object_path(uri)?; - let result = self - .store - .get(&location) - .await - .map_err(|err| storage_backend_error("read", uri, err))?; - let etag = result.meta.e_tag.clone(); - let bytes = result - .bytes() - .await - .map_err(|err| storage_backend_error("read", uri, err))?; - // Every S3-compatible store we target returns ETags; fall back to a - // content token rather than failing if one ever omits it. - let version = etag.unwrap_or_else(|| local_version_token(&bytes)); - let text = String::from_utf8(bytes.to_vec()).map_err(|err| { - OmniError::manifest_internal(format!("storage read failed for '{}': {}", uri, err)) - })?; - Ok((text, version)) - } - - async fn write_text_if_match( - &self, - uri: &str, - contents: &str, - expected_version: &str, - ) -> Result> { - let location = self.object_path(uri)?; - let mode = PutMode::Update(object_store::UpdateVersion { - e_tag: Some(expected_version.to_string()), - version: None, - }); - match self - .store - .put_opts( - &location, - PutPayload::from(contents.as_bytes().to_vec()), - mode.into(), - ) - .await - { - Ok(result) => Ok(Some( - result - .e_tag - .unwrap_or_else(|| local_version_token(contents.as_bytes())), - )), - Err(object_store::Error::Precondition { .. }) - | Err(object_store::Error::NotFound { .. }) => Ok(None), - Err(err) => Err(storage_backend_error("write_if_match", uri, err)), - } - } - - async fn delete_prefix(&self, prefix_uri: &str) -> Result<()> { - let dir_with_slash = if prefix_uri.ends_with('/') { - prefix_uri.to_string() - } else { - format!("{}/", prefix_uri) - }; - let prefix_loc = self.object_path(&dir_with_slash)?; - let mut entries = self.store.list(Some(&prefix_loc)); - let mut locations = Vec::new(); - while let Some(meta) = entries - .try_next() - .await - .map_err(|err| storage_backend_error("delete_prefix", prefix_uri, err))? - { - locations.push(meta.location); - } - for location in locations { - match self.store.delete(&location).await { - Ok(()) => {} - Err(object_store::Error::NotFound { .. }) => {} - Err(err) => return Err(storage_backend_error("delete_prefix", prefix_uri, err)), - } - } - Ok(()) - } } impl S3StorageAdapter { @@ -598,55 +444,6 @@ fn env_var_truthy(key: &str) -> bool { #[cfg(test)] mod tests { - - #[tokio::test] - async fn local_versioned_cas_roundtrip() { - let dir = tempfile::tempdir().unwrap(); - let uri = format!("{}/state.json", dir.path().display()); - let adapter = LocalStorageAdapter; - adapter.write_text(&uri, "v1").await.unwrap(); - let (text, version) = adapter.read_text_versioned(&uri).await.unwrap(); - assert_eq!(text, "v1"); - - // Matching token replaces and returns the next token. - let next = adapter - .write_text_if_match(&uri, "v2", &version) - .await - .unwrap() - .expect("fresh token must win"); - assert_ne!(next, version); - // The stale token must lose (CAS-lost is Ok(None), never silent). - assert!( - adapter - .write_text_if_match(&uri, "v3", &version) - .await - .unwrap() - .is_none() - ); - let (text, _) = adapter.read_text_versioned(&uri).await.unwrap(); - assert_eq!(text, "v2"); - // Missing object: precondition can't hold. - let missing = format!("{}/absent.json", dir.path().display()); - assert!( - adapter - .write_text_if_match(&missing, "x", &version) - .await - .unwrap() - .is_none() - ); - } - - #[tokio::test] - async fn local_delete_prefix_is_recursive_and_idempotent() { - let dir = tempfile::tempdir().unwrap(); - let root = format!("{}/tree", dir.path().display()); - let adapter = LocalStorageAdapter; - adapter.write_text(&format!("{root}/a.txt"), "a").await.unwrap(); - adapter.write_text(&format!("{root}/sub/b.txt"), "b").await.unwrap(); - adapter.delete_prefix(&root).await.unwrap(); - assert!(!adapter.exists(&format!("{root}/a.txt")).await.unwrap()); - adapter.delete_prefix(&root).await.unwrap(); // absent -> Ok - } use super::*; #[test] diff --git a/crates/omnigraph/src/storage_layer.rs b/crates/omnigraph/src/storage_layer.rs index d2f6b01..dac9482 100644 --- a/crates/omnigraph/src/storage_layer.rs +++ b/crates/omnigraph/src/storage_layer.rs @@ -7,32 +7,30 @@ //! way for new engine writers to advance Lance HEAD without coupling //! "write bytes" with "advance HEAD" in one Lance API call. //! -//! ## Inline-commit residuals live on a separate trait +//! ## Transitional residuals on the trait //! -//! The inline-commit writes that Lance cannot yet express as -//! stage-then-commit are NOT on `TableStorage`. They sit on -//! [`InlineCommitResidual`], reachable only via -//! `Omnigraph::storage_inline_residual()`, so the default `db.storage()` -//! surface is staged-only and cannot couple "write bytes" with "advance -//! HEAD" β€” MR-793 acceptance Β§1 closes by construction. The residuals: -//! -//! * `delete_where` β€” Lance #6658 (`DeleteBuilder::execute_uncommitted`) -//! did not backport to the 6.x line; it first ships in `v7.0.0-beta.10`. -//! Migration to staged two-phase delete is tracked as MR-A, gated on the -//! Lance v7.x bump. -//! * `create_vector_index` β€” segment-commit-path needs -//! `build_index_metadata_from_segments`, still `pub(crate)` in Lance -//! 6.0.1 ([#6666](https://github.com/lance-format/lance/issues/6666), -//! open). Scalar indices already stage. -//! -//! Each is named honestly at its call site; the forbidden-API guard test -//! catches direct lance::* misuse outside the storage layer. +//! Several inline-commit methods remain on the trait surface as +//! documented residuals: `delete_where` +//! ([#6658](https://github.com/lance-format/lance/issues/6658) closed +//! 2026-05-14, but the public `DeleteBuilder::execute_uncommitted` API +//! did not backport to the 6.x release line β€” it first ships in +//! `v7.0.0-beta.10`. Migration to staged two-phase delete is tracked as +//! MR-A and is gated on the Lance v7.x bump, not the current v6.0.1 pin), +//! `create_vector_index` (segment-commit-path requires +//! `build_index_metadata_from_segments` which is `pub(crate)` β€” see +//! [#6666](https://github.com/lance-format/lance/issues/6666), still open), and the +//! legacy `append_batch` / `merge_insert_batches` / `overwrite_batch` / +//! `create_btree_index` / `create_inverted_index` paths kept while +//! engine call sites finish migrating off of them (Phase 1b / Phase 9 +//! of MR-793). These are named honestly at every call site; the +//! forbidden-API guard test catches direct lance::* misuse outside the +//! storage layer. //! //! ## Sealed //! -//! Both `TableStorage` and `InlineCommitResidual` are `: sealed::Sealed`. -//! Only types in this crate can implement them, so a downstream crate -//! cannot subvert the contract by providing its own impl. +//! `TableStorage: sealed::Sealed`. Only types in this crate can implement +//! the trait, so a downstream crate cannot subvert the contract by +//! providing its own impl. //! //! ## Opaque handles //! @@ -42,15 +40,15 @@ //! through. This aligns with the storage-boundary invariant: //! `lance::Dataset` does not appear in trait signatures. //! -//! ## Migration status +//! ## Migration status (MR-793 PR #70) //! -//! Phases 1a / 2 / 4 / 5 / 6 landed in MR-793 PR #70 (trait scaffolding, -//! staged primitives, migration of `ensure_indices` / `branch_merge` / -//! `schema_apply` onto the staged surface). Phase 1b (call-site -//! conversion) and Phase 9 landed in MR-854, which also split the -//! inline-commit residuals onto `InlineCommitResidual` so `db.storage()` -//! is staged-only. Phase 7 (recovery reconciler) shipped as MR-847; -//! Phase 8 (index reconciler) is tracked as MR-848. +//! Phases 1a / 2 / 4 / 5 / 6 are landed: trait scaffolding, three new +//! staged primitives (`stage_overwrite`, scalar index staging), and +//! migration of `ensure_indices`, `branch_merge`, `schema_apply` onto +//! the staged surface. Phase 1b (call-site conversion to +//! `Arc`), Phase 9 (demote unused inline-commit +//! methods to `pub(crate)`), Phase 7 (recovery reconciler β€” MR-847), +//! and Phase 8 (index reconciler β€” MR-848) are deferred to follow-ups. use std::fmt::Debug; use std::sync::Arc; @@ -107,37 +105,12 @@ impl SnapshotHandle { &self.inner } - /// Take ownership of the inner `Arc`. Used by the - /// `TableStorage` impl when an op needs to mutate the dataset in - /// place (commit a staged write, append, overwrite, …). - /// - /// Performance note: callers consume the returned `Arc` via - /// `Arc::try_unwrap(...).unwrap_or_else(|arc| (*arc).clone())`. The - /// fast path (no clone) only fires when the snapshot is single-ref - /// β€” i.e. the caller dropped every other `SnapshotHandle` clone - /// before calling. Holding parallel clones (e.g. across an `await` - /// point or stashed in a struct) forces a deep `Dataset` clone on - /// every mutating op. Engine callers should pass `SnapshotHandle` - /// by value into the mutating method, not keep a side copy. + /// Take ownership of the inner `Arc`. Used when committing + /// staged writes (the call needs to consume the snapshot). pub(crate) fn into_arc(self) -> Arc { self.inner } - /// Take ownership of the inner `Dataset` by unwrapping the `Arc` - /// (or cloning if the snapshot is shared). `pub(crate)` β€” used - /// only by the maintenance path (`optimize`, `cleanup`) which - /// must hand `&mut Dataset` to Lance compaction / cleanup APIs - /// that the `TableStorage` trait does not (and should not) - /// surface. Engine code that participates in the staged-write - /// invariant must stay on the trait methods. - /// - /// Single-ref invariant: same fast-path/clone behavior as - /// `into_arc` β€” see that method's doc. Drop sibling - /// `SnapshotHandle` clones before calling. - pub(crate) fn into_dataset(self) -> Dataset { - Arc::try_unwrap(self.inner).unwrap_or_else(|arc| (*arc).clone()) - } - // ── public, lance-free accessors ── /// Current Lance manifest version of the snapshot. @@ -235,20 +208,6 @@ pub trait TableStorage: sealed::Sealed + Send + Sync + Debug { async fn delete_branch(&self, dataset_uri: &str, branch: &str) -> Result<()>; - /// Idempotent variant of `delete_branch` used by the best-effort fork - /// reclaim under branch delete (`db/omnigraph.rs::cleanup_deleted_branch_tables`) - /// and by the orphan-fork reconciler in `optimize`. Tolerates an - /// already-absent branch (both Lance's `RefNotFound` and the local-store - /// `NotFound` quirk on a missing `tree/{branch}/` dir). A still-referenced - /// branch (`RefConflict`) still surfaces as `OmniError::Lance`. - async fn force_delete_branch(&self, dataset_uri: &str, branch: &str) -> Result<()>; - - /// 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. - async fn list_branches(&self, dataset_uri: &str) -> Result>; - async fn reopen_for_mutation( &self, dataset_uri: &str, @@ -369,19 +328,74 @@ pub trait TableStorage: sealed::Sealed + Send + Sync + Debug { column: &str, ) -> Result; - // ── Index presence (reads, no HEAD advance) ────────────────────── + // ── Inline-commit residuals (named honestly per MR-793 Β§3.2) ────── // - // The inline-commit writes (`delete_where`, `create_vector_index`) are - // deliberately NOT on this trait. They live on - // the separate `InlineCommitResidual` trait, reachable only through - // `Omnigraph::storage_inline_residual()`. As a result the default - // `db.storage()` surface cannot couple "write bytes" with "advance HEAD" - // β€” closing MR-793 acceptance Β§1 by construction rather than by review. + // These methods advance Lance HEAD as a side effect of writing. + // They stay on the trait until the corresponding upstream Lance API + // ships: + // + // * `delete_where` β€” Lance #6658 (two-phase delete). + // * `create_*_index` β€” `build_index_metadata_from_segments` is + // `pub(crate)` for vector indices in lance-4.0.0; scalar indices + // migrate to staged in MR-793 Phase 2. + // * `append_batch`, `merge_insert_batches`, `overwrite_batch` β€” + // legacy paths that will be demoted to `pub(crate)` in MR-793 + // Phase 9 once all engine sites route through the staged + // primitives. + + async fn append_batch( + &self, + dataset_uri: &str, + snapshot: SnapshotHandle, + batch: RecordBatch, + ) -> Result<(SnapshotHandle, TableState)>; + + async fn merge_insert_batches( + &self, + dataset_uri: &str, + snapshot: SnapshotHandle, + batches: Vec, + key_columns: Vec, + when_matched: WhenMatched, + when_not_matched: WhenNotMatched, + ) -> Result; + + async fn overwrite_batch( + &self, + dataset_uri: &str, + snapshot: SnapshotHandle, + batch: RecordBatch, + ) -> Result<(SnapshotHandle, TableState)>; + + async fn delete_where( + &self, + dataset_uri: &str, + snapshot: SnapshotHandle, + filter: &str, + ) -> Result<(SnapshotHandle, DeleteState)>; async fn has_btree_index(&self, snapshot: &SnapshotHandle, column: &str) -> Result; async fn has_fts_index(&self, snapshot: &SnapshotHandle, column: &str) -> Result; async fn has_vector_index(&self, snapshot: &SnapshotHandle, column: &str) -> Result; + async fn create_btree_index( + &self, + snapshot: SnapshotHandle, + columns: &[&str], + ) -> Result; + + async fn create_inverted_index( + &self, + snapshot: SnapshotHandle, + column: &str, + ) -> Result; + + async fn create_vector_index( + &self, + snapshot: SnapshotHandle, + column: &str, + ) -> Result; + // ── URI helpers ──────────────────────────────────────────────────── // // These are pure string formatting; they live on the trait so engine @@ -408,38 +422,6 @@ pub trait TableStorage: sealed::Sealed + Send + Sync + Debug { ) -> Result; } -// ─── InlineCommitResidual trait ──────────────────────────────────────────── - -/// Inline-commit residual surface: the writes Lance cannot yet express as a -/// stage-then-commit pair, so they advance Lance HEAD as a side effect of -/// writing. Kept OFF `TableStorage` and reachable only through -/// `Omnigraph::storage_inline_residual()`, so the default `db.storage()` path -/// is staged-only and a new writer cannot reintroduce the write+commit coupling -/// by accident (MR-793 acceptance Β§1, by construction). -/// -/// Residual reasons (each is named honestly at its call site): -/// * `delete_where` β€” Lance has no public two-phase delete on the 6.x line -/// (`DeleteBuilder::execute_uncommitted` first ships in v7.x; MR-A / Lance -/// #6658). The D2 parse-time rule + recovery sidecars cover the gap meanwhile. -/// * `create_vector_index` β€” vector-index segment-commit needs -/// `build_index_metadata_from_segments`, still `pub(crate)` in Lance 6.0.1 -/// (Lance #6666). Scalar indices already stage. -#[async_trait] -pub(crate) trait InlineCommitResidual: sealed::Sealed + Send + Sync + Debug { - async fn delete_where( - &self, - dataset_uri: &str, - snapshot: SnapshotHandle, - filter: &str, - ) -> Result<(SnapshotHandle, DeleteState)>; - - async fn create_vector_index( - &self, - snapshot: SnapshotHandle, - column: &str, - ) -> Result; -} - // ─── single impl: TableStore ────────────────────────────────────────────── #[async_trait] @@ -514,14 +496,6 @@ impl TableStorage for TableStore { TableStore::delete_branch(self, dataset_uri, branch).await } - async fn force_delete_branch(&self, dataset_uri: &str, branch: &str) -> Result<()> { - TableStore::force_delete_branch(self, dataset_uri, branch).await - } - - async fn list_branches(&self, dataset_uri: &str) -> Result> { - TableStore::list_branches(self, dataset_uri).await - } - async fn reopen_for_mutation( &self, dataset_uri: &str, @@ -715,6 +689,61 @@ impl TableStorage for TableStore { .map(StagedHandle::new) } + async fn append_batch( + &self, + dataset_uri: &str, + snapshot: SnapshotHandle, + batch: RecordBatch, + ) -> Result<(SnapshotHandle, TableState)> { + 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)) + } + + async fn merge_insert_batches( + &self, + dataset_uri: &str, + snapshot: SnapshotHandle, + batches: Vec, + key_columns: Vec, + when_matched: WhenMatched, + when_not_matched: WhenNotMatched, + ) -> Result { + let ds = Arc::try_unwrap(snapshot.into_arc()).unwrap_or_else(|arc| (*arc).clone()); + TableStore::merge_insert_batches( + self, + dataset_uri, + ds, + batches, + key_columns, + when_matched, + when_not_matched, + ) + .await + } + + async fn overwrite_batch( + &self, + dataset_uri: &str, + snapshot: SnapshotHandle, + batch: RecordBatch, + ) -> Result<(SnapshotHandle, TableState)> { + 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)) + } + + async fn delete_where( + &self, + dataset_uri: &str, + snapshot: SnapshotHandle, + filter: &str, + ) -> Result<(SnapshotHandle, DeleteState)> { + 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)) + } + async fn has_btree_index(&self, snapshot: &SnapshotHandle, column: &str) -> Result { TableStore::has_btree_index(self, snapshot.dataset(), column).await } @@ -727,6 +756,36 @@ impl TableStorage for TableStore { TableStore::has_vector_index(self, snapshot.dataset(), column).await } + async fn create_btree_index( + &self, + snapshot: SnapshotHandle, + columns: &[&str], + ) -> Result { + 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)) + } + + async fn create_inverted_index( + &self, + snapshot: SnapshotHandle, + column: &str, + ) -> Result { + 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)) + } + + async fn create_vector_index( + &self, + snapshot: SnapshotHandle, + column: &str, + ) -> Result { + 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)) + } + fn root_uri(&self) -> &str { TableStore::root_uri(self) } @@ -756,27 +815,3 @@ impl TableStorage for TableStore { .await } } - -#[async_trait] -impl InlineCommitResidual for TableStore { - async fn delete_where( - &self, - dataset_uri: &str, - snapshot: SnapshotHandle, - filter: &str, - ) -> Result<(SnapshotHandle, DeleteState)> { - 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)) - } - - async fn create_vector_index( - &self, - snapshot: SnapshotHandle, - column: &str, - ) -> Result { - 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)) - } -} diff --git a/crates/omnigraph/src/table_store.rs b/crates/omnigraph/src/table_store.rs index 65123c0..10123b0 100644 --- a/crates/omnigraph/src/table_store.rs +++ b/crates/omnigraph/src/table_store.rs @@ -2,6 +2,7 @@ use arrow_array::{ Array, ArrayRef, RecordBatch, StringArray, StructArray, UInt8Array, UInt32Array, UInt64Array, }; use arrow_schema::SchemaRef; +use arrow_select::concat::concat_batches; use futures::TryStreamExt; use lance::Dataset; use lance::blob::BlobArrayBuilder; @@ -12,7 +13,7 @@ use lance::dataset::{ CommitBuilder, InsertBuilder, MergeInsertBuilder, WhenMatched, WhenNotMatched, WriteMode, WriteParams, }; -use lance::datatypes::{BlobKind, Schema as LanceSchema}; +use lance::datatypes::BlobKind; use lance::index::DatasetIndexExt; use lance::index::scalar::IndexDetails; use lance_file::version::LanceFileVersion; @@ -42,19 +43,6 @@ pub struct DeleteState { pub(crate) version_metadata: TableVersionMetadata, } -/// Whether a `key_col IN (...)` scan on a dataset will be served by the -/// persisted scalar (BTREE) index, or silently fall back to a full filtered -/// scan. Detection-only (metadata, no IO); the scan returns the correct rows -/// either way. Surfaced by the indexed traversal path so the silent perf -/// fallback is observable, and available to a future cost-based planner. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum IndexCoverage { - /// The column has a usable BTREE and every fragment records `physical_rows`. - Indexed, - /// Lance will not use the scalar index for this scan (correct, full scan). - Degraded { reason: String }, -} - /// A Lance write that has produced fragment files on object storage but is /// not yet committed to the dataset's manifest. The staged-write primitives /// are consumed by `MutationStaging` (`exec/staging.rs`, @@ -594,117 +582,6 @@ impl TableStore { .map_err(|e| OmniError::Lance(e.to_string())) } - /// Indexed neighbor lookup for graph traversal. Given an edge dataset and a - /// set of endpoint keys on `key_col` (`"src"` for out-traversal, `"dst"` for - /// in-traversal), return the matching edge rows projected to - /// `[key_col, opposite_col]`. - /// - /// The `key_col IN (keys)` predicate is built as a structured DataFusion - /// `Expr` and applied via `Scanner::filter_expr`, so Lance routes it through - /// the persisted BTREE on `key_col` (index-search β†’ take). Cost scales with - /// the frontier size, not |E| β€” the basis for serving selective traversals - /// without building the whole in-memory CSR. Empty `keys` returns empty - /// without scanning. - /// - /// Note: like any indexed scan, this observes only fragments the BTREE - /// covers plus an unindexed-fragment scan fallback; it reads the committed - /// snapshot `ds` was opened at. - pub async fn scan_edges_by_endpoint( - ds: &Dataset, - key_col: &str, - opposite_col: &str, - keys: &[String], - ) -> Result> { - use datafusion::prelude::{col, lit}; - - if keys.is_empty() { - return Ok(Vec::new()); - } - let key_list: Vec = - keys.iter().map(|k| lit(k.clone())).collect(); - let filter_expr = col(key_col).in_list(key_list, false); - Self::scan_stream_with( - ds, - Some(&[key_col, opposite_col]), - None, - None, - false, - |scanner| { - scanner.filter_expr(filter_expr); - Ok(()) - }, - ) - .await? - .try_collect() - .await - .map_err(|e| OmniError::Lance(e.to_string())) - } - - /// Metadata-only check (no IO) of whether `scan_edges_by_endpoint` β€” a - /// `key_col IN (...)` filter β€” on `ds` will be served by the persisted BTREE - /// on `column`, or silently fall back to a full filtered scan. Mirrors - /// Lance's own decision: scalar indices are disabled for the whole scan if - /// ANY fragment lacks `physical_rows` (lance `dataset/scanner.rs` - /// `create_filter_plan`), and are obviously unused if no BTREE on the - /// column exists. The scan is correct (returns all rows) either way β€” this - /// only surfaces the perf cliff so the indexed traversal can warn on it. - pub async fn key_column_index_coverage(ds: &Dataset, column: &str) -> Result { - let Some(field_id) = ds.schema().field(column).map(|field| field.id) else { - return Ok(IndexCoverage::Degraded { - reason: format!("column '{}' not in schema", column), - }); - }; - let indices = ds - .load_indices() - .await - .map_err(|e| OmniError::Lance(e.to_string()))?; - let btree = indices - .iter() - .filter(|index| !is_system_index(index)) - .filter(|index| index.fields.len() == 1 && index.fields[0] == field_id) - .find(|index| { - index - .index_details - .as_ref() - .map(|details| details.type_url.ends_with("BTreeIndexDetails")) - .unwrap_or(false) - }); - let Some(btree) = btree else { - return Ok(IndexCoverage::Degraded { - reason: format!("no BTREE index on '{}'", column), - }); - }; - // Same check Lance runs: a fragment missing physical_rows disables - // scalar indices for the entire scan (all-or-nothing). - if ds.fragments().iter().any(|f| f.physical_rows.is_none()) { - return Ok(IndexCoverage::Degraded { - reason: "a fragment is missing physical_rows".to_string(), - }); - } - // An index only covers the fragments it was built over; fragments - // appended afterward (edge-index creation is skipped once a BTREE exists) - // are scanned unindexed. If any CURRENT fragment is absent from the - // index's `fragment_bitmap`, the scan is partly a full scan β€” so the - // chooser must not price it as fully indexed. A `None` bitmap means Lance - // can't report coverage; don't over-degrade in that case. - if let Some(bitmap) = btree.fragment_bitmap.as_ref() { - let uncovered = ds - .fragments() - .iter() - .filter(|f| !bitmap.contains(f.id as u32)) - .count(); - if uncovered > 0 { - return Ok(IndexCoverage::Degraded { - reason: format!( - "{} fragment(s) not covered by the index on '{}'", - uncovered, column - ), - }); - } - } - Ok(IndexCoverage::Indexed) - } - pub async fn count_rows(&self, ds: &Dataset, filter: Option) -> Result { ds.count_rows(filter) .await @@ -724,14 +601,7 @@ impl TableStore { }) } - /// Legacy inline-commit append: writes fragments AND commits in one - /// call, advancing Lance HEAD as a side effect. Not on the - /// `TableStorage` trait surface β€” the staged primitive `stage_append` - /// + `commit_staged` is the engine write path. This inherent - /// `pub(crate)` method survives only for recovery test setup. Do not - /// add new engine call sites β€” they re-introduce the multi-phase - /// commit drift the trait surface was designed to eliminate. - pub(crate) async fn append_batch( + pub async fn append_batch( &self, dataset_uri: &str, ds: &mut Dataset, @@ -786,7 +656,139 @@ impl TableStore { } } - pub(crate) async fn delete_where( + pub async fn overwrite_batch( + &self, + dataset_uri: &str, + ds: &mut Dataset, + batch: RecordBatch, + ) -> Result { + ds.truncate_table() + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + self.append_batch(dataset_uri, ds, batch).await + } + + pub async fn overwrite_dataset(dataset_uri: &str, batch: RecordBatch) -> Result { + let reader = arrow_array::RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let params = WriteParams { + mode: WriteMode::Overwrite, + enable_stable_row_ids: true, + data_storage_version: Some(LanceFileVersion::V2_2), + allow_external_blob_outside_bases: true, + ..Default::default() + }; + Dataset::write(reader, dataset_uri, Some(params)) + .await + .map_err(|e| OmniError::Lance(e.to_string())) + } + + pub async fn merge_insert_batch( + &self, + dataset_uri: &str, + ds: Dataset, + batch: RecordBatch, + key_columns: Vec, + when_matched: WhenMatched, + when_not_matched: WhenNotMatched, + ) -> Result { + if batch.num_rows() == 0 { + return self.table_state(dataset_uri, &ds).await; + } + + // Precondition for the FirstSeen workaround below: every caller of + // this primitive must hand in a source batch that is unique by + // `key_columns`. Without this check, `SourceDedupeBehavior::FirstSeen` + // would silently collapse genuine duplicates instead of erroring. + check_batch_unique_by_keys(&batch, &key_columns, "merge_insert_batch")?; + + // TODO(lance-upstream): MergeInsertBuilder does not accept WriteParams, + // so allow_external_blob_outside_bases cannot be set here. External URI + // blobs via merge_insert (LoadMode::Merge, mutations) are unsupported + // until Lance exposes WriteParams on MergeInsertBuilder. + let ds = Arc::new(ds); + let mut builder = MergeInsertBuilder::try_new(ds, key_columns) + .map_err(|e| OmniError::Lance(e.to_string()))?; + builder.when_matched(when_matched); + builder.when_not_matched(when_not_matched); + // Workaround for a Lance 4.0.x bug class where sequential + // merge_insert calls against rows previously rewritten by + // merge_insert produce a spurious "Ambiguous merge inserts: + // multiple source rows match the same target row on (id = ...)" + // error. Lance's `processed_row_ids: Mutex>` + // (lance-4.0.0 `src/dataset/write/merge_insert.rs:2099`) + // double-processes the same source/target match against + // datasets previously rewritten by merge_insert, and the default + // `SourceDedupeBehavior::Fail` errors on the second insertion. + // `FirstSeen` makes Lance skip the duplicate match instead. + // + // Covers both observed surfaces: + // - PR #98 (sequential `load --mode merge` against same keys). + // - MR-920 (sequential `update T set {f} where x=y` on same row). + // + // Correctness-preserving for OmniGraph because every call path + // that reaches this primitive either pre-dedupes the source batch + // by id, or surfaces a real source dup via the + // `check_batch_unique_by_keys` precondition above (which fires + // before the FirstSeen setter has a chance to silently collapse + // anything): + // - Load path: `enforce_unique_constraints_intra_batch` + // (`loader/mod.rs:1453`) errors on intra-batch `@key` dups. + // - Mutate path: `MutationStaging::finalize` (`exec/staging.rs`) + // accumulates and dedupes by `id`. + // - Branch-merge path: `compute_source_delta` / + // `compute_three_way_delta` (`exec/merge.rs`) walk via + // `OrderedTableCursor` and `push_row` each id at most once. + // So FirstSeen only suppresses the spurious Lance behavior, never + // user data. Pinned by `loader_rejects_intra_batch_duplicate_keys` + // in `tests/consistency.rs` plus the + // `check_batch_unique_by_keys` precondition. + // + // Retire when upstream Lance fixes the bug class. Tracked at + // MR-957; upstream: lance-format/lance#6877. + builder.source_dedupe_behavior(SourceDedupeBehavior::FirstSeen); + let job = builder + .try_build() + .map_err(|e| OmniError::Lance(e.to_string()))?; + + let schema = batch.schema(); + let reader = arrow_array::RecordBatchIterator::new(vec![Ok(batch)], schema); + let (new_ds, _stats) = job + .execute(lance_datafusion::utils::reader_to_stream(Box::new(reader))) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + self.table_state(dataset_uri, &new_ds).await + } + + pub async fn merge_insert_batches( + &self, + dataset_uri: &str, + ds: Dataset, + batches: Vec, + key_columns: Vec, + when_matched: WhenMatched, + when_not_matched: WhenNotMatched, + ) -> Result { + if batches.is_empty() { + return self.table_state(dataset_uri, &ds).await; + } + let batch = if batches.len() == 1 { + batches.into_iter().next().unwrap() + } else { + let schema = batches[0].schema(); + concat_batches(&schema, &batches).map_err(|e| OmniError::Lance(e.to_string()))? + }; + self.merge_insert_batch( + dataset_uri, + ds, + batch, + key_columns, + when_matched, + when_not_matched, + ) + .await + } + + pub async fn delete_where( &self, dataset_uri: &str, ds: &mut Dataset, @@ -885,7 +887,7 @@ impl TableStore { } }; // Assign real fragment IDs. Lance's `InsertBuilder::execute_uncommitted` - // returns fragments with `id = 0` ("Temporary ID" β€” see lance-6.0.1 + // returns fragments with `id = 0` ("Temporary ID" β€” see lance-4.0.0 // `dataset/write.rs:1044/1712`); the real assignment happens during // commit via `Transaction::fragments_with_ids`. Because we expose // these fragments to `scan_with_staged` *before* commit, two staged @@ -956,12 +958,11 @@ impl TableStore { )); } - // Precondition for the FirstSeen workaround below: every call path that - // reaches stage_merge_insert (load, MutationStaging::finalize, - // branch_merge::publish_rewritten_merge_table) must hand in a source - // batch that is unique by `key_columns`. Without this check, - // `SourceDedupeBehavior::FirstSeen` would silently collapse genuine - // duplicates instead of erroring. + // Precondition for FirstSeen below. See the comment on + // `merge_insert_batch` for why this check is here, not on the caller: + // every call path that reaches stage_merge_insert (load, + // MutationStaging::finalize, branch_merge::publish_rewritten_merge_table) + // must hand in a source batch that is unique by `key_columns`. check_batch_unique_by_keys(&batch, &key_columns, "stage_merge_insert")?; let ds = Arc::new(ds); @@ -969,21 +970,11 @@ impl TableStore { .map_err(|e| OmniError::Lance(e.to_string()))?; builder.when_matched(when_matched); builder.when_not_matched(when_not_matched); - // Workaround for a Lance bug class where sequential merge_insert calls - // against rows previously rewritten by merge_insert produce a spurious - // "Ambiguous merge inserts: multiple source rows match the same target - // row on (id = ...)" error. Lance's `processed_row_ids: - // Mutex>` (lance-6.0.1 `src/dataset/write/merge_insert.rs`) - // double-processes the same source/target match against datasets - // previously rewritten by merge_insert, and the default - // `SourceDedupeBehavior::Fail` errors on the second insertion; FirstSeen - // makes Lance skip the duplicate match instead. Correctness-preserving - // because every call path pre-dedupes the source batch by id or surfaces - // a real source dup via `check_batch_unique_by_keys` above (load: - // `enforce_unique_constraints_intra_batch`; mutate: - // `MutationStaging::finalize`; branch-merge: the `OrderedTableCursor` - // walk in `exec/merge.rs`). Retire when upstream Lance fixes the bug - // class. Tracked at MR-957; upstream: lance-format/lance#6877. + // See `merge_insert_batch` for the FirstSeen rationale. Workaround + // for the Lance 4.0.x bug class where sequential merge_insert / + // update against rows previously rewritten by merge_insert trips + // Lance's `processed_row_ids` HashSet and errors under the default + // `SourceDedupeBehavior::Fail`. Retire when upstream Lance is fixed. builder.source_dedupe_behavior(SourceDedupeBehavior::FirstSeen); let job = builder .try_build() @@ -1059,51 +1050,40 @@ impl TableStore { /// MR-793 Phase 2: introduces this for the schema_apply rewrite path. /// Lance API verified in `.context/mr-793-design.md` Appendix A.1. pub async fn stage_overwrite(&self, ds: &Dataset, batch: RecordBatch) -> Result { - // `enable_stable_row_ids: true` is defensive β€” empirically Lance 6.0.1 + if batch.num_rows() == 0 { + return Err(OmniError::manifest_internal( + "stage_overwrite called with empty batch".to_string(), + )); + } + // `enable_stable_row_ids: true` is defensive β€” empirically Lance 4.0.0 // preserves the source dataset's flag through `Operation::Overwrite` // when WriteParams omits it (pinned by // `stage_overwrite_preserves_stable_row_ids` in tests/staged_writes.rs), - // but setting it explicitly keeps the invariant documented at every Overwrite site + // but setting it explicitly matches the public `overwrite_dataset` + // path and keeps the invariant documented at every Overwrite site // (see docs/storage.md "Stable row IDs"). Setting it on an existing // dataset that was created without stable row IDs is a no-op per // Lance's row-id-lineage spec, so this stays correct for legacy // datasets. - let (transaction, mut new_fragments) = if batch.num_rows() == 0 { - let schema = LanceSchema::try_from(batch.schema().as_ref()) - .map_err(|e| OmniError::Lance(e.to_string()))?; - let transaction = TransactionBuilder::new( - ds.manifest.version, - Operation::Overwrite { - fragments: Vec::new(), - schema, - config_upsert_values: None, - initial_bases: None, - }, - ) - .build(); - (transaction, Vec::new()) - } else { - let params = WriteParams { - mode: WriteMode::Overwrite, - enable_stable_row_ids: true, - allow_external_blob_outside_bases: true, - ..Default::default() - }; - let transaction = InsertBuilder::new(Arc::new(ds.clone())) - .with_params(¶ms) - .execute_uncommitted(vec![batch]) - .await - .map_err(|e| OmniError::Lance(e.to_string()))?; - let new_fragments = match &transaction.operation { - Operation::Overwrite { fragments, .. } => fragments.clone(), - other => { - return Err(OmniError::manifest_internal(format!( - "stage_overwrite: unexpected Lance operation {:?}", - std::mem::discriminant(other) - ))); - } - }; - (transaction, new_fragments) + let params = WriteParams { + mode: WriteMode::Overwrite, + enable_stable_row_ids: true, + allow_external_blob_outside_bases: true, + ..Default::default() + }; + let transaction = InsertBuilder::new(Arc::new(ds.clone())) + .with_params(¶ms) + .execute_uncommitted(vec![batch]) + .await + .map_err(|e| OmniError::Lance(e.to_string()))?; + let mut new_fragments = match &transaction.operation { + Operation::Overwrite { fragments, .. } => fragments.clone(), + other => { + return Err(OmniError::manifest_internal(format!( + "stage_overwrite: unexpected Lance operation {:?}", + std::mem::discriminant(other) + ))); + } }; // Overwrite REPLACES every committed fragment, and Lance restarts // fragment-ID and row-ID counters at the post-commit version. @@ -1116,7 +1096,7 @@ impl TableStore { // 2) For stable-row-id datasets, assign row_id_meta starting // at 0 (Overwrite is a fresh-start) so `scan_with_staged` // doesn't hit the "Missing row id meta" panic in - // lance-6.0.1 dataset/rowids.rs:22. + // lance-4.0.0 dataset/rowids.rs:22. assign_fragment_ids(&mut new_fragments, 1); if ds.manifest.uses_stable_row_ids() { assign_row_id_meta(&mut new_fragments, 0)?; @@ -1140,7 +1120,7 @@ impl TableStore { /// `IndexMetadata`; we manually wrap it in `Operation::CreateIndex /// { new_indices, removed_indices }` via the public `TransactionBuilder`, /// replicating the simple (non-segment-commit-path) branch of Lance's - /// `CreateIndexBuilder::execute` (lance-6.0.1 `src/index/create.rs:502-512`). + /// `CreateIndexBuilder::execute` (lance-4.0.0 `src/index/create.rs:502-512`). /// /// `removed_indices` mirrors `execute()` lines 466-476: when the /// build replaces an existing same-named index, those entries are @@ -1149,7 +1129,7 @@ impl TableStore { /// MR-793 Phase 2: scalar index types (BTree, Inverted) are /// stage-able. Vector indices are NOT (segment-commit-path requires /// `build_index_metadata_from_segments` which is `pub(crate)` in - /// lance-6.0.1); see `create_vector_index` and Appendix A.3. + /// lance-4.0.0); see `create_vector_index` and Appendix A.3. pub async fn stage_create_btree_index( &self, ds: &Dataset, @@ -1244,7 +1224,7 @@ impl TableStore { /// committed fragments carry; Lance's optimizer drops them from the /// filtered scan even when their data would match. Staged-fragment /// rows are silently absent from the result. `scanner.use_stats(false)` - /// does not fix this in lance 6.0.1. Callers needing correct filtered + /// does not fix this in lance 4.0.0. Callers needing correct filtered /// reads against staged data should use a different strategy β€” the /// engine's `MutationStaging` accumulator unions in-memory pending /// batches with the committed scan via DataFusion `MemTable` (see @@ -1468,7 +1448,25 @@ impl TableStore { })) } - pub(crate) async fn create_vector_index(&self, ds: &mut Dataset, column: &str) -> Result<()> { + pub async fn create_btree_index(&self, ds: &mut Dataset, columns: &[&str]) -> Result<()> { + let params = ScalarIndexParams::default(); + ds.create_index_builder(columns, IndexType::BTree, ¶ms) + .replace(true) + .await + .map(|_| ()) + .map_err(|e| OmniError::Lance(e.to_string())) + } + + pub async fn create_inverted_index(&self, ds: &mut Dataset, column: &str) -> Result<()> { + let params = InvertedIndexParams::default(); + ds.create_index_builder(&[column], IndexType::Inverted, ¶ms) + .replace(true) + .await + .map(|_| ()) + .map_err(|e| OmniError::Lance(e.to_string())) + } + + pub async fn create_vector_index(&self, ds: &mut Dataset, column: &str) -> Result<()> { let params = lance::index::vector::VectorIndexParams::ivf_flat(1, MetricType::L2); ds.create_index_builder(&[column], IndexType::Vector, ¶ms) .replace(true) @@ -1552,7 +1550,7 @@ fn prior_stages_fragment_count(prior_stages: &[StagedWrite]) -> u64 { } /// Assign sequential fragment IDs starting at `start_id`. Mirrors Lance's -/// commit-time `Transaction::fragments_with_ids` (lance-6.0.1 +/// commit-time `Transaction::fragments_with_ids` (lance-4.0.0 /// `dataset/transaction.rs:1456`) β€” fragments produced by /// `InsertBuilder::execute_uncommitted` start with `id = 0` as a temporary /// placeholder; we renumber here so they don't collide with committed @@ -1583,7 +1581,7 @@ fn prior_stages_row_count(prior_stages: &[StagedWrite]) -> Result { /// Assign sequential row IDs to fragments that lack them, starting from /// `start_row_id`. Mirrors the relevant arm of Lance's -/// `Transaction::assign_row_ids` (lance-6.0.1 `dataset/transaction.rs:2682`) +/// `Transaction::assign_row_ids` (lance-4.0.0 `dataset/transaction.rs:2682`) /// for the `row_id_meta = None` case β€” fragments produced by /// `InsertBuilder::execute_uncommitted` against a stable-row-id dataset. /// @@ -1756,7 +1754,7 @@ fn combine_committed_with_staged(ds: &Dataset, staged: &[StagedWrite]) -> Vec Person { - @unique(src, dst) -} -"#; - -const EDGE_UNIQUE_DATA: &str = r#"{"type":"Person","data":{"name":"Alice"}} -{"type":"Person","data":{"name":"Bob"}} -{"type":"Person","data":{"name":"Carol"}}"#; - -const EDGE_UNIQUE_MUTATIONS: &str = r#" -query add_knows($from: String, $to: String) { - insert Knows { from: $from, to: $to } -} -"#; - const CARDINALITY_SCHEMA: &str = r#" node Person { name: String @key @@ -1139,87 +1119,6 @@ async fn branch_merge_reports_unique_violation_conflict() { } } -/// Regression for the MR-983 follow-up: the branch-merge path must enforce an -/// edge composite `@unique(src, dst)` as a true composite key, consistent with -/// the intake path. Two branches inserting the *same* (src, dst) pair must -/// conflict on merge. -#[tokio::test] -async fn branch_merge_reports_composite_unique_violation_conflict() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let mut main = init_db_from_schema_and_data(&dir, EDGE_UNIQUE_SCHEMA, EDGE_UNIQUE_DATA).await; - main.branch_create("feature").await.unwrap(); - - let mut feature = Omnigraph::open(uri).await.unwrap(); - - mutate_main( - &mut main, - EDGE_UNIQUE_MUTATIONS, - "add_knows", - ¶ms(&[("$from", "Alice"), ("$to", "Bob")]), - ) - .await - .unwrap(); - - mutate_branch( - &mut feature, - "feature", - EDGE_UNIQUE_MUTATIONS, - "add_knows", - ¶ms(&[("$from", "Alice"), ("$to", "Bob")]), - ) - .await - .unwrap(); - - let err = main.branch_merge("feature", "main").await.unwrap_err(); - match err { - OmniError::MergeConflicts(conflicts) => { - assert!(conflicts.iter().any(|conflict| { - conflict.table_key == "edge:Knows" - && conflict.kind == MergeConflictKind::UniqueViolation - })); - } - other => panic!("expected merge conflicts, got {other:?}"), - } -} - -/// Sibling to the above: pairs sharing `src` but differing on `dst` are unique -/// on the (src, dst) tuple and must merge cleanly. Guards against the composite -/// degrading back into a single-field `@unique(src)` on the merge path. -#[tokio::test] -async fn branch_merge_allows_distinct_composite_unique_pairs() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let mut main = init_db_from_schema_and_data(&dir, EDGE_UNIQUE_SCHEMA, EDGE_UNIQUE_DATA).await; - main.branch_create("feature").await.unwrap(); - - let mut feature = Omnigraph::open(uri).await.unwrap(); - - mutate_main( - &mut main, - EDGE_UNIQUE_MUTATIONS, - "add_knows", - ¶ms(&[("$from", "Alice"), ("$to", "Bob")]), - ) - .await - .unwrap(); - - mutate_branch( - &mut feature, - "feature", - EDGE_UNIQUE_MUTATIONS, - "add_knows", - ¶ms(&[("$from", "Alice"), ("$to", "Carol")]), - ) - .await - .unwrap(); - - main.branch_merge("feature", "main") - .await - .expect("distinct (src, dst) pairs are unique on the composite and must merge cleanly"); - assert_eq!(count_rows(&main, "edge:Knows").await, 2); -} - #[tokio::test] async fn branch_merge_reports_cardinality_violation_conflict() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/omnigraph/tests/composite_flow.rs b/crates/omnigraph/tests/composite_flow.rs index dd41310..6c720da 100644 --- a/crates/omnigraph/tests/composite_flow.rs +++ b/crates/omnigraph/tests/composite_flow.rs @@ -294,19 +294,21 @@ async fn composite_flow_canonical_lifecycle() { ); // ───────────────────────────────────────────────────────────────── - // Step 10: optimize the post-merge graph β€” verify compaction is - // published to the manifest (so the manifest pin tracks the compacted - // Lance HEAD), indices stay valid and queryable, and a post-optimize - // strict write commits. + // Step 10: optimize the post-merge graph β€” verify indices stay + // valid and queryable. // - // This step used to carry a "Known limitation": `optimize_all_tables` - // ran Lance `compact_files` without publishing the new version to - // `__manifest`, so the manifest pin lagged the Lance HEAD and the next - // strict write / schema apply failed with `ExpectedVersionMismatch` - // ("stale view … refresh and retry") β€” so post-optimize mutations were - // deliberately omitted here. optimize now publishes the compacted - // version, and this flow exercises exactly that previously-failing - // write below. + // **Known limitation**: `optimize_all_tables` calls Lance + // `compact_files` directly β€” it advances per-table Lance HEAD + // without updating the omnigraph `__manifest` pin. After optimize, + // the next writer's expected_table_versions captures the + // pre-optimize manifest pin, but the publisher's pre-check reads + // a higher version from the manifest dataset (because some other + // path β€” possibly schema-state recovery on reopen β€” wrote a newer + // __manifest row). The `ExpectedVersionMismatch` is benign + // (re-issuing the mutation after a snapshot refresh succeeds), but + // a composite test cannot reliably exercise post-optimize mutations + // until that path is investigated. Coverage of post-optimize + // mutations is left to a focused optimize+cleanup integration test. // ───────────────────────────────────────────────────────────────── let optimize_stats = db.optimize().await.unwrap(); assert!( @@ -329,28 +331,6 @@ async fn composite_flow_canonical_lifecycle() { "row counts unchanged by optimize" ); - // A strict update on a compacted table is exactly the write that - // failed with "stale view" before optimize published its compaction. - // It must now commit (Alice is one of the seed Persons; an update - // leaves the row count at 6). - let post_optimize_update = mutate_main( - &mut db, - MUTATION_QUERIES, - "set_age", - &mixed_params(&[("$name", "Alice")], &[("$age", 41)]), - ) - .await - .expect("post-optimize strict update must commit β€” optimize published the manifest"); - assert_eq!( - post_optimize_update.affected_nodes, 1, - "post-optimize update must affect exactly Alice" - ); - assert_eq!( - count_rows(&db, "node:Person").await, - 6, - "an update must not change the Person row count" - ); - // ───────────────────────────────────────────────────────────────── // Step 11: cleanup β€” keep last 10 versions, only purge versions // older than 1 hour. With this small test, we have well under 10 @@ -393,27 +373,14 @@ async fn composite_flow_canonical_lifecycle() { branches, ); - // Final exercise β€” full read AND write path works post-reopen, - // post-cleanup. (The post-cleanup mutation was previously omitted - // pending resolution of the optimize-vs-manifest-pin interaction in - // Step 10; that is now fixed, so a strict write here must commit.) + // Final query exercise β€” full read path works post-reopen, + // 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(); assert!(!final_total.batches().is_empty()); - - let post_reopen_update = mutate_main( - &mut db, - MUTATION_QUERIES, - "set_age", - &mixed_params(&[("$name", "Alice")], &[("$age", 42)]), - ) - .await - .expect("post-reopen, post-cleanup strict update must commit"); - assert_eq!( - post_reopen_update.affected_nodes, 1, - "post-reopen update must affect exactly Alice" - ); } /// Cross-handle sequence that exercises operations after a schema_apply diff --git a/crates/omnigraph/tests/consistency.rs b/crates/omnigraph/tests/consistency.rs index aab0114..26517db 100644 --- a/crates/omnigraph/tests/consistency.rs +++ b/crates/omnigraph/tests/consistency.rs @@ -126,7 +126,7 @@ async fn load_merge_upserts_existing_and_inserts_new() { /// source batch had one row per key. /// /// Triggered by Lance's `processed_row_ids: Mutex>` -/// (lance-6.0.1 `src/dataset/write/merge_insert.rs:2099`) double- +/// (lance-4.0.0 `src/dataset/write/merge_insert.rs:2099`) double- /// processing the same source/target match against datasets previously /// rewritten by merge_insert. Worked around by opting /// `MergeInsertBuilder` into `SourceDedupeBehavior::FirstSeen` in @@ -188,7 +188,7 @@ node Thing { /// /// Defense in depth: /// 1. The loader's `enforce_unique_constraints_intra_batch` -/// (`loader/mod.rs:1442`), invoked unconditionally on any node type +/// (`loader/mod.rs:1453`), invoked unconditionally on any node type /// with a `@key`, errors on intra-batch duplicate `@key` values at /// intake β€” pinned by this test across every `LoadMode`. /// 2. The `check_batch_unique_by_keys` precondition at the top of @@ -229,122 +229,6 @@ node Thing { } } -/// Regression for MR-983: a node-level composite `@unique(a, b)` must be -/// enforced as a true composite key, not degraded into independent -/// single-field checks. Pre-fix, `unique_property_names_for_node` flattened -/// every constraint group into one property list, so `@unique(source, -/// external_id)` was enforced as `@unique(source)` *and* `@unique(external_id)` -/// β€” rejecting rows that were unique on the composite key and naming only the -/// first field in the error. -#[tokio::test] -async fn loader_enforces_composite_unique_as_composite_key() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let schema = r#" -node ExternalID { - slug: String @key - source: String @index - external_id: String @index - @unique(source, external_id) -} -"#; - let mut db = Omnigraph::init(uri, schema).await.unwrap(); - - // Same `source`, different `external_id` β†’ unique on the composite key. - // This is the exact repro from MR-983 and must be accepted. - let composite_ok = r#"{"type":"ExternalID","data":{"slug":"a","source":"whatsapp","external_id":"+E.164"}} -{"type":"ExternalID","data":{"slug":"b","source":"whatsapp","external_id":"pn:12345"}} -"#; - load_jsonl(&mut db, composite_ok, LoadMode::Overwrite) - .await - .expect("rows unique on the composite (source, external_id) must be accepted"); - assert_eq!(count_rows(&db, "node:ExternalID").await, 2); - - // Both composite columns equal β†’ genuine violation. The error must name - // the whole composite, not just the first field. - let composite_dupe = r#"{"type":"ExternalID","data":{"slug":"c","source":"whatsapp","external_id":"dup"}} -{"type":"ExternalID","data":{"slug":"d","source":"whatsapp","external_id":"dup"}} -"#; - let err = load_jsonl(&mut db, composite_dupe, LoadMode::Overwrite) - .await - .unwrap_err(); - let msg = err.to_string(); - // Columns are canonicalized to sorted order in the catalog, so the - // message reads `(external_id, source)`; assert order-agnostically that - // both composite columns are named (not just the first, as pre-fix). - assert!( - msg.contains("@unique violation") - && msg.contains("source") - && msg.contains("external_id"), - "composite violation must name both columns (got: {msg})" - ); -} - -/// Guard: the intake path (load/insert/update) and the branch-merge path must -/// derive the same composite `@unique(a, b)` key, so a pair of rows unique on -/// the tuple is accepted by BOTH. Both paths now key on the tuple itself (no -/// separator), so a value containing any byte β€” including the `|` that an -/// earlier merge-path join used as its separator β€” can't forge a collision. -/// `("x|y", "z")` and `("x", "y|z")` are distinct tuples and must survive a -/// load-on-branch then merge without a phantom `UniqueViolation`. This pins the -/// cross-path consistency against any future drift in the shared keying. -#[tokio::test] -async fn composite_unique_key_is_consistent_across_intake_and_merge() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let schema = r#" -node Item { - slug: String @key - a: String @index - b: String @index - @unique(a, b) -} -"#; - let insert_item = r#" -query insert_item($slug: String, $a: String, $b: String) { - insert Item { slug: $slug, a: $a, b: $b } -} -"#; - let main = Omnigraph::init(uri, schema).await.unwrap(); - main.branch_create("feature").await.unwrap(); - - // Two rows unique on the composite (a, b), where `a`/`b` carry a literal - // `|`. Distinct under a tuple key; identical (`x|y|z`) under a `|`-join. - let feature = Omnigraph::open(uri).await.unwrap(); - feature - .mutate( - "feature", - insert_item, - "insert_item", - ¶ms(&[("$slug", "r1"), ("$a", "x|y"), ("$b", "z")]), - ) - .await - .expect("intake must accept the first composite-unique row"); - feature - .mutate( - "feature", - insert_item, - "insert_item", - ¶ms(&[("$slug", "r2"), ("$a", "x"), ("$b", "y|z")]), - ) - .await - .expect("intake must accept the second composite-unique row (distinct on the tuple)"); - - // The merge re-validates uniqueness over the adopted source rows. Both - // rows are unique on (a, b), so this must merge cleanly with no phantom - // conflict β€” intake and merge must key the tuple identically. - let merge_result = feature.branch_merge("feature", "main").await; - assert!( - merge_result.is_ok(), - "rows unique on the composite (a, b) must merge cleanly; \ - intake and merge must key the tuple the same way (got: {:?})", - merge_result.err() - ); - - let reopened = Omnigraph::open(uri).await.unwrap(); - assert_eq!(count_rows(&reopened, "node:Item").await, 2); -} - /// Canary for the upstream Lance gap that the `FirstSeen` workaround /// in `table_store.rs` masks. The bug class is "Window 2": load β†’ /// indices built explicitly β†’ merge β†’ merge. Even with the engine diff --git a/crates/omnigraph/tests/end_to_end.rs b/crates/omnigraph/tests/end_to_end.rs index ea11d0e..a0fdb0e 100644 --- a/crates/omnigraph/tests/end_to_end.rs +++ b/crates/omnigraph/tests/end_to_end.rs @@ -1933,87 +1933,3 @@ query docs_with_tag($tag: String) { "contains-pushdown should return exactly the rows whose tags list contains 'red'" ); } - -// ─── Maintenance in the full lifecycle: optimize (compaction) ──────────────── - -/// `optimize` (Lance compaction) is part of a realistic graph lifecycle: it -/// advances the Lance HEAD and publishes the compacted version to the manifest. -/// The rest of the flow must keep working across that boundary β€” reads observe -/// the compacted data, strict updates (which check Lance HEAD == manifest -/// version) still commit, inserts still commit, and the state survives a reopen -/// (the open-time recovery sweep finds no leftover drift). Before optimize -/// published its compaction, the manifest lagged the Lance HEAD here and the -/// post-optimize update below failed with "stale view ... refresh and retry". -#[tokio::test] -async fn full_flow_optimize_then_query_update_and_reopen() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap().to_string(); - let mut db = init_and_load(&dir).await; - - // Build several Person fragments so compaction has something to merge. - for (name, age) in [("Eve", 40), ("Frank", 41), ("Grace", 42)] { - mutate_main( - &mut db, - MUTATION_QUERIES, - "insert_person", - &mixed_params(&[("$name", name)], &[("$age", age)]), - ) - .await - .unwrap(); - } - - let stats = db.optimize().await.unwrap(); - assert!( - stats.iter().any(|s| s.committed), - "a multi-fragment table should have compacted in this flow" - ); - - // Reads observe the compacted data. - let qr = query_main( - &mut db, - TEST_QUERIES, - "get_person", - ¶ms(&[("$name", "Alice")]), - ) - .await - .unwrap(); - assert_eq!(qr.num_rows(), 1); - - // Strict update after optimize commits (previously failed with "stale view" - // because the manifest lagged the compacted Lance HEAD). - let upd = mutate_main( - &mut db, - MUTATION_QUERIES, - "set_age", - &mixed_params(&[("$name", "Alice")], &[("$age", 31)]), - ) - .await - .unwrap(); - assert_eq!(upd.affected_nodes, 1); - - // Insert after optimize also commits. - mutate_main( - &mut db, - MUTATION_QUERIES, - "insert_person", - &mixed_params(&[("$name", "Ivan")], &[("$age", 50)]), - ) - .await - .unwrap(); - assert_eq!(count_rows(&db, "node:Person").await, 8); // 4 seed + Eve/Frank/Grace + Ivan - - // State survives a reopen β€” the recovery sweep runs and finds no drift. - drop(db); - let reopened = Omnigraph::open(&uri).await.unwrap(); - assert_eq!(count_rows(&reopened, "node:Person").await, 8); - let alice = reopened - .entity_at_target(ReadTarget::branch("main"), "node:Person", "Alice") - .await - .unwrap() - .unwrap(); - assert_eq!( - alice["age"], - serde_json::json!(31), - "Alice's post-optimize age update must persist across reopen" - ); -} diff --git a/crates/omnigraph/tests/failpoints.rs b/crates/omnigraph/tests/failpoints.rs index 3be0a56..149c63a 100644 --- a/crates/omnigraph/tests/failpoints.rs +++ b/crates/omnigraph/tests/failpoints.rs @@ -907,76 +907,6 @@ async fn recovery_rolls_forward_load_on_feature_branch() { ); } -#[tokio::test] -async fn recovery_rolls_forward_load_overwrite() { - use omnigraph::loader::{LoadMode, load_jsonl}; - - let _scenario = FailScenario::setup(); - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap().to_string(); - let operation_id; - let parent_commit_id; - - { - let mut db = Omnigraph::init(&uri, helpers::TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, helpers::TEST_DATA, LoadMode::Overwrite) - .await - .unwrap(); - parent_commit_id = branch_head_commit_id(dir.path(), "main").await.unwrap(); - - let _failpoint = ScopedFailPoint::new("mutation.post_finalize_pre_publisher", "return"); - let err = db - .load( - "main", - r#"{"type":"Person","data":{"name":"OverwriteLoad","age":41}} -"#, - LoadMode::Overwrite, - ) - .await - .unwrap_err(); - assert!( - err.to_string() - .contains("injected failpoint triggered: mutation.post_finalize_pre_publisher"), - "unexpected error: {err}" - ); - operation_id = single_sidecar_operation_id(dir.path()); - } - - let db = Omnigraph::open(&uri).await.unwrap(); - assert_eq!( - helpers::count_rows(&db, "node:Person").await, - 1, - "overwrite row must be visible after recovery rolls the load forward" - ); - drop(db); - - assert_post_recovery_invariants( - dir.path(), - &operation_id, - RecoveryExpectation::RolledForward { - tables: vec![ - TableExpectation::main("node:Person") - .expected_recovery_parent_commit_id(parent_commit_id) - .follow_up_mutation(FollowUpMutation::new( - "main", - MUTATION_QUERIES, - "insert_person", - mixed_params(&[("$name", "AfterOverwriteLoad")], &[("$age", 42)]), - )), - ], - }, - ) - .await - .unwrap(); - - let db = Omnigraph::open(&uri).await.unwrap(); - assert_eq!( - helpers::count_rows(&db, "node:Person").await, - 2, - "follow-up mutation must succeed after overwrite load recovery" - ); -} - #[tokio::test] async fn recovery_rolls_forward_ensure_indices_on_feature_branch() { use lance::index::DatasetIndexExt; @@ -1202,6 +1132,7 @@ async fn refresh_runs_roll_forward_recovery_in_process() { #[tokio::test] async fn refresh_defers_rollback_eligible_sidecar_to_next_open() { use omnigraph::loader::{LoadMode, load_jsonl}; + use omnigraph::table_store::TableStore; let _scenario = FailScenario::setup(); let dir = tempfile::tempdir().unwrap(); @@ -1231,8 +1162,12 @@ async fn refresh_defers_rollback_eligible_sidecar_to_next_open() { // touching the manifest) so the classifier can reach UnexpectedAtP1 // / UnexpectedMultistep / RolledPastExpected paths that require // a real restore on rollback. + let store = TableStore::new(&uri); let mut ds = lance::Dataset::open(&person_uri).await.unwrap(); - helpers::lance_delete_inline(&mut ds, "1 = 2").await; + store + .delete_where(&person_uri, &mut ds, "1 = 2") + .await + .unwrap(); let head_after_drift = ds.version().version; assert_eq!(head_after_drift, manifest_pin + 1); @@ -1310,7 +1245,7 @@ async fn refresh_defers_rollback_eligible_sidecar_to_next_open() { // the rollback (will use Dataset::restore safely; no concurrent // writers at open time). drop(db); - let db = Omnigraph::open(&uri).await.unwrap(); + let _db = Omnigraph::open(&uri).await.unwrap(); // After full-sweep recovery, the sidecar should be processed // (deleted). Sidecar's tables are eligible for rollback (UnexpectedAtP1): // restore happens on Person (HEAD advances by 1). @@ -1333,19 +1268,6 @@ async fn refresh_defers_rollback_eligible_sidecar_to_next_open() { "full sweep must run Dataset::restore (head advances); \ post_head={post_head}, final_head={final_head}", ); - // Convergence: roll-back published the restored HEAD, so the manifest pin - // tracks Lance HEAD afterward (no residual drift). - let entry_version = db - .snapshot_of(omnigraph::db::ReadTarget::branch("main")) - .await - .unwrap() - .entry("node:Person") - .unwrap() - .table_version; - assert_eq!( - entry_version, final_head, - "full-sweep roll-back must publish so manifest pin ({entry_version}) == Lance HEAD ({final_head})", - ); } /// Companion to the above β€” confirms that a finalizeβ†’publisher failure @@ -1539,15 +1461,10 @@ edge WorksAt: Person -> Company } let db = Omnigraph::open(&uri).await.unwrap(); - // Roll-back now publishes the restored version, so the manifest version - // advances β€” but to the OLD-schema content: the migration never applied - // (asserted by count_rows + the `_schema.pg` checks below), and the sweep - // converges (`manifest == Lance HEAD`, asserted by - // assert_post_recovery_invariants's RolledBack arm). - assert!( - version_main(&db).await.unwrap() > pre_failure_version, - "roll-back publishes the restored (old-schema) version, advancing the manifest; \ - pre={pre_failure_version}", + assert_eq!( + version_main(&db).await.unwrap(), + pre_failure_version, + "manifest must remain on the old schema when no schema staging files existed" ); assert_eq!( helpers::count_rows(&db, "node:Person").await, @@ -1720,101 +1637,6 @@ edge WorksAt: Person -> Company ); } -/// `optimize` Phase B β†’ Phase C residual: `compact_files` advanced the Lance -/// HEAD but the manifest publish hasn't run. The `Optimize` recovery sidecar -/// (loose-match, like SchemaApply/EnsureIndices) must roll the compacted version -/// forward on next open so the manifest tracks the Lance HEAD β€” and the healed -/// table must then accept a schema apply (the original bug's victim). -#[tokio::test] -async fn optimize_phase_b_failure_recovered_on_next_open() { - let _scenario = FailScenario::setup(); - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap().to_string(); - let operation_id; - - // Seed: several separate Person inserts β†’ multiple fragments, so compaction - // has real work and advances the Lance HEAD. - { - let db = Omnigraph::init(&uri, helpers::TEST_SCHEMA).await.unwrap(); - for (name, age) in [("alice", 30), ("bob", 31), ("carol", 32), ("dave", 33)] { - db.mutate( - "main", - MUTATION_QUERIES, - "insert_person", - &mixed_params(&[("$name", name)], &[("$age", age)]), - ) - .await - .unwrap(); - } - } - - let pre_failure_version = { - let db = Omnigraph::open(&uri).await.unwrap(); - version_main(&db).await.unwrap() - }; - - // Failpoint fires AFTER compact_files advanced the Lance HEAD but BEFORE the - // manifest publish. The Optimize sidecar persists (only node:Person has - // compactable fragments, so exactly one sidecar is written). - { - let db = Omnigraph::open(&uri).await.unwrap(); - let _failpoint = - ScopedFailPoint::new("optimize.post_phase_b_pre_manifest_commit", "return"); - let err = db.optimize().await.unwrap_err(); - assert!( - err.to_string().contains( - "injected failpoint triggered: optimize.post_phase_b_pre_manifest_commit" - ), - "unexpected error: {err}" - ); - - let recovery_dir = dir.path().join("__recovery"); - let sidecars: Vec<_> = std::fs::read_dir(&recovery_dir) - .unwrap() - .filter_map(|e| e.ok()) - .collect(); - assert_eq!( - sidecars.len(), - 1, - "exactly one Optimize sidecar must persist after optimize failure" - ); - operation_id = single_sidecar_operation_id(dir.path()); - } - - // Recovery: reopen runs the sweep. The Optimize sidecar classifies - // RolledPastExpected (loose-match) β†’ RollForward β†’ manifest extends to the - // compacted Lance HEAD. - let db = Omnigraph::open(&uri).await.unwrap(); - let post_recovery_version = version_main(&db).await.unwrap(); - assert!( - post_recovery_version > pre_failure_version, - "manifest version must advance post-recovery (compaction rolled forward); \ - pre={pre_failure_version}, post={post_recovery_version}", - ); - drop(db); - - assert_post_recovery_invariants( - dir.path(), - &operation_id, - RecoveryExpectation::RolledForward { - tables: vec![TableExpectation::main("node:Person")], - }, - ) - .await - .unwrap(); - - // The healed table accepts an additive schema apply β€” its HEAD-vs-manifest - // precondition is satisfied because recovery published the compacted version. - let db = Omnigraph::open(&uri).await.unwrap(); - let desired = helpers::TEST_SCHEMA.replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ); - db.apply_schema(&desired) - .await - .expect("schema apply after optimize recovery must succeed"); -} - #[tokio::test] async fn branch_merge_phase_b_failure_recovered_on_next_open() { use omnigraph::loader::{LoadMode, load_jsonl}; diff --git a/crates/omnigraph/tests/fixtures/search.gq b/crates/omnigraph/tests/fixtures/search.gq index d53fbc9..c39af82 100644 --- a/crates/omnigraph/tests/fixtures/search.gq +++ b/crates/omnigraph/tests/fixtures/search.gq @@ -42,17 +42,3 @@ query hybrid_search($vq: Vector(4), $tq: String) { order { rrf(nearest($d.embedding, $vq), bm25($d.title, $tq)) } limit 3 } - -query rrf_two_fts($q: String) { - match { $d: Doc } - return { $d.slug, $d.title } - order { rrf(bm25($d.title, $q), bm25($d.body, $q)) } - limit 3 -} - -query rrf_two_vectors($q1: Vector(4), $q2: Vector(4)) { - match { $d: Doc } - return { $d.slug, $d.title } - order { rrf(nearest($d.embedding, $q1), nearest($d.embedding, $q2)) } - limit 3 -} diff --git a/crates/omnigraph/tests/forbidden_apis.rs b/crates/omnigraph/tests/forbidden_apis.rs index e079464..1936815 100644 --- a/crates/omnigraph/tests/forbidden_apis.rs +++ b/crates/omnigraph/tests/forbidden_apis.rs @@ -29,21 +29,15 @@ //! the cross-table manifest commit. Documented exception. //! - `crates/omnigraph/src/storage_layer.rs` β€” IS the trait module. //! -//! ## Allow-list shape +//! ## Transitional allow-list //! -//! After MR-854, `db.storage()` (`&dyn TableStorage`) exposes only staged -//! primitives + reads. The inline-commit writes live on a separate -//! `InlineCommitResidual` trait reached via -//! `Omnigraph::storage_inline_residual()`, so the default storage surface -//! cannot couple "write bytes" with "advance HEAD" β€” engine code that -//! wants an inline residual must name the residual accessor explicitly. -//! The only residuals are `delete_where` (Lance #6658 / v7.x) and -//! `create_vector_index` (Lance #6666). The dead legacy methods -//! (trait `append_batch` / `merge_insert_batches`, inherent -//! `merge_insert_batch{,es}`, `create_{btree,inverted}_index`) were -//! removed entirely. This guard's scope is unchanged: it catches direct -//! `lance::*` inline-commit misuse outside the storage layer. The -//! file-level allow-list below matches that boundary. +//! The migration of writers onto staged primitives is incremental. +//! Several writers (ensure_indices, branch_merge, schema_apply rewrites) +//! already route through the staged primitives; others (bulk loader, +//! exec/mutation, exec/query) still use the legacy inherent +//! `TableStore` methods β€” they're not visible at the trait boundary, but +//! they DO call lance types. The file-level allow-list below reflects +//! this transitional state and tightens as call sites migrate. use std::path::{Path, PathBuf}; diff --git a/crates/omnigraph/tests/helpers/mod.rs b/crates/omnigraph/tests/helpers/mod.rs index 295cab7..c97ff72 100644 --- a/crates/omnigraph/tests/helpers/mod.rs +++ b/crates/omnigraph/tests/helpers/mod.rs @@ -195,14 +195,6 @@ pub async fn diff_since_branch( .await } -/// Advance a Lance dataset HEAD directly from tests without going through -/// OmniGraph's storage residual surface. Used to synthesize uncovered drift. -pub async fn lance_delete_inline(ds: &mut lance::Dataset, filter: &str) -> usize { - let result = ds.delete(filter).await.unwrap(); - *ds = (*result.new_dataset).clone(); - result.num_deleted_rows as usize -} - /// Build a ParamMap from string key-value pairs. pub fn params(pairs: &[(&str, &str)]) -> ParamMap { pairs @@ -244,15 +236,6 @@ pub fn vector_param(name: &str, values: &[f32]) -> ParamMap { map } -/// Build a ParamMap with two vector params. -pub fn two_vector_params(name1: &str, vals1: &[f32], name2: &str, vals2: &[f32]) -> ParamMap { - let mut map = vector_param(name1, vals1); - let key = name2.strip_prefix('$').unwrap_or(name2).to_string(); - let lit = Literal::List(vals2.iter().map(|v| Literal::Float(*v as f64)).collect()); - map.insert(key, lit); - map -} - /// Build a ParamMap with a vector param and a string param. pub fn vector_and_string_params( vec_name: &str, @@ -266,27 +249,6 @@ pub fn vector_and_string_params( map } -/// Test-only helper: perform a raw `Dataset::append` against Lance, -/// advancing Lance HEAD without going through the manifest. Used by -/// `recovery::*` and `staged_writes::*` tests that deliberately set up -/// HEAD-ahead-of-manifest drift scenarios. -/// -/// This mirrors the body of the engine's inline-commit -/// `TableStore::append_batch` (which is `pub(crate)` after MR-854) β€” -/// kept here as a test helper because integration tests need to -/// simulate drift without depending on the demoted crate-internal API. -pub async fn lance_append_inline(ds: &mut lance::Dataset, batch: RecordBatch) { - use lance::dataset::{WriteMode, WriteParams}; - let schema = batch.schema(); - let reader = arrow_array::RecordBatchIterator::new(vec![Ok(batch)], schema); - let params = WriteParams { - mode: WriteMode::Append, - allow_external_blob_outside_bases: true, - ..Default::default() - }; - ds.append(reader, Some(params)).await.unwrap(); -} - 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") diff --git a/crates/omnigraph/tests/helpers/recovery.rs b/crates/omnigraph/tests/helpers/recovery.rs index 90d9a25..c76009e 100644 --- a/crates/omnigraph/tests/helpers/recovery.rs +++ b/crates/omnigraph/tests/helpers/recovery.rs @@ -181,9 +181,6 @@ pub async fn assert_post_recovery_invariants( "audit row for {operation_id} recorded the wrong recovery_kind", ); assert_rollback_outcomes_record_drift(&audit); - // Roll-back now publishes the restored HEAD, so manifest == Lance - // HEAD afterward (symmetric with roll-forward) β€” no residual drift. - assert_manifest_pins_match_lance_heads(graph_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?; diff --git a/crates/omnigraph/tests/lance_surface_guards.rs b/crates/omnigraph/tests/lance_surface_guards.rs index 370f9e7..1d60c08 100644 --- a/crates/omnigraph/tests/lance_surface_guards.rs +++ b/crates/omnigraph/tests/lance_surface_guards.rs @@ -30,13 +30,9 @@ use arrow_schema::{DataType, Field, Schema}; use lance::Dataset; use lance::dataset::builder::DatasetBuilder; use lance::dataset::optimize::{CompactionOptions, compact_files}; -use lance::dataset::transaction::Operation; use lance::dataset::write::delete::DeleteResult; use lance::dataset::{MergeInsertBuilder, WhenMatched, WhenNotMatched, WriteMode, WriteParams}; -use lance::index::DatasetIndexExt; use lance_file::version::LanceFileVersion; -use lance_index::IndexType; -use lance_index::scalar::ScalarIndexParams; use lance_namespace::LanceNamespace; use lance_table::io::commit::ManifestNamingScheme; @@ -226,33 +222,6 @@ async fn _compile_compact_files_signature() -> lance::Result<()> { Ok(()) } -// --- Guard 7b: transaction history exposes repair's classification surface - -// -// `db/omnigraph/repair.rs` reads Lance transactions between manifest and HEAD -// and treats only `ReserveFragments` + `Rewrite` as safe maintenance drift. -// Compile-only. - -#[allow( - dead_code, - unreachable_code, - unused_variables, - unused_mut, - clippy::diverging_sub_expression -)] -async fn _compile_transaction_history_for_repair_signature() -> lance::Result<()> { - let ds: Dataset = unimplemented!(); - let tx = ds.read_transaction_by_version(1u64).await?; - if let Some(tx) = tx { - let operation = tx.operation; - let _name: &str = operation.name(); - match operation { - Operation::Rewrite { .. } | Operation::ReserveFragments { .. } => {} - _ => {} - } - } - Ok(()) -} - // --- Guard 8: Dataset::delete returns DeleteResult { new_dataset, num_deleted_rows } --- // // `table_store.rs::delete_where` consumes both fields. When MR-A migrates @@ -360,10 +329,7 @@ async fn compact_files_still_fails_on_blob_columns() { ])); RecordBatch::try_new( schema, - vec![ - Arc::new(StringArray::from(ids)) as _, - Arc::new(content) as _, - ], + vec![Arc::new(StringArray::from(ids)) as _, Arc::new(content) as _], ) .unwrap() } @@ -409,135 +375,3 @@ async fn compact_files_still_fails_on_blob_columns() { shifted): {err}" ); } - -// --- Guard 11: scalar-index coverage surface (physical_rows + index details) --- -// -// `table_store.rs::key_column_index_coverage` mirrors Lance's `create_filter_plan` -// C6 fallback: it reads `fragment.physical_rows` (the field whose absence on ANY -// fragment disables the scalar index for the whole scan) and sniffs the BTREE via -// `load_indices()` β†’ `index.fields` / `index.index_details.type_url`. This is the -// one real Lance-internal coupling on the indexed-traversal read path. If any of -// these surfaces renames or changes type, the coverage check (and the cost-based -// traversal chooser that consumes it) silently misclassifies. Compile-only. - -#[allow( - dead_code, - unreachable_code, - unused_variables, - unused_mut, - clippy::diverging_sub_expression -)] -async fn _compile_scalar_index_coverage_surface() -> lance::Result<()> { - let ds: Dataset = unimplemented!(); - // The create_filter_plan coupling: a fragment lacking `physical_rows` - // disables the scalar index for the entire scan. - for frag in ds.fragments().iter() { - let _physical_rows: Option = frag.physical_rows; - // `key_column_index_coverage` checks each current fragment id against the - // index `fragment_bitmap`. - let _id: u64 = frag.id; - } - // The index sniff: BTREE presence is detected by single-field index whose - // details type_url ends with "BTreeIndexDetails". The fragment coverage check - // reads `fragment_bitmap` (Option) and calls `.contains(u32)`. - let indices = ds.load_indices().await?; - for index in indices.iter() { - let _fields: &Vec = &index.fields; - if let Some(details) = index.index_details.as_ref() { - let _type_url: &str = details.type_url.as_str(); - } - let _covered: Option = index.fragment_bitmap.as_ref().map(|b| b.contains(0u32)); - } - Ok(()) -} - -// --- Guard 12: can a scalar BTREE be built on a system version column? -------- -// -// The deferred persisted-adjacency artifact plan assumed a cheap delta read of -// `_row_last_updated_at_version > V` could be a BTREE range lookup. Lance resolves -// index columns from the dataset schema, and the version columns are system -// metadata β€” so this probe documents whether the assumption holds. The outcome is -// the load-bearing fact, not a pass/fail of intent: if this starts SUCCEEDING when -// it currently errors (or vice versa), the artifact's delta-cost story changes. - -#[tokio::test] -async fn scalar_index_on_system_version_column_probe() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().join("guard12.lance"); - let mut ds = fresh_dataset(uri.to_str().unwrap()).await; - - // Sanity: the system version column is present (stable row ids + V2_2). - assert!( - ds.schema().field("_row_last_updated_at_version").is_none(), - "PROBE NOTE: `_row_last_updated_at_version` is NOT in the user schema \ - (it is system metadata); indexing it resolves through a different path." - ); - - let result = ds - .create_index_builder( - &["_row_last_updated_at_version"], - IndexType::BTree, - &ScalarIndexParams::default(), - ) - .replace(true) - .await; - - // Pin the observed behavior: a scalar index on the system version column is - // NOT buildable via the normal create-index path in this Lance. If this turns - // green (Ok), the artifact delta CAN use a version-column BTREE β€” revisit the - // deferred plan's Phase-2 delta-cost note in docs/dev/traversal handoff. - assert!( - result.is_err(), - "create_index on `_row_last_updated_at_version` unexpectedly SUCCEEDED β€” \ - a system-column scalar index is now buildable; the persisted-artifact \ - delta read could use it. Update the deferred-design notes." - ); -} - -// --- Guard 13: per-fragment deletion metadata is exposed without a scan ------- -// -// The deferred artifact's delete-correctness coverage model needs to detect, -// cheaply (O(fragments), no row scan), that a covered fragment acquired new -// deletions. That hinges on Lance tracking deletions at fragment-metadata level. -// This pins that a delete populates `fragment.deletion_file`, and probes whether -// the deleted-row COUNT is available as metadata (`num_deleted_rows`) β€” the -// difference between an O(fragments) coverage check and an O(|E|) scan. - -#[tokio::test] -async fn fragment_deletion_metadata_is_available() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().join("guard13.lance"); - let ds = fresh_dataset(uri.to_str().unwrap()).await; // 2 rows: alice, bob - - let deleted: DeleteResult = { - let mut ds = ds; - ds.delete("id = 'alice'").await.unwrap() - }; - assert_eq!(deleted.num_deleted_rows, 1, "one row deleted"); - let ds = deleted.new_dataset; - - // A delete must be tracked at fragment-metadata level (not only in data). - let with_deletion = ds - .fragments() - .iter() - .find(|f| f.deletion_file.is_some()) - .expect( - "after a delete, some fragment must carry a deletion_file β€” if not, \ - Lance changed deletion tracking; the artifact coverage model's \ - cheap delete-detection assumption is invalid.", - ); - - // Probe: is the deleted-row count available as metadata (cheap), or must the - // deletion vector be read? Pin whichever holds so the artifact plan knows. - let count: Option = with_deletion - .deletion_file - .as_ref() - .and_then(|df| df.num_deleted_rows); - assert_eq!( - count, - Some(1), - "PROBE: deletion_file.num_deleted_rows is not a populated metadata count \ - (got {count:?}); the artifact coverage model cannot cheaply detect \ - per-fragment deletions and would need to read the deletion vector.", - ); -} diff --git a/crates/omnigraph/tests/literal_filters.rs b/crates/omnigraph/tests/literal_filters.rs deleted file mode 100644 index a0b2bd7..0000000 --- a/crates/omnigraph/tests/literal_filters.rs +++ /dev/null @@ -1,96 +0,0 @@ -//! Execution goldens for filtering by non-string/non-integer scalar LITERALS -//! (F64, F32, Bool, Date, DateTime), across both the in-memory comparison arm -//! (standalone `$m.prop op lit`) and the Lance-pushdown arm (inline binding -//! `Metric { prop: lit }`). Param-bound scalar filters and list-column -//! `contains` are already covered elsewhere; this closes the literal-RHS gap. - -mod helpers; - -use arrow_array::{Array, StringArray}; - -use omnigraph::db::Omnigraph; -use omnigraph::loader::{LoadMode, load_jsonl}; -use omnigraph_compiler::ir::ParamMap; - -use helpers::*; - -const SCHEMA: &str = r#" -node Metric { - name: String @key - score: F64? - ratio: F32? - active: Bool? - born: Date? - seen: DateTime? -} -"#; - -// Seeds partition every predicate, so a dropped filter returns all 4 rows. -const DATA: &str = r#"{"type":"Metric","data":{"name":"m1","score":2.5,"ratio":0.5,"active":true,"born":"2024-06-01","seen":"2024-06-01T12:00:00Z"}} -{"type":"Metric","data":{"name":"m2","score":1.0,"ratio":0.25,"active":false,"born":"2023-01-01","seen":"2023-01-01T00:00:00Z"}} -{"type":"Metric","data":{"name":"m3","score":3.0,"ratio":0.75,"active":true,"born":"2025-01-01","seen":"2025-01-01T00:00:00Z"}} -{"type":"Metric","data":{"name":"m4","score":0.5,"ratio":0.1,"active":false,"born":"2022-12-31","seen":"2022-01-01T00:00:00Z"}}"#; - -async fn metric_db(dir: &tempfile::TempDir) -> Omnigraph { - let uri = dir.path().to_str().unwrap(); - let mut db = Omnigraph::init(uri, SCHEMA).await.unwrap(); - load_jsonl(&mut db, DATA, LoadMode::Overwrite).await.unwrap(); - db -} - -async fn sorted_metric_names(db: &mut Omnigraph, queries: &str, name: &str) -> Vec { - let r = query_main(db, queries, name, &ParamMap::new()).await.unwrap(); - if r.num_rows() == 0 { - return Vec::new(); - } - let b = r.concat_batches().unwrap(); - let col = b.column(0).as_any().downcast_ref::().unwrap(); - let mut v: Vec = (0..col.len()).map(|i| col.value(i).to_string()).collect(); - v.sort(); - v -} - -#[tokio::test] -async fn float_literal_filters_execute() { - let dir = tempfile::tempdir().unwrap(); - let mut db = metric_db(&dir).await; - let q = r#" -query gt() { match { $m: Metric $m.score > 1.5 } return { $m.name } } -query le() { match { $m: Metric $m.ratio <= 0.25 } return { $m.name } } -query inline() { match { $m: Metric { score: 3.0 } } return { $m.name } } -"#; - // F64 standalone: scores 2.5, 3.0 > 1.5 - assert_eq!(sorted_metric_names(&mut db, q, "gt").await, vec!["m1", "m3"]); - // F32 standalone: ratios 0.25, 0.1 <= 0.25 - assert_eq!(sorted_metric_names(&mut db, q, "le").await, vec!["m2", "m4"]); - // F64 inline-binding pushdown: score == 3.0 - assert_eq!(sorted_metric_names(&mut db, q, "inline").await, vec!["m3"]); -} - -#[tokio::test] -async fn bool_literal_filters_execute() { - let dir = tempfile::tempdir().unwrap(); - let mut db = metric_db(&dir).await; - let q = r#" -query standalone() { match { $m: Metric $m.active = true } return { $m.name } } -query inline() { match { $m: Metric { active: true } } return { $m.name } } -query negated() { match { $m: Metric $m.active != true } return { $m.name } } -"#; - assert_eq!(sorted_metric_names(&mut db, q, "standalone").await, vec!["m1", "m3"]); - assert_eq!(sorted_metric_names(&mut db, q, "inline").await, vec!["m1", "m3"]); - assert_eq!(sorted_metric_names(&mut db, q, "negated").await, vec!["m2", "m4"]); -} - -#[tokio::test] -async fn date_and_datetime_literal_filters_execute() { - let dir = tempfile::tempdir().unwrap(); - let mut db = metric_db(&dir).await; - let q = r#" -query born_ge() { match { $m: Metric $m.born >= date("2024-01-01") } return { $m.name } } -query seen_lt() { match { $m: Metric $m.seen < datetime("2024-01-01T00:00:00Z") } return { $m.name } } -"#; - // born: m1 2024-06, m3 2025 >= 2024-01-01 - assert_eq!(sorted_metric_names(&mut db, q, "born_ge").await, vec!["m1", "m3"]); - // seen: m2 2023, m4 2022 < 2024-01-01 - assert_eq!(sorted_metric_names(&mut db, q, "seen_lt").await, vec!["m2", "m4"]); -} diff --git a/crates/omnigraph/tests/maintenance.rs b/crates/omnigraph/tests/maintenance.rs index 13c9de7..3e61677 100644 --- a/crates/omnigraph/tests/maintenance.rs +++ b/crates/omnigraph/tests/maintenance.rs @@ -8,16 +8,10 @@ mod helpers; use std::time::Duration; use lance::Dataset; -use lance::dataset::optimize::{CompactionOptions, compact_files}; -use omnigraph::db::{ - CleanupPolicyOptions, Omnigraph, ReadTarget, RepairAction, RepairClassification, RepairOptions, - SkipReason, -}; +use omnigraph::db::{CleanupPolicyOptions, Omnigraph, SkipReason}; use omnigraph::loader::{LoadMode, load_jsonl}; -use helpers::{ - MUTATION_QUERIES, TEST_DATA, TEST_SCHEMA, count_rows, init_and_load, mixed_params, mutate_main, -}; +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 @@ -31,64 +25,11 @@ fn node_table_uri(root: &str, type_name: &str) -> String { format!("{}/nodes/{hash:016x}", root.trim_end_matches('/')) } -async fn person_manifest_and_head(db: &Omnigraph, root: &str) -> (u64, u64, String) { - let snap = db.snapshot_of(ReadTarget::branch("main")).await.unwrap(); - let entry = snap.entry("node:Person").unwrap(); - let full = format!("{}/{}", root.trim_end_matches('/'), entry.table_path); - let head = Dataset::open(&full).await.unwrap().version().version; - (entry.table_version, head, full) -} - -async fn add_person_fragments(db: &mut Omnigraph) { - for (name, age) in [("Eve", 40), ("Frank", 41), ("Grace", 42), ("Heidi", 43)] { - mutate_main( - db, - MUTATION_QUERIES, - "insert_person", - &mixed_params(&[("$name", name)], &[("$age", age as i64)]), - ) - .await - .expect("insert"); - } -} - -async fn forge_person_compaction_drift(db: &mut Omnigraph, root: &str) -> (u64, u64, String) { - add_person_fragments(db).await; - let (manifest_version, _, full) = person_manifest_and_head(db, root).await; - let mut ds = Dataset::open(&full).await.unwrap(); - let metrics = compact_files(&mut ds, CompactionOptions::default(), None) - .await - .expect("raw Lance compaction"); - let lance_head_version = ds.version().version; - assert!( - lance_head_version > manifest_version, - "raw Lance compaction should advance HEAD beyond manifest" - ); - assert!( - metrics.fragments_removed > 0 || metrics.fragments_added > 0, - "test precondition: raw compaction should rewrite fragments" - ); - (manifest_version, lance_head_version, full) -} - -async fn forge_person_delete_drift(db: &Omnigraph, root: &str) -> (u64, u64, String) { - let (manifest_version, _, full) = person_manifest_and_head(db, root).await; - let mut ds = Dataset::open(&full).await.unwrap(); - let deleted = ds.delete("name = 'Alice'").await.expect("raw Lance delete"); - assert_eq!(deleted.num_deleted_rows, 1, "fixture should delete Alice"); - let lance_head_version = deleted.new_dataset.version().version; - assert!( - lance_head_version > manifest_version, - "raw Lance delete should advance HEAD beyond manifest" - ); - (manifest_version, lance_head_version, full) -} - #[tokio::test] 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 db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); + let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); let stats = db.optimize().await.unwrap(); @@ -104,7 +45,7 @@ async fn optimize_on_empty_graph_returns_stats_per_table_with_no_changes() { #[tokio::test] async fn optimize_after_load_then_again_is_idempotent() { let dir = tempfile::tempdir().unwrap(); - let db = init_and_load(&dir).await; + let mut db = init_and_load(&dir).await; // First pass may compact (load wrote real fragments). let _first = db.optimize().await.unwrap(); @@ -222,404 +163,6 @@ node Tag {\n slug: String @key\n}\n"; assert_eq!(tag.skipped, None, "non-blob table must not be skipped"); } -// Regression: `optimize` must publish its compaction to the `__manifest` so the -// manifest's recorded `table_version` tracks the compacted Lance HEAD. -// -// Lance `compact_files` advances the *dataset's* version (reserve-fragments + -// rewrite commits) but knows nothing about OmniGraph's `__manifest`. If optimize -// does not publish a manifest update, the manifest's `table_version` lags the -// Lance HEAD: reads stay pinned to the pre-compaction version (compaction is -// invisible to them) and any subsequent schema apply / strict update/delete -// fails its HEAD-vs-manifest precondition with -// "stale view of '': expected manifest table version X but current is Y". -// This pins the fix β€” optimize publishes the compacted version, so manifest == -// HEAD and migrations after a compaction succeed. -#[tokio::test] -async fn optimize_publishes_compaction_to_manifest_so_schema_apply_succeeds() { - let dir = tempfile::tempdir().unwrap(); - let root = dir - .path() - .to_str() - .unwrap() - .trim_end_matches('/') - .to_string(); - let mut db = init_and_load(&dir).await; - - // Several separate inserts β†’ multiple Person fragments, so `compact_files` - // actually merges and moves the Lance HEAD (a single fragment is a no-op). - for (name, age) in [("Eve", 40), ("Frank", 41), ("Grace", 42), ("Heidi", 43)] { - mutate_main( - &mut db, - MUTATION_QUERIES, - "insert_person", - &mixed_params(&[("$name", name)], &[("$age", age as i64)]), - ) - .await - .expect("insert"); - } - - let stats = db.optimize().await.unwrap(); - let person = stats - .iter() - .find(|s| s.table_key == "node:Person") - .expect("Person stat present"); - assert!( - person.committed, - "Person is multi-fragment, so optimize must have compacted it" - ); - - // After optimize, the manifest's recorded table_version must equal the actual - // Lance HEAD β€” optimize published its compaction, so there is no drift. - let snap = db.snapshot_of(ReadTarget::branch("main")).await.unwrap(); - let entry = snap.entry("node:Person").unwrap(); - let manifest_version = entry.table_version; - let full = format!("{}/{}", root, entry.table_path); - let lance_head = Dataset::open(&full).await.unwrap().version().version; - assert_eq!( - manifest_version, lance_head, - "after optimize, manifest table_version ({manifest_version}) must equal Lance HEAD ({lance_head})", - ); - - // Reads observe the compacted version with rows preserved (4 seed + 4 inserts). - assert_eq!(count_rows(&db, "node:Person").await, 8); - - // The headline: an additive (nullable property) migration touching the - // just-compacted table succeeds, where it previously failed with "stale view". - let desired = TEST_SCHEMA.replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ); - let result = db - .apply_schema(&desired) - .await - .expect("additive schema apply after optimize must succeed"); - assert!(result.applied, "schema apply should report applied=true"); -} - -#[tokio::test] -async fn optimize_skips_preexisting_manifest_head_drift() { - let dir = tempfile::tempdir().unwrap(); - let root = dir - .path() - .to_str() - .unwrap() - .trim_end_matches('/') - .to_string(); - let mut db = init_and_load(&dir).await; - let (manifest_before, head_before, _) = forge_person_compaction_drift(&mut db, &root).await; - - let stats = db.optimize().await.unwrap(); - let person = stats - .iter() - .find(|s| s.table_key == "node:Person") - .expect("Person stat present"); - assert_eq!(person.skipped, Some(SkipReason::DriftNeedsRepair)); - assert!(!person.committed); - assert_eq!(person.manifest_version, Some(manifest_before)); - assert_eq!(person.lance_head_version, Some(head_before)); - - let (manifest_after, head_after, _) = person_manifest_and_head(&db, &root).await; - assert_eq!( - manifest_after, manifest_before, - "optimize must not publish uncovered drift" - ); - assert_eq!( - head_after, head_before, - "optimize must not move drifted HEAD" - ); -} - -#[tokio::test] -async fn repair_preview_reports_verified_maintenance_drift_without_healing() { - let dir = tempfile::tempdir().unwrap(); - let root = dir - .path() - .to_str() - .unwrap() - .trim_end_matches('/') - .to_string(); - let mut db = init_and_load(&dir).await; - let (manifest_before, head_before, _) = forge_person_compaction_drift(&mut db, &root).await; - - let stats = db - .repair(RepairOptions { - confirm: false, - force: false, - }) - .await - .unwrap(); - assert_eq!(stats.manifest_version, None); - let person = stats - .tables - .iter() - .find(|s| s.table_key == "node:Person") - .expect("Person repair stat present"); - assert_eq!( - person.classification, - RepairClassification::VerifiedMaintenance - ); - assert_eq!(person.action, RepairAction::Preview); - assert_eq!(person.manifest_version, manifest_before); - assert_eq!(person.lance_head_version, head_before); - assert!( - person - .operations - .iter() - .all(|op| op == "ReserveFragments" || op == "Rewrite"), - "maintenance drift should only include Lance maintenance operations: {:?}", - person.operations - ); - - let (manifest_after, head_after, _) = person_manifest_and_head(&db, &root).await; - assert_eq!(manifest_after, manifest_before); - assert_eq!(head_after, head_before); -} - -#[tokio::test] -async fn repair_confirm_heals_verified_maintenance_drift() { - let dir = tempfile::tempdir().unwrap(); - let root = dir - .path() - .to_str() - .unwrap() - .trim_end_matches('/') - .to_string(); - let mut db = init_and_load(&dir).await; - let (_, head_before, _) = forge_person_compaction_drift(&mut db, &root).await; - - let stats = db - .repair(RepairOptions { - confirm: true, - force: false, - }) - .await - .unwrap(); - assert!( - stats.manifest_version.is_some(), - "confirmed repair should publish one manifest commit" - ); - let person = stats - .tables - .iter() - .find(|s| s.table_key == "node:Person") - .expect("Person repair stat present"); - assert_eq!( - person.classification, - RepairClassification::VerifiedMaintenance - ); - assert_eq!(person.action, RepairAction::Healed); - - let (manifest_after, head_after, _) = person_manifest_and_head(&db, &root).await; - assert_eq!(manifest_after, head_before); - assert_eq!(head_after, head_before); - - let desired = TEST_SCHEMA.replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ); - let result = db - .apply_schema(&desired) - .await - .expect("strict schema apply should succeed after repair"); - assert!(result.applied); -} - -#[tokio::test] -async fn repair_refuses_raw_delete_without_force() { - let dir = tempfile::tempdir().unwrap(); - let root = dir - .path() - .to_str() - .unwrap() - .trim_end_matches('/') - .to_string(); - let db = init_and_load(&dir).await; - let (manifest_before, head_before, _) = forge_person_delete_drift(&db, &root).await; - - let stats = db - .repair(RepairOptions { - confirm: true, - force: false, - }) - .await - .unwrap(); - assert_eq!(stats.manifest_version, None); - let person = stats - .tables - .iter() - .find(|s| s.table_key == "node:Person") - .expect("Person repair stat present"); - assert_eq!(person.classification, RepairClassification::Suspicious); - assert_eq!(person.action, RepairAction::Refused); - assert!( - person.operations.iter().any(|op| op == "Delete"), - "raw Lance delete should be reported as a suspicious operation: {:?}", - person.operations - ); - - let (manifest_after, head_after, _) = person_manifest_and_head(&db, &root).await; - assert_eq!(manifest_after, manifest_before); - assert_eq!(head_after, head_before); - assert_eq!( - count_rows(&db, "node:Person").await, - 4, - "manifest-pinned reads should still see the pre-delete version" - ); -} - -#[tokio::test] -async fn repair_force_heals_suspicious_drift() { - let dir = tempfile::tempdir().unwrap(); - let root = dir - .path() - .to_str() - .unwrap() - .trim_end_matches('/') - .to_string(); - let db = init_and_load(&dir).await; - let (_, head_before, _) = forge_person_delete_drift(&db, &root).await; - - let stats = db - .repair(RepairOptions { - confirm: true, - force: true, - }) - .await - .unwrap(); - let person = stats - .tables - .iter() - .find(|s| s.table_key == "node:Person") - .expect("Person repair stat present"); - assert_eq!(person.classification, RepairClassification::Suspicious); - assert_eq!(person.action, RepairAction::Forced); - - let (manifest_after, head_after, _) = person_manifest_and_head(&db, &root).await; - assert_eq!(manifest_after, head_before); - assert_eq!(head_after, head_before); - assert_eq!( - count_rows(&db, "node:Person").await, - 3, - "forced repair publishes the raw delete's HEAD" - ); -} - -#[tokio::test] -async fn non_strict_load_refuses_uncovered_drift_before_folding_it() { - let dir = tempfile::tempdir().unwrap(); - let root = dir - .path() - .to_str() - .unwrap() - .trim_end_matches('/') - .to_string(); - let mut db = init_and_load(&dir).await; - let (manifest_before, head_before, _) = forge_person_compaction_drift(&mut db, &root).await; - - let err = load_jsonl( - &mut db, - "{\"type\":\"Person\",\"data\":{\"name\":\"Ivan\",\"age\":44}}", - LoadMode::Merge, - ) - .await - .expect_err("merge load must not silently fold uncovered drift"); - assert!( - err.to_string().contains("omnigraph repair"), - "error should point at explicit repair; got: {err}" - ); - - let (manifest_after, head_after, _) = person_manifest_and_head(&db, &root).await; - assert_eq!(manifest_after, manifest_before); - assert_eq!(head_after, head_before); -} - -#[tokio::test] -async fn delete_only_mutation_refuses_uncovered_drift_before_inline_commit() { - let dir = tempfile::tempdir().unwrap(); - let root = dir - .path() - .to_str() - .unwrap() - .trim_end_matches('/') - .to_string(); - let mut db = init_and_load(&dir).await; - let (manifest_before, head_before, _) = forge_person_compaction_drift(&mut db, &root).await; - - let err = mutate_main( - &mut db, - MUTATION_QUERIES, - "remove_person", - &mixed_params(&[("$name", "Alice")], &[]), - ) - .await - .expect_err("strict delete must reject uncovered drift before delete_where"); - assert!( - err.to_string().contains("expected"), - "delete should fail as a strict stale-version write; got: {err}" - ); - - let (manifest_after, head_after, _) = person_manifest_and_head(&db, &root).await; - assert_eq!(manifest_after, manifest_before); - assert_eq!( - head_after, head_before, - "delete_where must not run after the strict drift guard fails" - ); - assert_eq!( - count_rows(&db, "node:Person").await, - 8, - "manifest-pinned reads should still see all rows present before the failed delete" - ); -} - -// Regression: `optimize` must REFUSE when an unresolved recovery sidecar is -// pending. Operating on an unrecovered graph could publish a partial write that -// the all-or-nothing recovery sweep would roll back; the operator must reopen -// (run the recovery sweep) first. -#[tokio::test] -async fn optimize_defers_when_recovery_sidecar_is_pending() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let db = init_and_load(&dir).await; - - // Simulate an in-process failed write that left a recovery sidecar on disk. - let recovery_dir = dir.path().join("__recovery"); - std::fs::create_dir_all(&recovery_dir).unwrap(); - let person_path = node_table_uri(uri, "Person"); - let sidecar_json = format!( - r#"{{ - "schema_version": 1, - "operation_id": "01H000000000000000000DEFR", - "started_at": "0", - "branch": null, - "actor_id": "act-test", - "writer_kind": "Mutation", - "tables": [ - {{ - "table_key": "node:Person", - "table_path": "{}", - "expected_version": 1, - "post_commit_pin": 2 - }} - ] - }}"#, - person_path - ); - std::fs::write( - recovery_dir.join("01H000000000000000000DEFR.json"), - sidecar_json, - ) - .unwrap(); - - let err = db - .optimize() - .await - .expect_err("optimize must defer (error) while a recovery sidecar is pending"); - assert!( - err.to_string().to_lowercase().contains("recovery"), - "optimize defer error should mention recovery; got: {err}", - ); -} - #[tokio::test] async fn cleanup_without_any_policy_option_errors() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/omnigraph/tests/merge_truth_table.rs b/crates/omnigraph/tests/merge_truth_table.rs index e2df882..068b439 100644 --- a/crates/omnigraph/tests/merge_truth_table.rs +++ b/crates/omnigraph/tests/merge_truth_table.rs @@ -941,8 +941,8 @@ async fn merge_pair_truth_table() { unsupported_cells, 45, "expected 45 cells involving dropProperty/addLabel/removeLabel" ); - // No wall-clock assertion here: `elapsed` is logged above for visibility, but - // a fixed time budget in a correctness test flakes under parallel test load - // (it tripped at ~31s in the full `--test-threads=4` gate while passing at - // ~20s in isolation). Merge-perf regressions belong in a bench, not here. + assert!( + elapsed.as_secs() < 30, + "merge truth table exceeded 30s budget: {elapsed:?}" + ); } diff --git a/crates/omnigraph/tests/ordering.rs b/crates/omnigraph/tests/ordering.rs deleted file mode 100644 index 4e9296b..0000000 --- a/crates/omnigraph/tests/ordering.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! ORDER BY golden coverage: descending, multi-key precedence, deterministic -//! tie-break (total order), and NULL placement. -//! -//! These pin the observable output-ordering contract (deny-list: "output -//! ordering … become dependencies once shipped"). `apply_ordering` appends the -//! bound entities' key columns as an ascending tie-break, so equal user-sort -//! keys yield a TOTAL, deterministic order (and `ORDER … LIMIT` is -//! deterministic). NULL placement is `nulls_first = !descending` (NULLs first -//! under ASC, last under DESC). Both are documented in -//! `docs/user/query-language.md`. - -mod helpers; - -use arrow_array::{Array, StringArray}; - -use omnigraph::db::Omnigraph; -use omnigraph::loader::{LoadMode, load_jsonl}; -use omnigraph_compiler::ir::ParamMap; -use omnigraph_compiler::result::QueryResult; - -use helpers::*; - -/// Names in result ROW order (not sorted) β€” these tests assert positional order. -fn names_in_order(result: &QueryResult) -> Vec { - let batch = result.concat_batches().unwrap(); - if batch.num_rows() == 0 { - return Vec::new(); - } - let col = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - (0..col.len()).map(|i| col.value(i).to_string()).collect() -} - -/// Init the standard schema and load a custom Person-only dataset. -async fn init_people(dir: &tempfile::TempDir, jsonl: &str) -> Omnigraph { - let uri = dir.path().to_str().unwrap(); - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, jsonl, LoadMode::Overwrite).await.unwrap(); - db -} - -#[tokio::test] -async fn ordering_descending() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - let q = r#" -query q() { - match { $p: Person } - return { $p.name } - order { $p.age desc } -} -"#; - let got = names_in_order(&query_main(&mut db, q, "q", &ParamMap::new()).await.unwrap()); - // Charlie(35), Alice(30), Diana(28), Bob(25) - assert_eq!(got, vec!["Charlie", "Alice", "Diana", "Bob"]); -} - -#[tokio::test] -async fn ordering_multi_key_age_desc_name_asc() { - let dir = tempfile::tempdir().unwrap(); - // Alice & Bob tie at age 30; loaded Bob-first so the expected output order - // cannot be the load order. - let data = r#"{"type":"Person","data":{"name":"Bob","age":30}} -{"type":"Person","data":{"name":"Alice","age":30}} -{"type":"Person","data":{"name":"Charlie","age":25}}"#; - let mut db = init_people(&dir, data).await; - let q = r#" -query q() { - match { $p: Person } - return { $p.name } - order { $p.age desc, $p.name asc } -} -"#; - let got = names_in_order(&query_main(&mut db, q, "q", &ParamMap::new()).await.unwrap()); - // age desc -> [30,30,25]; the 30-tie broken by name asc -> Alice before Bob. - assert_eq!(got, vec!["Alice", "Bob", "Charlie"]); -} - -#[tokio::test] -async fn ordering_tiebreak_by_key_is_deterministic() { - let dir = tempfile::tempdir().unwrap(); - // Same tie at age 30, NO secondary sort key. Loaded Bob-first; the tie must - // break by the entity key (name) ascending -> Alice before Bob, regardless - // of load order. This locks the total-order tie-break in apply_ordering. - let data = r#"{"type":"Person","data":{"name":"Bob","age":30}} -{"type":"Person","data":{"name":"Alice","age":30}} -{"type":"Person","data":{"name":"Charlie","age":25}}"#; - let mut db = init_people(&dir, data).await; - let q = r#" -query q() { - match { $p: Person } - return { $p.name } - order { $p.age asc } -} -"#; - let got = names_in_order(&query_main(&mut db, q, "q", &ParamMap::new()).await.unwrap()); - // age asc -> Charlie(25), then the 30-tie broken by key asc -> Alice, Bob. - assert_eq!(got, vec!["Charlie", "Alice", "Bob"]); -} - -#[tokio::test] -async fn ordering_nulls_placement_asc_and_desc() { - let dir = tempfile::tempdir().unwrap(); - // Bob has a NULL age. - let data = r#"{"type":"Person","data":{"name":"Alice","age":30}} -{"type":"Person","data":{"name":"Bob","age":null}} -{"type":"Person","data":{"name":"Charlie","age":25}}"#; - let mut db = init_people(&dir, data).await; - - let asc = r#" -query q() { - match { $p: Person } - return { $p.name } - order { $p.age asc } -} -"#; - let got_asc = names_in_order(&query_main(&mut db, asc, "q", &ParamMap::new()).await.unwrap()); - // ASC: nulls_first -> Bob(null), then 25, 30. - assert_eq!(got_asc, vec!["Bob", "Charlie", "Alice"]); - - let desc = r#" -query q() { - match { $p: Person } - return { $p.name } - order { $p.age desc } -} -"#; - let got_desc = names_in_order(&query_main(&mut db, desc, "q", &ParamMap::new()).await.unwrap()); - // DESC: nulls last -> 30, 25, then Bob(null). - assert_eq!(got_desc, vec!["Alice", "Charlie", "Bob"]); -} diff --git a/crates/omnigraph/tests/policy_engine_chassis.rs b/crates/omnigraph/tests/policy_engine_chassis.rs index 8443940..def5349 100644 --- a/crates/omnigraph/tests/policy_engine_chassis.rs +++ b/crates/omnigraph/tests/policy_engine_chassis.rs @@ -243,7 +243,6 @@ async fn load_as_denies_when_policy_rejects_actor() { let result = db .load_as( "main", - None, ONE_PERSON_JSONL, LoadMode::Merge, Some("act-denied"), @@ -259,7 +258,6 @@ async fn load_as_allows_when_policy_permits_actor() { db.load_as( "main", - None, ONE_PERSON_JSONL, LoadMode::Merge, Some("act-allowed"), @@ -283,7 +281,6 @@ async fn load_file_as_denies_when_policy_rejects_actor() { let result = db .load_file_as( "main", - None, data_path.to_str().unwrap(), LoadMode::Merge, Some("act-denied"), @@ -301,7 +298,6 @@ async fn load_file_as_allows_when_policy_permits_actor() { db.load_file_as( "main", - None, data_path.to_str().unwrap(), LoadMode::Merge, Some("act-allowed"), @@ -311,7 +307,6 @@ async fn load_file_as_allows_when_policy_permits_actor() { } #[tokio::test] -#[allow(deprecated)] async fn ingest_as_denies_when_policy_rejects_actor() { let dir = tempfile::tempdir().unwrap(); let (db, _engine) = init_with_policy(&dir).await; @@ -329,7 +324,6 @@ async fn ingest_as_denies_when_policy_rejects_actor() { } #[tokio::test] -#[allow(deprecated)] async fn ingest_as_allows_when_policy_permits_actor() { let dir = tempfile::tempdir().unwrap(); let (db, _engine) = init_with_policy(&dir).await; diff --git a/crates/omnigraph/tests/proptest_equivalence.rs b/crates/omnigraph/tests/proptest_equivalence.rs deleted file mode 100644 index 3423a2f..0000000 --- a/crates/omnigraph/tests/proptest_equivalence.rs +++ /dev/null @@ -1,311 +0,0 @@ -//! Property-based query-correctness invariants over generated graphs. -//! -//! The cross-type id-collision bug (fixed in f6a0e53) was a silent wrong-result -//! divergence between the two Expand modes, caught only because someone -//! hand-built the one colliding fixture. This turns that single example into a -//! search over the whole class: node keys for BOTH types are drawn from a small -//! SHARED alphabet, so cross-type collisions β€” plus cycles and self-loops β€” -//! arise frequently. The invariants make any future fork divergence (the planned -//! third ExpandMode, the anti-join fast/slow fork) fail loudly instead of -//! silently. -//! -//! Each test is a sync `#[test]` + `#[serial]`: it builds its own runtime and -//! `block_on`s per generated case (proptest closures are sync), and the -//! mode-equivalence test writes `OMNIGRAPH_TRAVERSAL_MODE`, so serial execution -//! keeps env writes from racing other tests in this binary. - -mod helpers; - -use std::collections::HashSet; - -use arrow_array::{Array, StringArray}; -use proptest::prelude::*; -use proptest::test_runner::{Config, TestRunner}; -use serial_test::serial; - -use omnigraph::db::{Omnigraph, ReadTarget}; -use omnigraph::loader::{LoadMode, load_jsonl}; -use omnigraph_compiler::ir::ParamMap; -use omnigraph_compiler::query::ast::Literal; - -use helpers::*; - -/// Small SHARED key alphabet β€” Person and Company keys are both drawn from this, -/// so cross-type id collisions are common. -const KEYS: &[&str] = &["a", "b", "c", "d", "e"]; - -const QUERIES: &str = r#" -query friends($name: String) { - match { - $p: Person { name: $name } - $p knows{1,3} $f - } - return { $f.name } -} -query employers($name: String) { - match { - $p: Person { name: $name } - $p worksAt{1,2} $c - } - return { $c.name } -} -query all_persons() { - match { $p: Person } - return { $p.name } -} -query employed() { - match { - $p: Person - $p worksAt $c - } - return { $p.name } -} -query unemployed() { - match { - $p: Person - not { $p worksAt $_ } - } - return { $p.name } -} -"#; - -#[derive(Debug, Clone)] -struct GenGraph { - persons: Vec, - companies: Vec, - knows: Vec<(usize, usize)>, // indices into persons (self-loops & cycles allowed) - works_at: Vec<(usize, usize)>, // (person idx, company idx) -} - -impl GenGraph { - fn to_jsonl(&self) -> String { - let mut s = String::new(); - for p in &self.persons { - s.push_str(&format!("{{\"type\":\"Person\",\"data\":{{\"name\":\"{p}\"}}}}\n")); - } - for c in &self.companies { - s.push_str(&format!("{{\"type\":\"Company\",\"data\":{{\"name\":\"{c}\"}}}}\n")); - } - // Dedup exact-duplicate edge rows (the loader rejects intra-batch - // duplicate keys); collisions/cycles/self-loops are unaffected. - let mut seen = HashSet::new(); - for &(a, b) in &self.knows { - if seen.insert(("k", a, b)) { - s.push_str(&format!( - "{{\"edge\":\"Knows\",\"from\":\"{}\",\"to\":\"{}\"}}\n", - self.persons[a], self.persons[b] - )); - } - } - for &(a, b) in &self.works_at { - if seen.insert(("w", a, b)) { - s.push_str(&format!( - "{{\"edge\":\"WorksAt\",\"from\":\"{}\",\"to\":\"{}\"}}\n", - self.persons[a], self.companies[b] - )); - } - } - s - } -} - -fn arb_keys() -> impl Strategy> { - proptest::sample::subsequence(KEYS.to_vec(), 1..=KEYS.len()) - .prop_map(|v| v.into_iter().map(String::from).collect()) -} - -fn arb_graph() -> impl Strategy { - (arb_keys(), arb_keys()).prop_flat_map(|(persons, companies)| { - let np = persons.len(); - let nc = companies.len(); - let knows = prop::collection::vec((0..np, 0..np), 0..=10); - let works = prop::collection::vec((0..np, 0..nc), 0..=10); - (Just(persons), Just(companies), knows, works).prop_map( - |(persons, companies, knows, works_at)| GenGraph { - persons, - companies, - knows, - works_at, - }, - ) - }) -} - -fn config() -> Config { - Config { - cases: 48, - ..Config::default() - } -} - -fn clear_mode() { - unsafe { std::env::remove_var("OMNIGRAPH_TRAVERSAL_MODE") }; -} - -/// RAII guard that sets `OMNIGRAPH_TRAVERSAL_MODE` and clears it on drop β€” so a -/// panic mid-case (e.g. a query `unwrap`) cannot leak the forced mode into -/// proptest's subsequent shrink/cases and mask the divergence under test. SAFE: -/// every test in this binary is `#[serial]`, so no thread reads the env during -/// the write. -struct ModeGuard; -impl ModeGuard { - fn set(mode: &str) -> Self { - unsafe { std::env::set_var("OMNIGRAPH_TRAVERSAL_MODE", mode) }; - ModeGuard - } -} -impl Drop for ModeGuard { - fn drop(&mut self) { - unsafe { std::env::remove_var("OMNIGRAPH_TRAVERSAL_MODE") }; - } -} - -async fn load_graph(graph: &GenGraph) -> (tempfile::TempDir, Omnigraph) { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, &graph.to_jsonl(), LoadMode::Overwrite) - .await - .unwrap(); - (dir, db) -} - -fn one_param(val: &str) -> ParamMap { - let mut m = ParamMap::new(); - m.insert("name".to_string(), Literal::String(val.to_string())); - m -} - -/// First-column strings, sorted (MULTISET β€” preserves duplicate-row count so -/// mode comparisons catch dedup divergence, not just set divergence). -async fn col0_sorted(db: &mut Omnigraph, name: &str, params: &ParamMap) -> Vec { - let r = db - .query(ReadTarget::branch("main"), QUERIES, name, params) - .await - .unwrap(); - if r.num_rows() == 0 { - return Vec::new(); - } - let b = r.concat_batches().unwrap(); - let col = b.column(0).as_any().downcast_ref::().unwrap(); - let mut v: Vec = (0..col.len()).map(|i| col.value(i).to_string()).collect(); - v.sort(); - v -} - -async fn col0_set(db: &mut Omnigraph, name: &str, params: &ParamMap) -> HashSet { - col0_sorted(db, name, params).await.into_iter().collect() -} - -// INVARIANT 1: mode equivalence. For any generated graph and start key, the -// CSR, indexed, and auto paths return identical result multisets β€” over both a -// same-type traversal (knows{1,3}, exercises cycles/self-loops) and a cross-type -// one (worksAt{1,2}, collision-prone). This is the search-over-the-class version -// of the hand-built cross-type-collision fixture. -#[test] -#[serial] -fn prop_expand_indexed_eq_csr() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut runner = TestRunner::new(config()); - runner - .run(&arb_graph(), |graph| { - let mismatch = rt.block_on(async { - let (_dir, mut db) = load_graph(&graph).await; - for start in graph.persons.clone() { - let p = one_param(&start); - for q in ["friends", "employers"] { - // Each guard clears the mode on drop (end of the block, - // or on panic), so a forced mode never leaks across runs. - let csr = { - let _g = ModeGuard::set("csr"); - col0_sorted(&mut db, q, &p).await - }; - let indexed = { - let _g = ModeGuard::set("indexed"); - col0_sorted(&mut db, q, &p).await - }; - // No guard β†’ env unset β†’ auto (cost-based) path. - let auto = col0_sorted(&mut db, q, &p).await; - if csr != indexed || csr != auto { - return Some((start, q, csr, indexed, auto)); - } - } - } - None - }); - prop_assert!( - mismatch.is_none(), - "Expand mode divergence: {:?}", - mismatch - ); - Ok(()) - }) - .unwrap(); -} - -// INVARIANT 2: no phantom rows. Every key a traversal returns must belong to the -// destination type's loaded key set β€” independent of the two-mode comparison, so -// it catches over-emission even if both modes are wrong identically. -#[test] -#[serial] -fn prop_results_subset_of_existing_nodes() { - clear_mode(); - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut runner = TestRunner::new(config()); - runner - .run(&arb_graph(), |graph| { - let bad = rt.block_on(async { - let (_dir, mut db) = load_graph(&graph).await; - let persons: HashSet = graph.persons.iter().cloned().collect(); - let companies: HashSet = graph.companies.iter().cloned().collect(); - for start in graph.persons.clone() { - let p = one_param(&start); - for f in col0_set(&mut db, "friends", &p).await { - if !persons.contains(&f) { - return Some(("friends", start, f)); - } - } - for c in col0_set(&mut db, "employers", &p).await { - if !companies.contains(&c) { - return Some(("employers", start, c)); - } - } - } - None - }); - prop_assert!(bad.is_none(), "phantom row: {:?}", bad); - Ok(()) - }) - .unwrap(); -} - -// INVARIANT 3: anti-join complement. `not { $p worksAt $_ }` and its complement -// (persons WITH a worksAt) must be disjoint and together cover all persons. -#[test] -#[serial] -fn prop_antijoin_partitions_persons() { - clear_mode(); - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut runner = TestRunner::new(config()); - runner - .run(&arb_graph(), |graph| { - let err = rt.block_on(async { - let (_dir, mut db) = load_graph(&graph).await; - let all = col0_set(&mut db, "all_persons", &ParamMap::new()).await; - let unemployed = col0_set(&mut db, "unemployed", &ParamMap::new()).await; - let employed = col0_set(&mut db, "employed", &ParamMap::new()).await; - let overlap: Vec<_> = unemployed.intersection(&employed).cloned().collect(); - let union: HashSet<_> = unemployed.union(&employed).cloned().collect(); - if !overlap.is_empty() { - return Some(format!("overlap {overlap:?}")); - } - if union != all { - return Some(format!("union {union:?} != all {all:?}")); - } - None - }); - prop_assert!(err.is_none(), "anti-join partition broken: {:?}", err); - Ok(()) - }) - .unwrap(); -} diff --git a/crates/omnigraph/tests/recovery.rs b/crates/omnigraph/tests/recovery.rs index 37d46cb..a090178 100644 --- a/crates/omnigraph/tests/recovery.rs +++ b/crates/omnigraph/tests/recovery.rs @@ -175,6 +175,7 @@ async fn read_only_open_skips_recovery_sweep() { #[tokio::test] async fn recovery_rolls_back_synthetic_drift_on_open() { use omnigraph::loader::{LoadMode, load_jsonl}; + use omnigraph::table_store::TableStore; let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -201,9 +202,13 @@ async fn recovery_rolls_back_synthetic_drift_on_open() { // residual the sweep recovers from is the manifest-vs-Lance-HEAD gap; // it's agnostic to *what* op caused the gap. let person_uri = node_table_uri(uri, "Person"); + let store = TableStore::new(uri); let mut ds = Dataset::open(&person_uri).await.unwrap(); let head_before_drift = ds.version().version; - let _ = helpers::lance_delete_inline(&mut ds, "1 = 2").await; + let _ = store + .delete_where(&person_uri, &mut ds, "1 = 2") + .await + .unwrap(); let head_after_drift = ds.version().version; assert_eq!( head_after_drift, @@ -273,92 +278,6 @@ async fn recovery_rolls_back_synthetic_drift_on_open() { ); } -/// Regression: recovery roll-back must PUBLISH the restored version so -/// `manifest == Lance HEAD` afterward (no residual "orphaned drift"). Before the -/// fix, roll-back restored via `Dataset::restore` but left the manifest pin -/// behind HEAD, so a subsequent strict write / schema apply failed its -/// HEAD-vs-manifest precondition ("stale view … refresh and retry") β€” and a -/// failed schema apply's own roll-back leaked +1 each retry (the original bug's -/// loop). With convergence, one roll-back leaves `manifest == HEAD` and the -/// follow-up succeeds. -#[tokio::test] -async fn recovery_rollback_converges_manifest_so_schema_apply_succeeds() { - use omnigraph::db::ReadTarget; - use omnigraph::loader::{LoadMode, load_jsonl}; - - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl( - &mut db, - r#"{"type":"Person","data":{"name":"alice","age":30}} -{"type":"Person","data":{"name":"bob","age":25}} -"#, - LoadMode::Append, - ) - .await - .unwrap(); - drop(db); - - // Forge a Phase-B residual: advance Person's Lance HEAD without publishing to - // the manifest (the manifest pin stays at the load's committed version). - let person_uri = node_table_uri(uri, "Person"); - let mut ds = Dataset::open(&person_uri).await.unwrap(); - let manifest_pin = ds.version().version; - let _ = helpers::lance_delete_inline(&mut ds, "1 = 2").await; - drop(ds); - - // Roll-back-classified sidecar (post_commit_pin != observed head β‡’ - // UnexpectedAtP1 β‡’ RollBack). - let sidecar_json = format!( - r#"{{ - "schema_version": 1, - "operation_id": "01H0000000000000000000CVG", - "started_at": "0", - "branch": null, - "actor_id": "act-test", - "writer_kind": "Mutation", - "tables": [ - {{ - "table_key": "node:Person", - "table_path": "{}", - "expected_version": {}, - "post_commit_pin": {} - }} - ] - }}"#, - person_uri, manifest_pin, manifest_pin - ); - write_sidecar_file(dir.path(), "01H0000000000000000000CVG", &sidecar_json); - - // Reopen runs the sweep: restore Person to manifest_pin, then PUBLISH so the - // manifest tracks the restored Lance HEAD. - let db = Omnigraph::open(uri).await.unwrap(); - - // Convergence: manifest pin == Lance HEAD. Fails before the fix β€” the - // manifest stays at manifest_pin while HEAD advanced past it. - let snap = db.snapshot_of(ReadTarget::branch("main")).await.unwrap(); - let entry = snap.entry("node:Person").unwrap(); - let lance_head = Dataset::open(&person_uri).await.unwrap().version().version; - assert_eq!( - entry.table_version, lance_head, - "roll-back must publish so manifest pin ({}) == Lance HEAD ({})", - entry.table_version, lance_head, - ); - - // The +1-loop victim: an additive schema apply must now succeed (its - // HEAD-vs-manifest precondition is satisfied). Before the fix this failed - // with "stale view … refresh and retry". - let desired = TEST_SCHEMA.replace( - " age: I32?\n}", - " age: I32?\n nickname: String?\n}", - ); - db.apply_schema(&desired) - .await - .expect("schema apply after a converging roll-back must succeed"); -} - // ===================================================================== // Phase 4 β€” roll-forward path + audit row recording // ===================================================================== @@ -508,6 +427,7 @@ async fn count_recovery_actor_commits(graph_root: &Path) -> usize { #[tokio::test] async fn recovery_rolls_forward_after_phase_b_completes() { use omnigraph::loader::{LoadMode, load_jsonl}; + use omnigraph::table_store::TableStore; let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -524,12 +444,16 @@ async fn recovery_rolls_forward_after_phase_b_completes() { drop(db); let person_uri = node_table_uri(uri, "Person"); + let store = TableStore::new(uri); let mut ds = Dataset::open(&person_uri).await.unwrap(); let head_before = ds.version().version; // Synthesize a successful Phase B: advance Lance HEAD by one // (delete_where with no-match β€” no fragment changes, but version bumps). - let _ = helpers::lance_delete_inline(&mut ds, "1 = 2").await; + let _ = store + .delete_where(&person_uri, &mut ds, "1 = 2") + .await + .unwrap(); let head_after = ds.version().version; assert_eq!(head_after, head_before + 1); @@ -713,6 +637,7 @@ async fn recovery_records_rolled_forward_for_stale_sidecar_after_successful_roll #[tokio::test] async fn recovery_rolls_back_records_audit_row_with_recovery_actor() { use omnigraph::loader::{LoadMode, load_jsonl}; + use omnigraph::table_store::TableStore; let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -726,9 +651,13 @@ async fn recovery_rolls_back_records_audit_row_with_recovery_actor() { drop(db); let person_uri = node_table_uri(uri, "Person"); + let store = TableStore::new(uri); let mut ds = Dataset::open(&person_uri).await.unwrap(); let head_before = ds.version().version; - let _ = helpers::lance_delete_inline(&mut ds, "1 = 2").await; + let _ = store + .delete_where(&person_uri, &mut ds, "1 = 2") + .await + .unwrap(); let head_after = ds.version().version; let _ = head_after; @@ -775,6 +704,7 @@ async fn recovery_rolls_back_records_audit_row_with_recovery_actor() { #[tokio::test] async fn recovery_rolls_forward_with_null_actor() { use omnigraph::loader::{LoadMode, load_jsonl}; + use omnigraph::table_store::TableStore; let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -788,9 +718,13 @@ async fn recovery_rolls_forward_with_null_actor() { drop(db); let person_uri = node_table_uri(uri, "Person"); + let store = TableStore::new(uri); let mut ds = Dataset::open(&person_uri).await.unwrap(); let head_before = ds.version().version; - let _ = helpers::lance_delete_inline(&mut ds, "1 = 2").await; + let _ = store + .delete_where(&person_uri, &mut ds, "1 = 2") + .await + .unwrap(); let head_after = ds.version().version; // Sidecar with no actor_id (CLI-driven mutation; common case). @@ -846,6 +780,7 @@ async fn recovery_rolls_forward_with_null_actor() { #[tokio::test] async fn recovery_processes_multiple_sidecars_with_fresh_snapshot_per_iter() { use omnigraph::loader::{LoadMode, load_jsonl}; + use omnigraph::table_store::TableStore; let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -863,14 +798,21 @@ async fn recovery_processes_multiple_sidecars_with_fresh_snapshot_per_iter() { // Synthesize drift on both tables independently. let person_uri = node_table_uri(uri, "Person"); let company_uri = node_table_uri(uri, "Company"); + let store = TableStore::new(uri); let mut person_ds = Dataset::open(&person_uri).await.unwrap(); let person_pre = person_ds.version().version; - let _ = helpers::lance_delete_inline(&mut person_ds, "1 = 2").await; + let _ = store + .delete_where(&person_uri, &mut person_ds, "1 = 2") + .await + .unwrap(); let person_post = person_ds.version().version; let mut company_ds = Dataset::open(&company_uri).await.unwrap(); let company_pre = company_ds.version().version; - let _ = helpers::lance_delete_inline(&mut company_ds, "1 = 2").await; + let _ = store + .delete_where(&company_uri, &mut company_ds, "1 = 2") + .await + .unwrap(); let company_post = company_ds.version().version; // Drop two sidecars; ULID prefix ensures sort order is A then B. @@ -1050,6 +992,7 @@ async fn recovery_ensure_indices_handles_empty_tables() { #[tokio::test] async fn recovery_multi_sidecar_requires_fresh_snapshot_for_correctness() { use omnigraph::loader::{LoadMode, load_jsonl}; + use omnigraph::table_store::TableStore; let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_str().unwrap(); @@ -1068,6 +1011,7 @@ async fn recovery_multi_sidecar_requires_fresh_snapshot_for_correctness() { drop(db); let person_uri = node_table_uri(uri, "Person"); + let store = TableStore::new(uri); let mut ds = Dataset::open(&person_uri).await.unwrap(); let v1 = ds.version().version; @@ -1081,9 +1025,23 @@ async fn recovery_multi_sidecar_requires_fresh_snapshot_for_correctness() { // Bypassing __manifest is what `delete_where` and `append_batch` // both do (direct on Lance); using append_batch (instead of no-op // deletes) is what makes the fragment-set differ across versions. - helpers::lance_append_inline(&mut ds, person_batch(&[("bob-id", "bob", Some(25))])).await; + store + .append_batch( + &person_uri, + &mut ds, + person_batch(&[("bob-id", "bob", Some(25))]), + ) + .await + .unwrap(); let v2 = ds.version().version; - helpers::lance_append_inline(&mut ds, person_batch(&[("carol-id", "carol", Some(40))])).await; + store + .append_batch( + &person_uri, + &mut ds, + person_batch(&[("carol-id", "carol", Some(40))]), + ) + .await + .unwrap(); let v3 = ds.version().version; assert_eq!(v2, v1 + 1); assert_eq!(v3, v2 + 1); @@ -1248,7 +1206,14 @@ async fn recovery_classifies_feature_branch_sidecar_against_feature_branch() { .open_dataset_head(&person_uri, feature_branch_name.as_deref()) .await .unwrap(); - helpers::lance_append_inline(&mut ds, person_batch(&[("carol-id", "carol", Some(40))])).await; + store + .append_batch( + &person_uri, + &mut ds, + person_batch(&[("carol-id", "carol", Some(40))]), + ) + .await + .unwrap(); let v_head = ds.version().version; assert_eq!(v_head, v_pin + 1, "append must advance HEAD by 1"); @@ -1363,7 +1328,14 @@ async fn recovery_rolls_back_feature_branch_sidecar_against_feature_branch() { .open_dataset_head(&person_uri, feature_branch_name.as_deref()) .await .unwrap(); - helpers::lance_append_inline(&mut ds, person_batch(&[("dave-id", "dave", Some(50))])).await; + store + .append_batch( + &person_uri, + &mut ds, + person_batch(&[("dave-id", "dave", Some(50))]), + ) + .await + .unwrap(); let v_head = ds.version().version; assert_eq!(v_head, v_pin + 1); diff --git a/crates/omnigraph/tests/s3_storage.rs b/crates/omnigraph/tests/s3_storage.rs index 3814600..7e4f0a3 100644 --- a/crates/omnigraph/tests/s3_storage.rs +++ b/crates/omnigraph/tests/s3_storage.rs @@ -167,80 +167,3 @@ async fn s3_public_load_uses_hidden_run_and_publishes() { .to_rust_json(); assert_eq!(loaded[0]["p.name"], "Loaded-Over-S3"); } - -/// The conditional-write contract the cluster ledger depends on (RFC-006): -/// versioned read -> If-Match replace -> stale token refused. Pins the -/// S3-compatible backend's behavior (RustFS in CI) β€” turns red if a backend -/// bump regresses conditional puts. -#[tokio::test(flavor = "multi_thread")] -async fn s3_adapter_conditional_writes_contract() { - let Some(uri) = s3_test_graph_uri("adapter-cas") else { - eprintln!("skipping s3 adapter cas test: OMNIGRAPH_S3_TEST_BUCKET is not set"); - return; - }; - use omnigraph::storage::storage_for_uri; - let adapter = storage_for_uri(&uri).unwrap(); - let object = format!("{uri}/cas-probe.json"); - - assert!(adapter.write_text_if_absent(&object, "v1").await.unwrap()); - assert!(!adapter.write_text_if_absent(&object, "v1b").await.unwrap()); - - let (text, version) = adapter.read_text_versioned(&object).await.unwrap(); - assert_eq!(text, "v1"); - let next = adapter - .write_text_if_match(&object, "v2", &version) - .await - .unwrap() - .expect("fresh etag must win"); - assert!( - adapter - .write_text_if_match(&object, "v3", &version) - .await - .unwrap() - .is_none(), - "stale etag must be refused" - ); - let again = adapter - .write_text_if_match(&object, "v3", &next) - .await - .unwrap(); - assert!(again.is_some()); - - // Prefix delete: recursive + idempotent. - adapter - .write_text(&format!("{uri}/tree/a.json"), "a") - .await - .unwrap(); - adapter - .write_text(&format!("{uri}/tree/sub/b.json"), "b") - .await - .unwrap(); - adapter.delete_prefix(&format!("{uri}/tree")).await.unwrap(); - assert!(!adapter.exists(&format!("{uri}/tree/a.json")).await.unwrap()); - adapter.delete_prefix(&format!("{uri}/tree")).await.unwrap(); - adapter.delete(&object).await.unwrap(); -} - -/// Schema apply against an S3 graph β€” the cluster's schema executor will -/// lean on this; previously untested upstream on object storage. -#[tokio::test(flavor = "multi_thread")] -async fn s3_schema_apply_migrates_live_graph() { - let Some(uri) = s3_test_graph_uri("schema-apply") else { - eprintln!("skipping s3 schema apply test: OMNIGRAPH_S3_TEST_BUCKET is not set"); - return; - }; - let mut db = Omnigraph::init(&uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, TEST_DATA, LoadMode::Overwrite) - .await - .unwrap(); - - let desired = format!("{TEST_SCHEMA}\nnode Note {{\n title: String @key\n}}\n"); - let result = db.apply_schema(&desired).await.unwrap(); - assert!(result.applied, "{result:?}"); - - let reopened = Omnigraph::open(&uri).await.unwrap(); - assert!( - reopened.schema_source().contains("Note"), - "live S3 schema must carry the migration" - ); -} diff --git a/crates/omnigraph/tests/search.rs b/crates/omnigraph/tests/search.rs index 480ec3c..c4454cf 100644 --- a/crates/omnigraph/tests/search.rs +++ b/crates/omnigraph/tests/search.rs @@ -556,111 +556,6 @@ async fn bm25_returns_ranked_results() { assert!(result.num_rows() <= 3, "bm25 should respect limit 3"); } -// Full rank-ORDER golden (not just top-1 / non-empty): pins ranks 2..k so a -// regression corrupting the tail or reversing the sort direction fails loudly. -// nearest skips apply_ordering (is_search_ordered) and returns Lance native -// order, so result_slugs row order == rank order. -#[tokio::test] -#[serial] -async fn nearest_full_rank_order() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_search_db(&dir).await; - let result = query_main( - &mut db, - SEARCH_QUERIES, - "vector_search", - &vector_param("$q", &[0.1, 0.2, 0.3, 0.4]), - ) - .await - .unwrap(); - // [0.1,0.2,0.3,0.4] == ml-intro's embedding (dist 0); the rest by ascending L2. - assert_eq!(result_slugs(&result), vec!["ml-intro", "nlp-guide", "rl-intro"]); -} - -#[tokio::test] -#[serial] -async fn bm25_full_rank_order() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_search_db(&dir).await; - let result = query_main( - &mut db, - SEARCH_QUERIES, - "bm25_search", - ¶ms(&[("$q", "Learning")]), - ) - .await - .unwrap(); - // Descending BM25 score order. - assert_eq!(result_slugs(&result), vec!["rl-intro", "ml-intro", "dl-basics"]); -} - -// Characterization: fuzzy() does NOT match under the default tokenizer/index in -// this setup β€” a one-edit typo ("Introductio" for "Introduction") returns no -// rows. (`search`/`match_text` DO work, so FTS itself is fine; fuzzy term -// queries specifically are inert here.) This pins that documented limitation -// instead of leaving fuzzy silently unasserted: if a Lance/tokenizer change -// makes fuzzy match, this turns red and should be promoted to a real -// matched-set + exclusion golden. -#[tokio::test] -#[serial] -async fn fuzzy_does_not_match_under_default_tokenizer() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_search_db(&dir).await; - let r = query_main(&mut db, SEARCH_QUERIES, "fuzzy_search", ¶ms(&[("$q", "Introductio")])) - .await - .unwrap(); - assert!( - result_slugs(&r).is_empty(), - "fuzzy now matches β€” promote this to a real matched-set/exclusion golden" - ); -} - -// match_text is a FILTER on the body: assert the exact matched set, not contains. -#[tokio::test] -#[serial] -async fn match_text_matches_exact_set_excludes_unrelated() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_search_db(&dir).await; - // "neural" appears only in dl-basics's body ("neural networks"). - let r = query_main(&mut db, SEARCH_QUERIES, "phrase_search", ¶ms(&[("$q", "neural")])) - .await - .unwrap(); - let mut got = result_slugs(&r); - got.sort(); - assert_eq!(got, vec!["dl-basics"]); -} - -// RRF fuses arms OTHER than the default nearest+bm25: two FTS arms (title+body). -// Proves primary_var resolves when neither arm is `nearest`, and fusion runs. -#[tokio::test] -#[serial] -async fn rrf_fuses_two_fts_fields() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_search_db(&dir).await; - let r = query_main(&mut db, SEARCH_QUERIES, "rrf_two_fts", ¶ms(&[("$q", "learning")])) - .await - .unwrap(); - assert_eq!(result_slugs(&r), vec!["dl-basics", "ml-intro", "rl-intro"]); -} - -// RRF fuses two vector arms (no embedding creds β€” explicit vectors). A doc near -// BOTH query vectors out-ranks one near only one. -#[tokio::test] -#[serial] -async fn rrf_fuses_two_vector_queries() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_search_db(&dir).await; - let r = query_main( - &mut db, - SEARCH_QUERIES, - "rrf_two_vectors", - &two_vector_params("$q1", &[0.1, 0.2, 0.3, 0.4], "$q2", &[0.5, 0.6, 0.7, 0.8]), - ) - .await - .unwrap(); - assert_eq!(result_slugs(&r), vec!["rl-intro", "ml-intro", "dl-basics"]); -} - #[tokio::test] #[serial] async fn mutation_commit_refreshes_search_indices_without_manual_ensure() { diff --git a/crates/omnigraph/tests/staged_writes.rs b/crates/omnigraph/tests/staged_writes.rs index 3771ad4..5335057 100644 --- a/crates/omnigraph/tests/staged_writes.rs +++ b/crates/omnigraph/tests/staged_writes.rs @@ -23,9 +23,6 @@ use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; use lance::Dataset; use lance::dataset::{WhenMatched, WhenNotMatched}; -use lance::index::DatasetIndexExt; -use lance_index::IndexType; -use lance_linalg::distance::MetricType; use lance_table::format::Fragment; use omnigraph::table_store::{StagedWrite, TableStore}; use std::sync::Arc; @@ -37,22 +34,6 @@ fn person_schema() -> Arc { ])) } -/// Test-only helper: raw `Dataset::append` to advance Lance HEAD without -/// going through the manifest. Mirrors `TableStore::append_batch`'s body -/// (which is `pub(crate)` after MR-854) β€” kept local so these -/// drift-simulation tests don't depend on the demoted crate-internal API. -async fn lance_append_inline_local(ds: &mut Dataset, batch: RecordBatch) { - use lance::dataset::{WriteMode, WriteParams}; - let schema = batch.schema(); - let reader = arrow_array::RecordBatchIterator::new(vec![Ok(batch)], schema); - let params = WriteParams { - mode: WriteMode::Append, - allow_external_blob_outside_bases: true, - ..Default::default() - }; - ds.append(reader, Some(params)).await.unwrap(); -} - fn person_batch(rows: &[(&str, Option)]) -> RecordBatch { let ids: Vec<&str> = rows.iter().map(|(id, _)| *id).collect(); let ages: Vec> = rows.iter().map(|(_, age)| *age).collect(); @@ -370,7 +351,7 @@ async fn stage_merge_insert_then_commit_persists_merged_view() { /// `write_fragments_internal` lack per-column statistics. The result /// contains only matching committed rows; matching staged rows are /// silently absent. `scanner.use_stats(false)` does not bypass this in -/// lance 6.0.1. +/// lance 4.0.0. /// /// This test pins the actual behavior so a future change either /// preserves it (and updates the doc) or fixes it (and rewrites this @@ -635,58 +616,6 @@ async fn stage_overwrite_replaces_all_fragments() { ); } -#[tokio::test] -async fn stage_overwrite_empty_batch_replaces_all_rows() { - let dir = tempfile::tempdir().unwrap(); - let uri = format!("{}/people.lance", dir.path().to_str().unwrap()); - let store = TableStore::new(dir.path().to_str().unwrap()); - - let ds = TableStore::write_dataset( - &uri, - person_batch(&[("alice", Some(30)), ("bob", Some(25))]), - ) - .await - .unwrap(); - let pre_version = ds.version().version; - - let target_schema = Arc::new(Schema::new(vec![ - Field::new("id", DataType::Utf8, false), - Field::new("age", DataType::Int32, true), - Field::new("nickname", DataType::Utf8, true), - ])); - let staged = store - .stage_overwrite(&ds, RecordBatch::new_empty(target_schema.clone())) - .await - .unwrap(); - assert!( - staged.new_fragments.is_empty(), - "empty overwrite should produce a zero-fragment Lance Overwrite transaction" - ); - assert_eq!( - staged.removed_fragment_ids.len(), - ds.manifest.fragments.len(), - "empty overwrite still removes every committed fragment" - ); - assert_eq!( - ds.version().version, - pre_version, - "staging empty overwrite must not advance HEAD" - ); - - let new_ds = store - .commit_staged(Arc::new(ds.clone()), staged.transaction) - .await - .unwrap(); - assert_eq!(new_ds.version().version, pre_version + 1); - assert_eq!(new_ds.count_rows(None).await.unwrap(), 0); - assert!( - arrow_schema::Schema::from(new_ds.schema()) - .field_with_name("nickname") - .is_ok(), - "empty overwrite must commit the replacement batch schema" - ); -} - /// `stage_create_btree_index` writes index segments to object storage /// but does NOT advance Lance HEAD until `commit_staged`. After commit, /// the index is queryable. @@ -770,7 +699,7 @@ async fn stage_create_inverted_index_does_not_advance_head_until_commit() { ); } -/// Pin the inline-commit behavior of `delete_where`. Lance 6.0.1 does +/// Pin the inline-commit behavior of `delete_where`. Lance 4.0.0 does /// NOT expose a public `DeleteJob::execute_uncommitted` /// (`pub(crate)` β€” see lance-format/lance#6658). The trait deliberately /// does NOT introduce a `stage_delete` wrapper that would secretly @@ -785,6 +714,7 @@ async fn stage_create_inverted_index_does_not_advance_head_until_commit() { async fn delete_where_advances_head_inline_documents_residual() { let dir = tempfile::tempdir().unwrap(); let uri = format!("{}/people.lance", dir.path().to_str().unwrap()); + let store = TableStore::new(dir.path().to_str().unwrap()); let mut ds = TableStore::write_dataset( &uri, @@ -794,11 +724,13 @@ async fn delete_where_advances_head_inline_documents_residual() { .unwrap(); let pre_version = ds.version().version; - let result = ds.delete("id = 'alice'").await.unwrap(); - ds = (*result.new_dataset).clone(); - assert_eq!(result.num_deleted_rows, 1); + let result = store + .delete_where(&uri, &mut ds, "id = 'alice'") + .await + .unwrap(); + assert_eq!(result.deleted_rows, 1); assert!( - ds.version().version > pre_version, + result.version > pre_version, "delete_where ADVANCES Lance HEAD inline (the residual). When \ lance-format/lance#6658 ships and we migrate to stage_delete + \ commit_staged, flip this assertion to assert that staging does \ @@ -807,9 +739,9 @@ async fn delete_where_advances_head_inline_documents_residual() { } /// Companion to `delete_where_*`: pin the inline-commit behavior of -/// `create_vector_index`. Lance 6.0.1 vector indices take the +/// `create_vector_index`. Lance 4.0.0 vector indices take the /// "segment commit path" which calls `build_index_metadata_from_segments` -/// (`pub(crate)` in lance-6.0.1 `src/index.rs:111`). Until upstream +/// (`pub(crate)` in lance-4.0.0 `src/index.rs:111`). Until upstream /// exposes that helper (companion ticket to lance-format/lance#6658), /// the trait surface deliberately does NOT include /// `stage_create_vector_index` β€” same rationale as `stage_delete`'s @@ -848,9 +780,8 @@ async fn create_vector_index_advances_head_inline_documents_residual() { let pre_version = ds.version().version; assert!(!store.has_vector_index(&ds, "embedding").await.unwrap()); - let params = lance::index::vector::VectorIndexParams::ivf_flat(1, MetricType::L2); - ds.create_index_builder(&["embedding"], IndexType::Vector, ¶ms) - .replace(true) + store + .create_vector_index(&mut ds, "embedding") .await .unwrap(); assert!( @@ -873,7 +804,7 @@ async fn create_vector_index_advances_head_inline_documents_residual() { /// The Lance source confirms this β€” `restore()` (no args) takes the /// currently-checked-out version's content and applies it via /// `apply_commit` against the latest manifest, advancing HEAD by one. -/// See lance-6.0.1 `src/dataset.rs:1106` and the transaction-spec +/// See lance-4.0.0 `src/dataset.rs:1106` and the transaction-spec /// example at https://lance.org/format/table/transaction/. /// /// If the lance bump (4.0.0 β†’ 4.x) ever changes this delta or the call @@ -884,6 +815,7 @@ async fn create_vector_index_advances_head_inline_documents_residual() { async fn lance_restore_appends_one_commit_with_checked_out_content() { let dir = tempfile::tempdir().unwrap(); let uri = format!("{}/people.lance", dir.path().to_str().unwrap()); + let store = TableStore::new(dir.path().to_str().unwrap()); // Build version history: v1 = {alice}, v2 = {alice, bob}, v3 = {alice, bob, carol}. let mut ds = TableStore::write_dataset(&uri, person_batch(&[("alice", Some(30))])) @@ -891,10 +823,16 @@ async fn lance_restore_appends_one_commit_with_checked_out_content() { .unwrap(); assert_eq!(ds.version().version, 1); - lance_append_inline_local(&mut ds, person_batch(&[("bob", Some(25))])).await; + store + .append_batch(&uri, &mut ds, person_batch(&[("bob", Some(25))])) + .await + .unwrap(); assert_eq!(ds.version().version, 2); - lance_append_inline_local(&mut ds, person_batch(&[("carol", Some(40))])).await; + store + .append_batch(&uri, &mut ds, person_batch(&[("carol", Some(40))])) + .await + .unwrap(); assert_eq!(ds.version().version, 3); let head_before = ds.version().version; @@ -940,7 +878,7 @@ async fn lance_restore_appends_one_commit_with_checked_out_content() { /// and any future continuous-recovery reconciler's queue-acquisition /// requirement. /// -/// `Dataset::restore`'s `check_restore_txn` (lance-6.0.1 +/// `Dataset::restore`'s `check_restore_txn` (lance-4.0.0 /// `src/io/commit/conflict_resolver.rs:986`) returns `Ok(())` against /// almost every other op (Append, Update, Delete, CreateIndex, Merge, …), /// so a Restore commits successfully even with concurrent commits in @@ -970,6 +908,7 @@ async fn lance_restore_appends_one_commit_with_checked_out_content() { async fn lance_restore_loses_to_concurrent_append_via_orphaning() { let dir = tempfile::tempdir().unwrap(); let uri = format!("{}/people.lance", dir.path().to_str().unwrap()); + let store = TableStore::new(dir.path().to_str().unwrap()); // v1: seed with alice. let _ = TableStore::write_dataset(&uri, person_batch(&[("alice", Some(30))])) @@ -986,7 +925,10 @@ async fn lance_restore_loses_to_concurrent_append_via_orphaning() { // This simulates a per-table-queue model where another tenant wrote // between recovery's open and recovery's restore call. let mut writer_handle = Dataset::open(&uri).await.unwrap(); - lance_append_inline_local(&mut writer_handle, person_batch(&[("bob", Some(25))])).await; + store + .append_batch(&uri, &mut writer_handle, person_batch(&[("bob", Some(25))])) + .await + .unwrap(); assert_eq!(writer_handle.version().version, 2); // Recovery now restores. Because restore's `check_restore_txn` returns diff --git a/crates/omnigraph/tests/traversal.rs b/crates/omnigraph/tests/traversal.rs index 2f518fd..6efe7de 100644 --- a/crates/omnigraph/tests/traversal.rs +++ b/crates/omnigraph/tests/traversal.rs @@ -46,194 +46,6 @@ query not_at_acme() { assert_eq!(names_vec, vec!["Bob", "Charlie", "Diana"]); } -// Nested anti-join (double negation): proves `not { … not { … } }` recurses -// through execute_pipeline. "People who do NOT work at any NON-Acme company": -// inner `not { $c.name = "Acme" }` keeps the non-Acme employers, the outer `not` -// removes anyone who has one. Alice (Acme only), Charlie & Diana (no employer) -// remain β€” distinct from plain unemployed {Charlie, Diana}. -#[tokio::test] -async fn nested_anti_join_double_negation() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - - let queries = r#" -query no_nonacme_employer() { - match { - $p: Person - not { - $p worksAt $c - not { - $c.name = "Acme" - } - } - } - return { $p.name } -} -"#; - let result = query_main(&mut db, queries, "no_nonacme_employer", &ParamMap::new()) - .await - .unwrap(); - - let batch = result.concat_batches().unwrap(); - let names = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - let mut names_vec: Vec<&str> = (0..names.len()).map(|i| names.value(i)).collect(); - names_vec.sort(); - assert_eq!(names_vec, vec!["Alice", "Charlie", "Diana"]); -} - -// The anti-join has two execution forks: the CSR `has_neighbors` fast path -// (bare single-op Expand inner) and the set-oriented inner-pipeline replay (when -// dst_filters force a multi-op inner). They must agree. `not { $p worksAt $_ }` -// takes the fast path; the same negation with an always-true dst filter -// (`$c.name != ""`) is semantically identical but forces the slow path. -#[tokio::test] -async fn anti_join_fast_and_slow_paths_agree() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - - let queries = r#" -query fast() { - match { - $p: Person - not { $p worksAt $_ } - } - return { $p.name } -} -query slow() { - match { - $p: Person - not { - $p worksAt $c - $c.name != "" - } - } - return { $p.name } -} -"#; - let names = |result: omnigraph_compiler::result::QueryResult| { - let batch = result.concat_batches().unwrap(); - let col = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - let mut v: Vec = (0..col.len()).map(|i| col.value(i).to_string()).collect(); - v.sort(); - v - }; - - let fast = names(query_main(&mut db, queries, "fast", &ParamMap::new()).await.unwrap()); - let slow = names(query_main(&mut db, queries, "slow", &ParamMap::new()).await.unwrap()); - - assert_eq!(fast, slow, "anti-join fast and slow paths must agree"); - // Alice->Acme, Bob->Globex employed; Charlie & Diana have no employer. - assert_eq!(fast, vec!["Charlie", "Diana"]); -} - -// Regression: nested slow-path anti-joins must not collide on the synthetic -// correlation tag. The outer anti-join tags rows with a correlation column that -// rides through its inner pipeline; when the inner pipeline contains ANOTHER -// slow-path anti-join, a fixed tag name would duplicate, and reading it by name -// returns the OUTER tag β€” mis-correlating the inner negation. Fan-out (p1 works -// at two companies) makes the inner row indices diverge from the outer tags, so -// the bug produces a different person set than the correct one. -#[tokio::test] -async fn nested_anti_join_with_fanout_correlates_correctly() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - // p1 -> {Acme, Globex} (fan-out), p2 -> Globex, p3 -> Acme, p4 -> (none). - let data = r#"{"type":"Person","data":{"name":"p1"}} -{"type":"Person","data":{"name":"p2"}} -{"type":"Person","data":{"name":"p3"}} -{"type":"Person","data":{"name":"p4"}} -{"type":"Company","data":{"name":"Acme"}} -{"type":"Company","data":{"name":"Globex"}} -{"edge":"WorksAt","from":"p1","to":"Acme"} -{"edge":"WorksAt","from":"p1","to":"Globex"} -{"edge":"WorksAt","from":"p2","to":"Globex"} -{"edge":"WorksAt","from":"p3","to":"Acme"}"#; - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, data, LoadMode::Overwrite).await.unwrap(); - - let queries = r#" -query no_nonacme_employer() { - match { - $p: Person - not { - $p worksAt $c - not { - $c.name = "Acme" - } - } - } - return { $p.name } -} -"#; - let result = query_main(&mut db, queries, "no_nonacme_employer", &ParamMap::new()) - .await - .unwrap(); - let batch = result.concat_batches().unwrap(); - let names = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - let mut names_vec: Vec<&str> = (0..names.len()).map(|i| names.value(i)).collect(); - names_vec.sort(); - // p1 & p2 have a non-Acme employer (Globex) -> excluded; p3 (Acme only) and - // p4 (no employer) remain. - assert_eq!(names_vec, vec!["p3", "p4"]); -} - -// Regression: a multi-hop anti-join must not take the bulk fast path. The fast -// path answers via `has_neighbors` (ONE-hop existence), so `not { $p knows{2,2} -// $x }` would wrongly drop a node that has a 1-hop neighbor but no 2-hop path. -// Graph: a->b (b is a sink, so a has no 2-hop path), c->d->e (c has a 2-hop -// path). Only c has a 2-hop knows path, so only c is removed. -#[tokio::test] -async fn anti_join_respects_multi_hop_bounds() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let data = r#"{"type":"Person","data":{"name":"a"}} -{"type":"Person","data":{"name":"b"}} -{"type":"Person","data":{"name":"c"}} -{"type":"Person","data":{"name":"d"}} -{"type":"Person","data":{"name":"e"}} -{"edge":"Knows","from":"a","to":"b"} -{"edge":"Knows","from":"c","to":"d"} -{"edge":"Knows","from":"d","to":"e"}"#; - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, data, LoadMode::Overwrite).await.unwrap(); - - let queries = r#" -query no_two_hop() { - match { - $p: Person - not { $p knows{2,2} $x } - } - return { $p.name } -} -"#; - let result = query_main(&mut db, queries, "no_two_hop", &ParamMap::new()) - .await - .unwrap(); - let batch = result.concat_batches().unwrap(); - let names = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - let mut names_vec: Vec<&str> = (0..names.len()).map(|i| names.value(i)).collect(); - names_vec.sort(); - // Only c has a 2-hop knows path β†’ removed; everyone else (incl. a, which has - // a 1-hop neighbor but no 2-hop path) is kept. - assert_eq!(names_vec, vec!["a", "b", "d", "e"]); -} - // ─── Variable-length hops ─────────────────────────────────────────────────── const CHAIN_SCHEMA: &str = r#" diff --git a/crates/omnigraph/tests/traversal_indexed.rs b/crates/omnigraph/tests/traversal_indexed.rs deleted file mode 100644 index 2ceed85..0000000 --- a/crates/omnigraph/tests/traversal_indexed.rs +++ /dev/null @@ -1,327 +0,0 @@ -//! BTREE-indexed Expand path (`execute_expand_indexed`) coverage. -//! -//! These tests force the Expand execution mode via `OMNIGRAPH_TRAVERSAL_MODE` -//! and assert the indexed path matches the CSR path (both are semantically -//! identical β€” the indexed path just serves neighbor lookups from the persisted -//! src/dst BTREE instead of an in-memory CSR). They live in their own test -//! binary and are all `#[serial]`, so the env writes never race a concurrent -//! reader: within this process serial execution serializes every env read, and -//! other test binaries (e.g. `traversal.rs`) are separate processes whose env -//! stays unset (β†’ CSR), validating the shared hydrate/align tail on the CSR path. - -mod helpers; - -use arrow_array::{Array, StringArray}; - -use omnigraph::db::Omnigraph; -use omnigraph::loader::{LoadMode, load_jsonl}; -use omnigraph::table_store::{IndexCoverage, TableStore}; -use omnigraph_compiler::ir::ParamMap; -use serial_test::serial; - -use helpers::*; - -fn set_mode(mode: &str) { - // SAFE: every test here is #[serial] and this binary has no non-serial - // env reader, so no thread reads the environment during this write. - unsafe { std::env::set_var("OMNIGRAPH_TRAVERSAL_MODE", mode) }; -} - -fn clear_mode() { - unsafe { std::env::remove_var("OMNIGRAPH_TRAVERSAL_MODE") }; -} - -/// Run a name-returning query and return its first column, sorted. -async fn sorted_names(db: &mut Omnigraph, queries: &str, name: &str, params: &ParamMap) -> Vec { - let result = query_main(db, queries, name, params).await.unwrap(); - if result.num_rows() == 0 { - return Vec::new(); - } - let batch = result.concat_batches().unwrap(); - let col = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - let mut v: Vec = (0..col.len()).map(|i| col.value(i).to_string()).collect(); - v.sort(); - v -} - -/// Run the same query under CSR, indexed, and auto (cost-chooser) modes; assert -/// all three produce identical results and return them. The auto pass exercises -/// `choose_expand_mode` end to end: whichever path it selects, the rows must -/// match the forced paths (the chooser changes which path runs, never the result). -async fn both_modes(db: &mut Omnigraph, queries: &str, name: &str, params: &ParamMap) -> Vec { - set_mode("csr"); - let csr = sorted_names(db, queries, name, params).await; - set_mode("indexed"); - let indexed = sorted_names(db, queries, name, params).await; - clear_mode(); - let auto = sorted_names(db, queries, name, params).await; - assert_eq!( - indexed, csr, - "indexed Expand must produce identical results to CSR for query '{name}'" - ); - assert_eq!( - auto, csr, - "auto (cost-chooser) Expand must produce identical results to the forced paths for query '{name}'" - ); - indexed -} - -// The C6 index-coverage guard: `key_column_index_coverage` must report whether -// a `key_col IN (...)` scan will use the persisted BTREE or silently full-scan. -// Not #[serial] β€” it calls the helper directly and reads no env. -#[tokio::test] -async fn key_column_index_coverage_detects_btree_presence() { - let dir = tempfile::tempdir().unwrap(); - let db = init_and_load(&dir).await; - let snap = snapshot_main(&db).await.unwrap(); - - // Edge `src` gets a BTREE from ensure_indices on load β†’ Indexed. - let edge_ds = snap.open("edge:Knows").await.unwrap(); - let src_cov = TableStore::key_column_index_coverage(&edge_ds, "src") - .await - .unwrap(); - assert_eq!(src_cov, IndexCoverage::Indexed, "edge src is BTREE-indexed"); - - // A node property column with no scalar index β†’ Degraded (the warn path). - let node_ds = snap.open("node:Person").await.unwrap(); - let age_cov = TableStore::key_column_index_coverage(&node_ds, "age") - .await - .unwrap(); - assert!( - matches!(age_cov, IndexCoverage::Degraded { .. }), - "non-indexed column should be Degraded, got {age_cov:?}" - ); -} - -// An edge appended after the BTREE was built lands in a new fragment that the -// index does not cover (edge-index creation is skipped once a BTREE exists). The -// scan is then partly a full scan, so coverage must report `Degraded` β€” otherwise -// the cost chooser would price an unindexed-in-part scan as fully indexed. -// (Results stay correct regardless β€” `indexed_finds_unindexed_appended_edge`.) -#[tokio::test] -async fn coverage_degrades_for_appended_unindexed_fragment() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - - // Fresh load: the Knows BTREE covers every fragment β†’ Indexed. - let snap = snapshot_main(&db).await.unwrap(); - let edge_ds = snap.open("edge:Knows").await.unwrap(); - assert_eq!( - TableStore::key_column_index_coverage(&edge_ds, "src").await.unwrap(), - IndexCoverage::Indexed, - "freshly-loaded edge BTREE covers all fragments" - ); - - // Append an edge β†’ a new, unindexed fragment outside the index fragment_bitmap. - mutate_main( - &mut db, - MUTATION_QUERIES, - "add_friend", - ¶ms(&[("$from", "Alice"), ("$to", "Diana")]), - ) - .await - .unwrap(); - - let snap2 = snapshot_main(&db).await.unwrap(); - let edge_ds2 = snap2.open("edge:Knows").await.unwrap(); - let cov = TableStore::key_column_index_coverage(&edge_ds2, "src").await.unwrap(); - assert!( - matches!(cov, IndexCoverage::Degraded { .. }), - "appended unindexed fragment must degrade coverage, got {cov:?}" - ); -} - -#[tokio::test] -#[serial] -async fn indexed_matches_csr_one_hop_same_type() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - // friends_of: `$p knows $f` (Person -> Person, single hop). - let got = both_modes(&mut db, TEST_QUERIES, "friends_of", ¶ms(&[("$name", "Alice")])).await; - assert_eq!(got, vec!["Bob", "Charlie"], "Alice knows Bob and Charlie"); -} - -#[tokio::test] -#[serial] -async fn indexed_matches_csr_multi_hop_same_type() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - let queries = r#" -query reach($name: String) { - match { - $p: Person { name: $name } - $p knows{1,2} $f - } - return { $f.name } -} -"#; - // Alice -> Bob, Charlie (1 hop); Bob -> Diana (2 hops). - let got = both_modes(&mut db, queries, "reach", ¶ms(&[("$name", "Alice")])).await; - assert_eq!(got, vec!["Bob", "Charlie", "Diana"]); -} - -#[tokio::test] -#[serial] -async fn indexed_matches_csr_cross_type() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - let queries = r#" -query employer($name: String) { - match { - $p: Person { name: $name } - $p worksAt $c - } - return { $c.name } -} -"#; - let got = both_modes(&mut db, queries, "employer", ¶ms(&[("$name", "Alice")])).await; - assert_eq!(got, vec!["Acme"], "Alice works at Acme"); -} - -#[tokio::test] -#[serial] -async fn indexed_matches_csr_no_match() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - // Diana has no outgoing Knows edges β†’ empty in both modes. - let got = both_modes(&mut db, TEST_QUERIES, "friends_of", ¶ms(&[("$name", "Diana")])).await; - assert!(got.is_empty(), "Diana knows no one"); -} - -#[tokio::test] -#[serial] -async fn indexed_finds_unindexed_appended_edge() { - let dir = tempfile::tempdir().unwrap(); - let mut db = init_and_load(&dir).await; - - // Append Alice -> Diana AFTER the initial load. `ensure_indices`' existence - // guard means the src/dst BTREE built on the first load does NOT cover this - // new fragment. The indexed path must still find it via Lance's - // unindexed-fragment scan (fast_search=false default), so partial index - // coverage never silently drops rows. - mutate_main( - &mut db, - MUTATION_QUERIES, - "add_friend", - ¶ms(&[("$from", "Alice"), ("$to", "Diana")]), - ) - .await - .unwrap(); - - set_mode("indexed"); - let got = sorted_names(&mut db, TEST_QUERIES, "friends_of", ¶ms(&[("$name", "Alice")])).await; - clear_mode(); - - assert_eq!( - got, - vec!["Bob", "Charlie", "Diana"], - "indexed traversal must see the freshly-appended, unindexed edge" - ); -} - -// Regression: a node `id` is unique only WITHIN a type, so a `Person` and a -// `Company` can share an id string. A variable-length traversal over a -// cross-type edge (`worksAt`, Person -> Company) must structurally stop after -// one hop β€” a Company is not a `worksAt` source β€” so `worksAt{1,2}` returns -// exactly the one-hop companies. Before the structural hop-cap, the indexed -// path's single string interner de-interned the hop-1 Company id back to the -// colliding Person id and ran a hop-2 `worksAt src IN (...)` scan that matched -// that same-string Person's edges, emitting a spurious second-hop company the -// CSR path never produces. `both_modes` (csr == indexed == auto) plus the -// golden assert catch both the divergence and an over-emitting shared bug. -#[tokio::test] -#[serial] -async fn cross_type_id_collision_does_not_bleed_into_second_hop() { - const SCHEMA: &str = r#" -node Person { name: String @key } -node Company { name: String @key } -edge WorksAt: Person -> Company -"#; - // `shared` is BOTH a Person id and a Company id. alice worksAt the Company - // `shared`; the Person `shared` worksAt the Company `other`. - const DATA: &str = r#"{"type":"Person","data":{"name":"alice"}} -{"type":"Person","data":{"name":"shared"}} -{"type":"Company","data":{"name":"shared"}} -{"type":"Company","data":{"name":"other"}} -{"edge":"WorksAt","from":"alice","to":"shared"} -{"edge":"WorksAt","from":"shared","to":"other"}"#; - const QUERY: &str = r#" -query reach($name: String) { - match { - $p: Person { name: $name } - $p worksAt{1,2} $c - } - return { $c.name } -} -"#; - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let mut db = Omnigraph::init(uri, SCHEMA).await.unwrap(); - load_jsonl(&mut db, DATA, LoadMode::Overwrite).await.unwrap(); - - let got = both_modes(&mut db, QUERY, "reach", ¶ms(&[("$name", "alice")])).await; - assert_eq!( - got, - vec!["shared"], - "cross-type worksAt{{1,2}} must return only the one-hop company; a hop-2 \ - result means the id-string collision bled across types" - ); -} - -const REACH_5: &str = r#" -query reach($name: String) { - match { - $p: Person { name: $name } - $p knows{1,5} $f - } - return { $f.name } -} -"#; - -// A directed 3-cycle a->b->c->a, traversed with a hop ceiling (5) ABOVE the cycle -// length. Variable-length traversal must terminate and dedup (the source is -// seeded into `visited`, so the c->a back-edge does not re-emit a). Uses a -// bounded range deliberately: an unbounded `{1,}` is a typecheck error, not a -// runtime path. `both_modes` also confirms indexed == csr on the cycle. -#[tokio::test] -#[serial] -async fn variable_hops_terminate_and_dedup_on_cycle() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let data = r#"{"type":"Person","data":{"name":"a"}} -{"type":"Person","data":{"name":"b"}} -{"type":"Person","data":{"name":"c"}} -{"edge":"Knows","from":"a","to":"b"} -{"edge":"Knows","from":"b","to":"c"} -{"edge":"Knows","from":"c","to":"a"}"#; - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, data, LoadMode::Overwrite).await.unwrap(); - - let got = both_modes(&mut db, REACH_5, "reach", ¶ms(&[("$name", "a")])).await; - // From a: b (1 hop), c (2 hops); the c->a back-edge hits the seeded source - // and is not re-emitted. No infinite loop, each node at most once. - assert_eq!(got, vec!["b", "c"]); -} - -// A self-loop a->a plus a->b. Variable-length traversal must not loop forever and -// must not re-emit the seeded source. -#[tokio::test] -#[serial] -async fn variable_hops_handle_self_loop() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let data = r#"{"type":"Person","data":{"name":"a"}} -{"type":"Person","data":{"name":"b"}} -{"edge":"Knows","from":"a","to":"a"} -{"edge":"Knows","from":"a","to":"b"}"#; - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, data, LoadMode::Overwrite).await.unwrap(); - - let got = both_modes(&mut db, REACH_5, "reach", ¶ms(&[("$name", "a")])).await; - // a->a hits the seeded source (pruned); only b is reached. - assert_eq!(got, vec!["b"]); -} diff --git a/crates/omnigraph/tests/writes.rs b/crates/omnigraph/tests/writes.rs index b006f4c..13cb10f 100644 --- a/crates/omnigraph/tests/writes.rs +++ b/crates/omnigraph/tests/writes.rs @@ -6,8 +6,8 @@ //! What this file covers: //! - No `__run__*` branches are created by load or mutate. //! - Cancellation of a mutation future leaves no graph-level state. -//! - Concurrent non-strict inserts/merges rebase under the per-table queue; -//! strict updates/deletes surface `ExpectedVersionMismatch` on stale state. +//! - Concurrent writers to the same table land exactly one publish; the +//! loser surfaces `ManifestConflictDetails::ExpectedVersionMismatch`. //! - Failed mutations and loads leave the target unchanged. //! - Multi-statement mutations are atomic (one commit per query). //! - actor_id propagates through to the commit graph. @@ -17,7 +17,7 @@ mod helpers; use arrow_array::Array; use omnigraph::db::commit_graph::CommitGraph; use omnigraph::db::{Omnigraph, ReadTarget}; -use omnigraph::error::OmniError; +use omnigraph::error::{ManifestConflictDetails, ManifestErrorKind, OmniError}; use omnigraph::loader::{LoadMode, load_jsonl}; use helpers::*; @@ -241,11 +241,18 @@ async fn partial_failure_leaves_target_queryable_and_unblocks_next_mutation() { assert_eq!(frank.num_rows(), 1, "Frank must be visible after publish"); } -/// Stale non-strict writers rebase to the live manifest pin under the -/// per-table queue instead of folding raw drift or returning a false 409. -/// Strict update/delete semantics are covered by the consistency/server tests. +/// Concurrent writers to the same `(table, branch)` produce exactly one +/// success and one `ExpectedVersionMismatch`. The replacement for the old +/// `concurrent_conflicting_run_publish_fails_cleanly` test β€” the OCC fence +/// has moved from a graph-level run-publish merge into the publisher's +/// per-table CAS. +/// +/// Drives the race by interleaving two handles that captured the same +/// pre-write manifest snapshot: A commits first; B's commit then sees +/// `expected_versions[node:Person] = pre` while the manifest is at +/// `pre + 1`, and the publisher rejects. #[tokio::test] -async fn stale_non_strict_insert_rebases_to_live_manifest_pin() { +async fn concurrent_writers_one_succeeds_one_gets_expected_version_mismatch() { let dir = tempfile::tempdir().unwrap(); let uri = dir.path().to_string_lossy().into_owned(); @@ -274,30 +281,40 @@ async fn stale_non_strict_insert_rebases_to_live_manifest_pin() { .unwrap(); } - // Writer B's coordinator is still at the pre-A snapshot, but Insert is - // non-strict: commit_all re-reads the live manifest pin under the queue, - // verifies Lance HEAD equals that pin, and then lets Lance rebase the - // staged append. - db_b.mutate( - "main", - MUTATION_QUERIES, - "insert_person", - &mixed_params(&[("$name", "WriterB")], &[("$age", 42)]), - ) - .await - .unwrap(); - - for name in ["WriterA", "WriterB"] { - let person = query_main( - &mut db_b, - TEST_QUERIES, - "get_person", - ¶ms(&[("$name", name)]), + // Writer B's coordinator is still at the pre-A snapshot. Its mutation + // captures expected_versions[node:Person] = pre (stale), then publishes + // β€” the publisher's CAS pre-check sees the manifest is now at post and + // rejects with ExpectedVersionMismatch. + let result_b = db_b + .mutate( + "main", + MUTATION_QUERIES, + "insert_person", + &mixed_params(&[("$name", "WriterB")], &[("$age", 42)]), ) - .await - .unwrap(); - assert_eq!(person.num_rows(), 1, "{name} should be visible"); - } + .await; + + let err = result_b.expect_err("stale writer must hit ExpectedVersionMismatch"); + let OmniError::Manifest(manifest_err) = err else { + panic!("expected Manifest error, got {err:?}"); + }; + assert_eq!(manifest_err.kind, ManifestErrorKind::Conflict); + let Some(ManifestConflictDetails::ExpectedVersionMismatch { + ref table_key, + expected, + actual, + }) = manifest_err.details + else { + panic!( + "expected ExpectedVersionMismatch, got {:?}", + manifest_err.details, + ); + }; + assert_eq!(table_key, "node:Person"); + assert!( + actual > expected, + "actual ({actual}) should be ahead of expected ({expected})", + ); } /// The cancellation hole that motivated removing the Run state machine: dropping a mutation future @@ -354,10 +371,11 @@ async fn cancelled_mutation_future_leaves_no_state() { // Cancel-safety property: no graph-level run/staging state remains. // - // No `__run__` branches can ever be created: the Run state machine - // (`begin_run` etc.) was deleted in MR-771 β€” verified by the build itself, - // those symbols no longer exist. Any legacy `__run__*` branch on an - // upgraded graph is swept by the v2β†’v3 manifest migration. + // Note: `branch_list()` already filters `__run__*` via + // `is_internal_system_branch`, so a runtime "no `__run__` branches" check + // would be vacuous. The structural property that no `__run__` branches + // can ever be created is enforced by deletion of `begin_run` etc. in + // (verified by the build itself β€” those symbols no longer exist). // // (1) The branch list is unchanged: cancellation/completion cannot // synthesize new public branches. @@ -424,40 +442,34 @@ async fn repeated_loads_do_not_accumulate_branches() { assert_eq!(db.branch_list().await.unwrap(), vec!["main".to_string()]); } -/// After MR-770, `__run__*` is an ordinary branch name β€” the Run state machine -/// and its `is_internal_run_branch` guard are gone. The surviving internal-ref -/// guard still rejects the active `__schema_apply_lock__` branch on the public -/// create/merge APIs. +/// User code must not be able to write to internal `__run__*` names. +/// The branch-name guard predicate is kept as defense-in-depth; it +/// will be removed once a future production sweep retires the legacy +/// branches. #[tokio::test] -async fn public_branch_apis_reject_internal_system_refs() { +async fn public_branch_apis_reject_internal_run_refs() { let dir = tempfile::tempdir().unwrap(); let mut db = init_and_load(&dir).await; - // `__run__*` is no longer reserved β€” creating it now succeeds. - db.branch_create("__run__formerly_reserved") - .await - .expect("__run__ prefix is a normal branch name post-MR-770"); - - // The schema-apply lock branch is still rejected on public branch APIs. - let create_err = db.branch_create("__schema_apply_lock__").await.unwrap_err(); + let create_err = db.branch_create("__run__synthetic").await.unwrap_err(); let OmniError::Manifest(err) = create_err else { panic!("expected Manifest error"); }; assert!( - err.message.contains("internal system ref"), + err.message.contains("internal run ref"), "unexpected error: {}", err.message ); let merge_err = db - .branch_merge("__schema_apply_lock__", "main") + .branch_merge("__run__synthetic", "main") .await .unwrap_err(); let OmniError::Manifest(err) = merge_err else { panic!("expected Manifest error"); }; assert!( - err.message.contains("internal system refs"), + err.message.contains("internal run refs"), "unexpected error: {}", err.message ); @@ -778,47 +790,6 @@ async fn load_with_bad_edge_reference_unblocks_next_load() { ); } -#[tokio::test] -async fn load_overwrite_with_bad_edge_reference_unblocks_next_load() { - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let mut db = Omnigraph::init(uri, TEST_SCHEMA).await.unwrap(); - load_jsonl(&mut db, TEST_DATA, LoadMode::Overwrite) - .await - .unwrap(); - - let pre_persons = count_rows(&db, "node:Person").await; - let pre_edges = count_rows(&db, "edge:Knows").await; - - let bad = r#"{"type": "Person", "data": {"name": "Mallory", "age": 5}} -{"edge": "Knows", "from": "Mallory", "to": "Ghost"} -"#; - let err = load_jsonl(&mut db, bad, LoadMode::Overwrite) - .await - .expect_err("RI violation must fail overwrite before commit_staged"); - let OmniError::Manifest(manifest_err) = err else { - panic!("expected Manifest error, got {err:?}"); - }; - assert!( - manifest_err.message.contains("not found"), - "unexpected error: {}", - manifest_err.message, - ); - - assert_eq!(count_rows(&db, "node:Person").await, pre_persons); - assert_eq!(count_rows(&db, "edge:Knows").await, pre_edges); - - let good = r#"{"type": "Person", "data": {"name": "Pat", "age": 55}} -{"type": "Person", "data": {"name": "Quinn", "age": 56}} -{"edge": "Knows", "from": "Pat", "to": "Quinn"} -"#; - load_jsonl(&mut db, good, LoadMode::Overwrite) - .await - .unwrap(); - assert_eq!(count_rows(&db, "node:Person").await, 2); - assert_eq!(count_rows(&db, "edge:Knows").await, 1); -} - /// Same shape as the RI test above, but driven by a cardinality /// violation (`@card(0..1)` on `WorksAt`). The staged loader's pending /// edge accumulator drives the cardinality scan; a violation aborts @@ -883,56 +854,6 @@ edge WorksAt: Person -> Company @card(0..1) ); } -#[tokio::test] -async fn load_overwrite_with_cardinality_violation_unblocks_next_load() { - const CARD_SCHEMA: &str = r#" -node Person { - name: String @key - age: I32? -} -node Company { - name: String @key -} -edge WorksAt: Person -> Company @card(0..1) -"#; - - let dir = tempfile::tempdir().unwrap(); - let uri = dir.path().to_str().unwrap(); - let mut db = Omnigraph::init(uri, CARD_SCHEMA).await.unwrap(); - - let seed = r#"{"type": "Person", "data": {"name": "Alice", "age": 30}} -{"type": "Company", "data": {"name": "Acme"}} -{"type": "Company", "data": {"name": "Bigco"}} -"#; - load_jsonl(&mut db, seed, LoadMode::Overwrite) - .await - .unwrap(); - - let pre_works = count_rows(&db, "edge:WorksAt").await; - - let bad = r#"{"edge": "WorksAt", "from": "Alice", "to": "Acme"} -{"edge": "WorksAt", "from": "Alice", "to": "Bigco"} -"#; - let err = load_jsonl(&mut db, bad, LoadMode::Overwrite) - .await - .expect_err("cardinality violation must fail overwrite before commit_staged"); - let OmniError::Manifest(manifest_err) = err else { - panic!("expected Manifest error, got {err:?}"); - }; - assert!( - manifest_err.message.contains("@card violation"), - "unexpected error: {}", - manifest_err.message, - ); - assert_eq!(count_rows(&db, "edge:WorksAt").await, pre_works); - - let good = r#"{"edge": "WorksAt", "from": "Alice", "to": "Acme"}"#; - load_jsonl(&mut db, good, LoadMode::Overwrite) - .await - .unwrap(); - assert_eq!(count_rows(&db, "edge:WorksAt").await, 1); -} - // ─── Chained-mutation correctness β€” pinned coverage ───────────────────────── /// Chained `update` ops in one query must respect each previous op's diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 98587aa..a5fb275 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -9,17 +9,6 @@ fi bind="${OMNIGRAPH_BIND:-0.0.0.0:8080}" -# Cluster mode first, and exclusive (the server's mode-inference rule 0): -# a deployment serves from cluster state XOR omnigraph.yaml, never a merge. -# Fail fast here with the same contract the server enforces. -if [ -n "${OMNIGRAPH_CLUSTER:-}" ]; then - if [ -n "${OMNIGRAPH_TARGET_URI:-}" ] || [ -n "${OMNIGRAPH_CONFIG:-}" ] || [ -n "${OMNIGRAPH_TARGET:-}" ]; then - echo "OMNIGRAPH_CLUSTER is an exclusive boot source; unset OMNIGRAPH_TARGET_URI/OMNIGRAPH_CONFIG/OMNIGRAPH_TARGET" >&2 - exit 64 - fi - exec "$SERVER_BIN" --cluster "${OMNIGRAPH_CLUSTER}" --bind "${bind}" -fi - # 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 @@ -39,8 +28,6 @@ fi cat >&2 <<'EOF' omnigraph-server container startup requires one of: - - OMNIGRAPH_CLUSTER (serve a cluster directory's applied revision; - exclusive β€” cannot combine with the others) - OMNIGRAPH_TARGET_URI - OMNIGRAPH_CONFIG diff --git a/docker/entrypoint_test.sh b/docker/entrypoint_test.sh index 3ee668f..01fbee2 100755 --- a/docker/entrypoint_test.sh +++ b/docker/entrypoint_test.sh @@ -58,26 +58,6 @@ 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" -got=$(OMNIGRAPH_CLUSTER="/var/lib/omnigraph/company-brain" OMNIGRAPH_BIND="0.0.0.0:8080" sh "$ep") -check "CLUSTER only (Phase 5 mode switch)" \ - "ARGS: --cluster /var/lib/omnigraph/company-brain --bind 0.0.0.0:8080" "$got" - -# Exclusivity: OMNIGRAPH_CLUSTER refuses every combination, exit 64. -for combo in "OMNIGRAPH_TARGET_URI=s3://b/g" "OMNIGRAPH_CONFIG=/etc/o.yaml" "OMNIGRAPH_TARGET=active"; do - if out=$(env "$combo" OMNIGRAPH_CLUSTER="/data/cluster" sh "$ep" 2>&1); then - echo "FAIL: CLUSTER + ${combo%%=*} unexpectedly succeeded: $out" - fail=1 - else - status=$? - if [ "$status" -ne 64 ]; then - echo "FAIL: CLUSTER + ${combo%%=*} exited $status, want 64" - fail=1 - else - echo "ok: CLUSTER + ${combo%%=*} refused (64)" - fi - fi -done - if [ "$fail" -ne 0 ]; then echo "entrypoint_test: FAILED" exit 1 diff --git a/docs/dev/architecture.md b/docs/dev/architecture.md index 9d31545..813f30c 100644 --- a/docs/dev/architecture.md +++ b/docs/dev/architecture.md @@ -186,8 +186,7 @@ op-2 (insert/update) β†’ read committed via Lance + pending via DataFusion op-N β†’ push batch ─── end of query ─────────────────────────────────────── finalize: per pending table: - concat batches β†’ stage_append OR stage_merge_insert OR stage_overwrite - β†’ commit_staged + concat batches β†’ stage_append OR stage_merge_insert β†’ commit_staged publisher: ManifestBatchPublisher::publish (one cross-table CAS) ``` @@ -198,10 +197,9 @@ contracts: - `Dβ‚‚` parse-time rule: a query is either insert/update-only or delete-only. Mixed β†’ reject. Deletes still inline-commit (Lance 4.0.0 has no public two-phase delete); Dβ‚‚ keeps the inline path safe. -- `LoadMode::Overwrite` uses Lance `Operation::Overwrite` through the - same staged path. Loader validation runs against the replacement - in-memory batches before any `commit_staged`, and the publish window is - covered by `SidecarKind::Load` recovery. +- `LoadMode::Overwrite` keeps the inline-commit path + (truncate-then-append doesn't fit the staged shape; overwrite has no + in-flight read-your-writes requirement). - Read sites consume `TableStore::scan_with_pending`, which Lance-scans the committed snapshot at the captured `expected_version` and unions with a DataFusion `MemTable` over the pending batches. diff --git a/docs/dev/branch-protection.md b/docs/dev/branch-protection.md index 2b6cc37..9b2fa78 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 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 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 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,7 +16,7 @@ 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** | `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. | +| **Enforce on admins** | `true` | Even repository admins go through the gates. The point is no bypasses. | | **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 diff --git a/docs/dev/cluster-axioms.md b/docs/dev/cluster-axioms.md deleted file mode 100644 index dddecf1..0000000 --- a/docs/dev/cluster-axioms.md +++ /dev/null @@ -1,106 +0,0 @@ -# Cluster Control-Plane Axioms - -**Type:** Standing design filter -**Status:** Draft / thinking-in-progress -**Date:** 2026-06-07 -**Relationship:** the distilled axioms behind [cluster-config-specs.md](cluster-config-specs.md). The downstream implementation inventory and blast-radius assessment live in [cluster-config-implementation-spec.md](cluster-config-implementation-spec.md). The high-level spec is the argument; this is the checklist. Hold any config / control-plane / deployment proposal against these and cite them by number (e.g. "violates axiom 5"). - -This file is intentionally short and stable. The axioms are phrased so other -docs can reference "axiom 6" without churn. The motivating requirement comes -first; the core axioms are what the design is *based on*; the derived rules are -consequences that follow from them. - -> **Revision 2026-06-07 β€” committed to the Terraform paradigm.** State is now an -> **authoritative, locked ledger in a backend** (no longer framed as a -> "mostly-rebuildable projection"); `plan` is a **config ↔ state diff**; and -> **ETL pipelines** join schema as config-defined resources that trigger -> data-plane effects. Secrets live in a gitignored **`.env`** file (`${NAME}`), -> and **query exposure is a policy decision** (no registry `expose:` flag). -> Axioms **2, 5, 6** revised; **12, 13, 14** added. The earlier -> "state is just a rebuildable projection; config is the *only* truth" framing is -> superseded β€” see axiom 5. -> -> **Revision 2026-06-08 β€” JSON state first.** The baseline state backend is now -> Terraform-style JSON documents plus backend lock/CAS, not Lance control-plane -> datasets. Lance remains a possible later backend only if row-level history or -> queryability justifies the extra machinery. -> -> **Revision 2026-06-09 β€” single ownership during migration.** Axiom **15** -> added: while `omnigraph.yaml` and the cluster catalog coexist, every fact has -> exactly one owner at a time β€” coexistence is a **mode switch, never a merge**. -> `omnigraph.yaml` does not get replaced; its job description shrinks to the -> permanent per-operator layer. - ---- - -## Tenet 0 β€” the motivating requirement - -**0. The Sarah/Bob test.** If one operator changes schema / queries / policies / UI / pipelines / aliases, another operator (or their agent) must learn *what the deployment is and what changed* from **one source, one history, one diff**. Fragmentation across separate mechanisms is the failure the whole design exists to eliminate. Every other axiom is in service of passing this test. - ---- - -## Core axioms (what the design is based on) - -**1. The cluster is the unit of declarative state.** Not the graph (policies, queries, UI, and pipelines cross-cut graphs; "which graphs exist" has no per-graph home), not the fleet (the next scope up β€” named and deferred). The cluster is what two operators collaborate over; a graph is a *resource within* it. - -**2. Two sources of truth, for two different questions β€” config for *intent*, state for *deployed reality*.** The version-controlled **config** (a set of files in one folder) is the source of truth for what the cluster *should be*. The **state ledger** is the source of truth for what *is* currently deployed. Change flows one way only: you edit config and `apply` converges the cluster (**code β†’ cluster**, never edit-the-cluster-and-call-it-intent). But "what exists right now" is read from **state**, not re-derived from the world on every command. `plan` is the diff between the two. - -**3. Declarative, not imperative.** You describe the desired end state; the reconciler computes the steps. No runtime mutation API that makes the running system the place *intent* lives. - -**4. As-code is structural, not stylistic (the recursion argument).** Code is the base case; modeling the definition *as data* (a meta-graph describing graphs) recurses with no base case. Config must live **outside** the running system so it is reviewable (PRs), reproducible (clone + apply), diffable as text, and editable by an agent β€” without the system having to describe itself. - - -**5. The Terraform model: config / state / reconcile β€” and state is an authoritative, locked ledger.** Config (as code) = desired truth. **State = the authoritative record of what has been applied**, held in a **backend** β€” the cluster's own object-store backend *or* a separate cloud store, the operator's choice, exactly like a Terraform backend. The baseline representation is JSON documents (`state.json`, status/approval/recovery JSON records) protected by backend lock/CAS, not Lance control-plane tables. State is **locked** during apply so two operators cannot converge concurrently. `validate` parses and schema-checks desired config; `plan` = `diff(config, state)` as a structured artifact with resource digests, dependency edges, state observations, proposed changes, blast radius, and approval gates; `apply` converges the cluster from an accepted fresh plan and **updates state**, and does not acknowledge success until state has recorded the result. A cluster-hosted JSON backend is still a separate state CAS step from graph Lance manifest moves; failures surface a repair/import condition instead of being described as cross-object all-or-nothing. A future Lance-backed state backend or cluster manifest publisher is optional and must earn its complexity by needing row-level queryability/history or tighter publish fencing. Because OmniGraph's running cluster is self-describing (manifests, commit logs), state is *reconstructable* by import/refresh if lost β€” its edge over opaque-cloud Terraform β€” but it is **treated as the source of truth for current reality, not casually regenerated**. The one slice that can never be reconstructed (who approved an irreversible apply) lives in the durable audit ledger; state references it (axiom 11). - -**6. The control plane reconciles definition, not data β€” across two data-plane seams.** Definition β€” schema, policies, queries, UI, bindings, aliases, ETL **pipelines**, embeddings config, and the set of graphs β€” is reconciled. Data β€” rows, edges, vectors β€” is data-plane content, versioned by the commit DAG and produced by `load` / `mutate` and **pipeline execution**, sitting **outside** the reconcile loop. Exactly two definition kinds *trigger* a data-plane effect without owning data: **schema** (a migration conforms existing rows; `plan` previews its impact) and **ETL pipelines** (their execution ingests external data). The loop converges their *definitions*; the data they produce is never what it reconciles. - -**7. Operated by agent (agent-as-controller).** An agent authors config changes and drives reconciliation as an authenticated actor, subject to policy and approval gates β€” no human state-management burden. This fuses Terraform's as-code config with Kubernetes' continuous reconciliation. - ---- - -## Derived rules (consequences of the axioms) - -**8. The reversibility gradient gates apply β€” including drift correction.** Irreversible / data-loss operations (drop a graph, hard-drop schema data, a pipeline that overwrites) and compatibility-narrowing migrations (for example, future validated enum narrowing) are gated; reversible ones (recolor a dashboard) are not. The gate is keyed to physics, not to who operates it, and a reconciler "just fixing drift" is never an exception. - -**9. Atomicity and referential integrity are plan-time, not runtime.** `ApplyGroup` is the atomicity unit; cross-resource references *force* grouping (mandatory, not opt-in); references use typed resource/provider addresses (`graph.knowledge`, `query.knowledge.find_experts`, `provider.source.github_org`) so the planner can reject wrong-kind or missing targets before apply β€” bare names in a kind-fixed field are accepted shorthand and normalized to the typed address (fix 2026-06-08), while a kind-ambiguous value (e.g. `source: github`) is rejected; a reference to a missing or being-removed resource is a fail-closed `plan` error, not a deferred runtime failure. - -**10. Secrets live in a `.env` file; connection/identity is per-operator.** The committed cluster config carries **no secret values** β€” only `${NAME}` references. The values (embedding API keys, pipeline **source credentials**, per-deployment settings) live in a separate **`.env` file** β€” which is gitignored and supplied per deployment, never committed. Separately, an operator's own connection (which cluster, which token) is the per-operator layer, distinct from both the shared config and its `.env` file. - -**11. Approvals and audit live in a durable ledger, not inline in state.** State *references* the audit record by id. In the baseline, that ledger is append-only JSON records in the state backend; a future Lance table is an implementation option, not a requirement. This keeps the bulk of state reconstructable and keeps approval facts β€” "who authorized this irreversible apply" β€” where loss is impossible. - -**12. State lives in a backend and is locked.** The state ledger is stored in a configurable backend β€” the cluster's own backend, or a separate cloud store β€” and `plan`/`apply` acquire a **state lock** first, so concurrent applies serialize instead of racing. (Generalizes the existing `__schema_apply_lock__` from schema scope to cluster scope.) The backend choice is part of the safety model: the first backend should be JSON plus object-store lock/CAS; any Lance-backed state backend needs its own RFC-level proof that the table semantics are worth the control-plane complexity. - -**13. Pipelines are definition; their execution is data-plane.** An ETL pipeline (external source β†’ transform β†’ target graph) is **declared in config and reconciled like any resource**; *running* it produces ordinary data-plane writes (`load`/`mutate`) outside the reconcile loop. `apply` converges the pipeline's *definition* (create / update / delete / schedule); the rows it ingests are never reconciled. A fan-out run over several graphs is statusful rather than magically atomic: each target records commit id, status, retryability, and idempotency key unless the pipeline explicitly uses a branch/merge protocol that can fence the whole target set. Source credentials are secret references (axiom 10). - - -**14. Exposure is a policy decision, not a config flag.** Target design: which stored queries (and the tools/dashboards built on them) an actor may **list or invoke** is decided by the policy layer (Cedar: `invoke_query` + catalog visibility), not by a per-query `expose:` boolean. The registry only says a query *exists* (name β†’ file); **policy says who may see and run it**, so the MCP catalog (`GET /queries`) becomes each actor's policy-permitted set. This supersedes the engine's current `mcp.expose` flag only after per-query `invoke_query` scope and Cedar-filtered catalog listing land; until then, proposals must state the compatibility bridge to today's `mcp.expose` + coarse invocation gate. - -**15. Every fact has exactly one owner at a time; coexistence is a mode switch, never a merge.** `cluster.yaml` is not `omnigraph.yaml` v2 β€” the two documents end with disjoint jobs, and only the *shared-truth* parts of today's `omnigraph.yaml` (the set of graphs, stored-query registry, policy wiring, server boot source) migrate to the cluster catalog. The per-operator parts β€” connection/cluster selection, the operator's own credential reference, active graph/branch context, CLI ergonomics β€” are per-operator *by nature* (Sarah's and Bob's differ) and stay in the per-operator layer permanently; plan a **shrinking job description** for `omnigraph.yaml`, not an exit. During the migration window each fact is read from exactly one source at a time: a deployment serves from `omnigraph.yaml` **or** boots from cluster state (an exclusive mode switch), never from a precedence-merge of both. Two readers for one fact is the brittle-backcompat failure mode β€” it is the deny-list's "state that drifts from what it can be derived from" wearing a compatibility costume. Any compatibility bridge must name its replacement and its removal phase (the `mcp.expose` β†’ policy-owned exposure bridge of axiom 14 is the template); bridges that accumulate without an exit are rejected at review. - ---- - -## The one-line compression - -**One cluster; config (a folder of files) is desired truth and a locked state ledger in a backend is deployed truth; `plan` diffs them, `apply` converges the cluster and updates state, an agent drives the loop β€” reconciling the cluster's *definition* (schema, policies, queries, UI, pipelines, …) and never its data β€” so any operator sees the whole system and its history from one place.** - ---- - -## How to use this file - -- **Reviewing a proposal:** walk axioms 0–15; any conflict is the burden of the proposer to justify. The most common tensions: - - Treating the *running system* as the source of truth for **intent** β†’ axioms 2, 4 (intent lives in config). - - Treating state as a throwaway derivation rather than an authoritative, locked, backend-held ledger β†’ axiom 5, 12. - - A runtime config-mutation API instead of declarative apply β†’ axiom 3. - - "State" meaning a per-operator selection rather than the applied-cluster ledger β†’ axiom 5. - - The control plane reconciling (or owning) data β€” including treating pipeline *rows* as reconciled state β†’ axiom 6, 13. - - Treating fan-out pipeline execution as atomic without a branch/merge protocol or per-target status ledger β†’ axiom 13. - - Per-graph or per-server scoping of cluster-level definition β†’ axiom 1. - - Bare string references that force the planner to guess whether `knowledge` means a graph, query, provider, or path β†’ axiom 9. - - A secret value (token, embedding key, pipeline source credential) inline in config instead of in the gitignored `.env` file β†’ axiom 10. - - A per-query `expose:`/visibility flag in target-state cluster config instead of governing list/invoke in policy; or failing to account for today's `mcp.expose` compatibility bridge β†’ axiom 14. - - Shipping `apply` before hermetic `validate` + read-only `plan` tests, or shipping graph/schema-moving apply before recovery tests for the graph/resource-moved-before-cluster-publish gap β†’ axiom 5 and axiom 12. - - Reading one fact from both `omnigraph.yaml` and the cluster catalog with precedence rules (a merge instead of a mode switch), migrating per-operator concerns into shared cluster config, or adding a compatibility bridge with no named replacement and removal phase β†’ axiom 15. -- **Citing:** reference axioms by number in PRs and review comments so the rationale is stable across renames and refactors. diff --git a/docs/dev/cluster-config-implementation-spec.md b/docs/dev/cluster-config-implementation-spec.md deleted file mode 100644 index b58e531..0000000 --- a/docs/dev/cluster-config-implementation-spec.md +++ /dev/null @@ -1,741 +0,0 @@ -# Cluster Config Implementation Spec And Blast Radius - -**Status:** Draft / implementation planning -**Type:** Downstream design spec -**Date:** 2026-06-08 -**Relationship:** companion to [cluster-config-specs.md](cluster-config-specs.md) -and [cluster-axioms.md](cluster-axioms.md). The high-level spec explains why -the cluster control plane should exist; this file names what must change -downstream and how large the blast radius is. - - - -## Executive Summary - -Overall blast radius: **very high**. - -This is not a small extension to `omnigraph.yaml`. The target design creates a -new shared cluster desired-state document, a locked state ledger, a cluster -manifest publisher, and a reconciler that coordinates resources above a single -graph. The existing config system remains useful, but its role changes: - -- `omnigraph.yaml` / global config remains the per-operator and startup bridge. -- `cluster.yaml` becomes shared desired state for a deployment. -- The cluster state ledger becomes the authoritative record of applied reality. -- Server/runtime surfaces eventually read from the cluster catalog instead of - only from process-start config. - -Safe rollout requires an additive path. Do not replace the current config, -server, or policy behavior in one step. - -## Current Surfaces Surveyed - -| Surface | Current behavior | Why it matters | -|---|---|---| -| `omnigraph-config::OmnigraphConfig` | Layered global/state/project config for CLI and server startup; strict `version: 1`; named maps replace wholesale | A cluster spec needs different ownership and merge semantics; do not stretch this type until it becomes ambiguous | -| `omnigraph-server::load_server_settings` | Opens either one selected graph or every configured embedded graph in multi mode | Cluster config changes startup, registry identity, and eventually runtime reconcile | -| `GraphRegistry` | Holds open graph handles; production registry is startup-only today; runtime insert is test-only | Cluster apply wants graph add/remove/reload as real control-plane operations | -| `omnigraph-queries::QueryRegistry` | Loads `.gq` files from `queries:` and honors `mcp.expose` for catalog listing | Target cluster config removes exposure from the registry and moves list/invoke to policy | -| `omnigraph-policy::PolicyAction` | Per-graph actions plus server-scoped `graph_list`; `invoke_query` is graph-scoped and coarse | Cluster plan/apply and per-query exposure need new policy scope without breaking coarse rules | -| Engine graph manifest | Graph-level atomic visibility via `__manifest`, expected table versions, and recovery sidecars | Cluster apply needs a higher-level publisher; Lance still commits per dataset | -| Schema apply | Existing plan/apply/lock shape for one graph; soft/hard drops already modeled | This is the prototype resource reconciler, but cluster apply cannot call it blindly and then claim cluster atomicity | -| Public docs/tests | Config, policy, server, and query behavior are already documented and tested | Every behavior change below has user docs and test fallout | - -## Compatibility Stance - - - -1. `cluster.yaml` is a new target-state file, not `omnigraph.yaml` v2. -2. Existing `omnigraph.yaml` keeps working for CLI, server boot, aliases, - graph locators, bearer-token env lookup, and the current stored-query - registry. -3. Initial cluster commands are explicit: `omnigraph cluster validate`, - `omnigraph cluster plan`, `omnigraph cluster apply`, `omnigraph cluster - status`, `omnigraph cluster refresh`, and `omnigraph cluster import`. -4. Cluster config is one shared folder, resolved from the command's cluster - root or explicit path. It is not merged from global + project + active - context layers. -5. The per-operator connection layer selects the cluster root and actor - identity. It is not committed into `cluster.yaml`. -6. `mcp.expose` remains supported in current `omnigraph.yaml` until the - per-query policy replacement ships. -7. **Single ownership (axiom 15).** While `omnigraph.yaml` and the cluster - catalog coexist, each fact is read from exactly one source at a time. - Phase 5 server boot is an exclusive mode switch β€” boot from cluster state - XOR from `omnigraph.yaml` β€” never a precedence-merge of both. No phase may - introduce a surface that reads the same fact (graph set, query registry, - policy wiring, bind address) from both sources with tie-break rules. -8. **`omnigraph.yaml` shrinks; it does not get deprecated.** Its terminal role - is the per-operator layer: connection/cluster selection, the operator's - credential reference, active graph/branch context, CLI ergonomics, and - purely personal aliases (target home: the operator's global config dir per - RFC-002). Shared-truth keys migrate to `cluster.yaml`; per-operator keys - never do. -9. **Bridges carry sunsets.** Every compatibility bridge names its replacement - and the phase that removes it (`mcp.expose` β†’ Phase 6 policy-owned exposure - is the template). A bridge without an exit is a review-blocking finding. - -## Terraform-Aligned Schema Validation - - - -Every field in target-state `cluster.yaml` must be **honored or rejected**: - -- If a field is part of the declared resource schema, it must affect - validation, plan, apply, state, or status. -- If a field is misspelled, placed under the wrong resource kind, or reserved - for a future phase, `cluster validate` / `cluster plan` must fail with a - typed diagnostic. -- Compatibility warnings are allowed only in an explicit migration window for - old schema versions. They are not allowed in the target schema. -- Free-form extension areas must be named as such, for example `labels`, - `metadata`, `vars`, or `provider_options`; accidental unknown keys are never - treated as extension data. - -Examples: - -```yaml -graphs: - knowledge: - schema: ./knowledge.pg - lables: { team: platform } # invalid: typo, use `labels` - -pipelines: - github_sync: - source: { kind: github, token: ${GITHUB_TOKEN} } - into: - - { graph: engineering, map: ./github.map.yaml } - retry_magic: true # invalid unless `retry_magic` is in schema -``` - -```yaml -graphs: - knowledge: - schema: ./knowledge.pg - labels: { team: platform } # valid free-form metadata bucket - provider_options: - lance: - compaction_window: daily # valid only if this extension is declared -``` - -## Typed Resource And Provider Addresses - - - - -A locator is a typed address to another declared thing. **Internally β€” in plan and -state β€” every reference is a typed address** (axiom 9). At the config *surface* a -field may accept **bare shorthand when its schema fixes the referent kind** (a -policy `applies_to:` list is graph refs; a pipeline `into.graph` is a graph id) β€” -the parser normalizes it to the typed address before planning. A value whose -*kind* is ambiguous or wrong (a `source:` that could be a connector type, an -instance, or a provider) has no safe normalization and must be a typed -`provider.*` address or an explicit inline block. - -Target address forms: - -```text -graph. -schema. -query.. -policy. -ui.dashboard. -pipeline. -provider.storage. -provider.source. -provider.embedding. -``` - -Bad shape β€” the value's **kind is ambiguous or wrong**, not merely bare: - -```yaml -pipelines: - github_sync: - source: github # AMBIGUOUS kind: connector type, instance, or provider? - # β†’ provider.source. or inline { kind: github, ... } -policies: - base_rbac: - applies_to: [query.knowledge.find_experts] # WRONG kind: a query address in a graph-ref field -``` - -OK shorthand (kind fixed by the field β†’ normalized): - -```yaml -policies: - base_rbac: - applies_to: [knowledge, engineering] # bare names in a graph-ref field β†’ graph.knowledge, graph.engineering -``` - -Target shape: - -```yaml -providers: - storage: - prod_graphs: - kind: s3 - bucket: company - prefix: prod - source: - github_org: - kind: github - token: ${GITHUB_TOKEN} - -graphs: - knowledge: - storage: provider.storage.prod_graphs - path: graphs/knowledge.omni - schema: ./knowledge.pg - engineering: - storage: provider.storage.prod_graphs - path: graphs/engineering.omni - schema: ./engineering.pg - -policies: - base_rbac: - file: ./base_rbac.policy.yaml - applies_to: - - graph.knowledge - - graph.engineering - -pipelines: - github_sync: - source: provider.source.github_org - into: - - { graph: graph.engineering, map: ./github_to_engineering.map.yaml } - - { graph: graph.knowledge, map: ./github_to_people.map.yaml } -``` - - - -Validation rules: - -- A field that expects a graph address accepts `graph.`, not - `query..` or an arbitrary string. -- A field that expects a query address accepts `query..`, and the - planner validates both the graph and the query symbol. -- A field that expects a source provider accepts `provider.source.`, not - `provider.storage.`. -- A field that expects storage accepts `provider.storage.` or an explicit - storage block, not a server URL or source connector. - -- A field whose schema **fixes the kind** accepts bare shorthand (e.g. `knowledge` - in a graph-ref field) and normalizes it to the typed address; a kind-ambiguous - or wrong-kind value is rejected with a typed diagnostic. -- Plan and state always store the **normalized typed address**, regardless of - whether the surface used shorthand. - -## Target Components - -Preferred split: - -| Component | Responsibility | Depends on | -|---|---|---| -| `omnigraph-cluster` crate | Cluster spec types, path resolution, resource graph, plan model, state backend traits, apply orchestration | `omnigraph-config` only for shared simple config types if needed; avoid server deps | -| `omnigraph` engine additions | Graph lifecycle primitives, schema-apply integration, recovery hooks for graph moves during cluster apply; optional future cluster manifest publisher if JSON state is not enough | Lance, existing graph manifest/recovery | -| `omnigraph-cli` | `cluster *` commands, plan rendering, approval collection, state lock UX | `omnigraph-cluster`, engine | -| `omnigraph-server` | Optional boot from cluster state, registry reload, status endpoints, policy-filtered query catalog | `omnigraph-cluster`, engine, policy | -| `omnigraph-policy` | Cluster/server actions, per-query list/invoke scope, approval policy predicates | none above server | -| `omnigraph-queries` | Registry without exposure side-channel; dependency metadata for downstream validation | compiler/config | -| `omnigraph-api-types` | New status/plan/apply response types if cluster HTTP endpoints ship | serde only | - -If the first implementation avoids a new crate, keep the same boundary in -modules. The important constraint is that cluster spec parsing must not drag -HTTP/server code into compiler or engine crates. - -## Resource Model - -Resource identity is stable and typed: - -```text -ClusterRoot -ResourceKey = // -ResourceAddress = . | .. -ProviderAddress = provider.. - -graph/cluster/knowledge -schema/graph:knowledge/main -query/graph:knowledge/find_experts -policy/cluster/base_rbac -ui/cluster/dashboard.overview -pipeline/cluster/github_sync -alias/cluster/experts -embedding/cluster/default -``` - - - -Resource records carry: - -| Field | Meaning | -|---|---| -| `kind` | Graph, Schema, Query, PolicyBundle, UiSpec, Binding, Alias, EmbeddingConfig, Pipeline | -| `scope` | Cluster or graph id | -| `name` | Stable resource name inside scope | -| `fingerprint` | Content hash of the normalized spec and all referenced files | -| `dependencies` | Resource keys this resource references | -| `observed` | Applied graph manifest version, policy digest, query digest, schedule id, etc. | -| `status` | `Pending`, `Planned`, `Applying`, `Applied`, `Drifted`, `Blocked`, `Error` | -| `conditions` | Typed details such as `ActualAppliedStatePending`, `NeedsApproval`, `DependencyMissing`, `PartialPipelineRun` | - -The planner builds a dependency graph from these records and uses it for both -validation and blast-radius reporting. - -## Terraform-Style Validate / Plan / Apply - -The cluster workflow deliberately mirrors Terraform's safe sequence: - -```text -cluster validate # parse + schema-check desired config, no state mutation -cluster plan # diff desired config against state, with optional refresh -cluster apply # apply an accepted fresh plan and update state -cluster status # read state-backed deployed reality -cluster refresh # repair/import observations from actual cluster state -``` - -Implementation rollout follows the same safety posture: ship parser/validate -first, then read-only plan, then state backend and lock, then apply. - -The plan is a structured artifact, not just terminal text. It must include: - -| Plan field | Why it exists | -|---|---| -| `desired_revision` | Git commit / config digest being evaluated | -| `resource_digests` | Exact digest of every schema, query, policy, UI, pipeline, and map file | -| `dependencies` | Edges such as query -> graph/schema, dashboard -> query, pipeline -> source provider + graph | -| `state_observations` | Applied revision, resource fingerprints, graph manifest versions, status conditions, and drift | -| `changes` | Create/update/delete/replace/refresh-only operations | -| `blast_radius` | Downstream resources to revalidate or affected behavior to surface | -| `approvals_required` | Irreversible/data-loss or compatibility-narrowing gates | - -`cluster apply` must reject a stale plan when state, resource digests, or -observed graph versions no longer match the plan base. The operator or agent -must re-plan or explicitly refresh first. - -## Cluster Storage Layout - -Target Phase-1 cluster-root layout: - -```text -/ - __cluster/ - state.json - lock.json - status/ - .json - approvals/ - .json - recoveries/ - .json - resources/ - query///.gq - policy//.yaml - ui//.dashboard.yaml - pipeline//.pipeline.yaml - graphs/ - .omni/ -``` - - -The exact filenames can change, but the shape cannot: - -- There is one cluster-control namespace under the cluster root. -- Graph data remains in ordinary OmniGraph graph roots. -- State is a locked/CAS-updated JSON document, not a Lance dataset. -- Status, approval, and recovery ledgers are append-only or per-resource JSON - records until table semantics are proven necessary. -- Resource payloads are content-addressed by digest so apply can be idempotent. -- Cluster state is not inferred from the operator's working tree. -- A Lance-backed control-plane store is a future backend option only if - row-level queryability/history or tighter publish fencing justifies it. - -## State Backend Protocol - -### Cluster-Hosted JSON State - -When `state.backend: cluster`, the baseline backend stores JSON documents under -`/__cluster/` and protects `state.json` with object-store lock/CAS. -It is cluster-hosted, but it is still a separate state write from graph Lance -manifest movement. - -Apply protocol: - -1. Acquire the cluster state lock. -2. Read current `state.json` and backend CAS token / object generation. -3. Validate plan base still matches state. -4. Write a cluster recovery sidecar before any graph manifest or non-idempotent - resource can move. -5. Write content-addressed resource payloads and perform any required graph - manifest movements. -6. CAS-update `state.json` with the new applied revision, resource - fingerprints, observed graph versions, status references, and approval / - recovery references. -7. If step 6 fails after actual resources moved, do not acknowledge success. - Surface `ActualAppliedStatePending` and require `refresh` / `import` repair. -8. Delete the sidecar and release the lock only after the state outcome is - recorded. - -### External State - - - -When `state.backend` points outside the cluster root, the same JSON state shape -lives in an external store. It is locked and CAS-updated, but it is not atomic -with Lance or OmniGraph manifests. - -Apply protocol: - -1. Acquire the external state lock. -2. Read state and CAS token. -3. Validate plan base still matches state. -4. Write a cluster recovery sidecar. -5. Perform the cluster resource changes. -6. CAS-update external state with the new applied revision, statuses, and the - observed graph manifest / resource versions it records. -7. If step 6 fails, do not acknowledge success. Surface - `ActualAppliedStatePending` and require `refresh` / `import` repair. -8. Release the external lock only after the state outcome is recorded. - -This mode can be strongly coordinated, but it must never be documented as one -atomic commit across both stores. - -### Future Lance-Backed State - -A Lance-backed state/status/approval/recovery store is deliberately not the -baseline. It becomes attractive only if JSON files become a real liability: -large status sets need structured filtering, approval/recovery history needs -table scans, or cluster apply needs a manifest publisher that can fence state -and graph-version pins together. Until then, Lance datasets add bootstrapping, -schema migration, and control-plane recovery surface without enough benefit. - -## Cluster Manifest Publisher - -The cluster publisher is a possible later layer above today's graph publisher. -It does not replace Lance or the per-graph `__manifest` table, and it is not -required for Phase-1 JSON state / read-only plan. - -Required semantics: - -| Requirement | Detail | -|---|---| -| Expected-version CAS | Every resource in an apply group supplies its expected current version/fingerprint | -| Resource changes | Register/update/tombstone resource payloads and graph version pins | -| Graph-head fencing | If a graph schema/lifecycle operation moves a graph manifest, the cluster manifest records the exact graph manifest version | -| Sidecar coverage | Any graph or cluster resource that can move before cluster publish must be recoverable all-or-nothing | -| Deterministic publish order | Sidecars and apply groups process in stable order | -| Loud partials | If a group cannot be rolled back or forward in-process, status records the condition before more apply work proceeds | - -The risky case is nested publish: - -```text -schema apply moves graph:knowledge manifest -cluster apply has not yet published query/policy/state records -process crashes -``` - -That is not safe unless the cluster sidecar records enough information to roll -the graph movement forward into the cluster manifest or roll it back using the -same recovery discipline as current graph recovery. - -## Plan Model - -Plan output is a durable, replay-checked proposal, not just pretty text: - -```text -Plan { - plan_id, - desired_revision, - base_state_revision, - base_state_cas, - changes[], - apply_groups[], - approvals_required[], - blast_radius, - diagnostics[] -} -``` - -Each change records: - -| Field | Meaning | -|---|---| -| `resource` | Stable `ResourceKey` | -| `operation` | Create, Update, Delete, Replace, RefreshOnly | -| `reversibility` | Reversible, Recoverable, CompatibilityNarrowing, IrreversibleDataLoss | -| `effect` | ConfigOnly, Catalog, GraphDefinition, GraphDataRewrite, DataPlaneSchedule | -| `downstream` | Resources that must be revalidated or will observe changed behavior | -| `approval` | None, HumanRequired, PolicyRequired, AlreadySatisfied | - -`apply` must re-read state and reject stale plans unless an explicit -`--refresh` / `--replan` path recomputes the plan. - -## Downstream Dependency Rules - -These are the concrete "what requires downstream" rules. - -| Changed resource | Must revalidate / recompute downstream | Blocking failures | -|---|---|---| -| Graph create/delete/rename | Policies, queries, aliases, dashboards, pipelines, bindings, server registry, state graph set | Dangling graph references; duplicate URI; invalid `GraphId`; graph delete without irreversible approval | -| Schema | Stored queries, pipeline maps, UI bindings/query outputs, embedding/index config, data-impact preview, policy predicates once row/type pushdown exists | Unsupported migration; query breakage; missing target type/property; hard drop without approval | -| Stored query | Aliases, UI bindings, policy list/invoke grants, MCP/tool catalog compatibility, typed params | Query file parse/type errors; registry key != `query `; removed query still referenced | -| Policy bundle | Query catalog visibility, graph/server action authorization, approval gates, bootstrap permissions | Invalid Cedar/YAML; server-scoped action in graph policy; per-query list/invoke gap unhandled | -| UI/dashboard | Query bindings, graph refs, output field expectations, policy visibility for referenced queries | Binding to missing graph/query/param/output | -| Alias | CLI command resolution, graph/query refs, shared-vs-personal boundary | Dangling graph/query; mutation alias pointing at read-only context | -| Embedding config | Schema `@embed` columns, model dimension, index rebuild/reconcile, env refs | Dimension mismatch; missing env ref; unsupported model/provider | -| Pipeline definition | Target graph schemas, mapping files, env refs, scheduler/runtime state, per-target run ledger | Missing target graph/type/property; overwrite mode without approval; source secret missing | -| Binding | Referenced source/surface pair, dependency order, visibility policy | Missing source or target; incompatible params | -| State backend config | Lock implementation, import/refresh protocol, apply acknowledgements | Backend missing CAS/lock; state CAS failure after graph/resource movement | - -## Blast Radius Matrix - -| Area | Required downstream change | Blast radius | Notes | -|---|---|---|---| -| Config parsing | Add strict `cluster.yaml` parser, path/env-ref resolver, resource fingerprints, no layered merge | High | Separate from `OmnigraphConfig`; existing config tests still need backcompat coverage | -| CLI | Add `cluster validate/plan/apply/status/refresh/import`, plan rendering, approval flags, actor threading | High | Must not change existing command selection or `omnigraph use` behavior | -| State backend | Add JSON state document, status/approval/recovery records, lock/CAS, and import/refresh repair | High | Must not silently succeed after state CAS failure | -| Optional cluster publisher | Add a cluster manifest plus table-backed state/status store only if stronger all-or-nothing apply is required | Very high | Touches core atomicity and recovery invariants | -| Recovery | Add cluster sidecars and failpoint coverage for graph-move-before-state-publish gaps | Very high | Any missed sidecar is a correctness bug | -| Graph lifecycle | First-class graph resource create/delete/rename or stable-id story | High | Current server add/remove is intentionally not exposed | -| Schema apply integration | Make schema apply cluster-aware or wrap it with cluster recovery | High | Existing schema apply cannot be treated as cluster atomic by assertion | -| Query registry | Remove target-state exposure flag, add dependency metadata, keep `mcp.expose` bridge | Medium/high | Catalog behavior is observable public API | -| Policy | Add cluster plan/apply/admin actions and per-query list/invoke scope | High | Needs docs, tests, Cedar schema migration, and compatibility with coarse `invoke_query` | -| Server registry | Boot from cluster state, eventually reload/reconcile graph handles, expose statuses | High | Affects routing, OpenAPI, auth, and workload admission | -| API types/OpenAPI | Plan/status/apply DTOs if HTTP management endpoints ship | Medium/high | OpenAPI drift must be regenerated | -| UI specs | New renderer/spec validator/binding checker | High | New product surface, not currently implemented | -| Pipelines | New scheduler/runtime/connector/mapping/idempotency/run ledger | Very high | **Separate project** (socket reserved here); second data-plane seam, large product and correctness surface | -| Embeddings | Cluster-level defaults, env refs, model/dimension validation, index interaction | Medium | Existing embedding code is mostly offline/client-side | -| Docs | User docs for cluster config, policy, server, CLI; dev docs for invariants/testing | High | Public contract changes | -| Tests | New cluster suites plus extensions to config/server/policy/recovery/schema/query tests | High | Needs boundary-matched coverage | - -## Reversibility And Approval Tiers - -| Tier | Examples | Gate | -|---|---|---| -| Display-only | Dashboard layout, non-breaking alias addition | No approval beyond policy | -| Catalog behavior | Add query, hide/list query via policy, add policy grant | Policy check; no data-loss approval | -| Compatibility narrowing | Future validated enum narrowing, query param removal, policy removal that revokes access | Explicit compatibility warning; may require human approval by policy | -| Recoverable definition rewrite | Soft schema drop, graph schema rename, index rebuild | Plan warning; no data-loss approval unless policy requires | -| Irreversible data loss | Graph delete, hard schema drop, cleanup-triggered prior-version reclamation, overwriting pipeline target | Human approval artifact recorded in audit ledger | - -Future enum narrowing belongs in `CompatibilityNarrowing` unless the migration -also drops/coerces data or triggers cleanup. That distinction matters for plan -wording and for policy predicates. - -## Rollout Phases - - - -### Phase 0: Documentation And Parser Skeleton - -- Add cluster spec types and strict parser behind an unused feature/module. -- Implement `cluster validate --config ` with no state backend. -- Validate file paths, env refs, duplicate resource keys, and dependency graph. -- No behavior change to `omnigraph.yaml`, server boot, or query exposure. - -### Phase 1: Read-Only Planning - -- Add `cluster plan` against a mock/imported state snapshot. -- Produce plan JSON and human output. -- Reuse existing schema migration planner for schema resources. -- Validate stored queries against desired schema. -- Compute downstream dependencies and blast radius. -- Still no apply. - -### Phase 2: State Backend And Lock - -- Add `state.backend: cluster` JSON storage and lock/CAS. -- Add external backend trait only if lock + CAS semantics are explicit. -- Add `cluster status`, `refresh`, and `import`. -- Persist `AppliedRevision`, `ResourceStatus`, and audit references in JSON. - -### Phase 3: Config-Only Apply - -- Apply query, policy, UI, alias, embedding, and pipeline definition resources - that do not move graph manifests. -- Publish by writing content-addressed resource payloads and CAS-updating - `state.json`. -- Keep server boot from `omnigraph.yaml`; cluster state is inspectable but not - yet serving traffic. - -### Phase 4: Graph And Schema Apply - -Detailed design: [rfc-004-cluster-graph-schema-apply.md](rfc-004-cluster-graph-schema-apply.md) -(cluster sidecar schema, roll-forward-only recovery matrix, approval artifacts, -actor threading, 4A/4B/4C staging). - -- Add graph create/delete as cluster resources. -- Make schema apply cluster-aware, with sidecar coverage for graph manifest - movements before JSON state publish. -- Gate irreversible data-loss operations with approval artifacts. -- Consider a cluster manifest publisher only if the JSON sidecar + repair path - is not strong enough for the accepted safety contract. - -### Phase 5: Server Reads Cluster Catalog - -Detailed design: [rfc-005-server-cluster-boot.md](rfc-005-server-cluster-boot.md) -(the --cluster mode switch, applied-revision serving, serving metadata in -state, readiness table, migration path). - -- Allow server startup from cluster state. -- Add status and catalog endpoints as needed. -- Keep the current `omnigraph.yaml` startup path as compatibility mode β€” an - **exclusive mode switch** per deployment (cluster state XOR `omnigraph.yaml`), - never a merged read of both (Compatibility Stance #7, axiom 15). -- Regenerate OpenAPI for any HTTP surface. - -### Phase 6: Policy-Owned Query Exposure - -- Add per-query policy scope for list/invoke. -- Filter `GET /queries` by actor. -- Keep coarse `invoke_query` as a broad allow rule for compatibility until - docs and migrations say it can be narrowed. -- Deprecate and later remove `mcp.expose` from target-state cluster config. - -### Pipelines: separate project (socket only) - -Pipelines are **descoped from this rollout** (2026-06-10): the runtime -(scheduler/worker, connector contracts, mapping validation, idempotency keys, -per-target run status, retry behavior) is a separate project with its own -RFC. This rollout guarantees only the socket: - -- `pipelines:` stays a reserved config field, rejected with a typed - `future_phase_field` diagnostic (enforced + test-covered in - `omnigraph-cluster`). -- `pipeline.` stays a reserved typed address; the resource model - (kind-agnostic state entries, extensible sidecar kinds, dependency edges) - accepts the new kind without reshaping. -- Axiom 13 is the contract the future implementation must satisfy: the - definition is reconciled, the execution is data-plane; fan-out is statusful, - never silently atomic. - -## Test Ownership - -Tests must prove the Terraform-style workflow, not just individual parsers. -The minimum behavior contract: - -```text -validate catches bad config -plan is deterministic and complete -apply only applies a fresh accepted plan -state changes are locked and durable -drift and partial convergence are visible, not silent -``` - -| Change | Existing coverage to extend | New coverage likely needed | -|---|---|---| -| Cluster parser | `omnigraph-config` inline config tests for strictness/path resolution | `omnigraph-cluster` parser/dependency tests | -| Plan dependency graph | Schema planner tests, query registry tests | Golden plan JSON for cross-resource downstream impacts | -| State lock/backend | Existing schema apply lock tests as model | JSON state CAS/lock race tests | -| Optional cluster manifest publisher | `crates/omnigraph/src/db/manifest/tests.rs` | Cluster publisher CAS, expected-version, deterministic order tests if that backend ships | -| Cluster recovery | `recovery.rs`, `failpoints.rs` | Phase B -> state publish failpoints, external state CAS failure tests | -| Schema cluster apply | `schema_apply.rs`, failpoints schema apply cases | Nested graph/cluster recovery tests | -| Query exposure policy | `omnigraph-policy` invoke_query tests, server query catalog tests | Per-query list/invoke allow/deny and no-probing tests | -| Server cluster boot | `omnigraph-server/tests/server.rs`, `openapi.rs` | Boot from cluster state, registry reload/status tests | -| CLI cluster commands | `omnigraph-cli/tests/cli.rs`, `system_local.rs` | `cluster validate/plan/apply/status` system tests | -| Pipelines | None today | New runtime/mapping/idempotency/run-ledger suites | - -Workflow-specific tests: - -| Workflow area | Required assertions | -|---|---| -| Parser / validate | Unknown fields, wrong-kind typed addresses, missing providers, inline secret values, dangling graph/query/pipeline refs, and future-phase fields fail with typed diagnostics | -| Plan goldens | Given config + imported/fake state, plan JSON contains stable resource digests, dependency edges, state observations, proposed changes, blast radius, and approval gates in deterministic order | -| Fresh-plan apply | Changing config digest, state revision, resource digest, or observed graph manifest version after planning makes `cluster apply` reject and require re-plan/refresh | -| State lock / CAS | Concurrent applies against the same backend cannot both succeed; loser gets a typed lock/CAS conflict | -| Recovery / partial apply | Fail after graph/resource movement but before cluster state publish; assert recovery or status surfaces `ActualAppliedStatePending`/sidecar state and never returns success | -| Server/runtime phase | Before cluster state drives routing or registry reload, tests are hermetic: no real home dir, no real global config, no real credentials, no ignored remote tests | -| Pipeline phase | Fan-out run records per-target status, commit ids, retryability, and idempotency keys; no aggregate success unless every target succeeded | - -Hard gates: - -- Do not ship `cluster apply` until `cluster validate` and read-only - `cluster plan` have hermetic tests. -- Do not ship graph/schema-moving apply until failpoint recovery tests prove the - Phase B -> state publish gap is covered. (Stage 3B delivered the apply-side - half: `omnigraph-cluster` has failpoint infrastructure and tests for the - crash-after-payload and state-CAS-race windows of config-only apply, plus - catalog payload verification in status/refresh. Graph-moving sidecar - coverage remains Phase 4 work.) - -For docs-only changes, `scripts/check-agents-md.sh` is enough. For -implementation phases, run the boundary tests above before widening to -`cargo test --workspace --locked`. - -## User-Visible Documentation Fallout - -The following public docs must change when the corresponding phase ships: - -| Phase | User docs | -|---|---| -| Parser/validate | New `docs/user/cluster-config.md`; CLI reference for `cluster validate` | -| Plan/apply | CLI reference, transactions, policy, errors | -| State backend | Storage, deployment, constants, maintenance | -| Server cluster boot | Server, deployment, OpenAPI | -| Policy query exposure | Policy, server, query language / stored-query registry docs | -| Pipelines | New pipeline user guide, deployment, audit, errors | -| Embeddings config | Embeddings, indexes | - -Do not ship a user-visible command, flag, env var, endpoint, or config key -without updating the corresponding user doc in the same PR. - -## Known High-Risk Design Decisions - -1. **Cluster root identity.** Decide whether `metadata.name` is a label or - identity. Prefer root-derived stable identity plus display name to avoid a - rename breaking resource identity. -2. **Graph storage derivation.** The high-level sample omits graph storage. - Implementation should derive graph roots under `ClusterRoot/graphs/.omni` - by default and treat external graph roots as a separate, explicit feature. -3. **Nested apply.** Schema apply and graph lifecycle cannot move a graph - manifest outside cluster sidecar coverage. -4. **External state.** Must expose pending repair instead of returning success - when graph/resource movement succeeds and external state CAS fails. -5. **Per-query policy.** Catalog filtering must avoid probing leaks: callers - without list/invoke permission should not distinguish hidden from missing. -6. **Pipeline fan-out.** Do not promise atomic multi-graph ingestion unless the - runtime uses a real branch/merge or equivalent protocol for every target. -7. **Drift correction.** Reconciler-initiated deletes are the same data-loss - class as human-requested deletes. - -## Exit Criteria For A Real RFC - -Before implementation begins beyond parser/validate, the RFC must answer: - -1. Exact JSON state/status/approval/recovery schemas and object-store paths. -2. Exact sidecar JSON schema and recovery decision matrix. -3. State backend interface and supported lock/CAS implementations. -4. Cluster apply group syntax and dependency ordering rules. -5. Plan JSON schema, including blast-radius and approval fields. -6. Bootstrap authority and first-actor story. -7. Server startup and migration path from `omnigraph.yaml`. -8. Per-query policy schema and compatibility bridge for `mcp.expose`. -9. Pipeline runtime owner, status schema, and idempotency contract β€” **deferred to the separate pipelines project's own RFC**; this rollout only reserves the socket. diff --git a/docs/dev/cluster-config-specs.md b/docs/dev/cluster-config-specs.md deleted file mode 100644 index d248be2..0000000 --- a/docs/dev/cluster-config-specs.md +++ /dev/null @@ -1,496 +0,0 @@ -# Cluster Config Spec β€” Declarative, As-Code, Agent-Operated - -**Status:** Draft / thinking-in-progress -**Type:** Architecture direction -**Date:** 2026-06-07 -**Relationship:** generalizes today's `omnigraph.yaml` graph/query/policy configuration surface ([CLI reference](../user/cli-reference.md), [server docs](../user/server.md)) into a future cluster control plane. The distilled rules are in [cluster-axioms.md](cluster-axioms.md); detailed downstream implementation spec and blast-radius assessment in [cluster-config-implementation-spec.md](cluster-config-implementation-spec.md). This is a proposed architecture, not an implemented RFC. - -> **Implementation status.** The examples below describe the full target schema. -> Stage 2B only accepts the read-only subset documented in -> [cluster-config.md](../user/cluster-config.md). Future-phase fields such as -> `env_file`, `apply`, `providers`, `pipelines`, `embeddings`, `ui`, `aliases`, -> and `bindings` are intentionally rejected with typed diagnostics until their -> reconciler semantics are implemented. - -> **Revision 2026-06-07 β€” full commitment to the Terraform paradigm.** Three changes from the earlier draft: (1) **state is an authoritative, locked ledger in a backend** (server-hosted *or* a separate cloud store), not "a mostly-rebuildable projection"; (2) `plan` is framed as the **CLI diff between local config and state**; (3) **ETL pipelines** (external data sources) are a first-class config asset β€” a second seam, alongside schema, where a definition triggers a data-plane effect. The full set of config assets (incl. **aliases**, **embeddings**) is enumerated below. - ---- - -## The problem (the Sarah/Bob test) - -Two operators, Sarah and Bob, administer the same OmniGraph deployment. Sarah adds new queries, changes a schema, adds a dashboard, updates policies, and wires in a new data feed. - -**How does Bob find out?** - -Today he can't β€” not cleanly. Sarah's changes land in many different places via many different mechanisms: - -- schema β†’ the schema-apply path, accepted state in `_schema.pg`, `_schema.ir.json`, `__schema_state.json`, and table versions in the graph manifest -- queries β†’ `.gq` files passed per request or resolved through CLI query roots / aliases; not durable cluster state -- policies β†’ `policy.file` in `omnigraph.yaml`, pointing at Cedar/YAML files that are usually GitOps'd externally -- aliases β†’ CLI sugar in each operator's `omnigraph.yaml` -- external data β†’ ad-hoc `load`/`ingest` scripts, cron jobs, glue code that lives nowhere durable -- UI β†’ undefined - -There is no single diff that spans them, no single change record attributed to Sarah, no one place Bob (or Bob's agent) reads to answer "what is this deployment, and what changed?" The state is **fragmented**, and fragmentation is hostile to the one thing an agent must do: reason over the system *as a whole*. - -A design passes only if it answers the Sarah/Bob test directly. - ---- - -## Thesis - -The unit of declarative state is the **cluster** (the deployment), described by **a single config, as code, in version control**, operated by an **agent** through a plan/apply/reconcile loop against an authoritative state ledger. - -Every surface is a declarative as-code artifact β€” schema (`.pg`), queries (`.gq`), policies (`.yaml`), UI (`.yaml`), aliases, **ETL pipelines**, and embeddings config. The UI is not a separately-deployed application; it is a declarative spec, a first-class resource reconciled exactly like the others. - -Three pillars, none optional: - -1. **DECLARATIVE** β€” you describe the desired end state, not the steps. The reconciler computes the steps. -2. **AS CODE** β€” the config is declarative text in a repo, version-controlled. This is the **source of truth for *intent***. -3. **OPERATED BY AGENT** β€” an agent authors config changes and drives reconciliation as an authenticated actor, with policy and approval gates. No human state-management burden. - -This is **Terraform's model, taken literally**: config (as code) is desired truth; **state is an authoritative, locked ledger** of what has been applied β€” held in a backend (the cluster, or a separate cloud store); `plan` diffs config against state; `apply` converges reality to config and updates state β€” applied at **cluster** scope, with OmniGraph as its own data-aware provider and an agent as the controller. - ---- - -## Why as-code (the recursion argument) - -"As code" is not branding. It is the structural property that makes a self-describing system well-founded. - -Consider the rejected alternative: model the cluster's definition *as a graph* (a meta-graph whose nodes are graphs/policies/queries/UI). To describe a graph you need a schema. The meta-graph's schema is either: - -- **hardcoded** β†’ the base case is *code* (you smuggled code in at the bottom anyway), or -- **another graph** β†’ infinite regress, no base case. - -Graph-describing-graph never terminates. **Code is the base case.** A declarative config needs no meta-describer because it is parsed by the engine's compiled code β€” not described by more user-space data. - -> **Declarative-as-code terminates. Declarative-as-data (a graph of graphs) recurses.** - -This is also why **config** must live **outside** the running system: reviewable (PRs), reproducible (clone + apply), diffable as text, and editable by an agent β€” without depending on the running system to describe its own intent. - -Corollary on direction: change flows **code β†’ cluster, never the reverse.** You do not edit the running system and call that intent. (State, separately, *records* what the cluster currently is β€” see the next section β€” but it is never where you express what it *should* be.) - ---- - -## Why per-cluster, not per-graph - -The definition Sarah changed does not *belong* to any single graph: - -1. **Policies cross-cut graphs.** "Member can't delete on any graph," "who may list/create/delete graphs" β€” cluster facts. No graph could own them. -2. **"Which graphs exist" has no home in a per-graph model.** The set of graphs is state *above* any graph. -3. **Queries, UI, pipelines, and aliases span graphs.** The MCP/tool catalog an agent discovers is the *cluster's* surface; a dashboard renders multiple graphs; a pipeline may fan out into several. -4. **Cross-graph apply groups.** Sarah may add a graph *and* wire it into the UI *and* grant policy access *and* attach a feed as one logical change β€” only the cluster can express, plan, and eventually fence that as one apply group. -5. **Operators operate clusters.** Bob is Sarah's peer on a *deployment*, not a graph. The collaboration unit is the cluster. - -The graph is a *resource within* the cluster, not the unit of operation. - -The mirror question β€” *why not per-fleet?* β€” is the same one this section used against per-graph, one level up. A fleet of clusters may eventually want its own declarative spec describing which clusters exist. That recursion is real but **out of scope here**: this proposal stops at the cluster because the cluster is the unit two operators collaborate over. Fleet is the next scope up, named and deferred, not denied. - ---- - -## The model: config / state / reconcile (the Terraform model, literally) - -| Layer | What it is | Source of truth for… | Who manages it | -|---|---|---|---| -| **Config** (as code, a folder of files) | Desired state of the whole cluster β€” graphs, schemas, policies, queries, UI, bindings, aliases, embeddings, ETL pipelines | **Intent** ("what it should be") | Operators/agents, in version control | -| **State** (a locked ledger in a backend) | The authoritative record of what has been applied β€” applied revision, per-resource fingerprints, observed graph/table versions, audit-record references, resource conditions | **Deployed reality** ("what is") | The reconciler; humans don't hand-edit it | -| **Actual cluster** | The realized *definition* of the running graphs β€” schema/policies/queries/UI/pipelines as actually in force | β€” (reality itself) | The engine; `apply` converges it to config | - -**`plan`** = `diff(config, state)` β†’ proposed change set (optionally refreshed against the actual cluster). -**`apply`** = acquire the state lock β†’ converge actual β†’ config β†’ **update state** β†’ release lock. Apply does **not** acknowledge success until the state update succeeds; if actual moved but the state write failed, the next `plan` / `refresh` must surface the non-success state and repair or import it before more work proceeds. - -### State is an authoritative, locked ledger β€” not a throwaway projection - -This is the 2026-06-07 revision. State is treated exactly as Terraform treats `tfstate`: - -- **Authoritative.** State is the trusted record of what is deployed. `plan` diffs config against **state** (fast, deterministic), not against a full live scan of the cluster on every command. "What exists" is answered from state. -- **In a backend.** State lives in a configurable backend: the **cluster's own object-store backend**, or a **separate cloud store** (e.g. a different bucket/account) β€” the operator's choice, mirroring Terraform's local/S3/remote backends. The config declares which. -- **JSON first.** The baseline state format is Terraform-style JSON documents (`state.json` plus status/approval/recovery JSON records) protected by backend lock/CAS. Lance control-plane datasets are a possible later backend only if row-level history, queryability, or tighter publish fencing justifies the added machinery. -- **Atomicity depends on backend and publish scope.** A JSON state backend, even when stored under the cluster root, is a separate CAS step from graph Lance manifest moves. If actual resources move but the state write fails, apply must surface `ActualAppliedStatePending` (or equivalent) and require refresh/import repair instead of pretending one atomic commit covered every object. A future Lance-backed state backend or cluster manifest publisher may tighten this, but that is not the Phase-1 assumption. -- **Locked.** `plan`/`apply` acquire a **state lock** before touching state, so two operators (or two agents) cannot converge concurrently and corrupt the ledger. This generalizes the existing `__schema_apply_lock__` from schema scope to cluster scope. -- **Reconstructable, but not casually rebuilt.** OmniGraph's edge over opaque-cloud Terraform: the running cluster is self-describing (manifests, commit logs), so a lost state ledger can be **imported / refreshed** from the live cluster. That is a *resilience* property β€” not licence to treat state as disposable. State is protected and backed up like any source of truth. -- **One slice is never reconstructable.** Who *approved* an irreversible apply cannot be re-derived from a manifest scan. That approval/audit record lives in the **durable audit ledger** (baseline: append-only JSON records in the state backend; future: a Lance table only if needed). State *references* it by id; it never *is* it. - -**The control plane reconciles definition, not data.** The reconcile loop converges the cluster's *definition* β€” schema, policies, queries, UI, bindings, aliases, pipelines, and the set of graphs. It does **not** converge **data**: rows, edges, and vectors are data-plane content, mutated by `load`/`mutate` and by **pipeline execution**, versioned by the commit DAG, and they sit entirely outside the reconcile loop. (`load`/`mutate` never appear in `cluster.yaml`.) **Two** definition kinds *trigger* a data-plane effect without owning data β€” schema and ETL pipelines (see "ETL pipelines" below). - -### Cluster resource model - -Minimum vocabulary: - -- **ClusterRoot** β€” the object-store prefix / control namespace for one deployment. -- **DesiredRevision** β€” git commit, `cluster.yaml` digest, and per-resource digests. -- **ResourceKind** β€” `Graph`, `Schema`, `Query`, `PolicyBundle`, `UiSpec`, `Binding`, `Alias`, `EmbeddingConfig`, **`Pipeline`** (ETL), and future cluster-scoped resources. -- **ResourceAddress** β€” normalized typed references between resources, such as `graph.knowledge`, `query.knowledge.find_experts`, `policy.base_rbac`, and `pipeline.github_sync`; illustrative YAML may use shorthand, but plan/state store the typed form. -- **ProviderAddress** β€” typed references to provider instances, such as `provider.storage.prod_graphs`, `provider.source.github_org`, and `provider.embedding.default`; provider addresses keep storage, external sources, and embedding providers from being inferred from ambiguous strings. -- **StateBackend** β€” where the JSON state ledger is stored: `cluster` (this deployment's own backend) or an external store (a separate bucket/account). -- **StateLock** β€” the cluster-scope lock acquired before plan/apply. -- **AppliedRevision** β€” the durable, locked record (the heart of state) of which desired revision is applied, with audit-record references, resource fingerprints, and graph/table version observations. -- **ResourceStatus** β€” `Pending | Planned | Applying | Applied | Drifted | Blocked | Error`, with typed conditions and observed actual state. -- **ApplyGroup** β€” the explicit atomicity unit. Default is one independent resource per group; cross-resource references force planner-derived groups, and user-declared groups may opt into larger atomicity only for resources the active backend protocol can fence or repair. Baseline JSON state supports small, explicit groups; larger all-or-nothing groups require a future cluster publisher or equivalent proof. - ---- - -## State: backend, lock, and the config ↔ state diff - -The CLI is the operator's window onto the gap between config and state. - -The Terraform-aligned workflow is: - -```text -cluster validate # parse + schema-check desired config, no state mutation -cluster plan # diff desired config against state, with optional refresh -cluster apply # apply an accepted fresh plan and update state -cluster status # read what state says is deployed now -cluster refresh # update/import state observations from actual cluster state -``` - -`plan` is the central artifact. It records the desired revision, resource -digests for every referenced file, dependency edges between resources, observed -state fingerprints / graph manifest versions, proposed changes, and approval -gates. The human output below is a rendering of that structured plan, not the -only representation. - -``` - $ omnigraph cluster plan - config ./ β†’ diff against state (backend: cluster Β· lock: acquired) - - ~ schema knowledge hard-drop Person.legacy_id ⚠ prior versions reclaimed β€” needs approval - + query knowledge.find_experts (new stored query) - - query knowledge.orphan_pages (removed) - ~ policy base_rbac grant invoke find_experts β†’ members (this is what EXPOSES the new query) - + pipeline saas_sync notion β†’ knowledge, hourly - ~ ui dashboards.overview add panel "experts" - + alias experts - ───────────────────────────────────────────────────────────────────── - 6 changes Β· 1 requires approval (hard schema drop on knowledge) Β· run `apply` to converge -``` - - -That output **is** the answer to the Sarah/Bob test: one diff, spanning every surface, attributed to a git commit and concrete resource digests, with data-impact peeked (axiom-6 schema seam), dependency fallout visible, observed state compared, and approval gates surfaced *before* anything moves. Drift (someone poked the live cluster out-of-band) shows up here too β€” `plan` reconciles state against the actual cluster and flags resources whose observed version no longer matches the ledger. - - -`apply` then: acquire **state lock** β†’ execute the change set (ordered/grouped per the planner) β†’ **CAS-update the JSON state ledger** with the new applied revision/status observations β†’ release the lock. For config-only resources, content-addressed payload writes can happen before the state CAS because state is the publish point. For graph/schema moves, the graph manifest may move before the state CAS; a crash or CAS failure there leaves a loud repair/import condition and no success acknowledgement, not a silently successful atomic apply. A future cluster manifest publisher can tighten this gap, but the baseline protocol does not assume it. - ---- - -## ETL pipelines (the second data-plane seam) - -> **Scope note (2026-06-10): descoped to a separate project.** Pipelines are -> a product surface of their own (scheduler, connectors, mapping language, -> idempotency, run ledger) and will be designed and built outside the cluster -> control-plane track. What this spec retains is the **socket** they plug -> into, which is already enforced: (1) the `pipelines:` config field is -> reserved β€” `cluster validate` rejects it with a typed `future_phase_field` -> diagnostic, so it can never be silently squatted; (2) the typed address -> form `pipeline.` and the `Pipeline` resource kind are reserved in the -> resource model; (3) axiom 13 fixes the contract any future implementation -> must satisfy β€” the pipeline *definition* is a reconciled cluster resource, -> its *execution* is data-plane and never reconciled. The design text below -> stands as the requirements record for that project, not as a phase of this -> one. - - -External data β€” from another database, an API, a file drop, a stream β€” is a first-class config asset, not glue code that lives nowhere. - -A **Pipeline** is declared in config: a **source** (e.g. `notion`, `github`, `slack`, `gdrive`, `postgres`, `http`, `s3-files`, `kafka`), an optional **schedule/trigger**, and **one or more target graphs**, each with its own **mapping/transform** (external records β†’ graph types & properties). A single feed can **fan out across graphs** β€” e.g. a GitHub sync that populates both the `engineering` graph and the people/teams in `knowledge`. It is reconciled like any resource β€” `apply` creates / updates / deletes / (re)schedules the pipeline *definition*. This is the canonical "company brain" move: the deployment's graphs are continuously assembled from the SaaS tools the org already uses. - -The crucial boundary (axiom 6, axiom 13): the pipeline **definition** is control-plane and reconciled; the pipeline's **execution** β€” actually pulling rows and writing them β€” is a **data-plane effect** that produces ordinary `load`/`mutate` commits *outside* the reconcile loop. The reconciler converges the pipeline; the rows it ingests are never reconciled state (just as a cron *definition* is config but its output is not). This makes ETL the **second seam** where a definition triggers a data-plane effect β€” schema being the first (a migration conforms existing rows; ETL ingests new ones). - -Consequences that fall out of the existing model: - -- **`plan` previews the pipeline, not the data.** "pipeline `saas_sync`: notion β†’ `knowledge`, hourly" is a definition diff; it does not scan the source (data-volume-independent), the same way schema `plan` previews impact only at the bounded, opt-in data peek. -- **Source credentials come from the `.env` file** (axiom 10): `token: ${NOTION_TOKEN}` β€” resolved from the gitignored `.env` file per deployment, never inline. -- **Reversibility gradient applies** (axiom 8): a pipeline that *appends* is reversible-ish; one configured to *overwrite* a target is a data-loss path and hits the irreversible-op gate. -- **Referential integrity is plan-time** (axiom 9): a pipeline whose `into:` names a graph/type the same revision removes is a fail-closed `plan` error. -- **Fan-out is statusful, not magically atomic.** A pipeline execution that writes to several graphs is a set of ordinary per-target graph writes unless the pipeline explicitly stages through a branch/merge protocol that can fence those targets. A failed run may therefore leave `engineering=Applied`, `knowledge=Error` (for example), and the pipeline run ledger must expose per-target status, commit ids, retryability, and idempotency keys. Control-plane `apply` only converges the definition/schedule; it never means every future data-plane target has ingested successfully. - ---- - -## Config assets β€” the full set - -Everything below is **shared cluster config** (in the folder, version-controlled, secret-free) unless marked per-operator. The rule of thumb: if two operators must agree on it, it's config; if it's how *you personally* reach or view the cluster, it's per-operator. - -| Asset | In config? | Notes | -|---|---|---| -| **Graphs** (the set that exists) | βœ… config | the named graphs; their existence is cluster state | -| **Schema** (`.pg`, **one per graph**) | βœ… config | also encodes indexes (`@index`/`@unique`/vector), constraints, and search (`@embed`) β€” so indexes & search are reconciled *via* schema | -| **Stored queries** (`.gq`, **per graph**) | βœ… config | a `.gq` file declares **many** named queries; the registry declares which exist (name β†’ file, key must match the `query ` symbol). **Target design:** exposure β€” who may list/invoke each β€” is a policy decision, not a registry flag. **Current compatibility bridge:** shipped `omnigraph.yaml` still has `queries..mcp.expose`, and the HTTP catalog is not Cedar-filtered per query yet. Aliases & bindings reference a query by name | -| **Policy bundles** (`.yaml`) | βœ… config | YAML (not Cedar files); **shared across graphs** via `applies_to: [cluster \| ]` (many-to-many; fix 2026-06-08 unified the old `scope:`/`graphs:` split). Gates actions **and query exposure** (who may list/invoke each stored query) | -| **UI specs / dashboards** (`.yaml`) | βœ… config | first-class resources; a dashboard **reads from several graphs** (`graphs: [...]`) | -| **Bindings** | βœ… config | wiring between resources (query ⇄ UI surface) | -| **Aliases** | βœ… config* | CLI shortcut to a stored query: `{ command, query: <.gq file>, name: , args, format }` β€” `query` is the **file**, `name` the **query symbol** in it. See note | -| **Embeddings config** | βœ… config | model + dimension + which fields embed; the **API key comes from the `.env` file** (`${…}`) | -| **ETL pipelines** | βœ… config | source β†’ transform β†’ **one or more target graphs**; source credentials come from the `.env` file | -| **Apply settings** | βœ… config | `apply.default_grain`, grouping/ordering hints | -| **State backend + lock** | βœ… config | where the ledger lives, whether to lock | -| **Secrets (`.env` file)** | βœ… ref'd by config; values **gitignored** | a separate `.env` of secret values, referenced as `${NAME}`; never committed (OmniGraph's standard env-file convention) | -| **Connection** (which cluster URI) | ❌ per-operator | how *you* reach the cluster | -| **Operator token** | ❌ per-operator (secret) | each operator's own credential to reach the cluster | -| **CLI prefs** (output format, table layout, active graph/branch selection) | ❌ per-operator | personal ergonomics, not shared truth | - -\* **Aliases β€” the one with a split.** A shared alias that names a cluster resource (a stored query, a dashboard) is config β€” it's a vocabulary the whole team relies on, and it belongs in the spec (often it *is* just the stored-query catalog entry, since that already carries name + params + tool metadata). A *purely personal* shortcut (your own command abbreviations) stays in the per-operator layer. When in doubt: if it should survive `git clone` and be the same for Bob as for Sarah, it's config. - ---- - -## The synthesis (beyond vanilla Terraform) - -Embracing Terraform does not mean stopping at Terraform. Three extensions make this specifically right for OmniGraph and the agentic future: - -1. **OmniGraph is its own data-aware provider, and `plan` can peek across the data boundary.** A Terraform provider CRUDs resources blind to your data. Here, the control-plane resource is the schema **definition** (declarative, reconciled); converging it *triggers* a data-plane **effect** β€” currently soft/hard drops, rewrites, and index creation, with future validated migrations such as enum narrowing or `String`β†’`enum` conversion once the planner grows that tier. The leverage is that `plan`, before applying the definition change, can *peek* at bounded data-plane consequence and report it β€” **"hard-dropping this property requires approval and will make prior versions unreachable after cleanup"** or, in the future, **"narrowing this enum will fail on 37 rows"** β€” which Terraform structurally cannot do. This is deliberate and bounded: a data peek makes that `plan` cost scale with data volume, so it is **opt-in / bounded** (sampled or skippable for large tables), and it never makes the control plane the owner of data. Schema and ETL pipelines are the **two** seams where the control plane reaches into the data plane; everywhere else `plan` is data-volume-independent. - -2. **JSON state first, explicit partials, optional stronger fencing later.** Terraform apply is not transactional β€” partial applies are a real failure mode. Lance commits are per dataset, and today's OmniGraph manifest atomicity is graph-scoped: one graph commit flips the relevant sub-table versions together, protected by expected table versions and recovery sidecars. The first cluster-control backend should match Terraform's shape: a locked JSON state document plus append-only JSON status/approval/recovery records. That keeps Phase 1 inspectable and narrow. Cluster-level all-or-nothing apply is a later capability only if we add a **cluster manifest publisher** or Lance-backed state backend that fences graph *version pins*, query catalogs, policy bundles, UI specs, pipeline definitions, recovery sidecars, and state as one commit protocol. Until that exists, apply must surface partial convergence as `ResourceStatus`, not pretend it was atomic. - -3. **Agent-as-controller fuses Terraform with Kubernetes.** Terraform contributes the as-code config (truth outside the system, recursion-terminating) and the locked state ledger. Kubernetes contributes *continuous* reconciliation (controllers watch, not apply-on-demand). The agent is both author and controller: it reads a config change, runs the data-aware plan, evaluates blast radius against the reversibility gradient, **auto-applies the reversible parts only when policy permits, and escalates irreversible / data-loss gates to a human approval artifact recorded in the audit ledger and referenced by state.** - -> Terraform's as-code config + locked state Γ— Kubernetes' continuous reconciliation Γ— the agent as the controller that bridges them β€” on OmniGraph's data-aware, atomic substrate. - ---- - -## Concrete shape (illustrative) - -The config is **a set of files in one folder** (flat, Terraform-style β€” the extension carries the type): - -``` - company-brain/ - β”œβ”€β”€ cluster.yaml # the spec (graphs, policies, ui, bindings, aliases, pipelines, state, vars ref) - β”œβ”€β”€ .env # SECRET VALUES β€” gitignored, never committed - β”œβ”€β”€ knowledge.pg Β· engineering.pg # schemas (one per graph) (.pg) - β”œβ”€β”€ knowledge.gq Β· engineering.gq # query files β€” each holds MANY queries (.gq) - β”œβ”€β”€ cluster_admin.policy.yaml Β· base_rbac.policy.yaml Β· knowledge_pii.policy.yaml # shared policy bundles - β”œβ”€β”€ overview.dashboard.yaml # cross-graph UI spec (.dashboard.yaml) - └── notion_to_knowledge.map.yaml Β· github_to_engineering.map.yaml Β· github_to_people.map.yaml # pipeline maps -``` - -Secrets live in a gitignored `.env` file (OmniGraph's standard env-file convention); the config references them as `${NAME}`: - -```bash -# .env β€” secret values; gitignored; never committed. Referenced in cluster.yaml as ${NAME}. -NOTION_TOKEN=… -GITHUB_TOKEN=… -EMBEDDING_API_KEY=… -``` - -Resource relationships (so the wiring is unambiguous): - -``` - cluster ──has many──► graph ──has one──► schema - └────has──► query file(s) (.gq) ──each declares MANY──► query { … } symbols - registry entry key = the query symbol ──points to──► its .gq file (queries: { : { file } }) - (registry says a query EXISTS; it carries NO expose flag) - policy bundle ──applies to──► { cluster | one or MANY graphs } (SHARED, many-to-many) - └──governs query EXPOSURE──► who may LIST / INVOKE each stored query (no `expose:` in the registry) - alias (command, query = .gq FILE, name = symbol, args, format) ──selects one query from that file - binding names a query by registry name (graph.queryName) ──► resolved to (file, symbol) - dashboard ──reads from──► one or MANY graphs - pipeline ──writes into──► one or MANY graphs - secrets ──live in──► a separate gitignored `.env` file; config uses ${NAME} -``` - -```yaml -# cluster.yaml β€” desired state of the whole deployment (config = source of truth for INTENT) -version: 1 -metadata: - name: company-brain - -state: # the authoritative ledger's backend (Terraform-style) - backend: cluster # "cluster" = this deployment's own store; or s3://… (a separate store) - lock: true # acquire a state lock before plan/apply - -env_file: ./.env # secret VALUES live in a gitignored .env file; referenced below as ${NAME} - -apply: - default_grain: resource # references may force groups; explicit groups request more atomicity - -graphs: # the cluster's graphs β€” each is ONE schema + a set of named queries - knowledge: # people Β· teams Β· docs Β· decisions Β· projects - schema: ./knowledge.pg # desired schema; reconciler runs (and plan previews) the migration - queries: # the graph's stored (named) queries; KEY must match a `query ` in the file - find_experts: { file: ./knowledge.gq } # ─┐ `query find_experts` and `query related_docs` - related_docs: { file: ./knowledge.gq } # β”€β”˜ both live in knowledge.gq. Who may LIST/INVOKE β†’ policy (not here) - engineering: # repos Β· services Β· incidents Β· PRs - schema: ./engineering.pg - queries: - service_owners: { file: ./engineering.gq } - open_incidents: { file: ./engineering.gq } - -policies: # policy BUNDLES (YAML) β€” SHARED across graphs (many-to-many). - # Policy ALSO governs query EXPOSURE: who may list/invoke each stored query. - # Fix (2026-06-08): unified the binding field on `applies_to:` (was a - # `scope:` + `graphs:` split) β€” one field, takes `cluster` or graph refs; - # bare graph names are shorthand for `graph.` (see impl-spec typed addresses). - cluster_admin: # cluster-scoped: graph_list, create/delete, management - file: ./cluster_admin.policy.yaml - applies_to: [cluster] - base_rbac: # read/write + which roles may invoke which queries, across both graphs - file: ./base_rbac.policy.yaml - applies_to: [knowledge, engineering] - knowledge_pii: # an extra bundle, only for knowledge - file: ./knowledge_pii.policy.yaml - applies_to: [knowledge] - -pipelines: # ETL β€” ONE pipeline may write into SEVERAL graphs (definition only) - saas_sync: # the "company brain" move: assemble graphs from the SaaS tools - source: { kind: notion, token: ${NOTION_TOKEN} } # secret via ${NAME}, never inline - schedule: "0 * * * *" # hourly; execution is a data-plane effect, not reconciled state - into: # fans out across graphs - - { graph: knowledge, map: ./notion_to_knowledge.map.yaml } - github_sync: - source: { kind: github, token: ${GITHUB_TOKEN} } - schedule: "*/15 * * * *" - into: - - { graph: engineering, map: ./github_to_engineering.map.yaml } - - { graph: knowledge, map: ./github_to_people.map.yaml } # same feed enriches a SECOND graph - -embeddings: # semantic search over docs/decisions; key via the `.env` file - model: gemini-embedding-2 - dimension: 3072 - api_key: ${EMBEDDING_API_KEY} - -ui: # dashboards read from SEVERAL graphs - dashboards: - overview: - file: ./overview.dashboard.yaml - graphs: [knowledge, engineering] # cross-graph - -aliases: # CLI shortcuts. ⚠ an alias's `query:` is the .gq FILE PATH; - # `name:` selects the query SYMBOL inside it (a file declares many). - experts: { command: query, graph: knowledge, query: ./knowledge.gq, name: find_experts, args: [topic], format: table } - incidents: { command: query, graph: engineering, query: ./engineering.gq, name: open_incidents, format: table } - -bindings: # wiring between resources - - query: knowledge.find_experts - surface: ui.dashboards.overview -``` - - -What this is *not*: it is **not** a graph, and it carries **no credentials** β€” only secret *references* (`${…}`). It is parsed by the engine (the base case), describes the desired cluster, and is the thing two operators diff and review. - -The **state ledger** lives in the configured backend (the cluster, or a separate cloud store), versioned, CAS-updated, schema-versioned, locked during apply, agent-managed β€” the authoritative record of what is deployed. The baseline backend is JSON, so even cluster-hosted state is published through a state CAS and repaired explicitly if graph/resource movement happened first. A future cluster publisher can tighten that boundary, but it is not assumed by the high-level spec. - ---- - -## Boundaries that hold (orthogonal correctness, not Terraform-bias) - -1. **Secrets live in a `.env` file, never inline in config.** The committed config is what the cluster *is* (shared, reviewable, as code) and carries **no secret values** β€” only `${NAME}` references. The values (embedding API key, pipeline source credentials, per-deployment settings) live in a separate **`.env` file** β€” which is **gitignored and never committed**, and supplied per deployment. Separately, an *operator's own token* (how they personally reach the cluster) belongs to the per-operator connection layer, not the cluster config or its `.env` file. - -2. **The reversibility gradient gates apply β€” including drift correction.** Dropping a graph, hard-dropping schema data, or an overwriting pipeline is irreversible data loss; a future validated enum narrowing is a compatibility-narrowing migration unless it also drops or coerces stored values; recoloring a dashboard is not. Unified config, unified plan β€” but **tiered gates inside apply**, keyed to physics, not to who operates it. The gate applies to **drift correction too**: converging actualβ†’config can mean *dropping* something added out-of-band β€” a data-loss path that hits the same gate. A reconciler "just fixing drift" is never an exception. - -3. **Agents are actors, not ambient authority.** The reconciler runs with a resolved actor or service account, subject to Cedar policy. If it applies on behalf of a human, the durable audit ledger carries both the controller actor and the approving human / approval artifact, and state references that ledger entry. Client-supplied actor identity is never trusted. - -4. **Status is explicit when apply is not atomic.** A unified plan does not imply a unified commit. If an apply group partially converges, the cluster must expose `ResourceStatus` and typed conditions until reconciliation finishes or rolls back. Silent partial success is forbidden. - -5. **State integrity is protected.** State is locked during apply and stored durably in its backend. The baseline state backend is JSON plus lock/CAS, so state update failures surface a repair/import condition before success is acknowledged. A lost ledger is recoverable (import/refresh from the self-describing cluster), but state is never treated as disposable. - ---- - -## Relationship to current config - -This is not green field, but it is also not today's `omnigraph.yaml`. The current file is a shared convenience for CLI and server startup: named graph targets, server defaults, query roots, aliases, embeddings model, auth env-file lookup, and `policy.file`. It is **not** the cluster's source of truth, it has no separate state ledger, and parts of it are intentionally per-operator. - -This proposal: - -- **splits** per-operator connection/credential/preference config from shared cluster config, -- **adds** `cluster.yaml` + a flat config folder as the full declarative cluster config (graphs, schemas, query catalog, policy bundles, UI specs, bindings, **aliases**, **embeddings**, **ETL pipelines**), -- **adds** the **JSON state ledger** (authoritative, locked, in a backend) and the `cluster plan`/`apply` loop, -- **adds** the reconciler (with OmniGraph as its own data-aware provider), while treating a cluster manifest publisher as a later option rather than the baseline, -- **lets an agent drive** plan/apply/continuous-reconcile. - -The connection/credential/preference layer remains per operator: it points at a cluster, resolves that operator's identity, and holds personal ergonomics. The cluster config stays shared, secret-free, and reviewable; the state ledger stays authoritative and locked. - -### Migration model: single ownership, mode switch, shrinking job description (axiom 15) - -`omnigraph.yaml` is not being replaced; its **job description shrinks**. Only the -shared-truth parts of its current role migrate to the cluster catalog (the set of -graphs, the stored-query registry, policy wiring, the server boot source). The -per-operator parts are per-operator *by nature* β€” Sarah's and Bob's differ β€” and -keep `omnigraph.yaml`/the per-operator layer as a permanent, well-defined home. - -While both exist, **each fact has exactly one owner at any moment, and -coexistence is a mode switch, never a merge**. The brittle version of backward -compatibility β€” the server reading graphs from `omnigraph.yaml` *and* from -cluster state with precedence rules gluing them together β€” is rejected outright: -two readers for one truth means every bug becomes "which file won?" and every -feature pays the tax twice. The realistic timeline has three windows: - -1. **Now β†’ Phase 4 (no conflict).** Cluster apply writes only to its own catalog - (`__cluster/`); `omnigraph.yaml` serves traffic. `Applied` status must - visibly mean "recorded in the cluster catalog, not yet serving" so the - overlap is loud, not hidden. -2. **Phase 5 (the mode switch).** A deployment opts into booting from cluster - state; `omnigraph.yaml`'s server-role keys become inert *for that - deployment*. Exclusive β€” boot from cluster state XOR `omnigraph.yaml` β€” with - no key-level aliasing and no merged precedence. -3. **Phase 6+ (bridges with sunsets).** Targeted compatibility bridges are - allowed only with a named replacement and a removal phase; `mcp.expose` β†’ - policy-owned exposure is the template. Bridges that accumulate without an - exit are review-rejected. - -Key-by-key compatibility inside one evolving file is the expensive kind of -backcompat (the v1 `omnigraph.yaml` reshape's `--target`/legacy-key regressions -are the in-repo cautionary tale); resource-ownership seams between two files -with a mode switch is the cheap kind. Police the single-owner rule in every -Phase 3–6 PR: a proposal that merges the two sources for one fact is the -deny-list's "state that drifts from what it can be derived from" wearing a -compatibility costume. - -### The per-operator layer: contents and destination - -The per-operator layer must be **complete** β€” everything an operator needs to -work against any cluster from any directory, and nothing that two operators must -agree on: - -| Per-operator concern | Today | Target | -|---|---|---| -| Connection (which cluster/server, named endpoints) | `omnigraph.yaml` `graphs.` URIs / `servers:` refs | global config, per-operator | -| Operator credential **reference** (`bearer_token_env`, env-file lookup) | `omnigraph.yaml` + `.env` | global config references; secret values stay in env/`.env`, never in any config | -| Active context (current graph/branch selection) | ad-hoc per-command flags / `defaults` | global state layer (e.g. `omnigraph use`), explicitly **not** the cluster state ledger (axiom 5's "state" is the applied-cluster ledger, not a personal selection) | -| CLI ergonomics (output format, table layout) | `omnigraph.yaml` `cli:`/`defaults:` | global config, per-operator | -| Personal command shortcuts (purely personal aliases) | `omnigraph.yaml` `aliases:` | global config; *shared* aliases (team vocabulary) are cluster config β€” see the aliases split note above | - -Destination: this layer belongs in the operator's **global config dir** -(`~/.omnigraph`, per the RFC-002 global-first layered-config direction β€” -global config + active-context state file), not in a repo-committed file, so it -survives `git clone`, works from any directory, and never collides with the -shared cluster folder. The RFC-002 layering implementation is currently parked -(PRs #139/#162 closed over review findings), but the *boundary* it draws is the -one this spec depends on: per-operator β†’ global dir; shared deployment intent β†’ -the cluster config folder; deployed reality β†’ the state ledger. - -Implementation gate: the Terraform-style workflow must be testable in order. -`cluster validate` must catch bad config before any apply path exists; -read-only `cluster plan` must have deterministic structured-plan tests before -state mutation ships; and graph/schema-moving apply must have recovery tests for -the gap between graph/resource movement and JSON state publish. Otherwise the -control plane can look declarative while still hiding drift or partial success. - ---- - -## Open questions - -1. **Cluster state layout.** What exact JSON documents / object-store paths hold `AppliedRevision`, `ResourceStatus`, approval records, recovery records, sidecars, and resource content for query/policy/UI/pipeline specs? What evidence would justify a future Lance-backed state backend? -2. **State backend options.** Beyond "cluster" and "a separate bucket," what backends are first-class (a different account, a remote control service)? How is the backend itself bootstrapped and its lock implemented (object-store CAS vs an external lock service)? -3. **State import / refresh.** The exact actual-state scan that reconstructs a conservative `AppliedRevision` when the ledger is lost, and which fields become `Unknown`. -4. **Apply grain syntax.** Apply defaults to per-resource `ApplyGroup`; cross-resource references force planner-derived groups; user-declared groups opt into more atomicity. What's the YAML, and which combinations can the publisher actually fence? -5. **Pipeline runtime.** Where do pipelines *execute* (in the server? a worker? an external scheduler?), how are runs observed in `ResourceStatus`, and how does a failed/partial run reconcile vs. retry? -6. **Continuous reconciliation trigger.** Watch-and-converge (k8s-style) vs. apply-on-config-change. The agent-as-controller model leans toward continuous. -7. **Tenant partitioning (cloud).** A cluster may host multiple tenants; config/state is then tenant-partitioned, consistent with the reserved `GraphKey { tenant_id, graph_id }`. Tenant resolved from the token, never the config. -8. **Bootstrap β€” config, state, *and* authority.** How a cluster comes into existence from an initial config (`init` seeds; cluster owns; git mirrors for CI/DR), the first state write, and the chicken-and-egg of the very first apply (which needs an actor before any cluster exists to resolve policy against β€” so the bootstrap actor is necessarily out-of-band and privileged). Security-sensitive; needs an explicit story. -9. **Alias scoping.** Where exactly the shared/personal alias line falls, and whether shared aliases are just stored-query catalog entries. -10. **UI render and safety model.** Generic engine-side renderer vs. thin client, allowed components, query-binding validation, policy propagation, sandboxing, version compatibility. -11. **Cluster identity vs. `metadata.name`.** Is `metadata.name` a label or stable identity? If identity, renaming loses it β€” the stable-ID-across-rename gap already in `invariants.md`. Decide whether identity keys on `name` or on `ClusterRoot`, and reuse the existing known-gap framing. -12. **Resource dependency ordering.** Explicit dependency DAG (Terraform) vs. eventual convergence with retries (k8s). The most consequential unmade fork: it decides whether `plan` can promise an apply *order* before any data moves. -13. **Query exposure in policy (supersedes `mcp.expose`).** *Today* the stored-query registry carries a per-query `mcp.expose` flag and invocation is gated with the coarse `invoke_query` Cedar action β€” with **per-query authorization a documented gap** (the catalog isn't Cedar-filtered per query yet). This design **folds exposure fully into policy and drops the flag**: a stored query's visibility (catalog membership) and invocability are both policy decisions, so the catalog `GET /queries` returns each actor's policy-permitted set. The open work is the exact policy predicates for *list* vs *invoke* per query, and retiring `mcp.expose`. - ---- - -## Prior art - -- **Terraform** β€” declarative infra *as code*; config is desired truth, **state is an authoritative ledger in a backend**, **state locking** serializes applies, `plan` diffs config↔state, providers do the CRUD. The core model adopted here, taken literally. -- **Kubernetes** β€” one cluster store, many resource types under one API; controllers reconcile continuously; cluster-level RBAC. The continuous-reconciliation half of the synthesis. -- **dbt / Airflow / Dagster** β€” declarative, as-code data pipelines with lineage. Prior art for the **ETL-pipeline-as-config** asset (the second data-plane seam). -- **OmniGraph's own schema-apply** β€” already a faithful plan/apply/state/drift loop for the `schema` resource type, with `__schema_apply_lock__` as the lock seed; the reconciler this generalizes. diff --git a/docs/dev/codeowners.md b/docs/dev/codeowners.md index 80d59e9..9a7fb50 100644 --- a/docs/dev/codeowners.md +++ b/docs/dev/codeowners.md @@ -4,45 +4,24 @@ This setup gives every role change a reviewable PR and a permanent in-repository audit trail (`git log .github/codeowners-roles.yml`). -## Who owns what +## Current roles -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) | +| Role | Members | Scope | |---|---|---| -| `*` | @aaltshuler | engineering | -| `crates/**` | @aaltshuler | engineering | -| `docs/**` | @aaltshuler | docs | -| `README.md` | @aaltshuler | docs | -| `AGENTS.md` | @aaltshuler | docs | -| `CLAUDE.md` | @aaltshuler | docs | -| `SECURITY.md` | @aaltshuler | docs | +| `engineering` | `@ragnorc` | All code under `crates/**`, repository infrastructure, default for unmapped paths | +| `docs` | `@ragnorc` | `docs/**`, README.md, AGENTS.md, CLAUDE.md, SECURITY.md | -**Roles**: - -| Role | Members | Description | -|---|---|---| -| `engineering` | @aaltshuler | All production code under crates/**. Engine, CLI, server, compiler. | -| `docs` | @aaltshuler | 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). +GitHub treats multiple owners in 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. 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. +2. Run `python3 .github/scripts/render-codeowners.py` (requires PyYAML; `pip install pyyaml`). +3. Commit both files in the same PR. CI fails the PR if: -- 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). +- `CODEOWNERS` was edited without a corresponding yml change, or +- The yml was changed but the rendered `CODEOWNERS` doesn't match. ## How to add a new role diff --git a/docs/dev/execution.md b/docs/dev/execution.md index 0e8e3fc..3a108d7 100644 --- a/docs/dev/execution.md +++ b/docs/dev/execution.md @@ -84,7 +84,7 @@ Resolves expression values to literals, converts to typed Arrow arrays (`literal - `insert` (no `@key`, edges) β†’ accumulate into `MutationStaging.pending` (Append mode); finalize calls `stage_append` once per touched table. - `insert` (`@key` node) β†’ accumulate into `pending` (Merge mode); finalize calls `stage_merge_insert` once per touched table. - `update` β†’ scan committed via Lance + pending via DataFusion `MemTable` (read-your-writes), apply assignments, accumulate into `pending` (Merge mode). -- `delete` β†’ still inline-commits via `delete_where` (Lance v6.0.1 has no public two-phase delete; `DeleteBuilder::execute_uncommitted` first ships in v7.0.0-beta.10 β€” tracked as MR-A in [docs/dev/lance.md](lance.md)); recorded into `MutationStaging.inline_committed`. +- `delete` β†’ still inline-commits via `delete_where` (Lance 4.0.0 has no public two-phase delete); recorded into `MutationStaging.inline_committed`. **Dβ‚‚ parse-time rule.** A single mutation query is either insert/update-only or delete-only. Mixed β†’ reject before any I/O. The check fires in `enforce_no_mixed_destructive_constructive(&ir)` inside `execute_named_mutation`. @@ -162,18 +162,18 @@ Atomicity guarantee for multi-statement mutations: a mid-query failure leaves La | Mode | Semantics | Path (post-MR-794) | |---|---|---| -| `Overwrite` | Replace all data in the target tables on the branch | Same accumulator; one `stage_overwrite` + `commit_staged` per touched table at end-of-load (a staged Lance `Operation::Overwrite` transaction β€” HEAD does not advance until commit; MR-793 Phase 2); publisher CAS. | +| `Overwrite` | Replace all data in the target tables on the branch | Inline-commit per type, then publisher CAS at end-of-load. Truncate-then-append doesn't fit the staged shape; documented residual. | | `Append` | Strict insert; duplicates error | In-memory `MutationStaging` accumulator; one `stage_append` + `commit_staged` per touched table at end-of-load; publisher CAS. | | `Merge` | Upsert by `id` (`merge_insert`) | Same accumulator; one `stage_merge_insert` per touched table at end-of-load (Merge mode dedupes by `id`, last-write-wins); publisher CAS. | -For all three modes, a mid-load failure (RI / cardinality violation, validation error) leaves Lance HEAD untouched on the staged tables β€” the next load on the same tables proceeds normally with no `ExpectedVersionMismatch`. +For Append/Merge, a mid-load failure (RI / cardinality violation, validation error) leaves Lance HEAD untouched on the staged tables β€” the next load on the same tables proceeds normally with no `ExpectedVersionMismatch`. For Overwrite, a mid-load failure can still leave Lance HEAD on a partially-truncated table; the next overwrite replaces it. -## `load` and the deprecated `ingest` shims +## `load` vs `ingest` -- `load_as(branch, base, data, mode, actor)` β€” the unified entry (single publisher commit per call). `base: Some(b)` forks a missing `branch` from `b` first (via `branch_create_from_as`, which enforces `BranchCreate`); `base: None` requires the branch to exist β€” staging fails on an unknown branch, so a typo'd name can never create one. -- `load(branch, data, mode)` β€” convenience wrapper with `base: None` and no actor. -- Returns `LoadResult { branch, base_branch, branch_created, nodes_loaded, edges_loaded }`. -- `ingest{,_as,_file,_file_as}` are `#[deprecated]` shims over `load_as` preserving the historical contract (`from: None` forks from `main`; returns `IngestResult`); they are slated for removal. The CLI `ingest` command is a deprecated alias of `load --from `. +- `load(branch, data, mode)` β€” direct load to a branch (single publisher commit per call). +- `ingest(branch, from, data, mode)` β€” branch-creating wrapper: if `branch` doesn't exist, fork it from `from` (default `main`) via `branch_create_from`, then call `load(branch, data, mode)`. +- Returns `IngestResult { branch, base_branch, branch_created, mode, tables[] }`. +- `ingest_as(actor_id)` records the actor on the resulting commit. ## Embeddings during load diff --git a/docs/dev/index.md b/docs/dev/index.md index b23326b..600c969 100644 --- a/docs/dev/index.md +++ b/docs/dev/index.md @@ -51,18 +51,6 @@ constraints. User-facing behavior should still be documented through | Install and deployment packaging | [install.md](../user/install.md), [deployment.md](../user/deployment.md) | | Release history | [releases/](../releases/) | -## Contribution & Governance - -| Area | Read | -|---|---| -| How to contribute (external) | [CONTRIBUTING.md](../../CONTRIBUTING.md) | -| Governance model, roles, decision authority | [GOVERNANCE.md](../../GOVERNANCE.md) | -| Public contribution RFC track | [rfcs/](../rfcs/) | - -The `docs/rfcs/` track is the **public, externally-authorable** RFC process. The -maintainer/internal RFCs below (`rfc-00N-*.md`) are a separate, team-owned -track; don't conflate the two. - ## Active Implementation Plans Working documents for in-flight feature work. Removed when the work lands. @@ -73,11 +61,6 @@ Working documents for in-flight feature work. Removed when the work lands. | 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) | -| Future cluster control plane β€” declarative as-code config, JSON state ledger, reconciler | [cluster-config-specs.md](cluster-config-specs.md), [cluster-axioms.md](cluster-axioms.md), [cluster-config-implementation-spec.md](cluster-config-implementation-spec.md) | -| Cluster graph & schema apply β€” Phase 4 sidecars, roll-forward recovery, approval artifacts | [rfc-004-cluster-graph-schema-apply.md](rfc-004-cluster-graph-schema-apply.md) | -| Server boots from cluster state β€” Phase 5 mode switch, applied-revision serving | [rfc-005-server-cluster-boot.md](rfc-005-server-cluster-boot.md) | -| Per-operator config β€” `~/.omnigraph/` identity, keyed credentials, named servers (the operator slice of RFC-002) | [rfc-007-operator-config.md](rfc-007-operator-config.md) | -| Deprecate `omnigraph.yaml` β€” one concern per config surface; key-by-key migration map and staged retirement | [rfc-008-deprecate-omnigraph-yaml.md](rfc-008-deprecate-omnigraph-yaml.md) | ## Boundary diff --git a/docs/dev/invariants.md b/docs/dev/invariants.md index 655e360..5ee4f17 100644 --- a/docs/dev/invariants.md +++ b/docs/dev/invariants.md @@ -101,8 +101,8 @@ Use it this way: | 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; intake and branch-merge derive the composite key through one shared function (`loader::composite_unique_key`, a separator-free `Vec` tuple) and fail loudly on an un-keyable column type rather than silently exempting it; full cross-version uniqueness against already-committed rows is still a gap | [schema-language.md](../user/schema-language.md) | -| Storage trait | `TableStorage` (via `db.storage()`) is staged-only; the inline-commit residuals (`delete_where`, `create_vector_index`) are split onto a separate sealed `InlineCommitResidual` trait reached via `db.storage_inline_residual()` (MR-854), so Β§1 holds by construction; capability/stat surfaces are roadmap | [writes.md](writes.md), [architecture.md](architecture.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 | [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) | @@ -124,16 +124,9 @@ them explicit. renames. The current compiler still derives type IDs from `kind:name`; this must be fixed before relying on renamed IDs across accepted schemas. - **Storage abstraction:** `TableStorage` is present, sealed, and canonical for - staged writes. MR-854 sealed it: `db.storage()` exposes only staged primitives - + reads, and the inline-commit residuals are split onto a separate sealed - `InlineCommitResidual` trait reached via `db.storage_inline_residual()`, so a - new writer cannot couple a write with a HEAD advance through the default - surface. The dead legacy methods (`append_batch` on the trait, - `merge_insert_batch{,es}`, `create_{btree,inverted}_index`) were removed. The - remaining residuals are `delete_where` (gated on MR-A β€” Lance v7.x bump) - and `create_vector_index` (gated on Lance #6666); see - [lance.md](lance.md) and [writes.md](writes.md). New write paths should use - the staged shape unless a documented Lance blocker applies. + staged writes, but older inherent `TableStore` call sites and inline residuals + remain. New write paths should use the staged shape unless a documented Lance + blocker applies. - **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. @@ -146,20 +139,6 @@ them explicit. 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. -- **Manifestβ†’commit-graph publish atomicity:** a graph commit advances - `__manifest` (the visibility authority) and then appends `_graph_commits` as - two separate writes (`commit_updates_with_actor_with_expected`, failpoint - `graph_publish.before_commit_append`). A crash between them leaves the manifest - at version N with no commit-graph row for N. Live reads and durability are - unaffected β€” the live version resolves via the manifest - (`GraphCoordinator::version()`), not the commit-graph head β€” and the open-time - recovery sweep does NOT repair it (`lance_head == manifest_pinned` classifies - `NoMovement`; a recovery sidecar would not change this). Impact is bounded to - commit history: `commit list` misses N, time-travel by commit id to N fails, - and merge-base loses a node (a likely-benign off-by-one re-merge). This affects - every publish, not a specific maintenance command. Eventual fix: make the - commit graph reconcilable from the manifest (or the two writes atomic) β€” not a - recovery-sidecar concern. - **Planner capability/stat surfaces:** cost-aware planning, complete capability advertisement, and explain-with-cost are roadmap. Do not describe them as implemented. @@ -206,10 +185,6 @@ case is exceptional. fits. - Discarding retrieval score/rank before fusion or projection decisions. - Auto-creating placeholder nodes for orphan edges. -- Raw filesystem I/O for cluster-stored state (ledger, lock, sidecars, - approvals, catalog) outside the cluster crate's storage module β€” every - stored byte goes through the engine `StorageAdapter` so `file://` and - `s3://` stay one code path. - Wire-protocol-specific code in compiler or engine crates. - Cloud-only correctness fixes or forks of the OSS engine for correctness. - Mutating immutable substrate state in place, including Lance fragments or diff --git a/docs/dev/lance.md b/docs/dev/lance.md index a4e311f..9d2b990 100644 --- a/docs/dev/lance.md +++ b/docs/dev/lance.md @@ -55,18 +55,18 @@ Adding/changing index types, fixing coverage, debugging FTS or vector recall, de | Topic | URL | |---|---| -| Index spec overview | https://lance.org/format/index/ | -| BTREE scalar index | https://lance.org/format/index/scalar/btree/ | -| Bitmap scalar index | https://lance.org/format/index/scalar/bitmap/ | -| Bloom-filter scalar index | https://lance.org/format/index/scalar/bloom_filter/ | -| Label-list scalar index | https://lance.org/format/index/scalar/label_list/ | -| Zone-map scalar index | https://lance.org/format/index/scalar/zonemap/ | -| R-Tree scalar index (spatial) | https://lance.org/format/index/scalar/rtree/ | -| Full-text search (FTS) index | https://lance.org/format/index/scalar/fts/ | -| N-gram scalar index | https://lance.org/format/index/scalar/ngram/ | -| Vector index | https://lance.org/format/index/vector/ | -| Fragment-reuse system index | https://lance.org/format/index/system/frag_reuse/ | -| MemWAL system index | https://lance.org/format/index/system/mem_wal/ | +| Index spec overview | https://lance.org/format/table/index/ | +| BTREE scalar index | https://lance.org/format/table/index/scalar/btree/ | +| Bitmap scalar index | https://lance.org/format/table/index/scalar/bitmap/ | +| Bloom-filter scalar index | https://lance.org/format/table/index/scalar/bloom_filter/ | +| Label-list scalar index | https://lance.org/format/table/index/scalar/label_list/ | +| Zone-map scalar index | https://lance.org/format/table/index/scalar/zonemap/ | +| R-Tree scalar index (spatial) | https://lance.org/format/table/index/scalar/rtree/ | +| Full-text search (FTS) index | https://lance.org/format/table/index/scalar/fts/ | +| N-gram scalar index | https://lance.org/format/table/index/scalar/ngram/ | +| Vector index | https://lance.org/format/table/index/vector/ | +| Fragment-reuse system index | https://lance.org/format/table/index/system/frag_reuse/ | +| MemWAL system index | https://lance.org/format/table/index/system/mem_wal/ | | HNSW Rust example | https://lance.org/examples/rust/hnsw/ | | Distributed indexing | https://lance.org/guide/distributed_indexing/ | | Tokenizer (FTS, n-gram) | https://lance.org/guide/tokenizer/ | @@ -125,7 +125,7 @@ Touching `omnigraph optimize` / `cleanup`, the underlying `compact_files` / `cle |---|---| | Read-and-write guide (covers `compact_files`, `cleanup_old_versions`) | https://lance.org/guide/read_and_write/ | | Performance (compaction tradeoffs) | https://lance.org/guide/performance/ | -| Fragment-reuse index | https://lance.org/format/index/system/frag_reuse/ | +| Fragment-reuse index | https://lance.org/format/table/index/system/frag_reuse/ | ### DataFusion integration diff --git a/docs/dev/rfc-004-cluster-graph-schema-apply.md b/docs/dev/rfc-004-cluster-graph-schema-apply.md deleted file mode 100644 index e9c0336..0000000 --- a/docs/dev/rfc-004-cluster-graph-schema-apply.md +++ /dev/null @@ -1,211 +0,0 @@ -# RFC: Cluster Graph & Schema Apply β€” Phase 4 of the Cluster Control Plane - -**Status:** Landed (4A #170, 4B #171, 4C β€” all shipped) -**Implementation deviations:** (1) D3 row 8 retires the stale delete sidecar and lets the still-approved delete re-propose and retry, instead of a pending-block β€” prefix removal is idempotent, so the retry is the repair. (2) The approver/actor flag is the CLI's existing global `--as`, not a dedicated `--actor`/`--by`. (3) Consumed approval artifacts are rewritten with `consumed_at` rather than moved into state β€” the file and the ledger record both survive independently (axiom 11). -**Date:** 2026-06-10 -**Builds on:** cluster Stages 1–3B (shipped: validate/plan/status/refresh/import/force-unlock, config-only `cluster apply` with content-addressed catalog publish, catalog payload verification, failpoint-proven crash/CAS recovery for the apply protocol). Normative context: [cluster-config-specs.md](cluster-config-specs.md), [cluster-axioms.md](cluster-axioms.md), [cluster-config-implementation-spec.md](cluster-config-implementation-spec.md). -**Target release:** unversioned (phased β€” see Sequencing); no cluster functionality is in a tagged release yet. - -## Summary - -Extend `cluster apply` from config-only resources (stored queries, policy bundles) to **graph-moving resources**: graph create, cluster-driven schema apply, and graph delete. This is the nested-publish territory the implementation spec flags as its highest-risk decision: a graph's Lance manifest can move (via the engine's own atomic publish) *before* the cluster's JSON state CAS lands, and a crash in that window must never be silent, never acknowledged as success, and never repaired by guessing. - -Three design commitments make the phase tractable: - -1. **Cluster recovery is roll-forward-only.** The engine's recovery sidecars (`__recovery/{ulid}.json`, the open-time sweep in `db/manifest/recovery.rs`) already make every graph-level operation atomic *within the graph* β€” a schema apply either fully published or fully recovers at the next open. The cluster therefore never rolls a graph back. Cluster sidecars exist to **classify and record**: after a crash, the sweep observes the live graph, decides "moved / didn't move / moved unexpectedly," and either rolls the *cluster state* forward to match observable reality (axiom 5) or surfaces a loud pending-repair condition. The cluster holds no second transaction log and no rollback hammer β€” that would duplicate substrate behavior the engine already owns (invariant: respect the substrate). -2. **Irreversible operations require a digest-bound approval artifact.** Graph delete and `allow_data_loss` schema applies consume an explicit `__cluster/approvals/{ulid}.json` record bound to the exact change digests, written by a new `cluster approve` command and retired into the state ledger's `approval_records` (the durable audit reference of axiom 11). -3. **The operator identity becomes explicit.** `cluster apply` gains an actor, threaded to the engine's `apply_schema_as` so Cedar enforcement and commit attribution work unchanged. The cluster control plane adds no policy engine of its own (transport/auth stay at the boundary). - -## Motivation - -After Stage 3B, the control plane converges everything *except* the resources that define the data plane. The Sarah/Bob test is half-passed: Bob can see that Sarah changed a schema (`plan` shows the deferred change; `refresh` shows drift), but the system cannot act on it β€” Sarah still applies schemas with the per-graph tool and the cluster ledger trails reality. Graph creation is worse: a new graph in `cluster.yaml` blocks every dependent query and policy with `dependency_missing` until someone runs `omnigraph init` by hand at exactly the derived path. Phase 4 closes the loop: desired config in, converged deployment out, for the full resource vocabulary of Stage 1. - -The implementation spec's hard gate for this phase β€” failpoint recovery tests proving the movement-before-state-publish gap β€” was deliberately front-loaded: Stage 3B shipped the failpoint infrastructure and the apply-side crash/CAS tests. What remains is the design this RFC supplies: the sidecar schema, the recovery decision matrix, the approval artifact, and the ordering rules. - -## Non-Goals - -- **Server boot from cluster state** (Phase 5) β€” applied graphs/schemas still serve nothing; the server boots from `omnigraph.yaml` until the explicit per-deployment mode switch (axiom 15). -- **Policy-owned query exposure / `mcp.expose` retirement** (Phase 6). -- **Pipelines, embeddings, UI, aliases, bindings, providers, `env_file`** (Phase 7 and reserved fields). -- **External or Lance-backed state backends**; the local JSON backend + lock/CAS remains the substrate. -- **A cluster manifest publisher.** Deferred, per the spec: it becomes interesting only if the sidecar + repair path proves too weak for the accepted safety contract. Nothing in this design forecloses it. -- **Multi-graph atomic apply groups.** Cross-graph convergence remains statusful-partial per resource; one graph's failure never pretends to fence another's success. -- **Graph rename.** Stable-identity-across-rename is an open known gap at the schema level already; graph rename compounds it and is explicitly out of scope (see Open Questions). - -## Background - -What Phase 4 builds on (all shipped): - -- **The engine's recovery discipline.** Writers that can advance Lance HEAD before manifest publish write `__recovery/{ulid}.json` sidecars carrying per-table pins (`expected_version`, `post_commit_pin`); `Omnigraph::open` in read-write mode classifies every pinned table (`NoMovement` / `RolledPastExpected` / `UnexpectedAtP1` / `UnexpectedMultistep` / `InvariantViolation`) and decides all-or-nothing: roll forward via one manifest publish, or roll back via `Dataset::restore`, recording an audit row attributed to `omnigraph:recovery`. The cluster inherits the *vocabulary* of this design but not its mechanics β€” see the roll-forward-only argument below. -- **The engine's schema-apply surface.** `apply_schema_as(desired_source, SchemaApplyOptions { allow_data_loss }, actor)` returns `SchemaApplyResult { supported, applied, manifest_version, steps }`; `preview_schema_apply_with_options` returns the migration plan plus desired catalog without applying; the `__schema_apply_lock__` branch serializes schema applies graph-wide and refuses to run while user branches exist. Policy enforcement (`enforce(SchemaApply, TargetBranch("main"), actor)`) happens before the lock. -- **Graph init.** `Omnigraph::init(uri, schema_source)` with a strict preflight (errors if schema artifacts exist) and an atomic `_schema.pg` claim. A documented gap: a failed init does not clean up Lance datasets or `__manifest/` it already created. -- **No engine graph-delete primitive.** Deleting a graph today means removing its object-store prefix. This RFC works with that fact rather than waiting on a primitive. -- **Cluster state and observations.** `state.json` (locked, CAS-checked, atomically replaced) already records per-resource digests, statuses, `observations["graph."]` with `manifest_version` and live schema digest, plus empty `approval_records` / `recovery_records` placeholders reserved for this phase. -- **Stage 3A/3B apply mechanics.** Dispositions (`applied`/`derived`/`deferred`/`blocked`), content-addressed catalog publish before the state CAS, persisted-statuses contract on write failure, idempotent re-apply, payload verification with the drift + self-heal loop, and failpoints `cluster_apply.after_payload_phase` / `cluster_apply.before_state_write`. - -## Design - -### D1. Resource semantics: which dispositions change - -The Stage 3A classifier gains executable rows. Everything else (catalog resources, `derived` composites, blocked dependents) is unchanged: - -| Change | Stage 3A disposition | Phase 4 disposition | -|---|---|---| -| `graph.` Create | Deferred | **Applied** (4A): `Omnigraph::init` at the derived root | -| `schema.` Create | Deferred | **Applied with the graph create** (the init carries the schema) | -| `schema.` Update | Deferred | **Applied** (4B): `apply_schema_as` against the live graph | -| `graph.` / `schema.` Delete | Deferred | **Applied behind approval** (4C): prefix removal | -| `query.*`/`policy.*` blocked on the above | Blocked | Unblocked in the same apply once the dependency lands (ordering, D5) | - -Graph roots remain **derived**: `ClusterRoot/graphs/.omni` (high-risk decision #2 dispositioned: external graph roots are a separate, explicit future feature, not this phase). - -### D2. Cluster recovery sidecar (exit criterion 2, first half) - -Written under the state lock **before** any engine call that can move or create a graph manifest; deleted only **after** the cluster state CAS that records the outcome lands. - -```json -{ - "schema_version": 1, - "operation_id": "", - "started_at": "", - "actor": "", - "kind": "graph_create | schema_apply | graph_delete", - "graph_id": "", - "graph_uri": "", - "observed_manifest_version": 7, - "expected_manifest_version": null, - "desired_schema_digest": "", - "state_cas_base": "sha256:" -} -``` - -Path: `__cluster/recoveries/{operation_id}.json`, atomic write (temp + rename, the `write_state` discipline). Notes: - -- `observed_manifest_version` is the live graph's main-branch manifest version read at sidecar-write time (`null` for `graph_create` β€” no graph yet). This is the fencing value: apply refuses to proceed if it differs from the version recorded in `observations["graph."]` at plan time *and* re-observed under the lock (the same recompute-under-lock posture as Stage 3A's diff). -- `expected_manifest_version` starts `null` and is **rewritten into the sidecar immediately after the engine call returns** with `SchemaApplyResult.manifest_version` (or the post-init observation). A crash before that rewrite leaves `null`, which the sweep treats as "engine call outcome unknown β€” classify by observation only." For `graph_delete` the field is **always `null`** β€” prefix removal produces no new manifest version, so there is no rewrite step for that kind; delete sidecars are classified purely by root presence + state tombstone (D3 rows 7/7b/8). -- `state_cas_base` is **recorded for audit and diagnostics only β€” the sweep decision logic never consults it.** The sweep re-reads `state.json` under the lock and performs ordinary CAS-checked writes, so an independent state mutation between sidecar write and sweep is handled by the CAS like any other concurrent write, not by this field. Its value is forensic: a recovery audit entry can show which state revision the interrupted operation departed from. -- One sidecar per graph-moving resource operation. Apply processes graph-moving operations strictly sequentially (D5), so at most one sidecar is pending per apply run *per graph*, and the sweep processes sidecars in ULID order. - -### D3. Recovery decision matrix β€” roll-forward-only (exit criterion 2, second half) - -**Why no rollback.** The engine's sidecars already guarantee that a schema apply is atomic within the graph: by the time any cluster-visible manifest version moved, the engine either fully published or will recover all-or-nothing at its next read-write open. A cluster-level rollback would mean un-publishing a successfully published graph commit β€” rewriting substrate history the cluster does not own, duplicating the engine's transaction discipline (deny-list: custom transaction manager; state that drifts from what it can be derived from). The cluster's job after a crash is therefore *epistemic*, not transactional: observe what the graph actually is, and converge the ledger to it or refuse loudly. - -**Sweep trigger.** The sweep runs at the start of every state-mutating cluster command (`apply`, `refresh`, `import`), under the state lock, before the command's own work β€” mirroring the engine's open-time sweep gating (read-only `status`/`plan`/`validate` report pending sidecars as a warning, `cluster_recovery_pending`, but do not act). - -| # | Sidecar kind | Observation | Decision | -|---|---|---|---| -| 1 | any | Graph at `observed_manifest_version` (nothing moved) | Engine call never landed. Delete sidecar; the command's own plan/apply re-proposes the change. | -| 2 | `graph_create` / `schema_apply` | Graph at `expected_manifest_version`; state already records the outcome | Crash fell between state CAS and sidecar delete. Delete sidecar; done. | -| 3 | `schema_apply` | Graph at `expected_manifest_version` (or, when `expected` is `null`, live schema digest == `desired_schema_digest`); state stale | **Roll the cluster state forward**: record the live schema digest, recompute the graph composite, set statuses `applied`, append a `recovery_records` entry (audit), CAS-write, delete sidecar. | -| 4 | `graph_create` | Graph opens read-only and its schema digest == `desired_schema_digest`; state stale | Same roll-forward as #3 (the create completed). | -| 5 | `graph_create` | Root exists but the graph does not open (the engine's partial-init gap) | Status `error`, condition `graph_create_incomplete`, message: remove the root and re-run apply. **No auto-delete** β€” reconciler-initiated deletion is the same data-loss class as human deletion (high-risk decision #7). Sidecar kept until the operator acts and a sweep observes a clean state. | -| 6 | any | Graph at any other version (out-of-band movement during the crash window) | Status `drifted`, condition `actual_applied_state_pending`; sidecar kept; the command refuses graph-moving work for that graph until `cluster refresh` re-observes and the operator re-plans. No success is acknowledged for the interrupted operation. | -| 7 | `graph_delete` | Root absent; state already tombstoned | The delete kind's analog of row 2 (no manifest exists to version-check): crash fell between state CAS and sidecar delete. Delete sidecar; done. | -| 7b | `graph_delete` | Root absent; state stale | Roll forward: tombstone the graph subtree out of state (D6), record audit, delete sidecar. Idempotent β€” re-entry after a crash mid-row lands in row 7. | -| 8 | `graph_delete` | Root present (delete crashed mid-prefix-removal or never started) | If the approval artifact is still attached (D4), the delete is re-proposed by plan and re-runnable; status `drifted`, condition `graph_delete_incomplete`. Partial prefix removal leaves an unopenable graph β€” same operator message as #5. | - -Rows 3, 4 and 7b are the only mutations the sweep performs, and each is an ordinary CAS-checked state write under the lock β€” the sweep introduces no new write machinery. - -### D4. Approval artifacts (exit criteria 1-partial and 6-partial; axioms 8 and 11) - -The irreversible tier β€” graph delete, `allow_data_loss` schema apply (hard drops) β€” requires a recorded human decision that survives any reconstruction of state. `plan` already emits `approvals_required`; Phase 4 adds the consumption side. - -**Artifact** (`__cluster/approvals/{approval_id}.json`, written by the new command, never by apply): - -```json -{ - "schema_version": 1, - "approval_id": "", - "resource": "graph.scratch", - "operation": "delete", - "reason": "", - "bound_config_digest": "", - "bound_before_digest": "", - "bound_after_digest": "", - "approved_by": "", - "created_at": "" -} -``` - -**Flow.** `cluster approve --config --by ` re-runs the plan under the lock, locates the pending gated change for that address, prints it, and writes the artifact bound to the exact digests. `cluster apply` executes a gated change only when a pending artifact matches **all** bound digests β€” a stale approval (config moved since) matches nothing, is reported (`approval_stale` warning), and the change stays `blocked` with condition `approval_required`. On successful execution the artifact file is moved into `state.approval_records[approval_id]` in the same state CAS that records the outcome (the state references the audit fact; losing state does not lose the approval, which is also why `import` preserves `approval_records` it finds β€” see D7). - -`allow_data_loss` is **never** a CLI flag on `cluster apply`; destructive promotion is expressed only through an approval artifact for the specific schema change. The default schema apply path runs with `allow_data_loss: false` (soft drops), which the spec's tier table classes as a recoverable definition rewrite β€” plan warning, no artifact. - -### D5. Actor, ordering, and apply groups (exit criterion 4) - -**Actor.** `cluster apply --actor ` / `cluster approve --by `, with `OMNIGRAPH_CLUSTER_ACTOR` as the env fallback. The actor is threaded to `apply_schema_as` (so engine-side Cedar enforcement fires wherever a policy checker is installed and graph commits are attributed), recorded in sidecars, approvals, and `recovery_records`. The cluster adds no policy engine: graph-moving operations inherit the engine's gate; catalog-only operations remain ungated as today. When no actor is supplied and the target graph has no policy checker, behavior is unchanged from Stage 3A (`None` actor, as the engine's no-actor variants do); when a checker is installed the engine's existing "actor required" error surfaces as a typed diagnostic (`actor_required`). - -**Ordering.** Deterministic, dependency-shaped, within one apply run: - -1. graph creates (with their schemas) β€” ULID-stable order by graph id -2. schema applies β€” sequential, one graph at a time (each holds that graph's `__schema_apply_lock__`; the cluster state lock already serializes cluster-side) -3. catalog writes (queries/policies) β€” the Stage 3A path, unchanged -4. deletes last (catalog deletes, then approved graph deletes) - -Each graph-moving operation is its own apply group: sidecar β†’ engine call β†’ sidecar update β†’ continue. The **state CAS stays single and final** (one write at the end recording every outcome), preserving Stage 3A's protocol; sidecars cover the widened gap between individual engine calls and that final CAS. A failure mid-sequence stops graph-moving work, reports per-resource statuses for everything already done (loud partials), and leaves sidecars for the sweep. Cross-graph atomicity is explicitly not promised. - -**Failpoints.** Each engine-call boundary gets a failpoint (`cluster_apply.before_graph_create`, `cluster_apply.after_graph_create`, `cluster_apply.before_schema_apply`, `cluster_apply.after_schema_apply`, `cluster_apply.before_graph_delete`) so every row of the D3 matrix is testable with the Stage 3B harness. - -### D6. Graph delete (4C) - -With no engine primitive, delete is cluster-orchestrated prefix removal: verify the approval artifact β†’ sidecar (`kind: graph_delete`, current manifest version recorded) β†’ recursively remove `ClusterRoot/graphs/.omni` β†’ state CAS that tombstones the graph subtree (graph, schema, and its queries removed from `applied_revision.resources` and `resource_statuses`; observation replaced by a tombstone record `{deleted_at, approval_id}`) β†’ delete sidecar. Catalog blobs of the graph's queries stay (GC remains a later stage, consistent with Stage 3A deletes). The engine gap (no atomic prefix delete; partial removal leaves an unopenable root) is handled by D3 row 8, and this RFC registers a desire for an engine-level `destroy_graph` primitive as future work, not a dependency. - -### D7. Plan and import integration - -- **Plan** gains real data impact for schema updates: where Stage 3A showed only a digest diff, Phase 4 calls `preview_schema_apply_with_options` against the live graph (read-only) and embeds the migration steps + drop warnings in the change record β€” the "data-aware provider peek" from the high-level spec, bounded to graphs the plan already observes. Failure to preview (graph unreachable) degrades to the digest diff with a warning, never blocks planning. -- **Import/refresh** already observe live graphs; Phase 4 makes `import` preserve `approval_records` and pending `recoveries/` it finds (state reconstruction must not orphan audit facts or pending repairs). - -### D8. Invariants and axioms check - -- *Respect the substrate / no custom transaction manager*: cluster never rolls back graphs; engine sidecars own intra-graph atomicity (D3). -- *Axiom 5 (state = deployed reality)*: recovery converges the ledger to observation, never observation to ledger. -- *Axiom 8 (reversibility gates apply, including drift correction)*: approval artifacts for the irreversible tier; sweep never auto-deletes (D3 rows 5/8). -- *Axiom 9 (plan-time integrity)*: ordering is planner-derived from existing dependency edges; no runtime discovery. -- *Axiom 11 (approvals in a durable ledger)*: artifacts are files first, state-referenced after consumption; reconstructable state never re-derives who approved. -- *Axiom 12 (locked state)*: every new write path (sidecars, approvals consumption, sweep) runs under the existing state lock. -- *Axiom 15 (single owner / mode switch)*: nothing here reads from or writes to `omnigraph.yaml`; applied graphs still serve nothing until Phase 5. -- *Loud partials (deny-list)*: every crash window lands in a typed status/condition; no path acknowledges unverified success. - -## Migration / Compatibility - -Additive. Stage 3A/3B behavior is unchanged for catalog-only configs; existing state files gain no required fields (`approval_records`/`recovery_records` already exist, empty). New CLI surface: `cluster approve`, `--actor` on `cluster apply`. A deployment that never declares schema changes or graph creates sees identical behavior to Stage 3B. The honored-or-rejected posture continues: no new `cluster.yaml` fields are introduced by this phase (graph roots stay derived). - -## Sequencing - -| Stage | Scope | Gate | -|---|---|---| -| **4A graph create** | `Omnigraph::init` at derived roots; create-intent sidecar; D3 rows 1/2/4/5; dependents unblock in-run | Failpoint tests for crash-before/after-init; e2e: declare graph β†’ apply β†’ import-less convergence | -| **4B schema apply** | Full sidecar lifecycle; roll-forward sweep (D3 rows 3/6); actor threading; plan data-impact preview; soft-drop default | Failpoint tests per matrix row; e2e: schema evolution fully cluster-driven (replaces the Stage 3A deferβ†’manualβ†’refresh loop) | -| **4C graph delete** | `cluster approve` + artifact consumption; prefix removal; tombstones; D3 rows 7/7b/8 | Failpoint tests incl. partial-removal; e2e: gated delete refused without artifact, executed with it, stale artifact rejected | - -Each stage is a separate PR with boundary-matched tests (the Stage 1–3B discipline). 4A ships first because it moves no existing manifest; 4B is the heart; 4C last because it is the only irreversible-tier executor and consumes the approval machinery 4B's hard-drop path also needs. - -## Exit-criteria coverage (implementation spec) - -| # | Criterion | This RFC | -|---|---|---| -| 1 | State/status/approval/recovery schemas + paths | **Approval + recovery schemas: answered** (D2, D4). State/status: unchanged from shipped Stage 2A/3A. | -| 2 | Sidecar schema + recovery decision matrix | **Answered** (D2, D3) | -| 3 | State backend interface / lock+CAS | Unchanged (local JSON backend, shipped) β€” out of scope | -| 4 | Apply group syntax + dependency ordering | **Answered** (D5): per-resource groups, fixed kind-ordering; no user-declared group syntax this phase | -| 5 | Plan JSON schema incl. blast radius + approvals | **Extended** (D7 preview embedding); base schema shipped | -| 6 | Bootstrap authority + first-actor | **Partial** (D5 actor threading); cluster bootstrap authority remains open (below) | -| 7 | Server startup migration | Phase 5 β€” deferred | -| 8 | Per-query policy / `mcp.expose` bridge | Phase 6 β€” deferred | -| 9 | Pipeline runtime | Phase 7 β€” deferred | - -## Open Questions - -1. **Bootstrap authority.** The first apply against a fresh cluster has no policy engine to consult and no actor registry; today the answer is "whoever holds the object store wins." The durable story (out-of-band privileged bootstrap actor, per the high-level spec Β§open-questions) is unresolved and blocks nothing in this phase, since graph-level Cedar still gates wherever installed. -2. **Approval expiry.** Artifacts are digest-bound, so config drift invalidates them naturally; is wall-clock expiry also wanted (operator hygiene), or does digest binding suffice? -3. **Sweep on read-only commands.** This RFC has `status`/`plan` only *warn* about pending sidecars. If operator feedback shows the warn-but-don't-repair posture causes confusion, promoting `plan` to run the sweep (it already takes the lock) is a compatible change. -4. **Graph rename.** Deliberately out of scope; interacts with the rename-stable-identity known gap in [invariants.md](invariants.md). A rename today is delete + create β€” i.e., gated, lossy, and honest about it. -5. **Engine `destroy_graph` primitive.** 4C's prefix removal is correct but unatomic; if the engine grows a graph-destroy primitive with its own recovery, D6 collapses onto it (the cluster code is shaped to delegate). - -## References - -- [cluster-config-implementation-spec.md](cluster-config-implementation-spec.md) β€” phases, exit criteria, high-risk decisions, approval tiers -- [cluster-axioms.md](cluster-axioms.md) β€” axioms 5, 8, 9, 11, 12, 15 -- [cluster-config-specs.md](cluster-config-specs.md) β€” the data-aware provider peek; state/ledger model -- `crates/omnigraph/src/db/manifest/recovery.rs` β€” the engine sidecar + classifier this design mirrors in vocabulary and deliberately does not duplicate in mechanics -- [writes.md](writes.md), [invariants.md](invariants.md) β€” engine recovery protocol and the deny-list this design is checked against diff --git a/docs/dev/rfc-005-server-cluster-boot.md b/docs/dev/rfc-005-server-cluster-boot.md deleted file mode 100644 index 85df875..0000000 --- a/docs/dev/rfc-005-server-cluster-boot.md +++ /dev/null @@ -1,140 +0,0 @@ -# RFC: Server Boots from Cluster State β€” Phase 5 of the Cluster Control Plane - -**Status:** Landed (5A policy bindings #175; 5B/5C the `--cluster` boot mode β€” one PR) -**Implementation deviations:** (1) cluster mode reuses `ServerConfigMode::Multi` (a new settings *source*, not a new enum variant; `config_path` carries the cluster dir). (2) Stored queries load via `QueryRegistry::from_specs` from verified blob *content*, not blob paths. (3) More than one policy bundle binding a single scope is a boot error (the serving pipeline holds one bundle per graph + one server-level; stacking is a later slice). (4) `GET /graphs` keeps its closed-by-default contract β€” without a cluster-bound bundle there is no server-level Cedar engine, so enumeration refuses. -**Date:** 2026-06-10 -**Builds on:** Phase 4 complete ([rfc-004-cluster-graph-schema-apply.md](rfc-004-cluster-graph-schema-apply.md), Landed): `cluster apply` converges graphs, schemas, stored queries, and policies into the cluster catalog. Normative context: [cluster-config-specs.md](cluster-config-specs.md) (the migration model's "window 2"), [cluster-axioms.md](cluster-axioms.md) (axiom 15), [cluster-config-implementation-spec.md](cluster-config-implementation-spec.md) (Phase 5 rollout, Compatibility Stance #7–#9, exit criterion 7). -**Target release:** unversioned (phased β€” see Sequencing). - -## Summary - -Give `omnigraph-server` a second boot source: `omnigraph-server --cluster ` reads its graph set, stored queries, and Cedar policies from the **cluster catalog** β€” `state.json`'s applied revision plus the content-addressed blobs under `__cluster/resources/` β€” instead of `omnigraph.yaml`. This is the moment "applied" finally means "serving": the standing caveat in every cluster doc since Stage 3A ("the server still boots from `omnigraph.yaml`") retires for deployments that flip the switch. - -Three commitments: - -1. **An exclusive mode switch, never a merge** (axiom 15, Compatibility Stance #7). `--cluster ` is mutually exclusive with the positional URI, `--target`, and `--config`. In cluster mode, `omnigraph.yaml` is not read at all β€” not for graphs, not for queries, not for policies. There is no precedence, no key-level aliasing, no fallback read. A deployment serves from one source. -2. **The server serves the *applied* revision, not the desired config.** What's live is what `cluster apply` converged: graph roots recorded in state, query/policy content at the *applied* digests from the content-addressed catalog. Un-applied config drift never leaks into serving β€” the serving surface and the ledger cannot disagree (axiom 5 extended to the data path). -3. **The state ledger becomes serving-sufficient.** Today one fact needed to serve is missing from state: a policy's `applies_to` bindings live only in `cluster.yaml`. A prerequisite slice (5A) records binding metadata into the applied revision at apply time, so a booting server reads state + blobs and nothing else. Without this, "boot from state" would silently become "boot from state *and* config" β€” the merged read axiom 15 forbids. - -## Motivation - -Phase 4 closed the convergence loop but left it inert: an operator can declare, plan, approve, and apply an entire deployment, and the running server ignores all of it. The Sarah/Bob test still fails at the last step β€” Sarah's applied change is visible in `cluster status` but Bob's clients hit a server still wired to a hand-maintained `omnigraph.yaml`. Phase 5 makes the catalog the serving source, which is also the precondition for Phase 6 (policy-owned query exposure must filter a catalog the server actually reads). - -## Non-Goals - -- **Runtime reconciliation / hot reload.** Cluster-mode boot is static, exactly like today's boot: the server reads the applied revision once at startup; picking up a newer applied state means restarting the process. The registry's runtime-mutation seam (the test-only `insert()` + mutate `Mutex` in `registry.rs`) stays future-proofing for a later watch-and-reload slice, not this RFC. -- **Policy-owned query exposure** (Phase 6) β€” but this RFC defines the bridge it sunsets (Β§D5). -- **Remote cluster roots.** `--cluster ` is a local directory in this phase, same as the `cluster` CLI commands; S3-hosted cluster roots arrive with external state backends. -- **Retiring `omnigraph.yaml` server boot.** It remains a fully supported mode indefinitely (Compatibility Stance #8: the file's job shrinks; the *server-role* keys become inert only for deployments that switch). -- **New management endpoints** (`/cluster/status` etc.) β€” noted as future work; this RFC changes the boot source, not the HTTP surface (beyond OpenAPI regen if anything shifts). - -## Background (verified against main) - -- **Server boot today** (`omnigraph-server/src/main.rs`, `lib.rs:891-1029`): `load_server_settings` applies a four-rule mode inference (positional URI / `--target` / `server.graph` β†’ Single; `--config` + `graphs:` β†’ Multi), builds `ServerConfigMode::{Single,Multi}` with per-graph `GraphStartupConfig {graph_id, uri, policy_file, queries}`, loads `QueryRegistry` from `.gq` files at settings time (identity-checked), type-checks queries at engine open (`validate_and_attach`), loads Cedar via `PolicyEngine::load_graph`/`load_server`, installs it with `with_policy`, and assembles `GraphRegistry::from_handles` (startup-only; lock-free `ArcSwap` reads). Bind address and bearer tokens come from flags/env, not from graph config. No reload machinery exists. -- **The catalog today** (`omnigraph-cluster`): `state.json` records `applied_revision.resources` (address β†’ digest) for `graph.*`, `schema.*`, `query..`, `policy.`, plus statuses, observations (incl. tombstones), approval and recovery records. Query/policy *content* lives content-addressed at `__cluster/resources/query///.gq` and `policy//.yaml`. Graph roots are derived: `/graphs/.omni`. -- **The gap**: state records a policy's *digest* only; `applies_to` (cluster vs graph refs) lives in `cluster.yaml`. Queries are fine β€” their graph binding is encoded in the address itself. - -## Design - -### D1. The mode switch - -New server flag: `omnigraph-server --cluster ` (the directory containing `cluster.yaml`, `__cluster/`, and `graphs/`). Mutually exclusive β€” a hard startup error, not a precedence rule β€” with the positional URI, `--target`, and `--config`. `--bind`, `--unauthenticated`, and the bearer-token env vars keep working identically: listen address and credentials are **process-operational facts**, not cluster facts (they differ per replica/host and never belonged to the shared catalog; if a `serve:` section ever joins `cluster.yaml`, that's a separate proposal). - -Mode inference gains rule 0: `--cluster ` β†’ **Cluster mode**, which is always multi-graph routing (`/graphs/{graph_id}/...`), even for a single declared graph. No flat-route legacy surface in cluster mode β€” it's a new mode with no compatibility debt to carry. - -### D2. What the server reads (the applied revision, and only it) - -`load_server_settings` grows a cluster branch that reads, in order: - -1. `__cluster/state.json` β€” **missing state is a boot error** ("run `cluster import` + `cluster apply` first"). Pending recovery sidecars under `__cluster/recoveries/` are also a boot error (`cluster_recovery_pending`): a server must not start serving a ledger that a sweep is about to rewrite. -2. **Graph set** = state's `graph.` resources (tombstoned graphs are absent by construction). Each graph's URI is the derived root `/graphs/.omni`. A recorded graph whose root does not open is a boot error β€” same fail-fast posture as today's bad URI. -3. **Stored queries** = state's `query..` entries, content loaded from the catalog blob at the recorded digest. Blob-missing or digest-mismatched is a boot error (the catalog verification semantics from Stage 3B, applied at boot). Queries type-check at engine open exactly as today (`validate_and_attach` β€” unchanged). -4. **Policies** = state's `policy.` entries, content from catalog blobs, bindings from the applied metadata of D3: bundles bound to `cluster` load as the server-level Cedar engine (`PolicyEngine::load_server`); bundles bound to graphs load per-graph (`PolicyEngine::load_graph`) and install via `with_policy` β€” the existing two-gate structure, unchanged. -5. `cluster.yaml` is parsed **only** to validate that the directory is a cluster root (and for nothing else β€” explicitly not for resource content; a divergence between desired config and applied state is *served as applied*, visible via `cluster plan`). - -Everything downstream of settings construction β€” `GraphStartupConfig`, parallel engine opens, `GraphRegistry::from_handles`, routing middleware, auth, workload admission, OpenAPI β€” is reused as-is. Cluster mode is a new *source* for the same boot pipeline, not a new pipeline. - -### D3. Prerequisite: serving metadata in the applied revision (slice 5A) - -State's `StateResource` records only a digest. To make the ledger serving-sufficient, `cluster apply` (and the sweep's roll-forwards) additionally record **binding metadata** for policy resources at apply time: - -```json -"applied_revision": { - "resources": { - "policy.base_rbac": { - "digest": "", - "applies_to": ["cluster", "graph.knowledge"] - } - } -} -``` - -- Additive and optional (`#[serde(default)]`) β€” existing state files parse unchanged; a policy entry without `applies_to` (applied before 5A) is a **boot error in cluster mode** with the remedy "re-run `cluster apply`" (one apply rewrites the metadata; the digest needn't change β€” the metadata write is part of the state mutation, not the blob). -- `applies_to` is normalized to typed addresses (`cluster` | `graph.`) at apply time, mirroring the validator's normalization. -- Queries need no equivalent: the address (`query..`) already carries the binding, and the registry key/symbol invariant is enforced at apply (validate) time. -- This is deliberately *applied* metadata, not config mirroring: if `cluster.yaml` changes a binding, the server keeps serving the old binding until `cluster apply` converges it β€” the same contract as every other resource. - -### D4. Readiness and failure posture - -Boot is fail-fast, matching the server's existing stance (bad policy YAML refuses boot): - -| Condition | Behavior | -|---|---| -| `state.json` missing / unparseable / unsupported version | boot error | -| pending recovery sidecars | boot error (run any state-mutating cluster command to sweep) | -| recorded graph root missing or unopenable | boot error | -| query/policy blob missing or digest-mismatched | boot error (run `cluster refresh` + `apply` to self-heal, then restart) | -| policy entry without `applies_to` metadata | boot error ("re-run cluster apply", D3) | -| stored query fails type-check against the live schema | boot error (existing `validate_and_attach` behavior) | -| state lock held | **not** an error β€” boot takes no lock; it reads a point-in-time snapshot of an immutable-once-written state file (the CAS discipline means a concurrent apply produces a *new* file atomically; the server reads whichever was current at open) | - -### D5. The `mcp.expose` bridge in cluster mode - -The cluster query registry has no `expose` flag by design (axiom 14: exposure is a policy decision β€” Phase 6). Until Phase 6 ships, cluster-mode servers list **all** stored queries in `GET /queries`. This is the documented bridge: *cluster mode = everything exposed; omnigraph.yaml mode = `mcp.expose` honored as today*. Its named sunset is Phase 6's policy-filtered catalog (Compatibility Stance #9). Invocation remains gated by the existing coarse `invoke_query` Cedar action in both modes. - -### D6. Migration path (exit criterion 7) - -For an operator running multi-graph from `omnigraph.yaml`: - -1. Author `cluster.yaml` declaring the same graphs/queries/policies; place existing graph roots under `/graphs/.omni` (or start fresh). -2. `cluster import` (observes live graphs) β†’ `cluster plan` β†’ `cluster apply` (publishes queries/policies into the catalog; with 5A, records policy bindings). -3. Restart the server with `--cluster ` instead of `--config omnigraph.yaml`. -4. `omnigraph.yaml`'s `graphs:`/`serve:`/`queries:`/`policy:` keys are now inert for this deployment; the file remains the CLI's per-operator config. - -Rollback is the same switch in reverse β€” nothing in cluster mode mutates `omnigraph.yaml` or the graphs in a way the yaml mode can't serve. - -### D7. Invariants and axioms check - -- *Axiom 15 / Stance #7*: exclusive flag, hard mutual-exclusion error, zero `omnigraph.yaml` reads in cluster mode β€” no fact has two readers. -- *Axiom 5*: the server serves deployed reality (applied digests), never desired intent; D3 keeps the ledger the single serving source. -- *Axiom 12*: boot reads without the lock but relies on the atomic-replace write discipline; it never writes state. -- *Axiom 14 / Stance #9*: the expose-all bridge is named, scoped to cluster mode, and carries its Phase 6 sunset. -- *Loud failures (deny-list)*: every degraded condition is a typed boot error with a remedy; no partial serving, no silent fallback to the yaml. -- *Respect the boundaries*: `omnigraph-cluster` stays free of HTTP; the server reads the catalog through a small read-only loader (either a `pub` read surface on `omnigraph-cluster` or a thin module in the server consuming the documented file formats β€” implementation picks the one that keeps `omnigraph-cluster` dependency-light; the state/blob formats are already a documented contract). - -## Sequencing - -| Slice | Scope | Gate | -|---|---|---| -| **5A: serving metadata in state** | `applies_to` recorded on policy resources at apply + sweep roll-forward; additive state schema; `status`/plan surfacing | In-crate tests: metadata written/rolled-forward; old state parses; re-apply backfills | -| **5B: `--cluster` boot mode** | Flag + mode inference rule 0; catalog loader (state β†’ `GraphStartupConfig`s + registries + policy engines); readiness table; OpenAPI regen if surface shifts | Server tests: boot from a converged fixture dir, serve `/graphs/{id}/query` + stored queries + Cedar gates; every D4 row refuses boot; e2e: `cluster apply` then serve β€” "applied means serving" | -| **5C: docs + caveat retirement** | `cluster-config.md` mode-switch section; `server.md`/`deployment.md`; retire the "not serving" caveats for cluster-mode deployments; migration guide (D6) | `check-agents-md.sh`; doc accuracy review | - -## Exit-criteria coverage - -Answers implementation-spec exit criterion 7 (server startup + migration path) in full; touches 1 (state schema gains policy binding metadata β€” additive). Criteria 8 (per-query policy) and 9 (pipelines β€” descoped to a separate project) remain. - -## Open Questions - -1. **Loader home**: `pub` read-only API on `omnigraph-cluster` (server gains the dependency) vs a server-side reader of the documented formats. Leaning `omnigraph-cluster` API β€” one parser for the state schema beats two drifting ones; the crate stays HTTP-free either way. -2. **Boot-time blob re-hash**: D4 requires digest verification at boot; for large catalogs a stat-only fast path with full hashes behind a flag may matter later. Start with full verification (catalogs are small). -3. **`GET /graphs` enrichment**: cluster mode could expose applied digests/revision in the enumeration β€” deferred until a consumer exists. -4. **Watch-and-reload**: the natural follow-up once cluster mode exists; the registry's mutation seam is ready, but reload semantics (drain? cutover?) deserve their own design. - -## References - -- [rfc-004-cluster-graph-schema-apply.md](rfc-004-cluster-graph-schema-apply.md) β€” the convergence machinery this serves -- [cluster-config-specs.md](cluster-config-specs.md) Β§Migration model β€” window 2 is this RFC -- [cluster-axioms.md](cluster-axioms.md) β€” axioms 5, 12, 14, 15 -- [cluster-config-implementation-spec.md](cluster-config-implementation-spec.md) β€” Phase 5 rollout, Compatibility Stance #7–#9, blast-radius rows for the server registry -- `crates/omnigraph-server/src/lib.rs` (`load_server_settings`, `ServerConfigMode`, `GraphRegistry`) β€” the boot pipeline this extends without forking diff --git a/docs/dev/rfc-007-operator-config.md b/docs/dev/rfc-007-operator-config.md deleted file mode 100644 index 5bd8afb..0000000 --- a/docs/dev/rfc-007-operator-config.md +++ /dev/null @@ -1,327 +0,0 @@ -# RFC: Per-Operator Config β€” the Operator Slice of RFC-002 - -**Status:** Proposed -**Date:** 2026-06-11 -**Builds on:** [rfc-002-config-cli-architecture.md](rfc-002-config-cli-architecture.md) (Proposed; implementation parked β€” PRs #139/#162 closed over review findings), [rfc-005-server-cluster-boot.md](rfc-005-server-cluster-boot.md) (Landed), RFC-006 storage roots (#186/#190/#194, landed). The #139 review record is a normative input: every design rule in Β§D6 traces to a confirmed finding. -**Paired with:** [rfc-008-deprecate-omnigraph-yaml.md](rfc-008-deprecate-omnigraph-yaml.md) β€” together they define the two-surface architecture this RFC's operator half belongs to. -**Target release:** unversioned (staged; see Sequencing). - -## Summary - -Give OmniGraph the operator half of the **two-surface config architecture** -(RFC-008): **cluster config** (team-owned, in a repo β€” what the system *is*) -and **operator config** (person-owned, in `$HOME` β€” who *I* am). This is -Terraform's split: `~/.terraformrc` for the operator, the checkout for the -declaration. OmniGraph today has neither half cleanly β€” `omnigraph.yaml` -mixes both concerns (RFC-008 retires it), and there is no home-level config -at all: identity and credentials get re-declared per working directory, in -files that sit next to repo-committed config. - -This RFC introduces **`~/.omnigraph/config.yaml`** (the operator surface) -and a **keyed credentials chain**, scoped deliberately small: - -1. **Operator identity** β€” a default actor for every `--as` cascade. -2. **Credentials by server name** β€” no more inventing env-var names per - server; secrets never inline, never in any repo-committed file. -3. **Named servers** β€” operator-owned endpoint definitions; nothing a - checkout supplies can redefine them. - -It is explicitly a **subset of RFC-002**, sequenced to land. RFC-002 settled -the right long-term decisions (one `~/.omnigraph/` dir, credentials keyed by -server name, `OMNIGRAPH_CONFIG`/`OMNIGRAPH_HOME` env precedence) but its -implementation arrived as one 4,800-line PR mixing a crate extraction with -behavior changes, and died over ten confirmed findings. This RFC adopts -RFC-002's settled decisions verbatim where they apply, defers everything -else (`GraphLocator`, multi-homing, `omnigraph use`, the State layer), and -encodes the #139 findings as design rules so the same failures cannot recur. - -## Motivation - -Three concrete pains, all hit in real operation this cycle: - -- **Identity repetition.** The cluster actor cascade (#180) resolves - `--as` from the per-operator `omnigraph.yaml` β€” which means every - operator hand-maintains a copy in every working directory (the - `~/exp/intel` setup needed exactly this). A repo-committed - `omnigraph.yaml` cannot carry `as: act-andrew` without claiming every - contributor is Andrew. -- **Credential ergonomics.** `bearer_token_env` forces three coordinated - steps per server (invent a var name, reference it in config, set it in - the secret store). The peer group β€” AWS profiles, `gh hosts`, kubeconfig - users β€” keys secrets by the server's *name*. -- **Cluster-era working shape.** With clusters on object storage (RFC-006), - the project directory is a *declaration checkout* β€” operators run - `cluster apply --config ./checkout` from anywhere. The things that are - about the *operator* (who am I, which servers do I know, how do I like - output formatted) have no home that travels with them. - -## Non-Goals - -- **`GraphLocator` / multi-homed graph resolution** (RFC-002 Β§1) β€” the - biggest and riskiest part of config-v2; untouched here. -- **`omnigraph use` / the State layer** (`~/.omnigraph/state/`) β€” deferred - with it (finding #2 showed its precedence interacts badly with scaffolds; - that problem belongs to the slice that introduces it). -- **OS keychain integration** β€” the credentials *chain* (Β§D4) leaves a slot - for it; this RFC ships env + file sources only. -- **Config-file walk-up.** Terraform does not walk up from subdirectories - and neither do we β€” `--config` (or running in the directory) stays the - explicit, deterministic story for cluster checkouts. Rejected, not - deferred: walk-up makes "which config am I using" a function of cwd - depth, the class of surprise this RFC exists to remove. -- **Retiring `omnigraph.yaml`** β€” that is RFC-008's job, with its own - staging. This RFC builds the destination; during RFC-008's deprecation - window the legacy file keeps loading exactly as today. -- **Renaming or removing anything.** No flag renames, no key renames, no - schema-version bumps (findings #1, #3, #10). - -## Background (verified against main) - -- **Project-config lookup today** (`crates/omnigraph-server/src/config.rs:529-553`, - shared by CLI and server): `--config `, else `./omnigraph.yaml` in - cwd, else built-in defaults. Relative paths inside the file resolve - against the file's own directory (`base_dir`). No env var, no home file, - no walk-up. -- **Side-effect on load** (`crates/omnigraph-cli/src/helpers.rs:102-108`): - `load_cli_config` also loads `auth.env_file` into the process env β€” - this is how `OMNIGRAPH_BEARER_TOKEN` reaches remote commands today. -- **Actor resolution** (`helpers.rs:170`, #180): `--as` flag, else the - project config's actor β€” currently the end of the chain. -- **Existing credential mechanism**: `TargetConfig.bearer_token_env` names - an env var; `auth.env_file` points at a git-ignored dotenv. Both keep - working indefinitely (RFC-002 already committed to this; finding #3 - showed what happens otherwise). -- **`OMNIGRAPH_CONFIG`** exists today only as the *container entrypoint's* - translation to the server's `--config`. The CLI does not read it. - -## Design - -### D1. Files and discovery - -``` -~/.omnigraph/config.yaml # the operator surface (this RFC) -~/.omnigraph/credentials # keyed secrets, 0600, git-irrelevant (Β§D4) -./cluster.yaml + checkout # the team surface (unchanged; RFC-004..006) -./omnigraph.yaml # legacy, loads as today through RFC-008's window -``` - -Discovery order for the operator file: `$OMNIGRAPH_HOME/config.yaml` if -`OMNIGRAPH_HOME` is set, else `~/.omnigraph/config.yaml`. Absent file = -empty layer, never an error. `~` is expanded wherever paths are read -(finding #9 β€” today a literal `./~/...` directory gets created). - -`OMNIGRAPH_CONFIG=` becomes a first-class override for the `--config` -argument in the CLI (highest precedence below the flag itself), aligning the -CLI with the container contract that already uses this variable for the -server. One name, one meaning, both binaries β€” it points at whatever the -command's `--config` would (a cluster checkout for cluster commands; the -legacy file during RFC-008's window). - -Per RFC-002 Β§4 (adopted verbatim): `~/.omnigraph/` is the one canonical -dir β€” cache/state subdirectories arrive with their own slices; XDG roots are -not part of the mental model (`$XDG_CONFIG_HOME` may be honored as a -fallback read location if set, but is never written to). - -### D2. The operator schema (v1 of this layer) - -```yaml -# ~/.omnigraph/config.yaml β€” about the OPERATOR, never about the system -operator: - actor: act-andrew # default for every --as cascade - -servers: # operator-owned endpoint definitions - intel-dev: - url: http://127.0.0.1:8080 - prod: - url: https://graph.modernrelay.ai - # No token here, ever. Resolution: Β§D4. - -aliases: # personal shorthand over CLUSTER-owned queries - triage: - server: intel-dev # required: names an operator server above - graph: spike # optional (omit for single-mode servers) - query: weekly_triage # STORED query name on that server β€” never a file - args: [since] # positional CLI args -> params, in order - params: { limit: 20 } # optional fixed defaults (positionals/--params win) - format: table # optional; feeds the format cascade - -defaults: - output: table # read --format default -``` - -Unknown keys are a **warning, not an error** in this layer (an operator file -written by a newer CLI must not brick an older one; contrast with -`cluster.yaml`, where unknown keys are deliberately fatal because they -change what a *plan* means). - -#### Aliases are bindings, not content - -Three things must not be conflated: - -- **Stored queries (the cluster catalog)** are *content plus its canonical, - team-owned name* β€” reviewed, digest-pinned, invocable by name over HTTP. -- **Legacy `omnigraph.yaml` aliases** conflate a personal name with a - pointer to query *content in a local file* β€” which is why they break - across directories and can drift from the catalog. RFC-008 retires them. -- **Operator aliases** are pure **bindings, zero content**: a personal name - β†’ (server, graph, stored-query *name*, arg mapping, defaults). An alias - that carries content competes with the catalog; an alias that references - a name composes with it. - -The three senses of "global", resolved by this split: - -1. **Across graphs/servers** β€” preserved and strengthened: today's aliases - are "global" only within one per-directory config file; operator - aliases live in one `$HOME` file, each binding self-contained, usable - from any cwd. -2. **Across operators (team-shared shorthand)** β€” deliberately *no alias - mechanism*: the shared name IS the stored query's catalog name. A team - that wants a shorter shared name renames the query in `cluster.yaml` - (reviewed, one name). A parallel team-alias namespace would be two - shared names for one thing β€” pure drift surface. -3. **Across machines** β€” dotfile the one operator file; bindings carry no - local-file dependencies. - -Collision rule during the RFC-008 window: a legacy file-alias with the -same name **wins**, with a warning naming both definitions β€” consistent -with Β§D3's legacy-outranks-operator ordering. - -### D3. Precedence and the merge rule - -The end-state cascade is short, because the team surface (cluster config) -deliberately carries **no operator-resolvable keys** β€” no actor, no tokens, -no output preferences. Identity can never come from a checkout: - -``` -flag > env > operator config > built-in -``` - -During RFC-008's deprecation window, a legacy `omnigraph.yaml` slots in -between env and operator config (its keys win over operator defaults, -preserving today's behavior for unmigrated setups) β€” with the Β§D5 -credential inversion: **credentials and endpoint definitions never come -from a legacy/checkout file when an operator-layer definition exists for -the same server name.** - -Merging is **key-level**: scalars override per key; maps (`servers:`, -`aliases:`) merge per *entry*, and entries merge per *field* (finding #13 β€” -`merge_map` replacing whole entries silently dropped sibling fields). - -Concretely for the two flows this slice touches: - -- **Actor**: `--as` > legacy `cli.actor` (window only, unchanged semantics) - > `operator.actor` > none (commands that need an actor keep failing - loudly). -- **Output format**: `--format` > legacy default (window only) > - `defaults.output` > `table`. - -### D4. Credentials: keyed by server name, by-reference always - -Adopted from RFC-002 Β§5 unchanged, minus the keychain (a later source in -the same chain). For a server named ``, the resolution chain is: - -1. `OMNIGRAPH_TOKEN_` (uppercased, `-`β†’`_`) β€” explicit env, wins. -2. `[]` section in `~/.omnigraph/credentials` (INI-style, `0600`; - the loader refuses a group/world-readable file). -3. The legacy pair β€” `bearer_token_env` + `auth.env_file` β€” exactly as - today, for configs that already use it. - -No inline secrets in any YAML file, anywhere (the existing invariant 12 -posture extended to disk). A future `omnigraph login ` -writes/rotates one section of the credentials file via temp + rename -(finding #7: every operator-layer write is atomic), creating it `0600`. - -### D5. The trust boundary (the security findings, made structural) - -Findings #4, #5, #6 share one root cause: a file that arrives with a -*repo checkout* could redirect where requests go and what secrets they -carry. In the end state this is closed by construction β€” cluster config has -no server/credential keys at all, and the operator surface never comes from -a checkout. The rules below therefore govern the **RFC-008 window** (while -legacy `omnigraph.yaml` still loads) and stand as the permanent law for any -future checkout-supplied surface: - -1. **A checkout-supplied file may *reference* a server by name; it may not - *redefine* an operator-defined server.** If a legacy `./omnigraph.yaml` - declares `servers.prod.url` and `~/.omnigraph/config.yaml` also defines - `prod`, the operator definition wins and the CLI warns about the - shadowed entry. A legacy-only server name keeps working (compat), but - the keyed-credentials chain (Β§D4 steps 1–2) never resolves for it β€” - only the legacy explicit `bearer_token_env` does. Net effect: a - malicious checkout cannot point `prod` at an attacker host and harvest - the operator's `prod` token. -2. **`auth.env_file` keeps auto-loading (compat), but checkout-layer - env-files cannot *override* variables already set in the process or by - the operator layer** β€” first-set-wins, operator-before-checkout (the - existing real-env-wins rule, extended one layer down). Finding #5's - injection becomes a no-op against any var the operator actually uses. -3. **A token is sent only to the server it is keyed to.** The legacy - single `OMNIGRAPH_BEARER_TOKEN` fallback keeps working for the - single-server shape, but when a request resolves through a *named* - server, only that name's chain applies (finding #6's broadcast). - -### D6. Compatibility rules (the #139 findings as law) - -| Rule | Source finding | -|---|---| -| No flag or key is removed or renamed; new behavior is additive | #1, #3 | -| A config that loads today loads identically after this RFC; new validation applies only to new keys | #3, #8, #10 | -| Every operator-layer file write is temp + rename, never in-place | #7 | -| `~` expands wherever a path is read | #9 | -| Map merges are per-entry, per-field β€” never wholesale replace | #13 | -| One resolution path per concern β€” the actor chain and the token chain each have exactly one implementation, called by CLI and server alike | #11, #12 | -| Each slice lands as its own PR with the workspace gate green; no slice mixes mechanical moves with behavior changes | #139's disposition | - -## Sequencing - -Three PRs, each independently useful, each landable without the next: - -1. **PR 1 β€” the operator file + identity** *(landed: #196)*. Loader for - `~/.omnigraph/config.yaml` (+ `OMNIGRAPH_HOME`, `~`-expansion, warn-only - unknown keys), `operator.actor` joining the `--as` cascade, - `defaults.output` joining the format cascade, `OMNIGRAPH_CONFIG` env for - the CLI's `--config`. Docs: `cli-reference.md` gains the two-surface - table. -2. **PR 2 β€” keyed credentials** *(landed)*. `servers:` in the operator layer, the - Β§D4 chain (env + credentials file), the Β§D5 trust rules, and - `omnigraph login ` (atomic write, `0600`). Legacy mechanisms - untouched and tested-as-untouched. -3. **PR 3 β€” operator targeting** *(landed)*. `--server ` on remote-capable - commands and `aliases:` in the operator layer (server + graph + query + - default params), resolving through operator-defined servers. This is - the *bridge* toward RFC-002's locator β€” multi-server addressing in a - safe, minimal form without the `GraphLocator` rework β€” and the - replacement RFC-008 needs before legacy aliases can migrate. - -RFC-008's deprecation stages begin only after PRs 1–2 are on main: the -operator surface must exist before `config migrate` has somewhere to move -keys to. - -## Open questions - -- Should `operator.actor` apply to *local* (embedded-engine) writes too, or - only where a server/cluster boundary exists? Leaning yes-everywhere: one - identity chain (Β§D6 one-path rule), and local audit rows get better. -- Does `defaults.output` belong in slice 1, or is identity-only an even - cleaner first PR? (Cost of including it is one cascade hop; value is - immediate.) -- `omnigraph config view --resolved` (RFC-002 had it; #139 shipped a - version) β€” slice 1 or slice 2? It materially helps debugging precedence, - which argues early. - -## Relationship to RFC-002 and RFC-008 - -**RFC-008 is the other half of this design**: this RFC builds the operator -surface; RFC-008 retires the mixed-ownership file -([rfc-008-deprecate-omnigraph-yaml.md](rfc-008-deprecate-omnigraph-yaml.md)), -leaving exactly two config surfaces β€” cluster (team) and operator (person). -Every mention of `omnigraph.yaml` in this RFC describes the deprecation -window only. Sequencing couples them: RFC-007 PRs 1–2 land first, then -RFC-008's migration stages run against them. - -RFC-002 remains the umbrella architecture. This RFC implements its Β§2 -(layered config, global-first), Β§4 (file naming / one dir), and Β§5 -(credentials) in their minimal load-bearing form, and explicitly defers Β§1 -(`GraphLocator`/targets), Β§3 (roles), and the State layer. If/when the -locator work resumes, it builds on these layers rather than re-landing -them. RFC-002's header should gain a pointer here once this merges. diff --git a/docs/dev/rfc-008-deprecate-omnigraph-yaml.md b/docs/dev/rfc-008-deprecate-omnigraph-yaml.md deleted file mode 100644 index 72baaf6..0000000 --- a/docs/dev/rfc-008-deprecate-omnigraph-yaml.md +++ /dev/null @@ -1,178 +0,0 @@ -# RFC: Deprecate `omnigraph.yaml` β€” One Concern per Config Surface - -**Status:** Proposed -**Date:** 2026-06-11 -**Builds on:** [rfc-007-operator-config.md](rfc-007-operator-config.md) (the -operator layer that absorbs the identity/credential keys), -[rfc-005-server-cluster-boot.md](rfc-005-server-cluster-boot.md) (Landed β€” -cluster-booted serving), RFC-006 storage roots (landed: #186/#190/#194). -**Supersedes in part:** RFC-007's "project layer" framing (Β§Relationship -below) and [rfc-002-config-cli-architecture.md](rfc-002-config-cli-architecture.md)'s -assumption that `omnigraph.yaml` remains the project manifest. -**Target release:** staged; final removal at the next major (see Sequencing). - -## Summary - -Retire `omnigraph.yaml`. It is three unrelated concerns wearing one -filename β€” server deployment config, project/CLI conveniences, and operator -identity β€” and the mixture is not a cosmetic wart but the root cause of a -recurring class of problems: operators keeping personal copies of "project" -files, repo checkouts able to carry credential-adjacent keys (the #139 -security findings), `omnigraph init` scaffolding config into unrelated -directories, and every config discussion needing a paragraph to establish -which of the three files is meant. - -The end state is **two config surfaces with single owners**: - -| Surface | Owner | Declares | -|---|---|---| -| **Cluster config** (`cluster.yaml` + catalog) | the team, in a repo | what the system *is*: graphs, schemas, queries, policies, storage | -| **Operator config** (`~/.omnigraph/`) | one person, in `$HOME` | who *I* am: identity, credentials, known servers, ergonomics | - -plus **flags/env** for the zero-config tier (one graph, one server, no -control plane) β€” which already works today with no file at all. - -`omnigraph.yaml` has no role left once every key has a better home. This -RFC gives each key that home, and stages the retirement so that no working -setup breaks without a loud warning, a migration command, and a full -deprecation cycle first. - -## Motivation - -- **It breaks the ownership logic.** A config file must have one owner. A - file that carries `graphs:` (team-owned, reviewable) next to `cli.actor` - (one person's identity) and `auth.env_file` (credential loading) can be - neither safely committed nor sensibly personal. Every real deployment - this cycle tripped on it: per-operator copies in `~/exp/intel`, - graph-scoped alias URIs that only make sense per-person, the #139 - findings where a checkout-supplied file could redirect tokens. -- **The cluster made it redundant.** Since RFC-005/006, a cluster - deployment serves from the applied catalog β€” `--cluster` mode does not - read `omnigraph.yaml` *at all*. Stored queries, policies, bindings, and - graph addressing all have authoritative homes. What remains in - `omnigraph.yaml` for cluster users is dead weight that can silently - disagree with what is actually serving. -- **Two declarative dialects is one too many.** `cluster.yaml` and - `omnigraph.yaml` both declare graphs/queries/policies with different - schemas, different validation strictness, and different lifecycle - guarantees. Maintaining, documenting, and testing both β€” and explaining - when each applies β€” is a permanent tax (the "programming integrated over - time" lens says: this forks on every config-surface change). - -## Non-Goals - -- **Breaking anyone now.** Every `omnigraph.yaml` that works today keeps - working through the entire deprecation window, with warnings. -- **Retiring the zero-config tier.** `omnigraph-server s3://bucket/g.omni - --bind …` plus env vars stays first-class forever β€” that tier needs *no* - file, which is the point. -- **Forcing the control plane on single-graph users.** The migration target - for a multi-graph yaml deployment is a *minimal* cluster (file-rooted, - no bucket required, `cluster.yaml` barely longer than the `graphs:` map - it replaces) β€” but a single graph never needs even that. -- **Touching `cluster.yaml`** β€” its schema and strictness are unchanged. - -## Where every key goes (the complete migration map) - -The full `OmnigraphConfig` surface (verified against -`crates/omnigraph-server/src/config.rs:182-207`): - -| `omnigraph.yaml` key | Concern | New home | -|---|---|---| -| `graphs..uri` | what exists / where | `cluster.yaml` `graphs:` (storage-root-derived) β€” or a flag/env for the zero-config tier | -| `graphs..queries`, top-level `queries:` | what exists | cluster catalog (`.gq` discovery, RFC-004/#183) | -| `graphs..policy.file`, top-level `policy.file`, `server.policy.file` | what's enforced | `cluster.yaml` `policies:` + `applies_to` bindings | -| `server.bind` | deployment runtime | `--bind` / env (already authoritative; the key is a default) | -| `server.graph` | deployment runtime | `--target`-style flag / env in the zero-config tier; meaningless under cluster boot | -| `graphs..bearer_token_env`, `auth.env_file` | credentials | operator credentials chain (RFC-007 Β§D4) | -| `cli.actor` | identity | `operator.actor` (RFC-007 Β§D3) | -| `cli.output_format`, `cli.table_*` | personal ergonomics | `defaults:` in operator config (RFC-007 Β§D2) | -| `cli.graph`, `cli.branch` | personal targeting | operator config: named servers + a per-operator default target (RFC-007 PR 3) | -| `aliases.` | a personal name conflated with a content pointer | **splits in two** (RFC-007 Β§D2 "bindings, not content"): the referenced `.gq` file's *content* becomes a catalog stored query (team-reviewed); the *binding* becomes an operator alias referencing that name. `config migrate` proposes both halves but cannot publish catalog content itself β€” that is a `cluster apply` | -| `query.roots` | discovery convenience | obsolete β€” cluster query discovery (#183) replaced it | -| `project.name` | label | dropped (the cluster's `metadata.name` is the deployment label) | - -Two placements worth defending: - -- **Aliases are operator config, not cluster config.** The stored query is - the shared contract (catalog-owned, digest-pinned); an alias is one - person's shorthand with their favorite default params and target. Putting - aliases in the cluster would force team review on personal ergonomics; - leaving them per-directory recreates today's problem. Per-operator, - keyed by server/graph name, is the AWS-profile shape. -- **Multi-graph serving without a control plane migrates to a minimal - cluster, not to a new file.** The honest cost: `cluster import` + `apply` - once, on a `file://` root next to the graphs. The honest benefit: one - declarative dialect, one validation path, one serving source β€” and the - upgrade path to buckets/approvals is a one-line `storage:` change instead - of a re-platform. - -## Deprecation mechanics - -Per Hyrum's Law (the repo's own deny-list: shipped observable behavior is -contract), retirement is staged, loud, and tooled: - -1. **Warn** *(landed)*. Loading `omnigraph.yaml` emits a one-line deprecation notice - naming the replacement for each key actually present in the file (not a - generic banner β€” the migration map above, applied to *your* file). - Suppressible per-process (`OMNIGRAPH_SUPPRESS_YAML_DEPRECATION=1`) for - CI logs during the window. -2. **Migrate** *(landed)*. `omnigraph config migrate` reads an existing - `omnigraph.yaml` and writes the split: the team half as a ready-to-review - `cluster.yaml` (+ moves query/policy files into the checkout layout), - the personal half merged into `~/.omnigraph/config.yaml` β€” printing a - diff-style summary and touching nothing without `--write`. The command - is the test of the migration map's completeness: any key it cannot - place is a bug in this RFC. -3. **Stop scaffolding** *(landed)*. `omnigraph init` stops generating - `omnigraph.yaml` (it scaffolded one into cwd β€” the source of the - test-pollution bug). **No replacement scaffold**: a minimal - `cluster.yaml` is five lines; a generator would be a second copy of the - schema to keep in sync, producing a file that is unusable until - hand-edited anyway (Terraform has no config scaffolder either). New - users copy from the cluster quick-start; migrants get a ready-to-review - `cluster.yaml` from `config migrate`. -4. **Opt-in strict** *(landed β€” the release gap to stages 1–3 collapsed: no version boundary was crossed between them, so all four ship in the same release)*. `OMNIGRAPH_NO_LEGACY_CONFIG=1` turns the warning into - an error β€” for teams that finished migrating and want regressions caught. -5. **Remove at the next major.** Loading the file becomes an error pointing - at `config migrate`. The `OmnigraphConfig` code path, the dual - query-registry loaders, and the yaml-mode server boot source are deleted - β€” the payoff that makes the whole exercise worth it. - -Stages 1–3 can land in one release once RFC-007 PRs 1–2 exist (the operator -layer must exist before anything can migrate *to* it). Stage 4 the release -after. Stage 5 at the major, with the removal listed in release notes from -stage 1 onward. - -## What this deletes, eventually - -- The `OmnigraphConfig` struct and its 12-key surface, the - `load_config`/`load_cli_config` pair and its env-side-effect, the - scaffolder, and the legacy resolution paths (`resolve_cli_graph`'s dual - modes β€” finding #11's root cause). -- The yaml-mode multi-graph server boot (`ServerConfigMode::Multi` keeps - existing β€” cluster boot constructs it β€” but its `omnigraph.yaml` source - goes). -- An entire class of documentation ("which file does X go in?") and the - #139 security surface (a checkout cannot hijack what no longer loads). - -## Relationship to RFC-007 and RFC-002 - -RFC-007 ships the operator layer this RFC migrates *to*; its "project -layer" language should be read as transitional β€” after this RFC, the -project layer **is** the cluster checkout, and RFC-007's PR 3 (project -`server:` references) applies to `cluster.yaml`-adjacent operator targeting -rather than to `omnigraph.yaml`. RFC-002's locator/state-layer work, if -resumed, targets the two-surface world directly. RFC-002's file-naming -decisions (`~/.omnigraph/` as the one dir) are unaffected. - -## Open questions - -- **Window length**: one minor release between warn (stage 1) and strict - (stage 4), or two? Cookbooks, skills, and the deployment docs all need - the same pass; the migration command makes a short window defensible. -- **`omnigraph login` vs `config migrate` ordering** β€” both write - `~/.omnigraph/`; whichever lands first establishes the file-locking and - atomic-write helpers the other reuses. -- **Does the MCP server config** (RFC-003) reference `omnigraph.yaml` - anywhere that needs the same treatment? To be audited in stage 1. diff --git a/docs/dev/testing.md b/docs/dev/testing.md index a817428..425fcee 100644 --- a/docs/dev/testing.md +++ b/docs/dev/testing.md @@ -7,9 +7,8 @@ This file is the always-on map of the test surface. **Consult it before every ta | Crate | Path | Style | |---|---|---| | `omnigraph` (engine) | `crates/omnigraph/tests/` | Integration tests (21 files), fixture-driven, share `tests/helpers/mod.rs` | -| `omnigraph-cli` | `crates/omnigraph-cli/tests/` | `cli.rs` (unit-ish; includes the `cluster_e2e_*` lifecycle compositions over the spawned binary β€” lost-state re-import recovery, out-of-band drift, graph-root destruction, multi-graph mixed-disposition convergence), `system_local.rs` (incl. the full-cycle cluster lifecycle with a spawned `--cluster` server β€” declareβ†’serveβ†’evolveβ†’drift-healβ†’approved-delete β€” and applied-policy enforcement over HTTP), `system_remote.rs`, share `tests/support/mod.rs` | -| `omnigraph-cluster` | mostly in-source `#[cfg(test)] mod tests`; `tests/failpoints.rs` (feature-gated); `tests/s3_cluster.rs` (bucket-gated full lifecycle on object storage) | Cluster config parser, local JSON state diff, state CAS/lock handling/recovery, read-only validate/plan/status plus explicit refresh/import graph observations, config-only apply (content-addressed payload publish, disposition gating, composite-digest convergence, idempotent re-apply), catalog payload verification (status read-only, refresh drift + self-heal), failpoint crash-mid-apply / CAS-race coverage, Stage 4A graph creation (create executor, recovery sidecars + sweep rows, create crash windows), Stage 4B schema apply (migration previews in plan, schema executor, schema-apply sweep classification, schema crash windows), Stage 4C gated deletes (digest-bound approvals, delete executor + tombstones, delete sweep rows, delete crash windows), and 5A policy binding metadata (applies_to in the applied revision, binding-change diffing + convergence, pre-5A backfill), and the 5B serving-snapshot read API (converged read, refusal rows) | -| `omnigraph-server` | `crates/omnigraph-server/tests/` | `server.rs` (HTTP-level; incl. cluster-mode boot β€” converged-dir serving, policy binding wiring, boot refusals), `openapi.rs` (OpenAPI drift / regeneration) | +| `omnigraph-cli` | `crates/omnigraph-cli/tests/` | `cli.rs` (unit-ish), `system_local.rs`, `system_remote.rs`, share `tests/support/mod.rs` | +| `omnigraph-server` | `crates/omnigraph-server/tests/` | `server.rs` (HTTP-level), `openapi.rs` (OpenAPI drift / regeneration) | | `omnigraph-compiler` | mostly in-source `#[cfg(test)] mod tests` | Parser, type-checker, IR lowering, lint | The engine's `tests/` is the principal coverage surface; most graph-shaped behavior is exercised there. @@ -21,7 +20,7 @@ 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. | -| `writes.rs` | Direct-publish writes: cancellation, non-strict insert/merge rebase under the per-table queue, strict stale-write conflicts, 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` | Graph lifecycle, schema state | | `point_in_time.rs` | Snapshots, time travel (`snapshot_at_version`, `entity_at`) | @@ -35,10 +34,10 @@ The engine's `tests/` is the principal coverage surface; most graph-shaped behav | `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), `repair` (explicit uncovered-drift publish), and `cleanup` (version GC): empty/idempotent/no-op edges, policy validation, head preservation; `optimize` publishes its own compaction (`optimize_publishes_compaction_to_manifest_so_schema_apply_succeeds`), skips pre-existing uncovered drift (`optimize_skips_preexisting_manifest_head_drift`), and refuses to run while a `__recovery` sidecar is pending (`optimize_defers_when_recovery_sidecar_is_pending`); `repair` previews/heals verified maintenance drift, refuses raw semantic drift without `--force`, and forced repair publishes only by explicit operator choice | -| `failpoints.rs` | Failure-injection coverage (gated on `failpoints` feature). Includes the five per-writer Phase B β†’ recovery integration tests (`recovery_rolls_forward_after_finalize_publisher_failure`, `schema_apply_phase_b_failure_recovered_on_next_open`, `branch_merge_phase_b_failure_recovered_on_next_open`, `ensure_indices_phase_b_failure_recovered_on_next_open`, `optimize_phase_b_failure_recovered_on_next_open`). | +| `maintenance.rs` | `optimize` (compaction) + `cleanup` (version GC): empty/idempotent/no-op edges, policy validation, head preservation | +| `failpoints.rs` | Failure-injection coverage (gated on `failpoints` feature). Includes the four per-writer Phase B β†’ recovery integration tests (`recovery_rolls_forward_after_finalize_publisher_failure`, `schema_apply_phase_b_failure_recovered_on_next_open`, `branch_merge_phase_b_failure_recovered_on_next_open`, `ensure_indices_phase_b_failure_recovered_on_next_open`). | | `recovery.rs` | Open-time recovery sweep β€” sidecar I/O, classifier dispatch (NoMovement / RolledPastExpected / UnexpectedAtP1 / UnexpectedMultistep / InvariantViolation), all-or-nothing decision, roll-forward via `ManifestBatchPublisher::publish`, roll-back via `Dataset::restore`, audit row in `_graph_commit_recoveries.lance`, `OpenMode::ReadOnly` skip path | -| `composite_flow.rs` | Compositional/narrative end-to-end stories β€” multi-step flows that compose mechanics covered by other test files. Catches integration regressions where individual operations all pass their unit tests but their composition breaks (sequential merges, post-merge main writes, time-travel through merge DAG, reopen consistency over multi-merge histories, post-optimize and post-cleanup strict writes). | +| `composite_flow.rs` | Compositional/narrative end-to-end stories β€” multi-step flows that compose mechanics covered by other test files. Catches integration regressions where individual operations all pass their unit tests but their composition breaks (sequential merges, post-merge main writes, time-travel through merge DAG, reopen consistency over multi-merge histories). | ## Fixtures @@ -54,26 +53,21 @@ The engine's `tests/` is the principal coverage surface; most graph-shaped behav ## Failpoints (fault injection) -- Cargo feature: `failpoints = ["dep:fail", "fail/failpoints"]` (in `crates/omnigraph/Cargo.toml` **and** `crates/omnigraph-cluster/Cargo.toml`; the cluster feature does not enable the engine's). -- Wrappers: `crates/omnigraph/src/failpoints.rs` and `crates/omnigraph-cluster/src/failpoints.rs` expose `maybe_fail("name")` and `ScopedFailPoint` for tests. -- Call sites are inserted at sensitive transaction boundaries (branch create, graph publish commit, cluster apply's payloadβ†’state-write window, etc.). -- Activated tests: `crates/omnigraph/tests/failpoints.rs` and `crates/omnigraph-cluster/tests/failpoints.rs` (crash-mid-apply + state CAS race via `fail::cfg_callback`; integration binaries, never in-source β€” the fail registry is process-global). Run with `cargo test -p omnigraph-engine --features failpoints --test failpoints` / `cargo test -p omnigraph-cluster --features failpoints --test failpoints`. +- Cargo feature: `failpoints = ["dep:fail", "fail/failpoints"]` (in `crates/omnigraph/Cargo.toml`). +- Wrapper: `crates/omnigraph/src/failpoints.rs` exposes `maybe_fail("name")` and `ScopedFailPoint` for tests. +- Call sites are inserted at sensitive transaction boundaries (branch create, graph publish commit, etc.). +- Activated tests: `crates/omnigraph/tests/failpoints.rs`. Run with `cargo test -p omnigraph-engine --features failpoints --test failpoints`. ## RustFS / S3 integration 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 s3` (single-graph serving + config-free `--cluster s3://` boot) -- `cargo test -p omnigraph-cluster --test s3_cluster` (full control-plane lifecycle on the bucket) +- `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. -## System e2e requirements and suppression - -The CLI system tests (`system_local.rs`) spawn the workspace-built `omnigraph` and `omnigraph-server` binaries (cargo provides paths via `CARGO_BIN_EXE_*`), bind ephemeral localhost ports, and use local-FS temp dirs β€” no external services, no env vars required; they run in the default `cargo test --workspace`. The comprehensive cluster lifecycle e2es (multi-server-restart flows) honor an opt-out for constrained sandboxes: set `OMNIGRAPH_SKIP_SYSTEM_E2E=1` to skip them with a logged message (the same graceful-skip pattern as the S3 gate). Cargo-native filtering also works: `cargo test --test system_local -- --skip local_cluster`. - ## 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-repository PRs and otherwise runs in strict-check mode (env: `OMNIGRAPH_UPDATE_OPENAPI`). diff --git a/docs/dev/writes.md b/docs/dev/writes.md index 5647d82..974f7a6 100644 --- a/docs/dev/writes.md +++ b/docs/dev/writes.md @@ -14,11 +14,8 @@ publisher's row-level CAS on `__manifest` is the single fence. - No `RunRecord`, no `_graph_runs.lance`, no `_graph_run_actors.lance`. - No `omnigraph run *` CLI subcommands and no `/runs/*` HTTP endpoints. -- No `__run__` staging branches; `__run__*` is no longer a reserved - name. The branch-name guard was removed in MR-770, and any stale - `__run__*` branch on an upgraded graph is swept off `__manifest` by the - v2β†’v3 internal-schema migration on first read-write open. (The inert - `_graph_runs.lance` bytes remain until a `delete_prefix` primitive lands.) +- No `__run__` staging branches. (Legacy on-disk artifacts from + pre-MR-771 repos are inert; MR-770 sweeps them in production.) - Cancelled mutation futures leave **no graph-level state** β€” only orphaned Lance fragments, which the existing `omnigraph cleanup` pipe reclaims. @@ -48,7 +45,7 @@ shared by both `mutate_as` and the bulk loader: touched sub-tables. Cross-table conflicts surface as `ManifestConflictDetails::ExpectedVersionMismatch`. - **Deletes still inline-commit.** Lance's `Dataset::delete` is not - exposed as a two-phase op in 6.0.1; deletes go through `delete_where` + exposed as a two-phase op in 4.0.0; deletes go through `delete_where` immediately and record their post-write state in `MutationStaging.inline_committed`. The parse-time Dβ‚‚ rule (below) prevents inserts/updates from coexisting with deletes in one query, @@ -82,14 +79,16 @@ Three writers have been migrated onto staged primitives: * **`ensure_indices`** (`db/omnigraph/table_ops.rs::build_indices_on_dataset_for_catalog`) β€” scalar indices (BTree, Inverted) now use `stage_create_*_index` + `commit_staged`. Vector indices stay inline (residual β€” Lance - `build_index_metadata_from_segments` is `pub(crate)` in 6.0.1; + `build_index_metadata_from_segments` is `pub(crate)` in 4.0.0; companion ticket to lance-format/lance#6658 needed). * **`branch_merge::publish_rewritten_merge_table`** (`exec/merge.rs`) β€” merge_insert now uses `stage_merge_insert` + `commit_staged`. Deletes stay inline (Lance #6658 residual). * **`schema_apply` rewritten_tables** (`db/omnigraph/schema_apply.rs`) - β€” rewrites use `stage_overwrite` + `commit_staged`, including empty-table - rewrites via a zero-fragment Lance `Operation::Overwrite`. + β€” non-empty rewrites use `stage_overwrite` + `commit_staged`. + Empty-batch rewrites stay inline (Lance `InsertBuilder::execute_uncommitted` + rejects empty data; the empty case is rare and bounded by the + schema-apply lock branch). A defense-in-depth integration test (`tests/forbidden_apis.rs`) walks engine source and fails if non-allow-listed code calls Lance's @@ -104,32 +103,34 @@ the same drift class. Closing it requires either upstream Lance multi-dataset commit OR the omnigraph-side recovery-on-open reconciler described in `.context/mr-793-design.md` Β§15 (deferred to MR-795). -### Inline-commit residuals live on `InlineCommitResidual`, not `db.storage()` (MR-793 acceptance Β§1, by construction) +### Inline-commit method residuals on `TableStorage` (MR-793 acceptance Β§1 option b) -MR-793's acceptance criterion Β§1 ("`TableStore` (or successor) public API has no method that performs a manifest commit as a side effect of writing") holds **by construction** after MR-854. `db.storage()` (`&dyn TableStorage`) exposes only staged primitives + reads; the inline-commit writes Lance cannot yet stage live on a separate `InlineCommitResidual` trait reached via `Omnigraph::storage_inline_residual()`. A new engine writer cannot couple a write with a Lance HEAD advance through the default surface β€” it would have to name the residual accessor explicitly. The dead legacy methods (trait `append_batch` / `merge_insert_batches`, inherent `merge_insert_batch{,es}`, `create_{btree,inverted}_index`) were removed; appends/merges and scalar index builds all use the `stage_*` primitives. +MR-793's acceptance criterion Β§1 ("`TableStore` public API has no method that performs a manifest commit as a side effect of writing") is met **per-method** by enumerating every inline-commit method that remains on the trait surface, naming why it cannot yet be removed, and keeping the residual comment at every call site: -Two methods remain on `InlineCommitResidual`, each named honestly at its call site: - -| Residual method | Inline-commit reason | Closes when | +| Method on `TableStore` | Inline-commit reason | Closes when | |---|---|---| -| `delete_where` | `DeleteBuilder::execute_uncommitted` is not in Lance v6.0.1 (closed upstream as [#6658](https://github.com/lance-format/lance/issues/6658) but first ships in `v7.0.0-beta.10`); see [docs/dev/lance.md](lance.md) | MR-A: Lance v7.x bump migrates `delete_where` to staged, retires the parse-time Dβ‚‚ mutation rule, and extends recovery sidecar coverage | -| `create_vector_index` | Vector indices take Lance's "segment commit path"; `build_index_metadata_from_segments` is `pub(crate)` (Lance [#6666](https://github.com/lance-format/lance/issues/6666) still open) | Lance #6666 lands and `stage_create_vector_index` joins the staged surface | +| `delete_where` | `DeleteJob` is `pub(crate)` in lance-4.0.0 β€” no public two-phase delete API | [lance-format/lance#6658](https://github.com/lance-format/lance/issues/6658) lands and `stage_delete` joins the trait | +| `create_vector_index` | Vector indices take Lance's "segment commit path"; the helper `build_index_metadata_from_segments` is `pub(crate)` | [lance-format/lance#6666](https://github.com/lance-format/lance/issues/6666) lands and `stage_create_vector_index` joins the trait | +| `append_batch` | Legacy inherent method; some engine call sites haven't migrated to `stage_append + commit_staged` yet | MR-793 Phase 1b (call-site conversion) + Phase 9 (demote to `pub(crate)`) | +| `merge_insert_batch` / `merge_insert_batches` | Legacy inherent method | Same β€” Phase 1b + Phase 9 | +| `overwrite_batch` | Legacy inherent method | Same β€” Phase 1b + Phase 9 | +| `create_btree_index` (inherent) | Legacy inherent method (the migrated callers use `stage_create_btree_index` + `commit_staged`; the inherent stays for tests / un-migrated paths) | Same β€” Phase 1b + Phase 9 | +| `create_inverted_index` (inherent) | Same | Same β€” Phase 1b + Phase 9 + index-class split (MR-848) | +| `truncate_table` (inherent on `TableStore`) | Used by `overwrite_batch` internally | Phase 9 | -The `tests/forbidden_apis.rs` guard still catches direct `lance::*` inline-commit misuse outside the storage layer; the trait split makes the staged-only default a type-system guarantee on top of it. +After **lance#6658 + lance#6666 ship + MR-793 Phase 1b + MR-793 Phase 9 all complete**, the trait surface exposes only staged-write primitives + `commit_staged`. Until then this matrix names every residual explicitly, every call site carries a one-line residual comment, and no engine code outside `table_store.rs` is permitted to reach the inline-commit Lance APIs (enforced by the `tests/forbidden_apis.rs` guard). -### `LoadMode::Overwrite` uses staged Lance `Overwrite` +### `LoadMode::Overwrite` residual -The bulk loader's Append, Merge, and Overwrite modes all use the -staged-write path described above. `LoadMode::Overwrite` accumulates -replacement batches in memory, validates node/edge constraints, referential -integrity, and edge cardinality before any Lance HEAD movement, stages -each touched table with Lance `Operation::Overwrite`, then runs -`commit_staged` under the normal `SidecarKind::Load` recovery sidecar -before publishing `__manifest`. `OMNIGRAPH_LOAD_CONCURRENCY` applies to the -fragment-writing stage only; the commit and manifest publish still run -under the per-table write queues. Empty-table overwrite is represented as -a valid zero-fragment Lance `Overwrite` transaction, not as -truncate-then-append. +The bulk loader's Append and Merge modes use the staged-write path +described above. `LoadMode::Overwrite` keeps the legacy inline-commit +path: truncate-then-append doesn't fit the staged shape cleanly in +Lance 4.0.0, and overwrite has no in-flight read-your-writes +requirement (the prior data is being wiped). A mid-overwrite failure +can leave Lance HEAD on a partially-truncated table; the next overwrite +will replace it. Operator-driven (rare in agent workloads); document +permanently until Lance exposes `Operation::Overwrite { fragments }` as +a two-phase op. ### Open-time recovery sweep @@ -153,14 +154,10 @@ are left at `Lance HEAD = manifest_pinned + 1`. **Recovery protocol** (lifecycle of every staged-write writer β€” `MutationStaging::finalize`, `schema_apply::apply_schema_with_lock`, -`branch_merge_on_current_target`, `ensure_indices_for_branch`, -`optimize_all_tables`): +`branch_merge_on_current_target`, `ensure_indices_for_branch`): 1. **Phase A**: writer writes a sidecar JSON to - `__recovery/{ulid}.json` BEFORE its first HEAD-advancing commit - (`commit_staged`, or `compact_files` for `optimize_all_tables`, - which advances the Lance HEAD via a reserve-fragments + rewrite - commit rather than a staged write). The + `__recovery/{ulid}.json` BEFORE its first `commit_staged`. The sidecar names every `(table_key, table_path, expected_version, post_commit_pin)` it intends to commit + the writer kind + actor_id. @@ -195,13 +192,8 @@ recovery sweep in `crates/omnigraph/src/db/manifest/recovery.rs`: otherwise full open-time recovery rolls them back and refresh-time recovery leaves them for the next read-write open. - Otherwise **roll back**: per-table `Dataset::restore` to the - manifest-pinned table version, then a single `ManifestBatchPublisher::publish` - of the restored HEAD β€” symmetric with roll-forward, so `manifest == HEAD` - after recovery (no residual drift). This convergence is what lets a - failed-then-retried schema apply succeed instead of failing one version higher - each iteration. The audit row's `to_version` records the logical - rolled-back-to version (`manifest_pinned`); the manifest is published at the - restore commit (`manifest_pinned + 1`, same content). + manifest-pinned table version for that branch. Rollback records the + actual restore target in the audit row's `to_version`. - After a successful roll-forward or roll-back, an audit row is recorded β€” `_graph_commits.lance` carries a commit tagged `actor_id = "omnigraph:recovery"`, and a sibling @@ -253,14 +245,9 @@ list`. ## Migration code -`db/manifest/migrations.rs` carries the v2β†’v3 internal-schema step (MR-770): -a one-time sweep that deletes legacy `__run__*` staging branches off -`__manifest`. It runs in `Omnigraph::open(ReadWrite)` (via -`manifest::migrate_on_open`, before the coordinator reads branch state) and -again on the publisher's write path; both are idempotent once the stamp is at -v3. Deleting the inert `_graph_runs.lance` / `_graph_run_actors.lance` dataset -*bytes* is still deferred β€” it needs a `StorageAdapter::delete_prefix` -primitive β€” but those bytes are invisible to graph-level state. +`db/manifest/migrations.rs` does not change. Active deletion of +`_graph_runs.lance` belongs in MR-770 (the production sweep) β€” this PR +stops *creating* run state but does not destroy legacy bytes on disk. ## Mid-query partial failure: closed by MR-794 @@ -282,7 +269,7 @@ guarantee β€” the in-memory accumulator evaporates with the dropped task and no Lance write was ever issued. For delete-touching mutations the legacy inline-commit shape is -preserved (Lance has no public two-phase delete in 6.0.1) β€” the same +preserved (Lance has no public two-phase delete in 4.0.0) β€” the same narrow window remains. The parse-time Dβ‚‚ rule prevents inserts/updates from coexisting with deletes in one query, so a pure-delete failure cannot drift any staged-table state. If a delete-only multi-table diff --git a/docs/releases/v0.6.1.md b/docs/releases/v0.6.1.md index eb76e1f..aafe1af 100644 --- a/docs/releases/v0.6.1.md +++ b/docs/releases/v0.6.1.md @@ -7,7 +7,6 @@ v0.6.1 focuses on operational polish after v0.6.0: stored-query registries, safe - **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. -- **Legacy `__run__` cleanup (MR-770).** *(Correction: this item shipped in [v0.6.2](v0.6.2.md), not v0.6.1 β€” the v0.6.1 notes over-claimed it. At the v0.6.1 tag the `__run__` branch-name guard and `run_registry.rs` were still present and no v2β†’v3 sweep migration existed.)* The guard removal and the one-time v2β†’v3 `__manifest` migration that sweeps stale `__run__*` staging branches on first read-write open are described in the v0.6.2 release notes. - **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. @@ -18,7 +17,6 @@ v0.6.1 focuses on operational polish after v0.6.0: stored-query registries, safe - 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. -- **Legacy `__run__` migration.** *(Correction: deferred to [v0.6.2](v0.6.2.md).)* The automatic v2β†’v3 `__manifest` stamp migration that sweeps stale `__run__*` branches on first read-write open ships in v0.6.2, not v0.6.1; a v0.6.1 binary does not perform it. See the v0.6.2 notes for the migration behavior and the read-only caveat. - 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. diff --git a/docs/releases/v0.6.2.md b/docs/releases/v0.6.2.md deleted file mode 100644 index f97f67b..0000000 --- a/docs/releases/v0.6.2.md +++ /dev/null @@ -1,69 +0,0 @@ -# Omnigraph v0.6.2 - -v0.6.2 is a maintenance-safety release on top of v0.6.1. It tightens the -`optimize` / recovery boundary, adds an explicit repair path for uncovered -manifest/head drift, completes the legacy `__run__` branch cleanup (MR-770), -accepts pretty-printed JSON load input, and updates the project governance and -release automation around those fixes. - -## Highlights - -- **Explicit `omnigraph repair`.** New `repair` CLI support previews uncovered - manifest/head drift by default and reports each table's classification, - action, manifest version, Lance HEAD version, Lance operations, and any - classification error. `--confirm` publishes verified maintenance-only drift; - `--force --confirm` can publish suspicious or unverifiable drift after - operator review. -- **Optimize skips uncovered drift.** `omnigraph optimize` now refuses to - interpret Lance HEAD movement that is ahead of `__manifest` without a recovery - sidecar. Those tables are reported as `skipped: DriftNeedsRepair` and left - untouched until `omnigraph repair` classifies them. -- **Optimize publishes compaction.** Successful compaction now publishes the - compacted Lance version back through the graph manifest and is covered by an - `Optimize` recovery sidecar. A crash after Lance compaction but before - manifest publish converges through the normal recovery sweep instead of - leaving hidden drift. -- **Recovery roll-back convergence.** Recovery roll-back now aligns the - manifest-visible version after restoring a table, closing the residual where - Lance HEAD and `__manifest` could stay out of sync after recovery. -- **Legacy `__run__` branch cleanup (MR-770).** Completes the retirement of the - Run state machine (removed in v0.4.0). A one-time v2β†’v3 `__manifest` - internal-schema migration runs on the first read-write open and deletes any - stale `__run__*` staging branches left by pre-v0.4.0 graphs β€” they previously - leaked into `branch list` and counted as blocking branches at `schema apply` - time. The migration is idempotent, and the `is_internal_run_branch` guard - (and `run_registry.rs`) is retired now that `__run__*` is an ordinary branch - name. (The earlier v0.6.1 notes described this as shipped in v0.6.1; it - actually landed here in v0.6.2.) -- **Pretty-printed JSON load input.** `load` accepts multi-line JSON objects in - addition to one-object-per-line JSONL, so formatted fixture or export files no - longer need to be minified before import. - -## Operational Notes - -- `repair` requires a clean recovery state. Pending `__recovery` sidecars still - belong to automatic open-time recovery; reopen the graph first, then run - repair if drift remains. -- `repair --confirm` only auto-publishes drift made of Lance maintenance - operations (`Rewrite` and `ReserveFragments`). Semantic operations such as - append, delete, update, and merge are refused unless the operator uses - `--force --confirm`. -- `optimize` remains non-destructive. It still skips blob-bearing tables while - OmniGraph is pinned to the Lance version with the blob-v2 compaction issue. -- No manual on-disk migration is required. Existing graphs open under v0.6.2. - Graphs already at internal manifest schema stamp v3 are unchanged; graphs - created before v0.4.0 that still carry the v2 stamp auto-migrate v2β†’v3 on the - first **read-write** open (the `__run__*` sweep above). The migration is - write-path-only, so a long-lived **read-only** deployment still lists any - stale `__run__*` branch until it is next opened read-write. - -## Docs, Governance, And CI - -- Added issue, discussion, RFC, and pull-request templates plus governance docs - for the external contribution path. -- Regenerated CODEOWNERS tables and adjusted branch-protection docs so code - owners can bypass required PR review where repository rules allow it. -- Trimmed Windows release builds out of per-PR CI and kept Windows packaging on - tag releases. -- Made Homebrew audit diagnostic-only in the release workflow so a flaky audit - cannot block publishing an otherwise valid formula update. diff --git a/docs/rfcs/0000-template.md b/docs/rfcs/0000-template.md deleted file mode 100644 index 48f4bda..0000000 --- a/docs/rfcs/0000-template.md +++ /dev/null @@ -1,54 +0,0 @@ -# RFC NNNN: - -| | | -|---|---| -| **Status** | Proposed | -| **Author(s)** | <your name / handle> | -| **Discussion** | <link to the originating Discussion, if any> | -| **Implementation** | <issue/PR links, filled in as work lands> | - -> Status is maintained by maintainers: `Proposed` while the PR is open, -> `Accepted` on merge, `Declined` on close, `Superseded by NNNN` later. - -## Summary - -One paragraph: what this changes, in plain terms. - -## Motivation - -What problem does this solve, and why is it worth the ongoing cost? Tie it to a -concrete need (a Discussion, a recurring issue, a user request). Per the -project's first principle, argue the *long-run liability*, not just the -short-term convenience. - -## Guide-level explanation - -Explain the change as you'd teach it to a user or contributor: new commands, -syntax, API shapes, behavior. Examples first. - -## Reference-level design - -The precise design: data structures, IR/AST/planner changes, storage/format -impact, migration path, error behavior. Enough that a reviewer can find the -holes. - -## Invariants & deny-list check - -Which Hard Invariants in [../dev/invariants.md](../dev/invariants.md) does this -touch? Does it brush against any deny-list item β€” and if so, why is this the -justified exception? State explicitly that no invariant is weakened, or which -Known Gap moves. - -## Drawbacks & alternatives - -What does this cost, what did you reject, and why. "Do nothing" is a valid -alternative to weigh. - -## Reversibility - -Is this reversible? On-disk/wire/format and substrate choices are near-permanent -and demand more evidence; a CLI flag or doc is cheap to undo. Say which this is. - -## Unresolved questions - -What's deliberately left open for review to settle. diff --git a/docs/rfcs/README.md b/docs/rfcs/README.md deleted file mode 100644 index 99cdd76..0000000 --- a/docs/rfcs/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# RFCs - -Substantial changes to OmniGraph β€” new user-facing surface, format or protocol -changes, anything irreversible or cross-cutting β€” go through a lightweight RFC -so the design is agreed *as reviewable code* before implementation starts. This -is the public RFC track, open to **anyone, including external contributors**. - -This complements the always-on review bar in -[../dev/invariants.md](../dev/invariants.md): the invariants say *what every -change must respect*; an RFC says *why this particular change is worth making and -how*. - -> **Two tracks, don't conflate them.** This `docs/rfcs/` directory is the -> **public contribution** track (anyone authors; maintainers accept). The -> maintainer-internal RFCs under `docs/dev/rfc-00N-*.md` are a separate, -> team-owned track for in-flight internal work. If you're an outside -> contributor, you're in the right place here. - -## When you need one - -- **RFC required:** new query/schema/CLI/HTTP surface; on-disk or wire-format - changes; a new substrate dependency; anything the deny-list in - [../dev/invariants.md](../dev/invariants.md) flags; anything irreversible - ("reversibility shapes evidence demand"). -- **RFC not required:** bug fixes for an `accepted` issue, and the trivial - fast-lane (typos, docs, deps) β€” see [../../CONTRIBUTING.md](../../CONTRIBUTING.md). - -If you're unsure, start a [Discussion](../../../discussions); a maintainer will -tell you whether it needs an RFC. - -## Lifecycle - -``` -Discussion (incubate, get rough consensus) - β”‚ graduate - β–Ό -RFC pull request β†’ adds docs/rfcs/NNNN-title.md (Status: Proposed) - β”‚ -maintainer review ──▢ changes requested / declined (PR closed, with rationale) - β”‚ - β–Ό -merged == Accepted (the merged file is the durable decision record) - β”‚ - β–Ό -Implementation PR(s) reference the accepted RFC -``` - -- **Author:** anyone. **Acceptance:** a maintainer decision, performed by - merging the RFC PR. Declining is closing it with rationale. -- The merged RFC *is* the accepted record β€” there is no separate sign-off step. -- Later reversals don't edit history: supersede with a new RFC that links back - and flip the old one's `Status` to `Superseded`. - -## Numbering & naming - -- File: `docs/rfcs/NNNN-kebab-title.md`, where `NNNN` is the next free - zero-padded integer (`0001`, `0002`, …). `0000-template.md` is reserved. -- Pick the number when you open the PR; if it collides with another in-flight - RFC, the second to merge bumps theirs. - -## Status values - -`Proposed` (open PR) Β· `Accepted` (merged) Β· `Declined` (closed) Β· -`Superseded by NNNN` Β· `Implemented` (set once the work lands, optional). - -Copy [0000-template.md](0000-template.md) to start. diff --git a/docs/user/audit.md b/docs/user/audit.md index 845c2e0..e8abe5b 100644 --- a/docs/user/audit.md +++ b/docs/user/audit.md @@ -1,7 +1,7 @@ # Audit / Actor tracking - `Omnigraph::audit_actor_id: Option<String>` is the actor in effect. -- `_as` variants of every write API let callers override the actor: `mutate_as`, `load_as`, `branch_merge_as`, `apply_schema_as`, etc. +- `_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. The CLI resolves one actor chain everywhere: `--as` > legacy `cli.actor` in `omnigraph.yaml` > `operator.actor` in `~/.omnigraph/config.yaml` > none (RFC-007). -- 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. The v2β†’v3 manifest migration sweeps any stale `__run__*` branches on first write-open (MR-770); the inert dataset bytes remain until a `delete_prefix` primitive lands. +- HTTP server uses the bearer-token actor automatically; CLI uses the local user / explicit env (no implicit actor). +- 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 a4044cb..c1894f9 100644 --- a/docs/user/branches-commits.md +++ b/docs/user/branches-commits.md @@ -9,8 +9,8 @@ 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. 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 the internal** `__schema_apply_lock__` branch. -- `branch_delete(name)` β€” refuses if there are descendants on the branch, or if it is the current 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). +- `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. 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. @@ -51,13 +51,13 @@ Notes: ## L2 β€” Internal system branches -Internal or legacy branch refs: +Filtered from `branch_list()` but visible to internals: -- `__schema_apply_lock__` β€” serializes schema migrations; filtered from `branch_list()` but visible to internals. -- `__run__<run-id>` β€” legacy from the pre-v0.4.0 Run state machine (removed in MR-771). These are swept off `__manifest` on the first read-write open by the v2β†’v3 internal-schema migration (MR-770), and `__run__*` is no longer a reserved name. Known limitation: a pre-v0.4.0 graph opened **read-only** still surfaces any stale `__run__*` branch in `branch_list()` until its first read-write open (the migration is write-path-only, like all manifest migrations). +- `__schema_apply_lock__` β€” serializes schema migrations. +- `__run__<run-id>` β€” legacy from the pre-v0.4.0 Run state machine (removed in MR-771). The branch-name guard predicate `is_internal_run_branch` is kept as defense-in-depth so users cannot create a branch matching the legacy prefix; the filter will be removed once production legacy branches are swept (MR-770). ## L2 β€” Recovery audit trail -The five migrated writers (`MutationStaging::finalize`, `schema_apply`, `branch_merge`, `ensure_indices`, `optimize_all_tables`) protect their multi-table commits with a sidecar at `__recovery/{ulid}.json` written before Phase B and deleted after Phase C. The next `Omnigraph::open` (gated on `OpenMode::ReadWrite`) runs the recovery sweep in `crates/omnigraph/src/db/manifest/recovery.rs`: classify per-table state, decide all-or-nothing per sidecar, roll forward / back, record an audit row. +The four migrated writers (`MutationStaging::finalize`, `schema_apply`, `branch_merge`, `ensure_indices`) protect their multi-table commits with a sidecar at `__recovery/{ulid}.json` written before Phase B and deleted after Phase C. The next `Omnigraph::open` (gated on `OpenMode::ReadWrite`) runs the recovery sweep in `crates/omnigraph/src/db/manifest/recovery.rs`: classify per-table state, decide all-or-nothing per sidecar, roll forward / back, record an audit row. Audit rows live in `_graph_commit_recoveries.lance` (sibling to `_graph_commits.lance`) and reference the commit graph by `graph_commit_id`. The linked recovery commit is identified by that same `graph_commit_id`, and `actor_id="omnigraph:recovery"` is stored in `_graph_commit_actors.lance` (joined by `graph_commit_id`) β€” `_graph_commits.lance` itself does not carry the `actor_id` column. To find recoveries for a specific original actor: `omnigraph commit list --filter actor=omnigraph:recovery`, then join to `_graph_commit_recoveries.lance` by `graph_commit_id` to read `recovery_for_actor`. Schema: see `crates/omnigraph/src/db/recovery_audit.rs`. diff --git a/docs/user/cli-reference.md b/docs/user/cli-reference.md index b419adf..8263919 100644 --- a/docs/user/cli-reference.md +++ b/docs/user/cli-reference.md @@ -2,116 +2,32 @@ A reference for the `omnigraph` binary's command surface and `omnigraph.yaml` schema. For a quick-start guide, see [cli.md](cli.md). -Top-level command families and subcommands. Graph-targeting commands accept a positional `URI`, `--uri`, a `--target <name>` resolved against `omnigraph.yaml`, or `--server <name>` (an operator-defined server from `~/.omnigraph/config.yaml`, optionally with `--graph <id>` for multi-graph servers; exclusive with the other forms); `cluster` commands use `--config <dir>`. +17 top-level command families, 40+ subcommands. All commands accept either a positional `URI`, `--uri`, or a `--target <name>` resolved against `omnigraph.yaml`. ## Top-level commands | Command | Purpose | |---|---| -| `init` | `--schema <pg>` β†’ initialize a graph (no longer scaffolds `omnigraph.yaml` β€” RFC-008; start cluster configs from the [cluster.md](cluster.md) quick-start or `config migrate`) | -| `load` | bulk load a branch, local or remote (`--mode overwrite\|append\|merge` is **required** β€” overwrite is destructive, so there is no default). Without `--from` the target branch must exist; `--from <base>` forks a missing `--branch` from `<base>` first | -| `ingest` | deprecated alias of `load --from <base>` (defaults: `--from main --mode merge`); prints a one-line warning to stderr | +| `init` | `--schema <pg>` β†’ initialize a graph (also scaffolds `omnigraph.yaml` if missing) | +| `load` | bulk load a branch (`--mode overwrite\|append\|merge`) | +| `ingest` | branch-creating transactional load (`--from <base>`) | | `query` (alias: `read`) | run named read query; source via `--query <path>`, `-e`/`--query-string <GQ>`, or `--alias <name>` (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 | | `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` | -| `config migrate` | propose (or `--write`: apply) the RFC-008 split of a legacy `omnigraph.yaml` β€” team half β†’ ready-to-review `cluster.yaml`, personal half β†’ `~/.omnigraph/config.yaml` (key-level merge, existing entries win), plus dropped-key reasons and manual steps | -| `cluster validate \| plan \| apply \| approve \| status \| refresh \| import \| force-unlock` | declarative cluster control plane. `validate` checks a local `cluster.yaml` folder and referenced schema/query/policy files; `plan` diffs it against local JSON state at `__cluster/state.json`, annotates dispositions, and embeds real schema-migration previews; `apply` converges the cluster β€” stored-query/policy catalog writes (content-addressed under `__cluster/resources/`), graph creates, schema updates (soft drops only; `--as` records the actor), and graph deletes behind a digest-bound approval from `cluster approve <resource> --as <actor>` (`apply`/`approve` default the actor from the per-operator `omnigraph.yaml`'s `cli.actor` when `--as` is omitted; nothing else in that file affects cluster commands); what apply converges is what an `omnigraph-server --cluster <dir>` deployment serves on its next restart (omnigraph.yaml deployments are unaffected); `status` reads the state ledger; `refresh`/`import` explicitly update local JSON state from read-only graph observations; `force-unlock <LOCK_ID>` manually removes a held local state lock by exact id | -| `optimize` | non-destructive Lance compaction (skips tables with `Blob` columns or uncovered drift; `--json` reports `skipped`) | -| `repair [--confirm] [--force]` | preview or explicitly publish uncovered manifest/head drift. `--confirm` heals verified maintenance drift and exits non-zero if suspicious/unverifiable drift is refused; `--force --confirm` publishes suspicious/unverifiable drift after operator review | +| `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 <graph>` 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. Selects `cli.graph`, else `server.graph`, else top-level `policy.file` | | `version` / `-v` | print `omnigraph 0.3.x` | -## Config surfaces - -Two config surfaces with single owners (RFC-007/RFC-008), plus a zero-config -tier: - -| Surface | Owner | Location | Declares | -|---|---|---|---| -| Cluster config | the team, in a repo | `cluster.yaml` + checkout ([cluster-config.md](cluster-config.md)) | what the system **is**: graphs, schemas, queries, policies, storage | -| Operator config | one person | `~/.omnigraph/config.yaml` (override dir with `$OMNIGRAPH_HOME`) | who **I** am: identity, ergonomics | -| Flags / env | per invocation | β€” | everything, explicitly | - -`omnigraph.yaml` (below) is the legacy combined file β€” fully supported -today, slated for staged deprecation (RFC-008); its keys' future homes are -listed there. - -### `~/.omnigraph/config.yaml` (operator) - -```yaml -operator: - actor: act-andrew # default identity for every --as cascade: - # --as > legacy cli.actor > operator.actor > none -servers: # operator-owned endpoints; names key the credentials - prod: - url: https://graph.example.com # no tokens in this file, ever -defaults: - output: table # read format default, below --json/--format/alias/legacy -``` - -Absent file = empty layer. Unknown keys warn and load (a file written for a -newer CLI works on an older one). `$OMNIGRAPH_CONFIG=<path>` stands in for -`--config` (the flag wins) in both the CLI and the server. - -#### Credentials keyed by server name - -`omnigraph login <name>` stores a bearer token in -`~/.omnigraph/credentials` (created `0600`; group/world-readable files are -refused). Token from `--token`, or β€” preferred, keeps it out of shell -history β€” one line on stdin: `echo $TOKEN | omnigraph login prod`. -`omnigraph logout <name>` removes it (idempotent). - -#### Operator aliases β€” bindings, not content - -An operator alias is a personal name for *invoking a stored query on a -named server* β€” it carries no query content (the stored query in the -catalog is the team's contract; the alias, its defaults, and its name are -yours): - -```yaml -aliases: - triage: - server: intel-dev # names an entry under servers: - graph: spike # optional (multi-graph servers) - query: weekly_triage # the STORED query's name β€” never a file - args: [since] # positional args -> params, in order - params: { limit: 20 } # fixed defaults; positionals/--params win - format: table -``` - -`omnigraph query --alias triage 2026-06-01` invokes -`POST <server>/graphs/spike/queries/weekly_triage` with the keyed -credential. A legacy `omnigraph.yaml` alias with the same name wins during -the deprecation window (with a warning). - -A remote command whose URL prefix-matches an operator server's `url` (the -`gh` host model β€” no flags needed) resolves its token through: - -| Order | Source | -|---|---| -| 1 | `OMNIGRAPH_TOKEN_<NAME>` env (`prod` β†’ `OMNIGRAPH_TOKEN_PROD`) | -| 2 | `[<name>]` section in `~/.omnigraph/credentials` | -| 3 | the legacy chain unchanged (`bearer_token_env` β†’ `OMNIGRAPH_BEARER_TOKEN` β†’ `auth.env_file`) | - -A token is only ever sent to the server it is keyed to: URLs matching no -operator server use the legacy chain alone. - -## `omnigraph.yaml` schema (legacy combined file) - -> **Deprecated (RFC-008).** Loading this file prints a per-key notice -> naming each present key's new home (suppress in CI with -> `OMNIGRAPH_SUPPRESS_YAML_DEPRECATION=1`); `omnigraph config migrate` -> produces the split. The file keeps working through the deprecation -> window. Migrated teams can set `OMNIGRAPH_NO_LEGACY_CONFIG=1` to turn -> any legacy-file load into a hard error (regression guard; the file's -> absence is always fine). +## `omnigraph.yaml` schema ```yaml project: { name } @@ -138,7 +54,7 @@ cli: query: roots: [<dir>, …] # search path for .gq files auth: - env_file: .env.omni + env_file: ./.env.omni aliases: <alias>: # accepted values: `read` / `query` (read alias), `change` / `mutate` @@ -154,40 +70,9 @@ aliases: queries: # top-level registry β€” applies only to a bare-URI (anonymous) graph; a graph served by name uses its `graphs.<id>.queries`. Mirrors top-level `policy`. <query-name>: { file: <path-to-.gq> } # mcp.expose defaults to true policy: - file: policy.yaml + file: ./policy.yaml ``` -## Cluster config preview - -```bash -omnigraph cluster validate --config company-brain -omnigraph cluster plan --config company-brain --json -omnigraph cluster apply --config company-brain --json -omnigraph cluster approve graph.<id> --config company-brain --as <actor> -omnigraph cluster status --config company-brain --json -omnigraph cluster refresh --config company-brain --json -omnigraph cluster import --config company-brain --json -omnigraph cluster force-unlock <LOCK_ID> --config company-brain --json -``` - -`--config` is a directory containing `cluster.yaml`; it defaults to `.`. -Stage 3A accepts graphs, schemas, stored queries, and policy bundle file -references. `cluster plan` reads local JSON state from -`<config-dir>/__cluster/state.json`; a missing file means empty state. Plan, -apply, refresh, and import acquire `__cluster/lock.json` by default and release -it before returning. `cluster apply` executes only stored-query/policy catalog -writes (content-addressed under `__cluster/resources/`) and requires an -existing `state.json`; graph/schema changes are deferred with warnings, and -applied resources do not serve traffic β€” the server still boots from -`omnigraph.yaml`. `cluster status` reads state only and reports any existing -lock metadata. `force-unlock` removes a lock only when the supplied id exactly -matches the lock file. `refresh` requires an existing `state.json`; `import` -creates one only when it is missing. Both observe declared graphs read-only at -`<config-dir>/graphs/<graph-id>.omni`. External state backends, graph/schema -apply, automatic stale-lock breaking, `plan --refresh`, pipelines, UI specs, -embeddings, aliases, and bindings are reserved for later stages. See -[cluster-config.md](cluster-config.md). - ## Output formats (`query` command, alias: `read`) - `json` β€” pretty-printed object with metadata + rows diff --git a/docs/user/cli.md b/docs/user/cli.md index a6ce442..b6f2c09 100644 --- a/docs/user/cli.md +++ b/docs/user/cli.md @@ -3,11 +3,11 @@ ## Core Graph Flow ```bash -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 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`); @@ -21,11 +21,11 @@ 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 \ +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 \ +omnigraph mutate --uri ./graph.omni \ -e 'query add($name: String, $age: I32) { insert Person { name: $name, age: $age } }' \ --params '{"name":"Inline","age":42}' ``` @@ -38,14 +38,14 @@ only the source loader changes. ## Branching And Reviewable Data Flows ```bash -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 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 load --data batch.jsonl --branch review/import-2026-04-09 --from main --mode merge 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 <commit-id> --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 <commit-id> --json ``` ## Remote Server Mode @@ -53,7 +53,7 @@ omnigraph commit show --uri graph.omni <commit-id> --json Serve a graph: ```bash -omnigraph-server graph.omni --bind 127.0.0.1:8080 +omnigraph-server ./graph.omni --bind 127.0.0.1:8080 ``` Read through the HTTP API: @@ -61,7 +61,7 @@ Read through the HTTP API: ```bash omnigraph query \ --target http://127.0.0.1:8080 \ - --query queries.gq \ + --query ./queries.gq \ --name get_person \ --params '{"name":"Alice"}' ``` @@ -87,23 +87,23 @@ Runtime add/remove is **not** in v0.6.0. To add a graph, stop the server, add a 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 ... +omnigraph read --uri http://server.example.com/graphs/beta --query ./q.gq ... ``` ## Runs, Policy, And Diagnostics ```bash -omnigraph lint --query queries.gq --schema schema.pg --json -omnigraph check --query queries.gq graph.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 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 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 graph.omni --json -omnigraph commit show --uri graph.omni <commit-id> --json +omnigraph commit list ./graph.omni --json +omnigraph commit show --uri ./graph.omni <commit-id> --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.) @@ -120,7 +120,7 @@ query roots: ```yaml graphs: local: - uri: demo.omni + uri: ./demo.omni dev: uri: http://127.0.0.1:8080 bearer_token_env: OMNIGRAPH_BEARER_TOKEN diff --git a/docs/user/cluster-config.md b/docs/user/cluster-config.md deleted file mode 100644 index 59c9207..0000000 --- a/docs/user/cluster-config.md +++ /dev/null @@ -1,457 +0,0 @@ -# Cluster Config - -**Status:** Phase 5 β€” cluster-booted serving (`omnigraph-server --cluster`). - -> New to the cluster tooling? Start with the operator how-to guide, -> [cluster.md](cluster.md) β€” this document is the reference. - -Cluster config is the future control-plane configuration surface for a whole -OmniGraph deployment. In this stage, OmniGraph can validate a local -`cluster.yaml` folder, produce a deterministic read-only plan, inspect the -local JSON state ledger, explicitly refresh/import graph observations into -that ledger, manually remove a held local state lock by exact lock id, and -**apply the executable subset of the plan** β€” stored-query and policy-bundle -catalog writes, **graph creation** (a declared graph that does not exist yet -is initialized by apply at the derived root), **schema updates** (soft drops -only), and β€” behind an explicit, digest-bound **approval** β€” **graph -deletion**. It does not perform data-loss schema migrations, start servers, -or serve anything it applies: the server still boots from `omnigraph.yaml`. - -## Commands - -```bash -omnigraph cluster validate --config company-brain -omnigraph cluster plan --config company-brain --json -omnigraph cluster apply --config company-brain --json -omnigraph cluster approve graph.<id> --config company-brain --as <actor> -omnigraph cluster status --config company-brain --json -omnigraph cluster refresh --config company-brain --json -omnigraph cluster import --config company-brain --json -omnigraph cluster force-unlock <LOCK_ID> --config company-brain --json -``` - -`--config` points at a directory, not a file. The directory must contain -`cluster.yaml`. When omitted, it defaults to the current directory. - -## Relationship to `omnigraph.yaml` - -`cluster.yaml` does not replace `omnigraph.yaml`, and the two never describe -the same fact. `omnigraph.yaml` is the permanent **per-operator** layer (CLI -defaults, the operator's identity and credential references, graph targets -for data-plane commands); `cluster.yaml` is the shared desired state of a -whole deployment, read only by the `cluster` commands via `--config`. - -The exact contract: - -- **Cluster commands read `omnigraph.yaml` for exactly one thing**: the - `cli.actor` default used by `apply`/`approve` when `--as` is omitted β€” - operator identity is a per-operator fact. With `--as` present, no config - is read at all. Nothing else (its graph set, targets, bind, queries, - policies) ever influences a cluster command; a malformed `omnigraph.yaml` - breaks only the no-flag actor lookup, loudly. -- **A `--cluster` server reads `omnigraph.yaml` for nothing** β€” not even the - implicit current-directory search runs (mode-inference rule 0). Boot from - cluster state XOR `omnigraph.yaml`, never a merge. -- **The other direction is ergonomics, not coupling**: a per-operator - `omnigraph.yaml` may point `graphs.<name>.uri` at a cluster's derived root - (`company-brain/graphs/knowledge.omni`) so data-plane commands can use - `--target <name>` β€” an ordinary local path, no special handling. - -## Supported `cluster.yaml` - -Stage 3A accepts only this resource subset: - -```yaml -version: 1 -metadata: - name: company-brain - -state: - backend: cluster - lock: true - -graphs: - knowledge: - schema: knowledge.pg - queries: queries/ # discover every `query <name>` in queries/*.gq - -policies: - base: - file: base.policy.yaml - applies_to: [knowledge] -``` - -`queries` is Terraform-shaped β€” the `.gq` files are the declaration. Three -forms: - -```yaml -queries: queries/ # directory: top-level *.gq, sorted; every declaration registers -queries: [people.gq, extra/a.gq] # explicit files; every declaration in each -queries: # fine-grained name -> file map - find_experts: - file: knowledge.gq -``` - -Discovery is loud: an unreadable or unparseable `.gq`, or the same query name -declared in two files, fails validation (`query_parse_error`, -`duplicate_query_name`). Each discovered query is still an individually -addressed resource (`query.<graph>.<name>`) with its own plan/apply lifecycle; -the digest is the containing file's hash, so editing a multi-query file -updates all of its queries together. Paths are relative to the config -directory β€” the cluster is one explicit folder, so no `./` prefixes are -needed. - -`storage:` (optional) is the **storage root URI** for everything the cluster -stores β€” the state ledger, lock, content-addressed catalog, recovery -sidecars, approval artifacts, and the derived graph roots -(`<storage>/graphs/<id>.omni`). Absent, it defaults to the config directory -itself (the original layout, byte-compatible with pre-existing clusters). -`s3://bucket/prefix` puts the whole cluster on S3-compatible object storage: -the ledger CAS uses conditional writes (verified against AWS S3 semantics and -RustFS), the lock becomes genuinely cross-machine, and graph roots are -engine-native S3 URIs. Credentials are **never** in `cluster.yaml` β€” the -standard `AWS_*` environment contract applies, identical to graph storage. -Declared configuration (`cluster.yaml` and the schema/query/policy sources it -references) always stays in the working tree: config is versioned in git, -state lives in the store β€” the Terraform split. - -`metadata.name` is a display label. `state.backend` may be omitted or set to -`cluster`; external state backends are reserved for a later stage. `state.lock` -defaults to `true`. When enabled, `cluster plan`, `cluster apply`, -`cluster refresh`, and `cluster import` briefly acquire -`<config-dir>/__cluster/lock.json`, then remove it before returning. `cluster status` never acquires the lock; it only reports -whether one is present. `cluster force-unlock` is the only lock-removal command; -it requires the exact lock id and should be run only after confirming no cluster -operation is active. - -## Validation - -`cluster validate` checks: - -- `cluster.yaml` syntax and supported fields -- duplicate YAML keys -- schema, query, and policy file existence -- schema parsing and catalog construction -- stored-query parsing and query-name matching -- stored-query type-checking against the desired schema -- policy `applies_to` graph references - -Fields reserved for later phases, such as `pipelines`, `embeddings`, `ui`, -`aliases`, and `bindings`, fail with a typed diagnostic instead of being -silently ignored. - -## Planning - -`cluster plan` first performs validation, then reads local JSON state from: - -```text -<config-dir>/__cluster/state.json -``` - -If the file is missing, the state is treated as empty and every desired -resource is planned as a create. If present, the file must use this shape: - -```json -{ - "version": 1, - "state_revision": 0, - "applied_revision": { - "config_digest": "...", - "resources": { - "graph.knowledge": { "digest": "..." }, - "schema.knowledge": { "digest": "..." }, - "query.knowledge.find_experts": { "digest": "..." }, - "policy.base": { - "digest": "...", - "applies_to": ["cluster", "graph.knowledge"] - } - } - }, - "resource_statuses": { - "graph.knowledge": { - "status": "applied", - "conditions": [], - "message": "optional status detail" - } - }, - "approval_records": {}, - "recovery_records": {}, - "observations": {} -} -``` - -`state_revision`, `resource_statuses`, `approval_records`, `recovery_records`, -and `observations` are optional so older Stage 1 state fixtures keep working. -Missing `state_revision` is treated as `0`. Resource status values are -`pending`, `planned`, `applying`, `applied`, `drifted`, `blocked`, or `error`. - -Plan output compares desired resource digests against state resource digests -and reports `create`, `update`, and `delete` changes. It also reports the state -CAS (`sha256:<digest>`) and state revision. `state_observations.locked` means an -existing lock file was observed, along with its metadata (`lock_id`, -`lock_operation`, `lock_created_at`, `lock_pid`, `lock_age_seconds`); a -successful `plan` instead reports `lock_acquired: true` and an -`acquired_lock_id`, then releases the lock before returning. The command never -writes `state.json` and does not scan live graphs. Use explicit -`cluster refresh` / `cluster import` when the state ledger should be updated -from live observations. Live drift scans during plan are later-stage work. - -Policy entries additionally record their applied `applies_to` bindings as -normalized typed refs β€” the state ledger is serving-sufficient for the -future server-boot stage. A change to `applies_to` alone (the policy file -digest unchanged) appears in the plan as an Update marked `binding_change` -(human output: `[bindings]`), applies like any catalog change, and counts -toward convergence; ledgers written before this field existed are backfilled -by the next apply. - -Each plan change carries a `disposition` field β€” an honest preview of what -`cluster apply` will do with it in this stage: `applied` (executes), `derived` -(a `graph.<id>` composite-digest update that converges automatically once its -query digests land), `deferred` (graph/schema change, later phase), or -`blocked` (query/policy gated by an unapplied or missing dependency, with the -condition in `reason`). - -## Apply - -`cluster apply` executes the executable subset of the plan β€” stored-query and -policy-bundle changes, graph creates, and schema updates. There is no confirm -flag: `cluster plan` is the preview, -and apply recomputes the same diff under the state lock before executing, so a -stale preview can never be applied. Apply requires an existing `state.json` -(`state_missing` directs you to `cluster import` first). - -For each applied create/update, the resource payload is written -content-addressed into the local catalog: - -```text -<config-dir>/__cluster/resources/query/<graph>/<name>/<digest>.gq -<config-dir>/__cluster/resources/policy/<name>/<digest>.yaml -``` - -Extensions are fixed per kind regardless of the source file's name. Payloads -are written before the state update because `state.json` is the publish point: -if the final CAS-checked state write fails, no success is reported and the -digest-named blobs already written are inert β€” re-running apply is the repair. -Deletes remove the resource from state; their old payload blobs stay on disk -(garbage collection is a later stage). Re-running a converged apply is a no-op: -no state write, no revision change (`state_written: false`). - -**Applied means serving β€” for deployments that opt in.** A server started -with `--cluster <dir>` boots from the applied revision (see -[Serving from the cluster](#serving-from-the-cluster-the-mode-switch)); it -picks up newly applied state on its next restart. Deployments still booting -from `omnigraph.yaml` are untouched: for them, applied means recorded in the -catalog, nothing more. - -### Graph creation - -A `graph.<id>` create (the graph is declared but no root exists) is executed -by apply: the graph is initialized at the derived root - -```text -<config-dir>/graphs/<graph-id>.omni -``` - -with the declared schema, before any catalog writes, so queries and policies -that depend on the new graph apply **in the same run**. Each create is fenced -by a recovery sidecar under `__cluster/recoveries/{ulid}.json`, written before -the init and removed only after the state update lands. If apply crashes in -between, the next state-mutating command (`apply`, `refresh`, `import`) runs a -**recovery sweep** that classifies the survivor by observation: an absent root -removes the stale intent; a completed create rolls the cluster state forward -(recorded in the state's `recovery_records`); a partial root reports -`graph_create_incomplete` (status `error` β€” remove the root and re-run apply; -nothing is auto-deleted); unexpected graph content reports -`actual_applied_state_pending` (status `drifted` β€” run `cluster refresh` and -re-plan). While a kept sidecar is pending, that graph's create and its -dependents are blocked with `cluster_recovery_pending`. Read-only commands -(`status`, `plan`) warn about pending sidecars without acting on them. - -**Re-creation is convergence.** If a graph root disappears out-of-band, -`refresh` records the drift and the next `plan` proposes a create β€” and apply -will execute it, producing an **empty** graph at the root. The data was -already lost when the root vanished; the create is visible in the plan -(disposition `applied`) before anything runs. - -### Schema updates - -A `schema.<id>` update (the declared schema differs from what state records) -is executed by apply via the engine's schema-apply, after graph creates and -before catalog writes β€” so a query change that depends on the new schema -applies in the same run. Each schema apply is sidecar-fenced like a create: -pre-operation manifest version recorded, post-operation version written back, -sidecar retired only after the state update lands; the recovery sweep -classifies survivors by schema digest (consistent ledger β†’ retired; completed -on the graph β†’ state rolled forward with an audit entry; anything else β†’ -`drifted`/`actual_applied_state_pending`, kept). - -Migrations run with **soft drops only** β€” a removed property disappears from -the current version while prior versions retain the data (reversible until -`cleanup`). Data-loss migrations (`allow_data_loss`) are not reachable from -cluster apply until the approval-artifact stage. Unsupported migrations -(e.g. changing a property's type), engine lock contention, or graphs with -user branches fail loudly as `schema_apply_failed` with the engine's message; -dependent changes are demoted to `blocked` and graph-moving work stops for -the run. - -`cluster plan` previews schema updates with the engine's real migration plan: -each schema change carries a `migration` field (`supported` + typed steps), -and the human output prints the steps. If the live graph cannot be opened the -preview degrades to the digest diff with a `schema_preview_unavailable` -warning. - -**Drift is converged, not just reported.** A schema changed out-of-band on -the live graph shows up as `drifted` after `refresh`, and the next plan -proposes migrating it back to the declared schema β€” apply executes that like -any other soft migration. Drift correction is gated by the same rules as any -change; nothing about it is hidden (the plan shows the steps, including soft -drops of out-of-band fields). - -**Attribution.** `cluster apply --as <actor>` records the operator identity -in recovery sidecars and audit entries and threads it to the engine's -schema-apply (so commit attribution and Cedar enforcement β€” wherever a policy -checker is installed β€” work unchanged). - -### Approvals and graph deletion - -Deleting a graph is the irreversible tier: it requires a recorded human -decision. `cluster plan` lists the gate under `approvals_required` (one gate -per graph β€” the graph-level approval carries its schema and queries); -`cluster approve graph.<id> --as <actor>` writes a digest-bound artifact to - -```text -<config-dir>/__cluster/approvals/<approval-id>.json -``` - -bound to the exact desired config digest and the change's state digest, so -**any config or state drift after approving invalidates the artifact** -automatically (`approval_stale` warning; it never authorizes a different -change). An unapproved delete blocks with `approval_required`. - -An approved delete executes **last** in the apply run: the graph root is -removed recursively, the subtree (graph, schema, its queries) is tombstoned -out of the state ledger with a tombstone observation, and the approval is -consumed β€” recorded in the state's `approval_records` in the same state -update, and the artifact file rewritten with `consumed_at` (the file is never -deleted: the audit fact survives the loss of either store). A failed run -consumes nothing; the approval stays valid for the retry. Catalog blobs of -the deleted graph's queries stay on disk (GC is a later stage). - -Crash recovery for deletes: a completed-but-unrecorded delete is rolled -forward by the sweep (tombstone + approval consumption + audit entry); an -incomplete delete (root still present) is retired with a -`graph_delete_incomplete` warning and simply **re-proposed** β€” prefix removal -is idempotent, so the still-approved retry is the repair. - -Standalone schema deletes are never executed by this stage. They are -reported as `deferred` (warning `apply_unsupported_change`), and query/policy -changes that depend on them are `blocked` (warning `apply_dependency_blocked`, status -`blocked` in state). A partially-applicable plan still exits 0 with warnings; -the JSON `converged` field is the automation signal for "state now matches the -desired revision". The applied `config_digest` is only recorded when apply -fully converges. The `graph.<id>` composite digest is recomputed from state's -own schema/query digests after each apply, so applied query changes converge -without graph movement. - -## Serving from the cluster (the mode switch) - -```bash -omnigraph-server --cluster company-brain --bind 0.0.0.0:8080 -``` - -`--cluster <dir>` is an **exclusive boot source** (axiom 15): it cannot -combine with a graph URI, `--target`, or `--config`, and in this mode -`omnigraph.yaml` is never read β€” not for graphs, not for queries, not for -policies. The server serves the **applied revision**: graph roots recorded in -`state.json`, stored-query and policy content from the content-addressed -catalog at the applied digests (re-verified at boot), and policy bundles -wired by their applied `applies_to` bindings β€” `cluster`-bound bundles become -the server-level Cedar engine, graph-bound bundles attach per graph. -Un-applied config drift never leaks into serving; `cluster plan` is where -drift is visible. Routing is always multi-graph (`/graphs/{id}/...`). Bearer -tokens and the bind address stay process-level (flags/env) β€” they are -per-replica facts, not cluster facts. - -Boot is fail-fast: missing or unreadable state, pending recovery sidecars, -missing/tampered catalog blobs, policy entries without binding metadata -(pre-binding ledgers β€” re-run `cluster apply`), an empty graph set, more than -one policy bundle binding a single scope (split or merge bundles; stacked -scopes are a later stage), unopenable graph roots, and stored queries that no -longer type-check all refuse startup with a remedy. A held state lock is -*not* an error β€” boot reads the atomically-replaced state file without -locking. - -Serving is static per process: the server reads the applied revision once at -startup, so picking up newly applied state means restarting it. Stored -queries are all listed in `GET /queries` in cluster mode (the cluster -registry has no expose flag; exposure becomes a policy decision in a later -phase). - -## Status - -`cluster status` reads the same local JSON state ledger and prints what the -ledger says is deployed. It does not validate referenced schema/query/policy -files and does not inspect live graphs. Missing `state.json` succeeds with a -warning; invalid state JSON or an unsupported state version fails. If a lock is -present, status reports its id, operation, creation time, pid, and age. - -Status also verifies the catalog payloads read-only: every query/policy digest -recorded in state is checked against its content-addressed blob under -`__cluster/resources/` (existence and full digest re-hash). A missing or -mismatched blob is reported as a warning (`catalog_payload_missing` / -`catalog_payload_mismatch`); an unreadable blob is an error -(`catalog_payload_read_error`) because an unverifiable catalog must not report -healthy. Status never writes state β€” persisting the `drifted` condition is -refresh's job. The check runs without the state lock, so it is a point-in-time -report. - -## Refresh And Import - -`cluster refresh` updates an existing `state.json` from actual observations. -`cluster import` creates the first `state.json` when the ledger is missing. -Both commands open declared graphs read-only at: - -```text -<config-dir>/graphs/<graph-id>.omni -``` - -They observe only branch `main`, recording graph existence, manifest version, -live schema digest, desired schema digest, and schema-match status under -`observations["graph.<id>"]`. Missing graph roots are recorded as drift and -remove the graph/schema digests from state so a later `plan` proposes creates. -Invalid graph roots are recorded as errors; `refresh` persists the error -observation and exits non-zero, while `import` exits non-zero without creating -initial state. - -Refresh also verifies the catalog payloads of every query/policy digest -recorded in state (the same check `cluster status` reports read-only), and -closes the loop: - -- a **missing** or **digest-mismatched** blob marks the resource `drifted` - (condition `payload_missing` / `payload_mismatch`) and removes its digest - from state β€” so the next `cluster plan` proposes a create and the next - `cluster apply` republishes the blob (the self-heal loop, mirroring how a - missing graph root is handled); -- an **unreadable** blob (IO error other than not-found) keeps the digest, - marks the resource `error` (condition `payload_read_error`), and exits - non-zero β€” transient IO must not trigger a spurious republish. - -Upgrade note: a state ledger written before catalog publish existed records -query/policy digests with no blobs on disk; the first refresh after upgrading -flags them all `payload_missing`, and a single `cluster apply` republishes -everything and converges. - -Refresh/import do not observe query or policy resources beyond their catalog -payloads yet. Existing query and policy state digests are preserved on refresh -(unless their payload drifted, above) and are not invented on import. - -## Force Unlock - -`cluster force-unlock <LOCK_ID>` removes `<config-dir>/__cluster/lock.json` only -when the file exists, is valid version-1 lock JSON, and its `lock_id` exactly -matches the argument. A wrong id, missing lock, invalid lock JSON, or unsupported -lock version exits non-zero and leaves the file untouched. - -This is manual recovery for abandoned local locks. OmniGraph does not perform -PID-liveness checks, TTL expiry, stale-lock breaking, or automatic unlock in -Stage 2C. diff --git a/docs/user/cluster.md b/docs/user/cluster.md deleted file mode 100644 index 0d6dac5..0000000 --- a/docs/user/cluster.md +++ /dev/null @@ -1,269 +0,0 @@ -# Operating an OmniGraph Cluster - -This is the operator's guide to the cluster control plane: how to go from an -empty directory to a served deployment, and how to run it day to day β€” -evolving schemas, rotating queries and policies, healing drift, approving -destructive changes, and recovering from crashes. - -It is a **how-to**. The reference for every `cluster.yaml` key, command flag, -state-file field, and diagnostic code is -[cluster-config.md](cluster-config.md); the HTTP surface is -[server.md](server.md). - -## The model in one paragraph - -You declare the entire deployment β€” graphs, schemas, stored queries, Cedar -policies β€” as files in one directory (`cluster.yaml` plus the `.pg`/`.gq`/ -`.yaml` files it references). `cluster apply` converges reality to that -declaration and records what it did in a state ledger -(`__cluster/state.json`); `cluster plan` previews exactly what apply would -do, including real schema-migration steps. A server started with -`omnigraph-server --cluster <dir>` serves what was applied β€” never what is -merely written in config. Terraform users will recognize the shape: config -is desired state, the ledger is recorded state, plan is the diff, apply is -the only thing that changes the world, and irreversible changes require an -explicitly recorded approval. - -## 1. Deploy a cluster from zero - -Lay out a config directory: - -``` -company-brain/ -β”œβ”€β”€ cluster.yaml -β”œβ”€β”€ people.pg # schema for the "knowledge" graph -β”œβ”€β”€ queries/ # stored queries β€” the .gq files ARE the declaration -β”‚ └── people.gq -└── base.policy.yaml # a Cedar policy bundle -``` - -```yaml -# cluster.yaml -version: 1 -# storage: s3://omnigraph-local/clusters/company-brain # optional: put the -# ledger, catalog, and graph data on object storage (default: this folder) -metadata: - name: company-brain -graphs: - knowledge: - schema: people.pg - queries: queries/ # every `query <name>` in queries/*.gq registers -policies: - base: - file: base.policy.yaml - applies_to: [knowledge] # graph-bound; use [cluster] for server-level -``` - -Bring it to life: - -```bash -omnigraph cluster validate --config company-brain # parse + typecheck everything -omnigraph cluster import --config company-brain # create the state ledger -omnigraph cluster plan --config company-brain # preview: what would apply do? -omnigraph cluster apply --config company-brain # converge -``` - -That single `apply` **creates the graph** (at the derived root -`company-brain/graphs/knowledge.omni`), applies its schema, and publishes -the query and policy into the content-addressed catalog -(`__cluster/resources/…`). The output lists every change with its -disposition; `converged: true` means there is nothing left to do β€” re-running -`apply` is always safe and idempotent. - -Load data through the normal graph plane (the control plane manages -*definitions*, not rows): - -```bash -omnigraph load --data seed.jsonl company-brain/graphs/knowledge.omni -``` - -Serve it: - -```bash -OMNIGRAPH_SERVER_BEARER_TOKENS_JSON='{"act-reader":"s3cret"}' \ - omnigraph-server --cluster company-brain --bind 0.0.0.0:8080 -``` - -`--cluster` accepts either a **config directory** (the storage root resolves -through `cluster.yaml`'s `storage:` key) or a **storage-root URI directly** -(`--cluster s3://bucket/prefix`) β€” config-free serving: a serving box needs -only the URI and credentials, no checkout of the config repo. The ledger and -catalog on the bucket are the deployment artifact. - -`--cluster` is an **exclusive boot source**: it cannot be combined with a -graph URI, `--target`, or `--config`, and `omnigraph.yaml` is never read in -this mode. Routing is always multi-graph: - -```bash -curl -H 'authorization: Bearer s3cret' \ - -X POST http://localhost:8080/graphs/knowledge/queries/find_person \ - -H 'content-type: application/json' -d '{"params":{"name":"Ada"}}' -``` - -Bearer tokens and the bind address are deliberately *not* cluster facts β€” -they are per-replica, set by flag or environment -([server.md](server.md#modes) for the token sources). - -## 2. The day-2 loop: edit β†’ plan β†’ apply β†’ restart - -Every change follows the same loop, whatever its kind: - -```bash -$EDITOR company-brain/people.pg # or any .gq / policy / cluster.yaml edit -omnigraph cluster plan --config company-brain -omnigraph cluster apply --config company-brain --as andrew -# restart cluster-booted servers to pick it up -``` - -`--as <actor>` attributes the run: it is recorded in recovery sidecars and -audit entries and threaded into the engine's commit history. Set -`cli: { actor: <you> }` in your per-operator `omnigraph.yaml` to make it the -default when `--as` is omitted (the flag always wins; `approve` requires one -of the two). - -What each change kind does: - -| You edit | Plan shows | Apply does | -|---|---|---| -| a `.gq` file or `queries:` entry | `Update query.<g>.<n>` | publishes the new content-addressed blob, updates the ledger | -| a policy file | `Update policy.<n>` | same β€” new blob, ledger update | -| a policy's `applies_to` | `Update policy.<n> [bindings]` | records the new bindings (the file digest is unchanged; bindings are first-class changes) | -| a `.pg` schema | `Update schema.<g>` **with the real migration steps embedded** | runs the engine's schema apply on the live graph β€” soft drops only, sidecar-fenced | -| `graphs:` gains an entry | `Create graph.<g>` (+ schema, queries) | initializes the graph at its derived root; dependents apply in the same run | -| `graphs:` loses an entry | `Delete graph.<g>` β€” **blocked, `approval_required`** | nothing, until approved (see Β§4) | - -Two properties worth internalizing: - -- **One apply, ordered correctly.** Creates run first, then schema - migrations, then catalog writes, then (approved) deletes β€” so a schema - change plus a query that uses the new field converge together in one run. -- **Soft drops only.** A removed schema property disappears from the current - version while prior versions retain the data (reversible until `cleanup`). - Data-loss migrations are not reachable from cluster apply. - -Read the plan before applying when the change is non-trivial β€” for schema -updates it embeds the engine's actual migration plan (`add_property`, -`drop_property [soft]`, `unsupported: …`), so you see data impact before -anything runs. - -## 3. Inspect: status, refresh, drift - -```bash -omnigraph cluster status --config company-brain --json # ledger only, read-only -omnigraph cluster refresh --config company-brain # re-observe live graphs -``` - -`status` never touches the graphs; `refresh` opens them read-only and -records what it finds β€” manifest versions, live schema digests, catalog blob -integrity. If someone changed a graph behind the control plane's back (a -direct `omnigraph schema apply`, a tampered catalog file), refresh marks the -resource **`drifted`**. - -**Drift is converged, not just reported.** After a refresh records drift, -the next `plan` proposes migrating the live graph back to the declared -schema β€” with the steps visible, including the soft drops of out-of-band -fields β€” and `apply` executes it like any other change. If the out-of-band -change is the one you want, change the *config* to match instead, and apply -converges the ledger. - -## 4. Destructive changes: the approval gate - -Removing a graph from `cluster.yaml` never executes silently: - -```bash -omnigraph cluster apply --config company-brain -# Delete graph.scratch [Blocked: approval_required] - -omnigraph cluster approve graph.scratch --config company-brain --as andrew -# cluster approve: delete graph.scratch approved by andrew (approval 01KT…) - -omnigraph cluster apply --config company-brain --as andrew -# Delete graph.scratch [Applied] ← root removed, subtree tombstoned -``` - -The approval artifact (`__cluster/approvals/<id>.json`) is **digest-bound**: -it authorizes exactly the change you saw when you approved it. Any config or -state movement afterwards invalidates it automatically (`approval_stale` -warning) β€” a stale approval can never authorize a different delete. One -approval covers the graph's whole subtree (its schema and queries ride -along). Consumed artifacts are kept (rewritten with `consumed_at`) and -summarized in the ledger's `approval_records`, so the audit trail of *who -approved what* survives the loss of either store. - -## 5. When things go wrong - -**Crashes are designed for.** Every graph-moving operation (create, schema -apply, delete) writes a recovery sidecar before acting. If an apply dies -mid-run, the next state-mutating command sweeps the sidecars and reconciles -β€” rolling the ledger forward when the operation completed on the graph, -retiring stale intent when nothing moved, and flagging anything it cannot -verify. You generally fix a crashed run by **running `cluster apply` -again**. - -**A held lock** (a crashed process left `__cluster/lock.json`): - -```bash -omnigraph cluster status --config company-brain # shows the lock holder + id -omnigraph cluster force-unlock <LOCK_ID> --config company-brain -``` - -Force-unlock requires the exact lock id (from status) β€” there is no blind -unlock. - -**A lost or corrupted state ledger**: the cluster is self-describing. -`cluster import` rebuilds `state.json` from the config plus read-only -observation of the live graphs; the next `apply` re-converges onto the same -content-addressed catalog. - -**A server that refuses to boot** with `--cluster` is telling you the -applied revision is not safely servable. Each refusal names its remedy: - -| Boot error | Meaning | Remedy | -|---|---|---| -| `cluster_state_missing` | no ledger | `cluster import`, then `apply` | -| `cluster_recovery_pending` | interrupted operation awaiting sweep | run `cluster apply` (or any state-mutating command), restart | -| `catalog_payload_missing` / `…_digest_mismatch` | catalog blob lost or tampered | `cluster refresh`, then `apply`, restart | -| `policy_bindings_missing` | ledger predates binding metadata | re-run `cluster apply` (backfills), restart | -| `cluster_empty` | applied revision has no graphs | apply a cluster with β‰₯1 graph | -| multiple bundles bind one scope | serving holds one policy bundle per graph + one server-level | split or merge bundles | - -A held *state lock* is deliberately **not** a boot error β€” the server reads -the atomically-replaced ledger without locking, so serving never contends -with an in-flight apply. - -## 6. Deployment patterns - -- **Replicas**: any number of `--cluster` servers can serve the same config - directory; boot is read-only. Roll out a change by `apply` once, then - restarting replicas (serving is static per process β€” there is no hot - reload yet). Container/cloud recipes (AWS ECS+EFS, Railway volumes): - [deployment.md](deployment.md#cluster-mode-in-containers-aws-railway). -- **The directory is the deployable unit**: config, catalog, ledger, - approvals, and graph data all live under it. Back it up as a whole; - version the *config files* (not `__cluster/` or `graphs/`) in git. -- **CI-driven convergence**: `validate` and `plan --json` are read-only and - safe in pipelines; gate `apply --as ci` on plan review. Approvals are the - human step by design β€” keep `cluster approve` out of automation. -- **`omnigraph.yaml` still has a job**: per-operator settings β€” your - `cli.actor` default for `--as`, CLI defaults, credentials, and data-plane - ergonomics (point `graphs.<name>.uri` at a derived root like - `company-brain/graphs/knowledge.omni` to use `--target <name>` for - loads). It just no longer describes the deployment β€” a server boots from - one source or the other, never a merge of both. - -## What the control plane does not do (yet) - -- **No hot reload** β€” applied changes serve on the next restart. -- **No S3-hosted cluster directories** β€” the config dir, ledger, catalog, - and derived graph roots are local-filesystem paths today. (Individual - *graphs* on S3 are a server feature outside cluster mode.) -- **No data operations** β€” rows move through `omnigraph load / ingest / - mutate` against the graph roots, with branches and merges as usual. -- **Stored-query exposure is all-or-nothing per cluster** β€” every applied - query is listed and invokable (subject to Cedar `invoke_query`); per-query - exposure policy is a planned phase. -- **Pipelines (ETL)** are a separate project; the `pipelines:` key is - reserved and rejected loudly. - -For the full reference β€” every key, flag, status, disposition, and -diagnostic β€” see [cluster-config.md](cluster-config.md). diff --git a/docs/user/constants.md b/docs/user/constants.md index f523042..8f13555 100644 --- a/docs/user/constants.md +++ b/docs/user/constants.md @@ -4,19 +4,15 @@ |---|---|---| | `MANIFEST_DIR` | `__manifest` | `db/manifest/layout.rs` | | Commit graph dir | `_graph_commits.lance` | `db/commit_graph.rs` | -| Run registry dir (legacy, removed MR-771) | `_graph_runs.lance` | inert post-v0.4.0; bytes remain until a `delete_prefix` primitive lands | -| Run branch prefix (legacy, removed MR-771/MR-770) | `__run__` | swept off `__manifest` by the v2β†’v3 migration; no longer a reserved name | +| Run registry dir (legacy, removed MR-771) | `_graph_runs.lance` | inert post-v0.4.0; reclaimed by MR-770 | +| Run branch prefix (legacy, removed MR-771) | `__run__` | filtered by `is_internal_run_branch` defense-in-depth | | Schema apply lock | `__schema_apply_lock__` | `db/mod.rs` | | Manifest publisher retry budget | `PUBLISHER_RETRY_BUDGET = 5` | `db/manifest/publisher.rs` | -| Internal manifest schema version | `INTERNAL_MANIFEST_SCHEMA_VERSION = 3` | `db/manifest/migrations.rs` | +| 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` | -| Expand indexed-path frontier ceiling | `OMNIGRAPH_EXPAND_INDEXED_MAX_FRONTIER=1024` | `exec/query.rs` | -| Expand indexed-path hop ceiling | `OMNIGRAPH_EXPAND_INDEXED_MAX_HOPS=6` | `exec/query.rs` | -| Expand CSR-build cost factor | `CSR_BUILD_FACTOR = 1.5` | `exec/query.rs` | -| Expand mode override | `OMNIGRAPH_TRAVERSAL_MODE` (`indexed`\|`csr`; unset = cost-based auto) | `exec/query.rs` | | Default body limit | `1 MB` | `omnigraph-server/lib.rs` | | Ingest body limit | `32 MB` | `omnigraph-server/lib.rs` | | Engine embed model | `gemini-embedding-2-preview` | `omnigraph/embedding.rs` | @@ -25,16 +21,3 @@ | Embed retries | `4` | both clients | | Embed retry backoff | `200 ms` | both clients | | LANCE memory pool default | `1 GB` (raised in v0.3.0) | runtime | - -**Expand traversal dispatch.** With `OMNIGRAPH_TRAVERSAL_MODE` unset, the engine -chooses the indexed (per-hop BTREE) vs CSR (whole-graph in-memory) path with a -cost model over cheap manifest counts (frontier size, |E|, source-vertex count, -hops) plus the index-coverage signal: the indexed path is preferred when its -frontier-relative work beats building the CSR (β‰ˆ when `hops Γ— frontier` is a -small fraction of the source-vertex set), and CSR is preferred for dense/deep -traversals or when the BTREE coverage is degraded and a full scan would be paid -per hop. The two ceilings bound the **initial dispatch** frontier/hops (beyond -them CSR is always used); they are not a hard per-hop bound β€” the cost model -*estimates* total indexed work as ~`hops Γ— frontier Γ— fanout`, so dense fan-out is -priced toward CSR rather than capped mid-traversal. The override flag forces a path (the `auto` result is identical either way; -only the path differs). diff --git a/docs/user/deployment.md b/docs/user/deployment.md index ece7b5d..9a4466c 100644 --- a/docs/user/deployment.md +++ b/docs/user/deployment.md @@ -13,14 +13,6 @@ Omnigraph supports two broad deployment shapes: The server binary and container image expose the same HTTP surface. -The server also has two **boot sources**: `omnigraph.yaml` (graph targets -declared in the per-operator config) or a **cluster directory** -(`omnigraph-server --cluster <dir>`), which serves the cluster control -plane's applied revision β€” see -[cluster-config.md](cluster-config.md#serving-from-the-cluster-the-mode-switch). -The two are exclusive per deployment; switching is a restart with a different -flag. - ## Binary Deployment Build or install: @@ -33,7 +25,7 @@ On Windows, the binaries are `omnigraph.exe` and `omnigraph-server.exe`. Run against a local graph: ```bash -omnigraph-server graph.omni --bind 0.0.0.0:8080 +omnigraph-server ./graph.omni --bind 0.0.0.0:8080 ``` Run against an object-store-backed graph: @@ -45,91 +37,6 @@ omnigraph-server s3://my-bucket/graphs/example/releases/2026-04-10-v0.1.0 \ --bind 0.0.0.0:8080 ``` -## Cluster Mode in Containers (AWS, Railway) - -A cluster-booted deployment has **two shapes** since the `storage:` root -(RFC-006): - -- **Bucket, no volume (preferred for cloud)** β€” the cluster's ledger, - catalog, and graph data live under an object-storage root - (`storage: s3://bucket/prefix` in `cluster.yaml`). The server boots - **config-free** from the bare URI; the container needs no volume at all: - - ```bash - docker run -d \ - -e OMNIGRAPH_CLUSTER=s3://my-bucket/clusters/company-brain \ - -e AWS_ACCESS_KEY_ID=... -e AWS_SECRET_ACCESS_KEY=... \ - -e OMNIGRAPH_SERVER_BEARER_TOKEN=... \ - -p 8080:8080 <image> - ``` - - Day-2 runs from any operator checkout of the config repo: - `omnigraph cluster apply --config ./company-brain` (the `storage:` key - routes every stored byte to the bucket), then restart the service. The - state lock is genuinely cross-machine on object storage, so CI and - operator shells contend safely. - -- **Volume (file-rooted)** β€” the original shape: the whole cluster - directory on a mounted volume. Still fully supported; the container - contract: - -```bash -docker run -d \ - -v /srv/company-brain:/var/lib/omnigraph/cluster \ - -e OMNIGRAPH_CLUSTER=/var/lib/omnigraph/cluster \ - -e OMNIGRAPH_SERVER_BEARER_TOKEN=... \ - -p 8080:8080 <image> -``` - -`OMNIGRAPH_CLUSTER` is exclusive: combining it with `OMNIGRAPH_TARGET_URI`, -`OMNIGRAPH_CONFIG`, or `OMNIGRAPH_TARGET` fails fast (exit 64), the same -rule the server itself enforces. The image also ships the `omnigraph` CLI, -so the day-2 loop runs in-container with no `omnigraph.yaml`: - -```bash -docker exec -it <container> sh -c \ - 'omnigraph cluster apply --as <you> --config /var/lib/omnigraph/cluster' -# then restart the container to pick up the applied state -``` - -### AWS (ECS/Fargate + EFS) - -1. Push the image to ECR (the `package.yml` workflow builds it). -2. Create an EFS filesystem; mount it in the task definition at - `/var/lib/omnigraph/cluster`. -3. Task environment: `OMNIGRAPH_CLUSTER=/var/lib/omnigraph/cluster`, bearer - tokens via Secrets Manager/SSM into `OMNIGRAPH_SERVER_BEARER_TOKENS_JSON` - (or the `--features aws` build's native Secrets Manager source). -4. ALB in front for TLS; target the container's 8080 with `/healthz` checks. -5. Day-2: ECS exec into the task β†’ edit/upload config on the volume β†’ - `omnigraph cluster apply --as <you> --config /var/lib/omnigraph/cluster` - β†’ force a new deployment (restart). - -For a deployment that doesn't need the cluster control plane, the classic -stateless shape β€” `OMNIGRAPH_TARGET_URI=s3://bucket/graph.omni`, no volume β€” -remains the simplest AWS architecture (see Binary/Container Deployment -above). - -### Railway - -1. Create a service from the image; attach a **volume** mounted at - `/var/lib/omnigraph/cluster`. -2. Variables: `OMNIGRAPH_CLUSTER=/var/lib/omnigraph/cluster`, - `OMNIGRAPH_SERVER_BEARER_TOKEN=<token>`. Railway terminates TLS at its - edge and routes to the exposed 8080. -3. Day-2: `railway shell` (or `railway run`) β†’ `omnigraph cluster apply - --as <you> --config /var/lib/omnigraph/cluster` β†’ redeploy/restart the - service. - -### Constraints (current honest list) - -- **No hot reload** β€” applied changes serve on the next restart. -- **Single-writer apply** β€” run `cluster apply` from one place at a time - (the state lock enforces this; CI or one operator shell, not both). -- **Multi-replica serving off a shared volume (EFS) is documented but - unvalidated** β€” boot is lock-free read-only so it should compose, but it - is not yet exercised by tests. - ## One-Command Local RustFS Bootstrap The easiest local S3-backed deployment path is: @@ -227,7 +134,7 @@ docker run --rm -p 8080:8080 \ -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 }`; +# /etc/omnigraph/omnigraph.yaml contains `policy: { file: ./policy.yaml }`; # policy.yaml (+ optional policy.tests.yaml) sit beside it in the mount. ``` diff --git a/docs/user/index.md b/docs/user/index.md index 956fa0b..1b93efa 100644 --- a/docs/user/index.md +++ b/docs/user/index.md @@ -13,8 +13,6 @@ of MRs, internal recovery mechanics, or contributor-only invariants. | Install OmniGraph | [install.md](install.md) | | Run the CLI locally | [cli.md](cli.md) | | Look up every CLI flag and config field | [cli-reference.md](cli-reference.md) | -| Deploy and operate a cluster (how-to guide) | [cluster.md](cluster.md) | -| Validate and plan cluster config | [cluster-config.md](cluster-config.md) | | Write schemas | [schema-language.md](schema-language.md) | | Read schema-lint diagnostic codes | [schema-lint.md](schema-lint.md) | | Write queries and mutations | [query-language.md](query-language.md) | diff --git a/docs/user/indexes.md b/docs/user/indexes.md index df898c4..ce6c728 100644 --- a/docs/user/indexes.md +++ b/docs/user/indexes.md @@ -21,6 +21,6 @@ This is OmniGraph-specific (not Lance): - `TypeIndex`: dense `u32 ↔ String id` mapping per node type. - `CsrIndex`: Compressed Sparse Row representation of edges per edge type β€” `offsets[i]..offsets[i+1]` slices into `targets`. -- `GraphIndex { type_indices, csr (out), csc (in) }` β€” built on demand from a snapshot's edge tables, **lazily**: only when an `Expand` the planner routes to the CSR path (dense / large frontier) or an `AntiJoin` actually needs it. +- `GraphIndex { type_indices, csr (out), csc (in) }` β€” built on demand from a snapshot's edge tables. - Cached in `RuntimeCache::graph_indices` (LRU, max 8 entries, keyed by snapshot id + edge table versions). -- Selective `Expand`s resolve neighbors from the persisted `src`/`dst` BTREE instead (one indexed scan per hop) and never trigger the CSR build; see [query-language](query-language.md) β†’ Expand. Pure scans, and queries served entirely by the indexed traversal path, skip it. +- Built only when an `Expand` or `AntiJoin` IR op is present in the lowered query, so pure scans skip it. diff --git a/docs/user/maintenance.md b/docs/user/maintenance.md index e69bba3..3628fa0 100644 --- a/docs/user/maintenance.md +++ b/docs/user/maintenance.md @@ -1,26 +1,15 @@ -# Maintenance: Optimize, Repair & Cleanup +# Maintenance: Optimize & Cleanup -`db/omnigraph/optimize.rs` and `db/omnigraph/repair.rs`. +`db/omnigraph/optimize.rs`. ## `optimize_all_tables(db)` β€” non-destructive -- Lance `compact_files()` on every node + edge table on `main`, then **publishes the compacted version to the `__manifest`** so the manifest's `table_version` tracks the compacted Lance HEAD. Reads pin the manifest version, so without this publish compaction would be invisible to readers *and* would break the HEAD-vs-manifest precondition of the next schema apply / strict update/delete ("stale view … refresh and retry"). The publish advances the graph version (a system-attributed commit) only for tables that actually compacted. -- Rewrites small fragments into fewer large ones; old fragments remain reachable via older manifests until `cleanup` runs. -- Each table's compactβ†’publish runs under its per-`(table, main)` write queue (serializing with concurrent mutations β€” compaction is a Lance `Rewrite` op that retryable-conflicts with a concurrent merge/update/delete on overlapping fragments). The Lance-HEAD-before-manifest-publish gap is covered by a `SidecarKind::Optimize` recovery sidecar (loose-match): a crash in that window rolls the compacted version forward on the next `Omnigraph::open` (compaction is content-preserving, so roll-forward is always safe). -- **Requires a recovered graph.** `optimize` refuses (errors) when an unresolved recovery sidecar is present under `__recovery` β€” operating on an unrecovered graph could publish a partial write the open-time recovery sweep would roll back. Reopen the graph to run the recovery sweep, then re-run `optimize`. -- **Uncovered drift is skipped, not interpreted.** If a table's Lance HEAD is ahead of the version recorded in `__manifest` and no recovery sidecar covers that movement, `optimize` reports `skipped: Some(DriftNeedsRepair)` with the manifest/head versions and leaves the table untouched. Run `omnigraph repair` to classify and explicitly publish that drift. +- 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, skipped, manifest_version, lance_head_version }]`. +- 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. -## `repair_all_tables(db, options)` β€” explicit - -- Handles **uncovered manifest/head drift**: a table's Lance HEAD is ahead of the manifest pin and no recovery sidecar records the writer intent. -- Preview by default. `omnigraph repair --json <uri>` reports each table's `classification`, `action`, manifest/head versions, Lance operation names, and any classification error. `--confirm` publishes only verified maintenance drift; if any suspicious or unverifiable table is refused, the CLI prints the per-table output and exits non-zero. `--force --confirm` also publishes suspicious or unverifiable drift after operator review. -- Classifies drift by reading Lance transactions from `manifest_version + 1` through `lance_head_version`. Only `ReserveFragments` and `Rewrite` are verified maintenance. Semantic operations such as `Append`, `Delete`, `Update`, `Merge`, or missing transaction history are not auto-healed. -- Publishes repair by advancing `__manifest` to the existing Lance HEAD; it does **not** rewrite Lance data. If the publish succeeds, normal reads and strict writes use the repaired version. If it fails, no new data-side partial state was created. -- Requires a clean recovery state. Pending `__recovery` sidecars still belong to automatic sidecar recovery, not manual repair. - ## `cleanup_all_tables(db, options)` β€” destructive - Lance `cleanup_old_versions()` per table. diff --git a/docs/user/policy.md b/docs/user/policy.md index 91684d8..ec0d214 100644 --- a/docs/user/policy.md +++ b/docs/user/policy.md @@ -35,13 +35,13 @@ In multi mode (`omnigraph.yaml` with a non-empty `graphs:` map), policy files at ```yaml server: policy: - file: server-policy.yaml # server-level: graph_list + 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 + 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 @@ -78,8 +78,8 @@ rules: ```yaml policy: - file: policy.yaml # Cedar rules + groups - tests: policy.tests.yaml # declarative test cases + file: ./policy.yaml # Cedar rules + groups + tests: ./policy.tests.yaml # declarative test cases cli: actor: act-andrew # default actor for CLI direct-engine writes @@ -105,13 +105,12 @@ 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. -- `omnigraph --as <ACTOR> <subcommand>` β€” set the actor for the duration of one invocation. Effective for `change`, `load` (and its deprecated `ingest` alias), `branch create|delete|merge`, and `schema apply` against local URIs. No-op against remote HTTP URIs (actor is bearer-token-resolved server-side). +- `omnigraph --as <ACTOR> <subcommand>` β€” set the actor for the duration of one invocation. Effective for `change`, `load`, `ingest`, `branch create|delete|merge`, and `schema apply` against local URIs. No-op against remote HTTP URIs (actor is bearer-token-resolved server-side). ## Enforcement Policy is a property of the **engine**, not the transport. Every mutating -write β€” `mutate_as`, `load_as` (the deprecated `ingest_as` shims route -through it), `apply_schema_as`, +write β€” `mutate_as`, `load_as`, `ingest_as`, `apply_schema_as`, `branch_create_as`, `branch_create_from_as`, `branch_delete_as`, `branch_merge_as` β€” calls `Omnigraph::enforce(action, scope, actor)` at the head of the method. The gate fires identically whether the call diff --git a/docs/user/query-language.md b/docs/user/query-language.md index bcab67c..6c7516f 100644 --- a/docs/user/query-language.md +++ b/docs/user/query-language.md @@ -55,8 +55,6 @@ Used inside MATCH or as expressions inside RETURN/ORDER: - `order { <expr> [asc|desc], … }` β€” supports plain expressions and `nearest(...)`. - `limit <integer>` β€” required when there is a `nearest(...)` ordering. -- **Total, deterministic order.** Rows with equal user-sort keys are broken by the bound entities' key columns (`<var>.id`, ascending) appended as a final tie-break, so the result is a *total* order β€” reproducible across runs, and `order … limit N` returns a deterministic top-N even when ties straddle the cutoff. (Aggregate results have no entity-key columns; their group rows are already distinct on the projected group keys.) -- **NULL placement** is *nulls-first ascending, nulls-last descending* (i.e. `nulls_first = !descending`): a NULL sorts as if smaller than any value. ## Mutation statements @@ -72,7 +70,7 @@ A single mutation query must be **either insert/update-only or delete-only**. Mi > `mutation '<name>' 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 v6.0.1 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 the MR-A Lance v7 bump migrates `delete_where` to staged (`DeleteBuilder::execute_uncommitted` first ships in `v7.0.0-beta.10`), the parse-time rejection keeps both paths atomic and correct. See [docs/dev/writes.md](../dev/writes.md), [docs/dev/lance.md](../dev/lance.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) @@ -81,7 +79,7 @@ Reason: under the staged-write rewire (MR-794), inserts and updates accumulate i Pipeline operations: - `NodeScan { variable, type_name, filters }` -- `Expand { src_var, dst_var, edge_type, direction (Out|In), dst_type, min_hops, max_hops, dst_filters }` β€” destination filters are pushed *into* the expand so Lance scalar pushdown can prune. Executed one of two ways, chosen per-expand by a cost model over cheap manifest counts (frontier size, |E|, source-vertex count, hops) plus index coverage: selective traversals (small frontier relative to the source set) resolve neighbors from the persisted `src`/`dst` BTREE (one indexed scan per hop); dense / deep / large-frontier traversals β€” or those whose BTREE coverage is degraded so a full scan would be paid per hop β€” use the in-memory CSR adjacency index. Both produce identical results. The `OMNIGRAPH_EXPAND_INDEXED_MAX_FRONTIER` / `OMNIGRAPH_EXPAND_INDEXED_MAX_HOPS` ceilings bound the *initial dispatch* frontier/hops (beyond them CSR is always used); the cost model estimates total indexed work as ~`hops Γ— frontier Γ— fanout` and prices dense fan-out toward CSR β€” they are not a hard per-hop bound. `OMNIGRAPH_TRAVERSAL_MODE=indexed|csr` forces a mode (see [constants](constants.md)). +- `Expand { src_var, dst_var, edge_type, direction (Out|In), dst_type, min_hops, max_hops, dst_filters }` β€” destination filters are pushed *into* the expand so Lance scalar pushdown can prune. - `Filter { left, op, right }` - `AntiJoin { outer_var, inner: Vec<IROp> }` β€” for `not { … }` diff --git a/docs/user/server.md b/docs/user/server.md index 391b7ae..67b5afe 100644 --- a/docs/user/server.md +++ b/docs/user/server.md @@ -1,6 +1,6 @@ # HTTP Server (`omnigraph-server`) -Axum 0.8 + tokio + utoipa-generated OpenAPI. **Two modes** (v0.6.0+): single-graph (legacy) and multi-graph (MR-668), with **two boot sources** for multi mode: `omnigraph.yaml` or β€” exclusively β€” a cluster directory (`--cluster`, RFC-005). Mode is inferred from CLI args + config shape. +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 @@ -14,20 +14,8 @@ Axum 0.8 + tokio + utoipa-generated OpenAPI. **Two modes** (v0.6.0+): single-gra `omnigraph-server --config omnigraph.yaml` with a non-empty `graphs:` map and **no** single-mode selector (no `server.graph`, no `<URI>`, 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. -### Cluster-booted multi mode (Phase 5) +Mode inference (four-rule matrix): -`omnigraph-server --cluster <dir-or-uri>` boots from the cluster catalog's **applied -revision** (`state.json` + content-addressed blobs) instead of -`omnigraph.yaml` β€” an exclusive boot source: combining it with `<URI>`, -`--target`, or `--config` is a startup error, and `omnigraph.yaml` is never -read in this mode. Always multi-graph routing. See -[cluster-config.md](cluster-config.md#serving-from-the-cluster-the-mode-switch) -for what is read and the fail-fast readiness rules. `--bind`, -`--unauthenticated`, and the bearer-token env vars work identically. - -Mode inference: - -0. CLI `--cluster <dir | s3://…>` β†’ **multi, cluster-booted** (exclusive; a scheme-qualified argument reads the ledger straight from the storage root, no local config) 1. CLI positional `<URI>` β†’ single 2. CLI `--target <name>` β†’ single 3. `server.graph` in config β†’ single @@ -56,7 +44,7 @@ Per-graph endpoints β€” same body shape across modes; URLs differ: | 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` (only when `from` is set and the branch is created) + `change` | bulk load; branch creation is opt-in via `from` β€” without it a missing `branch` is a 404, never an implicit fork | `server_ingest` (32 MB body limit) | +| 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` | diff --git a/docs/user/storage.md b/docs/user/storage.md index 2c57a92..c22d4d6 100644 --- a/docs/user/storage.md +++ b/docs/user/storage.md @@ -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 graphs are inert; the run state machine was removed in MR-771. The v2β†’v3 manifest migration sweeps stale `__run__*` branches on first write-open; the inert dataset bytes themselves remain until a `delete_prefix` storage primitive lands) + - (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:<TypeName> | edge:<EdgeName>` @@ -47,7 +47,6 @@ Adding a new on-disk shape change is one constant bump (`INTERNAL_MANIFEST_SCHEM |---|---| | v1 (implicit, pre-stamp) | `__manifest.object_id` had no PK annotation; publisher had no row-level CAS protection. | | v2 | `__manifest.object_id` carries `lance-schema:unenforced-primary-key=true`; row-level CAS engaged. Stamped as `omnigraph:internal_schema_version=2`. | -| v3 | One-time sweep of legacy `__run__*` staging branches (pre-v0.4.0 Run state machine, removed MR-771) off `__manifest`. Runs at `Omnigraph::open(ReadWrite)` and on publish. Stamped as `omnigraph:internal_schema_version=3`. | ## On-disk layout @@ -92,9 +91,9 @@ flowchart TB - **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 graphs also have inert `_graph_runs.lance` / `_graph_run_actors.lance` from the removed Run state machine; the v2β†’v3 migration sweeps their stale `__run__*` branches, and the dataset bytes are reclaimed once `delete_prefix` lands.) +- **`_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 five migrated writers (`MutationStaging::finalize`, `schema_apply`, `branch_merge`, `ensure_indices`, `optimize_all_tables`) 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`. +- **`__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. - **Inside each Lance dataset** (orange): the standard Lance directory layout. `_versions/{n}.manifest` records every commit; `data/` holds the actual Arrow fragments; `_indices/{uuid}/` holds index segments with their own `fragment_bitmap` for partial coverage; `_refs/` holds Lance-native per-dataset branches and tags. diff --git a/docs/user/transactions.md b/docs/user/transactions.md index 39a86c4..d6c79f4 100644 --- a/docs/user/transactions.md +++ b/docs/user/transactions.md @@ -47,8 +47,8 @@ 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"}' graph.omni +omnigraph change --query ./mutations.gq --name register_employee_with_team \ + --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}' graph.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"}' graph.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 graph.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}' graph.omni + --query ./mutations.gq --name register_employee \ + --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}' graph.omni + --query ./mutations.gq --name register_employee \ + --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"}' graph.omni + --query ./mutations.gq --name link_to_team \ + --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 graph.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 graph.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 graph.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 graph.omni -omnigraph change --branch agent-a/work … graph.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 graph.omni +omnigraph branch merge agent-a/work --into main ./graph.omni # Agent B (running concurrently) -omnigraph branch create --from main agent-b/work graph.omni -omnigraph change --branch agent-b/work … graph.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 graph.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. diff --git a/openapi.json b/openapi.json index 85c5b8d..aced64d 100644 --- a/openapi.json +++ b/openapi.json @@ -7,7 +7,7 @@ "name": "MIT", "identifier": "MIT" }, - "version": "0.6.2" + "version": "0.6.1" }, "paths": { "/branches": { @@ -670,8 +670,8 @@ "tags": [ "mutations" ], - "summary": "Bulk-load NDJSON data into a branch.", - "description": "`data` is NDJSON with one record per line. `mode` controls behavior on\nexisting rows: `merge` upserts by id (default), `append` blindly inserts,\n`overwrite` replaces table contents. Branch creation is opt-in by\npresence of `from`: with `from` set, a missing `branch` is created from\nit; without `from`, `branch` must already exist β€” a missing branch is a\n404, never an implicit fork. **Destructive** when `mode` is `overwrite`\nor when the load produces conflicting writes.", + "summary": "Bulk-ingest NDJSON data into a branch.", + "description": "`data` is NDJSON with one record per line. `mode` controls behavior on\nexisting rows: `merge` upserts by id (default), `append` blindly inserts,\n`overwrite` replaces table contents. If `branch` does not exist it is\ncreated from `from` (defaults to `main`). **Destructive** when `mode` is\n`overwrite` or when ingest produces conflicting writes.", "operationId": "ingest", "requestBody": { "content": { @@ -1710,6 +1710,7 @@ "required": [ "uri", "branch", + "base_branch", "branch_created", "mode", "tables" @@ -1722,11 +1723,7 @@ ] }, "base_branch": { - "type": [ - "string", - "null" - ], - "description": "Base branch a fork was requested from (the request's `from`), echoed\neven when the branch already existed. `null` when `from` was absent." + "type": "string" }, "branch": { "type": "string" @@ -1759,7 +1756,7 @@ "string", "null" ], - "description": "Target branch. Defaults to `main`. Without `from`, the branch must\nalready exist β€” a missing branch is a 404, never an implicit fork." + "description": "Target branch. Created from `from` if it does not yet exist. Defaults to `main`." }, "data": { "type": "string", @@ -1771,7 +1768,7 @@ "string", "null" ], - "description": "Parent branch used to create `branch` if it does not exist. Branch\ncreation is opt-in by presence of this field; omit it to require an\nexisting branch." + "description": "Parent branch used to create `branch` if it does not exist. Defaults to `main`." }, "mode": { "oneOf": [ diff --git a/scripts/check-agents-md.sh b/scripts/check-agents-md.sh index 02a177a..abc6469 100755 --- a/scripts/check-agents-md.sh +++ b/scripts/check-agents-md.sh @@ -34,15 +34,10 @@ PY canonical=() while IFS= read -r line; do canonical+=("$line") -done < <(find docs -type f -name '*.md' ! -path 'docs/releases/*' ! -path 'docs/internal/*' ! -path 'docs/rfcs/*' | sort) +done < <(find docs -type f -name '*.md' ! -path 'docs/releases/*' ! -path 'docs/internal/*' | sort) if [[ -d docs/releases ]]; then canonical+=("docs/releases/") fi -# RFCs are a growing collection (like releases): represent the directory, not -# every per-RFC file. The dir must be linked from an audience index. -if [[ -d docs/rfcs ]]; then - canonical+=("docs/rfcs/") -fi linked=() for index_file in "${index_files[@]}"; do diff --git a/scripts/local-rustfs-bootstrap.sh b/scripts/local-rustfs-bootstrap.sh index 2425c77..c4fdcbe 100755 --- a/scripts/local-rustfs-bootstrap.sh +++ b/scripts/local-rustfs-bootstrap.sh @@ -6,12 +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}" -# Pinned to 1.0.0-beta.8 (2026-06-10), matching CI (.github/workflows/ci.yml). -# beta.4+ has a credentials-policy check that refuses to start when the -# access/secret keys are values it considers "default" (rustfsadmin/rustfsadmin -# here); this script passes RUSTFS_ALLOW_INSECURE_DEFAULT_CREDENTIALS=true -# below, so overriding RUSTFS_IMAGE to another tag is safe. -RUSTFS_IMAGE="${RUSTFS_IMAGE:-rustfs/rustfs:1.0.0-beta.8}" +# 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}"