Skip to the page

Testing

Testing & verification

Verify schemas, access policies, deployed queries, dry-run writes and agent grants against isolated branches locally and in CI.

Test access rules with napalm test#

napalm test executes declarative access-rule suites in dbschema/tests against a branch. Each test runs an ordered sequence of EdgeQL steps under explicit caller identities and asserts the returned rows, row count or structured refusal code.

Napalm typechecks every statement before the first test begins so syntax or schema mismatches fail fast, and wraps each test in a single rolled-back transaction on the branch primary, so suites need no sign-in round trips, service keys or post-test cleanup.

Rolled-back transaction bracket

Each declarative test case and is_dry_run preview executes inside an atomic transaction bracket that rolls back before commit, leaving zero test rows behind.

Admit & refuse verdict assertions

Steps assert exact returned rows, readable reach counts or structured refusal codes (access_refused, read_only, grant_refused) under compiled policies.

dbschema/tests/notes.yaml
setup:  - as: setup    query: |      select (insert Person {        name := 'Maya',        identity := (insert ext::auth::Identity { issuer := 'napalm:test', subject := 'maya' }),      }).identity    bind: maya  - as: setup    query: |      select (insert Person {        name := 'Sam',        identity := (insert ext::auth::Identity { issuer := 'napalm:test', subject := 'sam' }),      }).identity    bind: sam  - as: { person: maya }    call: addNote    variables: { title: Q4 roadmap }    bind: roadmap tests:  Maya reads her own notes:    - as: { person: maya }      call: myNotes      expect:        rows:          - { title: Q4 roadmap, author: { name: Maya }, shared: false }   Sam can't rename Maya's note:    - as: { person: sam }      query: |        update Note        filter .id = <uuid>$id        set { title := 'Overwritten' }      variables: { id: { $bound: roadmap } }      expect: { count: 0 }   Sam can't write a note as Maya:    - as: { person: sam }      query: insert Note { title := 'Forged', author := assert_single((select Person filter .name = 'Maya')) }      expect: { refused: access_refused }   A read-only key writes nothing:    - as: { key: { isReadOnly: true } }      call: addNote      variables: { title: Blocked }      expect: { refused: read_only }   Outsiders read no notes:    - as: anonymous      reach: Note      expect: { count: 0 }   Maya and Sam share no notes:    - as: [{ person: maya }, { person: sam }]      disjoint: Note

Steps under setup seed baseline identities and rows ahead of every test in the file while bypassing access policies. bind: maya captures the returned object ID so subsequent steps can authenticate with as: { person: maya } or reference { $bound: roadmap } inside variables, and call: addNote executes the same dbschema/queries/addNote.edgeql file that napalm queries push deploys.

StepDoes
queryRuns one EdgeQL statement.
callRuns a file in dbschema/queries by its name.
variablesSets the statement’s parameters. { $bound: roadmap } passes a bound id.
bindKeeps the returned object’s id under a name. The step must return one object.
reach: NoteCounts the caller’s readable Note objects. expect: { count: 0 } gives the count.
disjoint: NotePasses when the two callers in as read no Note in common.
CallerRuns as
setupNo rules. Setup steps make each test’s people and objects.
anonymousA signed-out caller with the branch’s user globals and no identity.
keyA new read-write service key with the branch’s service globals.
{ key: { isReadOnly: true } }A new read-only key. globals: { default::role: auditor } gives the key its own globals.
{ key: <key-id> }The branch’s service key with this id.
{ person: maya }The identity bound as maya in an earlier step.
{ person: sam@orbit.io }A person signed up on the branch. Name the person by email or identity id.
{ person: maya, grant: { isReadOnly: true } }Maya through an agent’s grant. globals holds the globals a person sets at consent.
ExpectationPasses when
{ count: 2 }The step returns 2 rows.
{ rows: [{ title: Q4 roadmap }] }The step returns these rows in any order. A row matches by the fields the test lists. isOrdered: true holds the order too.
{ refused: true }The step fails with any error.
{ refused: access_refused }The step fails with this code: access_refused, read_only, grant_refused, query_rejected or query_failed. An engine error such as ConstraintViolationError matches too.
No expectThe step runs without an error.

