# Schema Language (`.pg`)

Source: https://www.omnigraph.dev/docs/schema

A schema declares the node and edge types a graph accepts. OmniGraph validates
the same schema and constraints for mutation queries, loads, and branch merges.
Actor attribution on a commit does not create a graph node. Applications may
declare their own `Actor`, `OmniActor`, or other provenance types; these are
ordinary customer-owned types with no automatic rows or permission grants.

```graphql
node Person {
  email: String @key
  display_name: String
  age: I32?
  @range(age, 0..150)
}

node Company {
  slug: String @key
  name: String
}

edge WorksAt: Person -> Company @card(0..) {
  role: String?
  @unique(@src, @dst)
}
```

Comments use `// ...` or `/* ... */`.

## Declarations

```text
interface <Name> { <properties> }
node <Name> [implements <Interface>, ...] { <properties and constraints> }
edge <Name>: <FromNode> -> <ToNode> [@card(...)] { <properties and constraints> }
```

Interfaces provide reusable properties. An edge's endpoint node types must
already be declared. Query traversals spell an edge with a lowercase first
letter (`worksAt` for `WorksAt`); lookup is otherwise case-insensitive.

## Property types

| Type              | Values                                                                  |
| ----------------- | ----------------------------------------------------------------------- |
| `String`          | UTF-8 text                                                              |
| `Bool`            | `true` or `false`                                                       |
| `I32`, `I64`      | Signed integers                                                         |
| `U32`, `U64`      | Unsigned integers                                                       |
| `F32`, `F64`      | Floating-point numbers                                                  |
| `Date`            | Calendar date                                                           |
| `DateTime`        | Timestamp with millisecond precision                                    |
| `Vector(N)`       | `N` 32-bit floating-point values                                        |
| `Blob`            | Managed bytes or an external reference; see [Blobs](https://www.omnigraph.dev/docs/schema/blobs.md) |
| `enum(a, b, ...)` | One of the declared strings                                             |
| `[T]`             | A list of scalar `T` values                                             |
| `T?`              | A nullable value                                                        |

Property names starting with `_` are reserved for system columns and are
rejected when a schema is admitted. The reserved namespace covers Lance's
virtual system columns (`_rowid`, `_rowaddr`, `_rowoffset`,
`_row_created_at_version`, `_row_last_updated_at_version`) and OmniGraph's
own implicit stored columns, spelled `__id` on nodes and edges and
`__src`/`__dst` on edges for newly created graphs.
Supported existing graphs without the `system-columns` feature keep the earlier spellings `id`, `src`,
and `dst` for their implicit columns. They reserve `id` on nodes and edges,
and `src`/`dst` on edges. On current graphs all three names are ordinary
property names. Query meta-fields use `@id`, `@src`, and `@dst`; projected
node objects use `@id`, and JSONL exports use a top-level `id`. The schema
endpoint (`GET /schema`) reports the physical spellings in `system_columns`.
`_distance` and `_score` are also reserved for new declarations: search-ordered
queries rank results by those columns. A graph whose schema already declared
either name before this reservation keeps opening; only new schemas are
refused.

On edge types the names `from` and `to` are also reserved: they are the
insert parameters that name the endpoints.

## Constraints

Constraints can be written in the type body. `@key`, `@unique`, and `@index`
also have a single-property shorthand.

| Constraint            | Applies to   | Meaning                                                                                                                                                                                                                                                                                               |
| --------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@key(p, ...)`        | node or edge | The property tuple identifies the entity; its id is derived from it. Key properties must be non-null scalar values. An edge key must include both `@src` and `@dst`, and a key may be declared only when the type is created.                                                                         |
| `@unique(p, ...)`     | node or edge | No two entities may share the property tuple. Edge constraints may include `@src` and `@dst`.                                                                                                                                                                                                         |
| `@index(p, ...)`      | node or edge | Declares index intent. Indexes affect performance, not correctness.                                                                                                                                                                                                                                   |
| `@range(p, min..max)` | node         | Restricts a numeric property, or each element of a numeric list, to an inclusive range; either bound may be omitted. Values compare with the bounds exactly at any magnitude, and a decimal bound on an integer property admits the integers on its side: `@range(n, -2.5..2.5)` admits -2 through 2. |
| `@check(p, "regex")`  | node         | Requires a String property to match the expression.                                                                                                                                                                                                                                                   |
| `@card(min..max)`     | edge         | Bounds how many edges of the type start at each source node; omit `max` for an unbounded range, as in `@card(1..)`. The default is unbounded from zero. See [Edge cardinality](#edge-cardinality).                                                                                                    |

`@range(p, ..10)` supplies only a maximum, and `@range(p, 10..)` supplies
only a minimum; both endpoints are inclusive. Integer bounds must fit `I64`
(`-9223372036854775808` through `9223372036854775807`), even for a `U64`
property. Decimal bounds use their `F64` value.

Already accepted graph schemas keep their stored bounds. Older versions
interpreted an upper-only bound as a minimum and converted oversized integer
bounds to `F64`, possibly rounding their value. Opening or upgrading a graph
does not rewrite those accepted meanings. Reapplying that source, or using an
exported schema to create another graph, uses the corrected admission rules:
to preserve the accepted constraint, spell the historical minimum as `min..`
and a stored floating-point bound as a decimal with the recorded value.
Complete outstanding deployments containing affected schema source before
upgrading the binary; deployment source validation uses the admission rules.

`Blob`, list, and vector properties cannot be keys or unique, in the
property-level or the body form. Blob properties also cannot be indexed.

Earlier releases admitted a body-level `@unique` on a list or vector property.
A graph that already declares one still opens, but a write that gives the
property a value is refused, and reapplying that source is refused at
admission. In a cluster, every `cluster apply` of a deployment that contains
such a graph is refused, even one that changes only another graph, query or
policy, until the constraint is removed. To remove the constraint in place, drop every property it names in
one schema change, then add the properties back without it; dropping a
property discards its stored values. A constraint that also names another
property or `@src`/`@dst` cannot be removed in place: rebuild the graph
without it.

Current automatic property indexes are created for single-property node declarations:
orderable scalars and enums receive a scalar index, free-text Strings receive a
full-text index, and vectors receive a vector index. Composite declarations and
edge-property declarations are accepted as schema intent but do not currently
create a property index. Edge endpoints are indexed independently for traversal.
See [Search](https://www.omnigraph.dev/docs/queries-search/search.md#indexes).

### Edge cardinality

`@card(min..max)` counts, for each node of the edge's source type, the edges of
that type that start at it. A write is refused before publication when it
leaves one of these nodes outside the bounds:

* a source node the write inserts or updates, when `min` is above zero;
* a source node whose edges of the type the write adds, removes, or moves,
  including the edges an `overwrite` load omits and the edges a node delete
  cascades to.

A source node the write deletes is not counted. A node whose type needs edges
(`min` above zero) must therefore arrive in the same write as those edges: one
mutation query that inserts the node and its edges, or one JSONL load that
carries both. A load of the node type alone cannot add such a node, and neither
can a [`load csv`](https://www.omnigraph.dev/docs/queries-search/mutations.md#csv-loading) into it, which carries no
edges.

Schema apply refuses a new edge type with a non-zero minimum whose source node
type already exists (`OG-MF-107`): its existing nodes have none of the new
edges. Declare such an edge with its source type, or without a minimum.

Schema apply widens an existing edge type's range in place: lowering `min`, or
raising or removing `max`, as in `@card(1..1)` to `@card(0..1)`, rewrites no
data, because every stored count inside the old range is also inside the new
one. The new range holds from the next write. Raising `min` or lowering `max`
is refused, because the stored counts would need a check that apply does not
make.

Earlier Omnigraph versions did not count inserted source nodes, so a graph they
wrote can hold nodes below the minimum. Each is counted the next time a write
inserts or updates it or changes its edges of the type, and a load that
rebuilds the graph from an export refuses it. An orphan query lists them:

```graphql
query people_without_employer() {
    match {
        $p: Person
        not { $p worksAt $c }
    }
    return { $p.email }
}
```

## IDs

Every node and edge has a String id. On the wire it rides at the top level of
the load or export envelope, under the fixed key `id`, beside `type` (nodes) or
`edge`; `data` holds user properties. Legacy-vintage graphs also accept
`data.id` as identity when the top-level `id` is absent; providing both is
refused. In queries the id is the meta-field
`$p.@id` and an edge's endpoints are `$e.@src` and `$e.@dst`
([system fields](https://www.omnigraph.dev/docs/queries-search/queries.md#system-fields)); a bare `id` in a query
is always a user property of that name.

* A node with `@key` derives its id from the complete typed key tuple. Renaming a
  key property with `@rename_from` does not change existing ids.
* A node without a key receives a generated id unless input supplies one.
* An edge with `@key` derives its id the same way, in the catalog's key
  order: `@src`, then `@dst`, then any scalar members. A composite id encodes
  as a JSON array of the member values, for example `["Alice","Bob"]`.
* An edge without a key uses generated or supplied ids. Edges store their
  endpoints as the graph's endpoint columns, `__src` and `__dst` on graphs
  created by this binary.

For hand-authored load data, omit a keyed node's or keyed edge's top-level `id`
and let OmniGraph derive it; a supplied id on a keyed edge must equal the
derived id exactly. Export includes ids so a graph can be rebuilt without losing edge
references.

## Annotations

* `@rename_from("OldName")` on a node, edge, or property declares a rename
  during schema migration. Use the current name everywhere after applying it.
* `@description("...")` adds human-readable metadata to types and properties.
* `@instruction("...")` adds usage guidance to node and edge types.
* `@embed("source_property", model="model-id")` associates a vector with its
  source String property. The model is optional; see
  [Embeddings](https://www.omnigraph.dev/docs/queries-search/embeddings.md).

Property-level `@key`, `@unique`, and `@index` are shorthands for their
single-property constraints. Unknown annotations are retained as metadata but
have no built-in behavior.

## Schema changes

Always preview a direct schema change before applying it:

```bash
omnigraph schema plan --schema next.pg --target ./graph.omni
omnigraph schema apply --schema next.pg --target ./graph.omni
```

Supported changes include adding types, adding nullable properties, renaming
nodes, edges, or properties with `@rename_from`, adding index declarations,
widening an enum with new values, making a nullable property required, adding
`@unique` to a node type, updating descriptions or instructions, and
dropping node, edge, or property declarations. Dropping a property also drops
every constraint that names only dropped properties: its own `@index`,
`@unique`, `@range` or `@check`, and a composite constraint whose members are
all dropped.

None of these changes rewrites existing rows. Adding a nullable property,
renaming a property, or dropping a property changes only the table's metadata:
existing rows read the new property as null, no stored value or Blob is read,
and the indexes of the remaining properties keep covering the rows they
covered. A dropped property's index is removed by the same commit, and index
maintenance does not build it again. The time and memory
the apply takes therefore do not grow with the number of rows or the size of
their values. They still grow with the table's metadata: its columns, its
indexes and its fragments, of which a table written by many small commits has
more until `omnigraph optimize` compacts them.

Making a nullable property required (on a node or an edge) and adding `@unique`
to a node type read the stored rows first, under the locks the apply holds, and
change nothing if a row breaks the rule: a live row holding a null refuses with
`OG-MF-104`, two rows sharing a key with `OG-MF-108`. The `@unique` check holds
the keys in memory and refuses a table whose keys need more than an estimated
1 GiB. A `@unique` that names a property the same apply adds needs no check,
because every stored row holds a null there and a key with a null part is not
compared. A refused apply leaves the accepted schema in force. A successful one keeps entity
ids, relationships and retained commits, and later writes are checked against
the new rule. To add a required or unique property to a populated type, add it
nullable, load its values, then promote it, with a `@rename_from` in the same
apply if you like. Promotion rewrites no data file, with one exception: a
deleted row keeps its value in storage, so a fragment whose deleted rows hold a
null in the promoted property is rewritten without them. Making a property
required also makes its storage column non-nullable.

Applying changed schema text, including comments or formatting, records the new
source in one graph commit even when no table changes are needed. Applying the
same accepted source again leaves the graph unchanged.

Changes such as adding a required property to existing entities (add it nullable,
then promote it), changing a property
type (except enum widening and making a property required), changing edge endpoints, raising an edge's `@card` minimum or lowering its maximum, adding an
edge type with a non-zero `@card` minimum from an existing node type, changing a
node's implemented interfaces, adding a constraint other than `@index` and a node's `@unique`,
removing a constraint from a property that stays, and adding, removing or
changing an existing type's `@key` are rejected. A drop is rejected when it
would remove a constraint that also names a field that stays, such as
`@unique(a, b)` when only `a` is dropped. The plan reports the exact
unsupported step before anything changes.

A drop removes the declaration from the current schema and reclaims no storage
at apply. Older commits still read the dropped data until `omnigraph cleanup`
stops retaining them. Re-adding a property under a dropped name starts a new
property, so a historical query never reads the dropped values through it; see
[historical reads](https://www.omnigraph.dev/docs/branching.md#historical-reads). A dropped type's data is reclaimed by that cleanup. A
dropped property's values also stay in the table's current data files, beside
the properties that remain, until the next `omnigraph optimize`: every
optimize rewrites each fragment of a table that still stores a dropped
property's values, copying only the remaining properties. Optimize rewrites
main only, and cleanup deletes the old files only once nothing it retains
references them: a live branch keeps the commit it was created from and its
head, a tag keeps the snapshot it names, and the retention policy keeps older
commits. Merging a branch releases none of its files; only deleting the branch
does. To erase dropped data, run optimize after the drop, delete every branch
created from a commit before that optimize and every tag naming such a commit,
then run cleanup with a retention that excludes the commits before the
optimize, for example `--keep 1`; after that, the dropped data cannot be
recovered. Review the plan carefully, and treat that cleanup as the step that
cannot be undone. See [optimize](https://www.omnigraph.dev/docs/operations/maintenance.md#optimize) and
[cleanup](https://www.omnigraph.dev/docs/operations/maintenance.md#cleanup).

Cluster-managed graphs change schema through `omnigraph cluster apply`. Direct
schema apply and the server schema-apply endpoint refuse cluster-managed graphs.

## Diagnostic codes

Migration rejections may include a stable `OG-...` code. Match automation on the
code rather than the message text.

| Code        | Meaning                                                                                      |
| ----------- | -------------------------------------------------------------------------------------------- |
| `OG-DS-102` | Drop a node type that contains entities.                                                     |
| `OG-DS-103` | Drop an edge type that contains entities.                                                    |
| `OG-DS-104` | Drop a populated property.                                                                   |
| `OG-MF-103` | Add a required property to a populated type.                                                 |
| `OG-MF-104` | Make a property required while a stored row holds a null (reported by `schema apply`).       |
| `OG-MF-106` | Change a property's type, including enum narrowing or renaming.                              |
| `OG-MF-107` | Add an edge type with a non-zero `@card` minimum from an existing node type.                 |
| `OG-MF-108` | Add `@unique` to a node type while two stored rows share a key (reported by `schema apply`). |

`omnigraph schema plan` includes these codes in human and JSON output, except
`OG-MF-104` and `OG-MF-108`, which only `schema apply` can know from the stored
rows.