Reference · Schema & extensions
Schema & extensions
Reference for every Napalm schema extension, access policy clause, file record property, vector index, background job, agent grant and shard placement annotation.
- API
- —
Core schema declarations#
Every Napalm project compiles one declarative schema in dbschema/default.gel. Apply migrations atomically with napalm schema push and export the active branch schema with napalm schema pull.
Single schema file
Types, links, policies, rewrites, triggers and notifications compile together from one file.
Query-checked migrations
Schema pushes compile every deployed query before applying changes atomically.
Every schema must declare using extension napalm;, which supplies the Project API’s settings, keys, deployed queries, jobs and sessions. napalm schema push sends your file verbatim without injecting lines, and schemas missing that declaration fail with an error naming the missing line.
using extension auth;using extension files;using extension ai;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; function normalize_slug(raw: str) -> str { set is_private := true; set volatility := 'Immutable'; using (str_lower(str_trim(raw))); } type SlugAudit { required note_id: uuid; required previous_slug: str; access policy closed_over_api allow select using (false); } type Note { required author: ext::auth::Identity; required slug: str { rewrite insert, update using (normalize_slug(__subject__.slug)); }; required updated_at: datetime { rewrite insert, update using (datetime_of_statement()); }; access policy author_full_access allow all using (.author ?= global caller); access policy reserved_slug when (exists global caller) deny insert, update write using (.slug = 'admin') { errmessage := 'Reserved slug'; }; trigger record_slug_change after update for each when (__old__.slug != __new__.slug) do (insert SlugAudit { note_id := __new__.id, previous_slug := __old__.slug }); notify note_changed after insert, update, delete; }}The declarations below define application types, policies, mutation rules and private helpers inside dbschema/default.gel.
| Declaration | Syntax and scope | Execution semantics |
|---|---|---|
using extension …; | auth, files, ai, napalm or pgcrypto at file top. | Execution semanticsImports extension types, globals, indexes and annotations. Every schema declares using extension napalm;, which also includes auth, pgcrypto and ai. |
module default | module default { … } around project declarations. | Execution semanticsDefault namespace for application types, globals, aliases and functions. Unqualified names in Project API queries resolve in default. |
global | Stored (global role: str) or computed (global caller := …). | Execution semanticsBound from the verified credential and endpoint settings before each statement runs. Request bodies cannot set or override globals. |
access policy | [when (<expr>)] allow | deny <kinds> [using (<expr>)] with select, insert, update read, update write, delete or all. | Execution semanticsStored types without a policy deny all Project API access. Multiple allow rules combine by OR, and any matching deny rule overrides every allow rule. Set errmessage for write refusals. |
rewrite | rewrite insert, update using (<expr>) inside a field block. | Execution semanticsReplaces caller-supplied values inside the SQL statement before constraints and insert or update write policies run. |
trigger | trigger <name> after <kinds> for each | all [when (<expr>)] do (<stmt>). | Execution semanticsRuns inside the same transaction with __new__ and __old__ bindings. Aborting the trigger rolls back the outer write. |
notify | notify <event> after insert, update, delete; on an object type. | Execution semanticsEmits commit-only webhook events subscribed via napalm webhooks add and records previous field values on updates in GET /changes. |
set is_private := true | Inside function <name>(…) -> <type> { … }. | Execution semanticsRestricts calls to schema expressions (computeds, policies, rewrites and triggers) declared in the same module. Direct Project API calls fail. |
Project API statement boundaries#
Every Project API call executes one EdgeQL data statement inside a single transaction. Disallowed constructs fail before compilation with 400 query_rejected.
| Boundary | Project API rule |
|---|---|
| Transaction control | Multi-statement scripts and start transaction are rejected. Each request executes one statement atomically. |
| DDL and configuration | create, alter, drop, migrate and configure are rejected. Run schema changes through napalm schema push or POST /. |
| Session commands | set global, set module and reset are rejected. |
| System introspection | sys::*, cfg::*, schema::* and .__type__ paths other than .__type__.name are rejected. |
| Extension modules and outbound HTTP | Only ext::pgcrypto, job types (ext::napalm::Job, JobRun, JobStep, JobStatus and JobRunStatus), ext::napalm::AgentGrant, ext::ai::search, ext::ai::hybrid_search and ext::ai::to_context are open to caller statements. std::net is blocked. |
Identity and sessions#
Declaring using extension auth; links application records and access policies to authenticated callers and verified sign-in factors. See Access and sign-in and Sessions and keys.
using extension auth;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; global role: str; global caller_emails := str_lower(( select ext::auth::EmailFactor filter .identity ?= global caller and exists .verified_at ).email); type Account { # Optional so service_read succeeds when Identity rows are hidden from service keys. identity: ext::auth::Identity { constraint exclusive; }; required handle: str; access policy owner_manage allow all using (.identity ?= global caller); access policy service_read allow select using (global role ?= 'service'); }}| Type, global or setting | Fields and shape | Semantics |
|---|---|---|
ext::auth::Identity | id: uuid, issuer: str, subject: str, created_at: datetime, modified_at: datetime | SemanticsAuthenticated user identity created at sign-up. issuer holds the OAuth or OIDC issuer URL, or local for password, magic-link and passkey accounts. |
global ext::auth::ClientTokenIdentity | optional ext::auth::Identity | SemanticsVerified Identity bound from a user session JWT or OAuth 2.1 agent token. Evaluates to {} on service key (ndb_…) calls. |
ext::auth::EmailFactor | identity: ext::auth::Identity, email: str, verified_at: optional datetime, created_at: datetime | SemanticsBase type for local email factors (EmailPasswordFactor, MagicLinkFactor and WebAuthnFactor). Check exists .verified_at before trusting .email in policies. |
ext::auth::WebAuthnFactor | email: str, verified_at: optional datetime, credential_id: bytes, public_key: bytes, user_handle: bytes | SemanticsRegistered passkey credential extending ext::auth::EmailFactor and bound to the project’s configured WebAuthn origin. |
userGlobals | Endpoint JSON map (module::name → scalar) | SemanticsForced globals injected automatically on every user session request for the branch. |
serviceGlobals | Endpoint JSON map (module::name → scalar) | SemanticsForced globals injected automatically on every service key request for the branch. |
napalm keys create --global | Key globals map (module::name → scalar) | SemanticsPer-key global overrides layered above serviceGlobals for calls, queued jobs and webhook reads using that key. |
grantGlobals | Endpoint list of module::name | SemanticsGlobals a user may set on an agent grant at consent time. The consent page sends those values in globals, overriding userGlobals for calls made under that grant. Because the user chooses each value directly, reference grant globals only inside deny rules. |
Endpoint and per-key global maps populate user-defined schema modules only and cannot set globals in ext, sys, cfg or schema.
Agent grants and clients#
OAuth 2.1 user consent flows record approved assistants in ext::napalm::AgentGrant and ext::napalm::AgentClient.
Scoped agent grants
Consent grants restrict each agent by allowed queries, read-only mode and expiry.
Pair ClientTokenAgentGrant with custom grant types in module default to narrow unattended agents to selected rows and deadlines. See Agent access and grants and Sign-in.
using extension auth;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; global agent_grant := global ext::napalm::ClientTokenAgentGrant; alias MyAgents := ( select ext::napalm::AgentGrant filter .identity ?= global caller and not exists .revoke_time ); type ScopedGrant { required owner: ext::auth::Identity; required agent: ext::auth::Identity; multi notes: Note; required expires_at: datetime; access policy owner_manage allow all using (.owner ?= global caller); } type Note { required owner: ext::auth::Identity; required title: str; access policy owner_full allow all using (.owner ?= global caller); access policy read_only_agent_cannot_write deny insert, update, delete using ((global agent_grant).is_read_only ?= true); access policy scoped_agent_read allow select using (exists ( select .<notes[is ScopedGrant] filter .agent ?= global caller and .expires_at > datetime_of_statement() )); }}| Type or global | Fields | Semantics |
|---|---|---|
ext::napalm::AgentGrant | identity: ext::auth::Identity, client: ext::napalm::AgentClient, client_name: str, resource: str, is_read_only: bool, allowed_queries: optional array<str>, globals: optional str, create_time: datetime, expire_time: datetime, revoke_time: optional datetime | SemanticsUser consent grant created by POST /. A grant with allowed_queries calls only those deployed queries. globals holds the globals the person set at consent as JSON text. Built-in policy ap_own lets the owning Identity select and delete matching rows. Deleting a row revokes access on the next call. |
global ext::napalm::ClientTokenAgentGrant | optional ext::napalm::AgentGrant | SemanticsActive AgentGrant when an OAuth 2.1 agent (or handler token exchange) calls before expire_time without revoke_time. Policies and rewrites read .is_read_only, .identity, .client, .client_name and .expire_time. Evaluates to {} for direct user sessions and service keys. |
ext::napalm::AgentClient | name: str, uri: optional str, metadata_url: optional str, metadata: json, create_time: datetime, last_use_time: optional datetime | SemanticsRegistered OAuth 2.1 agent client metadata from POST / or client metadata discovery. Readable only from schema expressions. |
Files and object storage#
Declaring using extension files; lets any object type extend ext::files::File. Every inherited field starts with file_ and carries a safe default, so existing populated types can extend ext::files::File in one migration.
Typed file records
Inherited file fields track upload state, check formats and gate download links.
Constrain file_format or overload file_is_public on each subtype to enforce accepted media formats and bucket routing. See Files and object storage and File uploads.
using extension auth;using extension files;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; type Attachment extending ext::files::File { required owner: ext::auth::Identity; overloaded file_format: ext::files::Format { constraint one_of( ext::files::Format.Pdf, ext::files::Format.Png, ext::files::Format.Jpeg, ext::files::Format.Webp, ); }; access policy owner_full allow all using (.owner ?= global caller); } type DatasetArtifact extending ext::files::File { overloaded required file_is_public: bool { default := true; }; constraint expression on (std::contains( [ext::files::Format.Parquet, ext::files::Format.Glb, ext::files::Format.Mp4], .file_format )) { errmessage := 'Unsupported artifact format'; }; access policy public_read allow select; }}| Inherited property | Type | Mutability and lifecycle |
|---|---|---|
file_name | optional str | Mutability and lifecycleCaller-mutable on insert and update. Populates the Content-Disposition filename without touching stored bytes. |
file_size | optional int64 | Mutability and lifecycleCaller-mutable before Ready (0 to 5 TiB). Setting file_size opens a write-once upload session, clearing file_size cancels an open upload and Ready freezes the value. |
file_status | required ext::files::Status | Mutability and lifecycleEngine-managed (Empty by default). Moves to Uploading when file_size is set, Ready after POST /uploads/complete succeeds and Empty if the upload expires. |
file_format | optional ext::files::Format | Mutability and lifecycleEngine-managed ({} until Ready). Sniffed from stored magic bytes during POST /uploads/complete before schema constraints run. |
file_error | optional ext::files::UploadError | Mutability and lifecycleEngine-managed ({} when clean). Records why the last verification failed or expired, and clears when a new upload opens. |
file_is_public | required bool | Mutability and lifecycleCaller-mutable when opening an upload (false by default) and frozen once Ready. Routes bytes to the cluster’s public bucket. |
file_upload | optional json | Mutability and lifecycleComputed upload plan (token, expires and presigned PUT url + headers, or part_size + part_count for POST /uploads/parts). Returned only in the mutation that sets file_size. |
file_url | optional str | Mutability and lifecycleComputed viewing URL once Ready ({} before Ready). Unsigned and permanent for public files. Signed per 1-hour window and valid for 6 hours on private files. |
file_download_url | optional str | Mutability and lifecycleComputed presigned GET URL once Ready ({} before Ready) that sets Content-Disposition: attachment with file_name. |
Three extension enums report upload lifecycle state, verification failures and detected media formats.
| Extension enum | Variants and verification rules |
|---|---|
ext::files::Status | Empty (no verified object or active upload), Uploading (session open awaiting POST /uploads/complete) and Ready (bytes verified and immutable). |
ext::files::UploadError | SizeMismatch (409 size_mismatch), TypeMismatch (409 type_mismatch on public media-type mismatch), NotAccepted (409 not_accepted on failed format constraint), NotUploaded (409 not_uploaded) and Expired (410 expired_upload). |
ext::files::Format | Around 120 magic-byte variants including Pdf, Png, Jpeg, Webp, Mp4, Parquet, Glb, Text and Other. Active formats (Svg, Html, Xml) and Other never render inline and always serve as downloads. |
Vector and full-text search#
using extension napalm; includes the AI extension, though a schema may also declare using extension ai; explicitly. The extension provides deferred vector indexes (ext::ai::index), vector similarity search (ext::ai::search) and reciprocal-rank hybrid search (ext::ai::hybrid_search) paired with fts::index.
Deferred vector indexes
Writes commit immediately while background workers embed indexed text asynchronously.
Reciprocal-rank hybrid search
Hybrid search fuses vector similarity with full-text ranking under caller read policies.
Declare both indexes on an object type so writes commit immediately while background workers embed indexed text. See Vector and hybrid search and Models and embeddings.
using extension ai;using extension napalm;using future simple_scoping; module default { type Article { required title: str; body: str; deferred index ext::ai::index( embedding_model := 'text-embedding-3-small', distance_function := ext::ai::DistanceFunction.Cosine, ) on (.title ++ '\n\n' ++ (.body ?? '')); index fts::index on (fts::with_options(.title ++ ' ' ++ (.body ?? ''), language := fts::Language.eng)); access policy readable allow select; }}To embed rows through Napalm’s managed model provider instead of an external provider key, declare a custom ext::ai::EmbeddingModel subtype setting ext::ai::model_provider := 'napalm'.
module default { abstract type NapalmTextEmbedding3Small extending ext::ai::EmbeddingModel { annotation ext::ai::model_name := 'openai/text-embedding-3-small'; annotation ext::ai::model_provider := 'napalm'; annotation ext::ai::embedding_model_max_input_tokens := '8191'; annotation ext::ai::embedding_model_max_batch_tokens := '8191'; annotation ext::ai::embedding_model_max_output_dimensions := '1536'; annotation ext::ai::embedding_model_supports_shortening := 'true'; } type Note { required title: str; deferred index ext::ai::index(embedding_model := 'openai/text-embedding-3-small') on (.title); }}| Index, function or provider | Signature and return tuple | Semantics |
|---|---|---|
ext::ai::index | deferred index ext::ai::index(embedding_model := …, distance_function := …) on (<str>) | SemanticsAsynchronous vector index over a str expression. Distance metrics on ext::ai::DistanceFunction are Cosine (default), InnerProduct and L2. |
fts::index | index fts::index on (fts::with_options(<str>, language := fts::Language.eng)) | SemanticsSynchronous PostgreSQL full-text index. Required alongside ext::ai::index on any type queried with ext::ai::hybrid_search or POST /search. |
ext::ai::search | (Type, <str>$q | <array<float32>>$v) -> optional tuple<object: Type, distance: float64> | SemanticsScores permitted rows by vector distance. Must stand as the subject of a select with order by .distance, limit and a $q or $v query parameter. |
ext::ai::hybrid_search | (Type, <str>$q, language := 'eng') -> optional tuple<object: Type, score: float64> | SemanticsFuses ext::ai::search and fts::search by reciprocal rank under caller policies. Must stand as the subject of a select with order by .score desc and limit. |
ext::ai::to_context | (object: anyobject) -> str | SemanticsEvaluates the indexed on (…) text expression declared for the object’s ext::ai::index. |
| Model providers | napalm, builtin::openai, builtin::mistral | SemanticsEnable managed embeddings with napalm models --give (napalm), or attach your own API key with napalm models --add openai or napalm models --add mistral. Missing providers return 409 model_not_configured, and provider errors return 424 model_unavailable. |
Schema functions cannot wrap ext::ai::search or ext::ai::hybrid_search because the search input must bind directly to a query $parameter. Deploy search statements as .edgeql query files or call POST /search.
# Vector similarity search: returns tuple<object, distance> ordered ascendingwith hits := (select ext::ai::search(Article, <str>$words) order by .distance limit 5)select (for hit in hits union { id := hit.object.id, distance := hit.distance, snippet := ext::ai::to_context(hit.object) })order by .distance; # Reciprocal-rank hybrid search: returns tuple<object, score> ordered descendingwith hits := (select ext::ai::hybrid_search(Article, <str>$words, language := 'eng') order by .score desc limit 5)select (for hit in hits union { id := hit.object.id, title := hit.object.title, score := hit.score })order by .score desc;Background jobs#
Insert ext::napalm::Job inside a mutation or schema trigger to execute a deployed query or action asynchronously as the queueing caller.
Transactional job queue
Job inserts commit with your write and run asynchronously as the caller.
Because the job row commits in the same transaction as your write, rolled-back mutations never leak background work. See Jobs and schedules.
# Queue a delayed background job inside the same transaction as a mutationwith invite := (insert Invite { email := <str>$email, sender := global caller }), job := (insert ext::napalm::Job { query := 'expireInvite', variables := <json>(invite := <str>invite.id), run_time := datetime_of_statement() + <duration>'168 hours', expire_time := datetime_of_statement() + <duration>'192 hours', }),select { invite_id := invite.id, job_id := job.id }; # Inspect job status and attempt historyselect ext::napalm::Job { id, query, status, run_time, expire_time, finish_time, runs: { status, start_time, finish_time, error } order by .start_time,}filter .id = <uuid>$job;| Type and field | Field type | Mutability and semantics |
|---|---|---|
Job.query | required str | Mutability and semanticsReadonly after insert. Name of the deployed query or action to execute. |
Job.variables | required json | Mutability and semanticsReadonly after insert ({} JSON object by default). Named $variables passed to the deployed query. |
Job.run_time | required datetime | Mutability and semanticsDefaults to datetime_of_statement() on insert. Advances automatically across exponential retry delays. |
Job.expire_time | required datetime | Mutability and semanticsRetry cutoff. Defaults to 24 hours after run_time when omitted and caps at 30 days after run_time. |
Job.status | ext::napalm::JobStatus | Mutability and semanticspending, running, completed, failed or cancelled. An org manager’s cancel sets cancelled. Caller inserts must start at pending. |
Job.identity, Job.agent_grant | optional Identity, optional AgentGrant | Mutability and semanticsStamped by insert rewrite from ClientTokenIdentity and ClientTokenAgentGrant. Deleting the user or revoking the grant prevents execution. |
Job.insert_time, Job.finish_time | required datetime, optional datetime | Mutability and semanticsinsert_time is stamped at creation, and finish_time is set when the job reaches completed, failed or cancelled. scheduled_time marks cron runs from napalm schedules add. |
Job.runs | multi ext::napalm::JobRun | Mutability and semanticsComputed backlink to every execution attempt (JobRun.job), ordered by start_time in status queries. |
Job.steps | multi ext::napalm::JobStep | Mutability and semanticsComputed backlink to finished steps (JobStep.job). Stores at most one step per name across all attempts. |
ext::napalm::JobRun | JobRunStatus | Mutability and semanticsAttempt row with job: Job, status (running, completed, failed, timeout or cancelled), start_time: datetime, finish_time: optional datetime, error: optional str, timeout_time: datetime and accept_time: optional datetime. Any run not completed before timeout_time marks timeout. accept_time records when an action handler answers 202 Accepted to continue asynchronously. |
ext::napalm::JobStep | name: str, answer: optional json | Mutability and semanticsFinished step of a long job, recorded by the job’s handler through POST /jobs/{id}/steps. Holds job: Job, a name of up to 200 characters, an answer of up to 64 KiB and finish_time: datetime. Readonly once recorded. |
is_ready | bool computed | Mutability and semanticsControls when a due job on a subtype of ext::napalm::Job may start. Napalm starts a due job only while is_ready is true, and waiting jobs consume zero attempts. Subtypes cannot override an inherited is_ready rule. |
Failed attempts retry after 10 seconds, doubling each delay up to 1 hour until expire_time. Each attempt runs up to 120 seconds, up to 10 attempts run per branch on each engine and each caller can hold up to 10,000 waiting jobs (429 job_limit_reached). Signed-in callers can select their own jobs, runs and steps and delete their own jobs, while service keys have the same access to jobs queued by keys and schedules. Finished jobs remain stored until deleted, and Napalm never removes finished jobs automatically.
Shard placement annotations#
Napalm infers shard placement roots by walking required single links upward to top-level owner types (such as Account, Project, Site, World or Organization) while preserving standard UUID primary keys.
Top-level placement roots
Required owner links keep each root and its descendants on one shard.
Rooted and reference types
The compiler classifies root, rooted and replicated reference types while keeping UUID keys.
Inspect inferred classifications with napalm roots or napalm schema push --plan before running napalm placement enable. Add ext::napalm::root annotations only when overriding the default inference. See Schema, Horizontal sharding and rebalancing and Multi-tenant B2B SaaS.
using extension auth;using extension napalm;using future simple_scoping; module default { type BillingPlan { annotation ext::napalm::root := 'reference'; required slug: str { constraint exclusive; }; } type Organization { annotation ext::napalm::root := 'root'; required name: str; required plan: BillingPlan; } type Workspace { required org: Organization { readonly := true; on target delete delete source; }; required name: str; } type Document { required workspace: Workspace { annotation ext::napalm::root := 'owner'; on target delete delete source; }; required author: ext::auth::Identity { annotation ext::napalm::root := 'none'; }; required title: str; }}| Target | Annotation | Placement behavior |
|---|---|---|
| Object type | ext::napalm::root := 'root' | Placement behaviorMarks the type as an explicit top-level placement root even when outbound required links exist. |
| Object type | ext::napalm::root := 'reference' | Placement behaviorReplicates a lookup table across every shard in one atomic commit so single-root queries join locally. |
| Link | ext::napalm::root := 'owner' | Placement behaviorSelects the required single link that determines shard ownership when a type declares multiple required links. |
| Link | ext::napalm::root := 'none' | Placement behaviorExcludes a link from root inference so cross-root links (author, guest or partner references) break multi-root ambiguity and cycles. |
Root inference and shard routing follow four compiler and runtime rules.
- Compiler precedence
- When a type has multiple
required singlelinks and no explicit annotation, the compiler chooses one owner link in fixed order:on target delete delete source, inherited owner link,readonlylink, deepest path to a root and alphabetical link name. - Readonly and writable links
- Any
required singleowner chain makes a root placeable. Updating a writable owner link re-parents child rows between roots on the same shard and refuses cross-shard moves once roots sit on different shards. Mark the linkreadonly := trueto fix every row under one root permanently. - Single-root policy paths
- Access policies and queries pinned to one root chain (such as
.projector.workspace.org) execute locally on that root’s shard. Unrooted tables read by single-root policies (such asext::auth::Identity) replicate across shards automatically. - Root overrides
- A root override places one root UUID on a dedicated shard without moving unrelated roots. Overrides isolate a high-traffic root or pin a root to a region via
napalm placement move --root.