Run the tests against a branch. A name after the project runs only the tests with that text in the test’s name or file name. Here a loosened rule lets Sam write a note as Maya.

Running the access-rule tests on a test branch
napalm test notes --branch test-suite
notes.yaml Maya reads her own notes
notes.yaml Sam can't rename Maya's note
notes.yaml Sam can't write a note as Maya
dbschema/tests/notes.yaml:39 step 1 as sam
insert Note { title := 'Forged', author := assert_single((select Person filter .name = 'Maya')) }
Expected a refusal with access_refused
Got 1 row: {"id":"0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f"}
notes.yaml A read-only key writes nothing
notes.yaml Outsiders read no notes
notes.yaml Maya and Sam share no notes
1 of 6 tests failed against test-suite in notes.
Each test rolled back. Nothing was kept.

Each failure names the file and line, the step, the caller, the statement, the expectation and the answer. --json prints the results for a script. The command exits 1 when a test fails.

One transaction
Every step reads the branch as of the test’s first statement. Each step also reads the test’s own writes. Nothing commits. Webhooks, jobs and the change log never see a test.
Limits
Each test can run up to 100 steps (including setup) within 20 seconds, and the CLI batches up to 100 tests per request. Both the initial compile check and each batch request count once toward the branch’s limit of 100 dry runs, tests, checks and plans per minute.
Org token
napalm test needs an org token with manage scope.
Activity
A step as a person named by email or id adds a projectPersonAccessChecked entry to napalm activity. A person made in setup adds no entry.
Sharded branches
A branch on more than one shard runs no tests yet.

Test an agent’s grant#

A test step can also execute as a user acting through an inline agent grant without running an interactive OAuth consent flow first. Declare the consent fields (isReadOnly and globals, including any $bound IDs) directly on the step so the engine layers the grant’s globals over the branch’s userGlobals just like a live agent call. The suite below verifies the tenant-scoping rules from Grants held to one tenant.

dbschema/tests/agents.yaml
setup:  - as: setup    query: |      select (insert Person {        name := 'Maya',        identity := (insert ext::auth::Identity { issuer := 'napalm:test', subject := 'maya' }),      }).identity    bind: maya  - as: setup    query: |      select (insert Ticket {        title := 'Acme launch',        org := (insert Organization { name := 'Acme', members := (select Person filter .name = 'Maya') }),      }).org    bind: acme  - as: setup    query: |      insert Ticket {        title := 'Globex launch',        org := (insert Organization { name := 'Globex', members := (select Person filter .name = 'Maya') }),      } tests:  Maya reads both organizations' tickets:    - as: { person: maya }      reach: Ticket      expect: { count: 2 }   Maya's agent for Acme reads Acme's tickets alone:    - as: { person: maya, grant: { globals: { default::current_org: { $bound: acme } } } }      query: select Ticket { title }      expect:        rows:          - { title: Acme launch }   Maya's agent for another organization reads no tickets:    - as: setup      query: insert Organization { name := 'Initech' }      bind: initech    - as: { person: maya, grant: { globals: { default::current_org: { $bound: initech } } } }      reach: Ticket      expect: { count: 0 }

Although Maya belongs to both Acme and Globex, the deny policy confines her Acme-scoped agent to Acme’s tickets, while an agent scoped to Initech reads zero tickets because the allow policy never admits non-members. Passing grant: { isReadOnly: true } exercises a read-only grant where every write fails with read_only, and setting any global omitted from the branch’s grantGlobals fails with grant_refused just as the consent endpoint does.

Each test creates its declared grant rows inside the transaction and rolls those rows back on exit. During a grant step, global ext::napalm::ClientTokenAgentGrant resolves to that grant just as in production, so a type guarded by deny select using (exists global ext::napalm::ClientTokenAgentGrant) returns zero rows to any agent step while remaining readable to the user directly, and subsequent steps as that user can query the synthetic grant row. Inline test grants omit allowedQueries because allowedQueries restricts named deployed queries whereas test steps execute statements directly.

Test layers on a branch#

Napalm provides no local emulator that could drift from production. Every test suite runs against an isolated database branch on your cluster, so PostgreSQL 18, the EdgeQL compiler and your compiled access policies behave identically across local runs, pull requests and main.

One test harness covers web and mobile apps, AI agents, model evaluation sets and outbound integrations. Compiler checks catch broken query shapes before code runs, caller-matrix suites verify positive and negative row rules across real credentials and dry-run requests preview mutations without altering branch state.

Rolled-back write previews

Passing "is_dry_run": true on POST /query or POST /ask (or --dry-run on napalm call) runs policies, constraints and rewrites inside a rolled-back transaction and returns before/after diffs.

Isolated test branches

napalm branches create --preview forks main’s schema onto an isolated database branch with dedicated session keys and zero production webhooks or cron schedules.

LayerMechanismVerifies
Access-rule testsnapalm test, dbschema/testsVerifiesReads, writes and refusals match the tests for every caller. Every test rolls back.
Schema and query typesnapalm schema push --plan, napalm generateVerifiesdbschema/decisions.yaml answers every decision a migration needs, deployed queries still compile and generated SDK types match every .edgeql file.
Caller access matrixSignIn, NapalmClient, POST /query/{name}VerifiesUser sessions, service keys, --read-only keys and AgentGrant rows read and mutate only authorized records.
Dry-run write previews"is_dry_run": true on POST /query and POST /askVerifiesMutations, schema rewrites and model-proposed statements produce exact before and after diffs and roll back cleanly.
Actions, jobs and webhookshandleCalls, ext::napalm::Job, napalm webhooks testVerifiesGatekeeper queries reject unauthorized callers with 403 nothing_found before handlers run, and receivers verify HMAC headers.
Reach and rule auditsnapalm explain-access, napalm people reach, napalm keys reachVerifiesIndividual policy expressions and link traversals pass or fail for the expected reason, and keys expose only intended row counts.
Pull-request CI gatespr-<number> branch, napalm schema push --reviewVerifiesEvery schema change, generated client, policy suite and model golden set passes on a disposable branch before merge.

Isolate test runs on branches#

Create a dedicated branch from main for automated tests. Without --data, napalm branches create copies main’s schema, extensions and sign-in settings with empty tables and returns right away. Pass --preview so clusters with a preview shard place test branches away from main’s primary.

Isolated branch track

Forking /branches/test-suite gives local and CI suites main’s schema, dedicated session signing keys and branch-scoped ndb_… credentials away from live traffic.

Terminal
# Create an empty schema-only branch away from main's primarynapalm branches create notes test-suite --preview # Enable the branch API, allow statement passthrough and share the schema for dry-run row countsnapalm endpoint notes --branch test-suite --enable --passthrough all --share-schema # Push your local schema and typecheck all files in dbschema/queries against the branchnapalm schema push notes --branch test-suite --yesnapalm generate notes --lang ts --branch test-suite # Issue a read-write service key and a read-only service key scoped to test-suitenapalm keys create notes --label test-service --branch test-suite --days 7napalm keys create notes --label test-reader --branch test-suite --read-only --days 7

Deployed queries belong to main, so a branch serves no deployed queries by name. Generate your test client without --deployed so each request sends both the statement text and variables against https://notes.napalmdata.com/branches/test-suite, and set --passthrough all so user sessions and service keys alike can run those statements on the branch.

Keep parameter-free reference rows and model golden cases in dbschema/seed.edgeql with unless conflict clauses. Napalm’s GitHub App runs dbschema/seed.edgeql automatically on new pull-request branches, and local scripts run the same file with napalm query --file using a branch service key and service globals. Sign up per-caller identities (maya@acme.co, sam@orbit.io and triage-bot@acme.co) through the branch’s /sign-in routes inside your test setup.

dbschema/seed.edgeql
# dbschema/seed.edgeql: parameter-free baseline fixtures run on every new test branchwith  pro_plan := (    insert BillingPlan { slug := 'pro', seat_limit := 25 }    unless conflict on .slug else (update BillingPlan set { seat_limit := 25 })  ),  eval_case := (    insert EvalCase {      name := 'high-value-claim',      features := <json>(tier := 'pro', amount_cents := 420000),      expected := 'approve',    }    unless conflict on .name else (update EvalCase set { expected := 'approve' })  ),select {  plan_id := pro_plan.id,  eval_case_id := eval_case.id,}
Credential isolation
A branch signs sessions with a dedicated keypair and rejects keys or tokens from main. Every key created with --branch test-suite works on test-suite alone.
No live side effects
New branches start with no webhooks, actions or cron schedules copied from main, so test writes never page production receivers.
Fast resets
Between test files, clear mutable tables with napalm query notes "delete Note" --key "$SERVICE_KEY" and re-run dbschema/seed.edgeql, or drop and recreate the branch.
Volume budget
Branches share up to 80% of a shard’s volume. Schema-only branches with small fixtures use minimal space, while --data clones count full row storage and return 409 volume_full when space runs out.

Test your app across callers#

napalm test covers the rules. A caller matrix in Vitest or pytest also covers your app’s own code: sign-in flows, generated clients and request handling.

Access bugs hide in the gaps between callers. Run every read and write query through a matrix of clients: an owner (mayaDb), a member of another organization (samDb), an agent holding a scoped AgentGrant (agentDb), an unauthenticated caller (outsiderDb), a --read-only service key (readerDb) and a backend service key (serviceDb).

NapalmClient tracks Napalm-Bookmark per client instance automatically. Reads that follow a write on the same client observe the committed state immediately without polling or artificial delays.

User identity sessions

Owner and cross-organization ext::auth::Identity sessions verify positive visibility and silent row filtering across tenants.

Read-write & read-only keys

Branch-scoped ndb_… credentials seed baseline fixtures while --read-only keys prove mutations fail with DisabledCapabilityError.

Delegated agent callers

Agent clients bound to scoped ext::napalm::AgentGrant rows verify narrowed visibility and instant revocation on the next read.

test/access-matrix.test.ts
import createClient from 'openapi-fetch'import { NapalmClient, NapalmError, SignIn } from 'napalm-client'import { beforeAll, describe, expect, test } from 'vitest'import type { paths } from '../napalm/schema'import { queries } from '../napalm/queries' const branchUrl = process.env.NAPALM_TEST_URL ?? 'https://notes.napalmdata.com/branches/test-suite' function clientForToken(token?: string) {  const runtime = new NapalmClient(branchUrl, { knock: false, ...(token ? { token } : {}) })  return createClient<paths>({ baseUrl: branchUrl, fetch: runtime.fetch })} async function clientForUser(email: string, password: string) {  const signIn = new SignIn(branchUrl, { knock: false })  const session = await signIn.signUp(email, password, { verifyUrl: `${branchUrl}/signed-in` }).catch((err) => {    if (err instanceof NapalmError && err.code === 'user_already_registered') {      return signIn.withPassword(email, password)    }    throw err  })  const runtime = new NapalmClient(branchUrl, { signIn, knock: false })  return { identityId: session!.identity_id, db: createClient<paths>({ baseUrl: branchUrl, fetch: runtime.fetch }) }} describe('Note and AgentGrant access matrix', () => {  let mayaDb: ReturnType<typeof clientForToken>  let samDb: ReturnType<typeof clientForToken>  let agentDb: ReturnType<typeof clientForToken>  let roadmapId: string  let privateNoteId: string  const outsiderDb = clientForToken()  const readerDb = clientForToken(process.env.NAPALM_READONLY_KEY)  const serviceDb = clientForToken(process.env.NAPALM_SERVICE_KEY)   beforeAll(async () => {    const password = process.env.TEST_USER_PASSWORD ?? 'correct-horse-battery-staple'    const maya = await clientForUser('maya@acme.co', password)    const sam = await clientForUser('sam@orbit.io', password)    const agent = await clientForUser('triage-bot@acme.co', password)    mayaDb = maya.db    samDb = sam.db    agentDb = agent.db     // Reset prior Note and AgentGrant rows, then seed multi-caller fixtures    await serviceDb.POST('/query/resetNotes', { body: { query: queries.resetNotes, variables: {} } })    const samProfile = await samDb.POST('/query/upsertPerson', {      body: { query: queries.upsertPerson, variables: { name: 'Sam' } },    })    await mayaDb.POST('/query/upsertPerson', {      body: { query: queries.upsertPerson, variables: { name: 'Maya' } },    })     const roadmap = await mayaDb.POST('/query/addNote', {      body: { query: queries.addNote, variables: { title: 'Q4 roadmap' } },    })    const privateDraft = await mayaDb.POST('/query/addNote', {      body: { query: queries.addNote, variables: { title: 'Board compensation' } },    })    await samDb.POST('/query/addNote', {      body: { query: queries.addNote, variables: { title: 'Partner terms' } },    })     roadmapId = roadmap.data!.data[0]!.id    privateNoteId = privateDraft.data!.data[0]!.id     await mayaDb.POST('/query/shareNote', {      body: { query: queries.shareNote, variables: { note: roadmapId, person: samProfile.data!.data[0]!.id } },    })    await mayaDb.POST('/query/grantAgentNotes', {      body: { query: queries.grantAgentNotes, variables: { agent: agent.identityId, notes: [roadmapId] } },    })  })   test('filters select results per caller without leaking existence', async () => {    const mayaNotes = await mayaDb.POST('/query/myNotes', { body: { query: queries.myNotes, variables: {} } })    const samNotes = await samDb.POST('/query/myNotes', { body: { query: queries.myNotes, variables: {} } })    const agentNotes = await agentDb.POST('/query/myNotes', { body: { query: queries.myNotes, variables: {} } })    const outsiderNotes = await outsiderDb.POST('/query/myNotes', { body: { query: queries.myNotes, variables: {} } })     expect(mayaNotes.data?.data.map((row) => row.title)).toEqual(['Board compensation', 'Q4 roadmap'])    expect(samNotes.data?.data.map((row) => row.title)).toEqual(['Partner terms', 'Q4 roadmap'])    expect(agentNotes.data?.data.map((row) => row.title)).toEqual(['Q4 roadmap'])    expect(outsiderNotes.data?.data).toEqual([])  })   test('skips unauthorized targets on update and delete', async () => {    // Sam has neither update read nor delete access on Maya's private note    const attempt = await samDb.POST('/query/renameNote', {      body: { query: queries.renameNote, variables: { id: privateNoteId, title: 'Overwritten' } },    })    expect(attempt.data?.data).toEqual([])     const unchanged = await mayaDb.POST('/query/getNote', {      body: { query: queries.getNote, variables: { id: privateNoteId } },    })    expect(unchanged.data?.data[0]?.title).toBe('Board compensation')  })   test('aborts spoofed inserts and read-only writes with structured errors', async () => {    // Inserting a row attributed to another author violates allow insert    const spoofed = await samDb.POST('/query/insertNoteForAuthor', {      body: { query: queries.insertNoteForAuthor, variables: { authorName: 'Maya', title: 'Forged' } },    })    expect(spoofed.response.status).toBe(400)    expect(spoofed.error).toMatchObject({ error: { code: 'query_failed', type: 'AccessPolicyError' } })     // A --read-only service key cannot run mutations    const readOnlyWrite = await readerDb.POST('/query/addNote', {      body: { query: queries.addNote, variables: { title: 'Blocked write' } },    })    expect(readOnlyWrite.response.status).toBe(400)    expect(readOnlyWrite.error).toMatchObject({ error: { code: 'query_failed', type: 'DisabledCapabilityError' } })  })   test('revokes delegated visibility on the next read', async () => {    await mayaDb.POST('/query/revokeAgentGrants', {      body: { query: queries.revokeAgentGrants, variables: {} },    })    const afterRevoke = await agentDb.POST('/query/myNotes', {      body: { query: queries.myNotes, variables: {} },    })    expect(afterRevoke.data?.data).toEqual([])  })})
Operation under testExpected response when deniedAssertion to write
select, /search or /changes200 with unreadable rows omittedAssertion to writeAssert exact visible IDs or titles for each caller and [] for outsiders.
update or delete target200 with data: [] (update read / delete)Assertion to writeRe-read as the record owner afterward and assert every field stayed unchanged.
Disallowed insert or post-update state400 query_failed (AccessPolicyError)Assertion to writeAssert HTTP 400, error.code === "query_failed" and error.type === "AccessPolicyError".
Write from a --read-only caller400 query_failed or 403 read_onlyAssertion to writeStatements abort with DisabledCapabilityError, and write actions fail before execution with 403 read_only.
Action gatekeeper miss403 nothing_foundAssertion to writeAssert HTTP 403 and verify your handler received zero requests for the unauthorized caller.

Python and model pipelines with pytest#

Backend services and ML pipelines in Python generate typed bindings with napalm generate notes --lang python --branch test-suite and run the same caller matrix under pytest. Pair policy tests with model evals so CI verifies both consent rules (such as .allows_training on training exports) and golden-set accuracy on the same branch.

tests/test_access.py
import osimport httpximport pytestfrom napalm.client import AuthenticatedClientfrom napalm.client.api.default import my_notesfrom napalm.client.models import MyNotesRequest, MyNotesVariables BRANCH_URL = os.environ["NAPALM_TEST_URL"] @pytest.fixturedef reader_client() -> AuthenticatedClient:    return AuthenticatedClient(base_url=BRANCH_URL, token=os.environ["NAPALM_READONLY_KEY"]) def test_readonly_key_blocks_mutations(reader_client: AuthenticatedClient):    # Generated request models pre-fill each query string on branch builds    rows = my_notes.sync(client=reader_client, body=MyNotesRequest(variables=MyNotesVariables()))    assert rows is not None     response = httpx.post(        f"{BRANCH_URL}/query",        headers={"Authorization": f"Bearer {os.environ['NAPALM_READONLY_KEY']}"},        json={"query": "insert Note { title := 'Blocked' }", "variables": {}},    )    assert response.status_code == 400    assert response.json()["error"]["code"] == "query_failed"

Preview writes without committing#

Pass "is_dry_run": true on POST /query or POST /query/{name} (or --dry-run on napalm query and napalm call) to execute a single insert, update or delete inside a rolled-back transaction. The engine evaluates every access policy, constraint, default and schema rewrite as the caller, captures before and after object snapshots and aborts before commit.

test/dry-run.test.ts
test('previews a mutation and rewrite fields without committing side effects', async () => {  const response = await fetch(`${branchUrl}/query/archiveNote`, {    method: 'POST',    headers: {      Authorization: `Bearer ${await mayaSignIn.token()}`,      'Content-Type': 'application/json',    },    body: JSON.stringify({      query: queries.archiveNote,      variables: { id: roadmapId },      is_dry_run: true,    }),  })  expect(response.status).toBe(200)   const preview = await response.json()  expect(preview.changes[0]).toMatchObject({    id: roadmapId,    type: 'default::Note',    action: 'update',    before: { pinned: true },    after: { pinned: false },  })  // Schema sharing adds table-level counts across triggers and mutation rewrites  expect(preview.rows).toContainEqual({    type: 'default::Note',    inserted: 0,    updated: 1,    deleted: 0,  })  expect(preview.position).toMatch(/^nbm_/)})
Statement shape
A dry run requires one insert, update or delete whose result is the changed objects. Wrapping a mutation in a custom tuple or sending a select returns 400 dry_run_unsupported.
Webhooks and jobs
Rolled-back transactions never fire notify webhooks and never persist ext::napalm::Job rows. To test webhook signature handling directly, run napalm webhooks test against a receiver registered on your branch.
Actions
Sending "is_dry_run": true to an action at POST /query/{name} runs the gatekeeper query alone and never calls the external HTTPS handler.
Agent and model proposals
On POST /ask (napalm.ask(question, { isDryRun: true }) or napalm ask --dry-run) and on /a2a SendMessage calls, dry runs execute proposed writes under the caller’s rules and return the diff in proposed.dry_run without modifying rows.

Audit reach and failed rules#

When a caller-matrix test returns an unexpected [] or AccessPolicyError, inspect the exact policy verdict with napalm explain-access (POST /projects/{id}/explain-access) rather than weakening schema rules or adding debug fields.

Value-blind access policy trace

napalm explain-access evaluates every allow and deny clause on a target UUID as the chosen user or key, pinpointing broken link hops without exposing stored field values.

Inspecting a failed policy on a test branch
napalm explain-access notes 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --as sam@orbit.io --branch test-suite
Object default::Note 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f
Access ✗ read ✗ change ✗ delete
author_has_full_access allows all
✗ .author.identity ?= global caller
shared_can_read allows reading
✗ (global caller in .shared_with.identity) ?? false
.shared_with is empty for this object
global caller was set

The command evaluates every allow and deny policy on the target UUID as the specified user (--as) or service key (--key), pinpoints the first empty link step on any path expression and never prints stored field values. Each --as check records a projectPersonAccessChecked entry in napalm activity.

Terminal
# Check query compilation and filter warnings without deployingnapalm queries push notes --branch test-suite --check # Count readable, updatable and deletable objects for one user on the branchnapalm people reach notes maya@acme.co --branch test-suite # Preview blast radius for a prospective read-only key before issuing the credentialnapalm keys reach notes --new --read-only --branch test-suite # Evaluate one object's rules as an existing service key (runs on the key's bound branch)napalm explain-access notes 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --key 0b6f1f5e-2a4c-4d7e-9f3b-8c1d2e3f4a5b
GET /projects/{id}/schema/warnings
Flags allow policies that query another object type without filtering by global caller. Because subqueries inside policies bypass the target type’s own rules, an unfiltered subquery opens access whenever any row exists.
POST /projects/{id}/check
Compiles an EdgeQL statement against a branch without executing the query, returning inferred parameter types, output JSON Schema and whether the statement writes.
napalm queries push --check
Typechecks every .edgeql file in dbschema/queries and warns when != compares an optional field or = / != compares an optional $parameter that evaluates to {}.
napalm keys reach --new
Counts readable, updatable and deletable rows plus readable ext::files::File bytes for a prospective key before you issue the key in CI or production.

Gate pull requests in CI#

Projects linked through Napalm’s GitHub App provision pr-<number> branches, run dbschema/seed.edgeql and post migration reviews automatically. When running your own CI pipeline, combine static migration review, ephemeral branch setup, SDK typechecking and your test runner in one workflow, then tear down the branch when the pull request closes.

.github/workflows/test.yml
name: Verify schema and policieson:  pull_request:    types: [opened, synchronize, reopened, closed] jobs:  verify:    if: github.event.action != 'closed'    runs-on: ubuntu-latest    env:      NAPALM_TOKEN: ${{ secrets.NAPALM_TOKEN }}      BRANCH: pr-${{ github.event.number }}    steps:      - uses: actions/checkout@v4      - uses: actions/setup-node@v4        with:          node-version: 22      - run: npm ci      - run: curl -fsSL https://downloads.napalmdata.com/cli/install.sh | sh && echo "$HOME/.napalm/bin" >> "$GITHUB_PATH"       # Fail early if the migration is incomplete or breaks a deployed query on main      - run: napalm schema push notes --review > review.md       # Provision or update the isolated pull-request branch      - run: |          napalm branches ls notes --json | grep -q "\"$BRANCH\"" || \            napalm branches create notes "$BRANCH" --preview          napalm endpoint notes --branch "$BRANCH" --enable --passthrough all --share-schema          napalm schema push notes --branch "$BRANCH" --yes       # Regenerate SDK types against the branch schema and fail on drift      - run: napalm generate notes --lang ts --branch "$BRANCH"      - run: npx tsc --noEmit       # Run the access-rule tests in dbschema/tests on the pull-request branch      - run: napalm test notes --branch "$BRANCH"       # Issue short-lived branch keys, seed fixtures and run the Vitest caller matrix      - run: |          NAPALM_SERVICE_KEY=$(napalm keys create notes --label ci-rw --branch "$BRANCH" --days 1 --json | jq -r .token)          NAPALM_READONLY_KEY=$(napalm keys create notes --label ci-ro --branch "$BRANCH" --read-only --days 1 --json | jq -r .token)          napalm query notes --file dbschema/seed.edgeql --key "$NAPALM_SERVICE_KEY"          NAPALM_TEST_URL="https://notes.napalmdata.com/branches/$BRANCH" \            NAPALM_SERVICE_KEY="$NAPALM_SERVICE_KEY" \            NAPALM_READONLY_KEY="$NAPALM_READONLY_KEY" \            npx vitest run   teardown:    if: github.event.action == 'closed'    runs-on: ubuntu-latest    env:      NAPALM_TOKEN: ${{ secrets.NAPALM_TOKEN }}      BRANCH: pr-${{ github.event.number }}    steps:      - run: curl -fsSL https://downloads.napalmdata.com/cli/install.sh | sh && echo "$HOME/.napalm/bin" >> "$GITHUB_PATH"      - run: napalm branches remove notes "$BRANCH" --yes

Store a dedicated manage org token (napalm tokens create --label ci --scope manage --days 30) as NAPALM_TOKEN. Branches created from a workflow are cleaned up immediately by the teardown job on pull-request close, and Napalm’s nightly sweep drops any leftover manual branch after 14 days without a schema push.

Check the test suite#

  1. Break a rule and run napalm test

    Change Note’s author_has_full_access rule to using (exists global caller) and push the schema to test-suite. napalm test notes --branch test-suite names each failing step and exits 1.

  2. Introduce a policy leak on the test branch

    Remove the .agent ?= global caller filter from an AgentGrant rule and push to test-suite. GET /projects/{id}/schema/warnings reports the unguarded policy read, and the outsider assertion in Vitest fails immediately.

  3. Break a query contract locally

    Rename a field referenced in dbschema/queries/myNotes.edgeql. Both napalm schema push notes --review and napalm generate notes --lang ts --branch test-suite exit non-zero with the compiler’s line diagnostic before tests start.

  4. Run a dry-run mutation twice

    Execute the is_dry_run test twice in a row against the same seeded note. Both runs observe the same before state, and napalm queue ls notes --branch test-suite lists zero queued jobs.

  5. Verify branch teardown

    Run napalm branches remove notes test-suite --yes. napalm branches ls notes no longer lists test-suite, and calling https://notes.napalmdata.com/branches/test-suite/query with the branch’s service key fails with 401 invalid_key.

Once your branch suite passes, rehearse migrations against production data volumes in Release rehearsals, plan multi-step rollouts in Live schema changes and diagnose live policy questions in Troubleshooting & auditing.

Type a word or two to search every docs page.