Documentation

Overview

Grid Language

Grid is a declarative, reactive language for building live computational models. It combines the spatial reasoning of spreadsheets, the relational reasoning of SQL, and the expressive vocabulary of mathematics and modern programming without requiring authors to manage execution order, memory, parallelism, or runtime placement.

Grid is not a green-field language that asks people to discard what they already know. Cell references, formulas, ranges, named values, tables, queries, functions, units, rules, schedules, and mathematical operators retain their familiar purpose. Grid gives them one model in which they can be composed, reactive, typed, inspected, and scaled.

This documentation is for two audiences:

  • People writing models by hand or reviewing them.
  • AI agents generating Grid code from natural-language intent.

Both audiences share the same surface. The grammar accepts the same forms, the type system enforces the same rules, and Grid returns the same values regardless of who wrote the code. The split is in how the docs are written, not what they cover.

concepts.md defines the shared vocabulary: model, binding, cell, address, symbol, alias, region, and resident value.


What A Grid Model Does

A Grid model describes computation rather than a sequence of machine steps. Its statements can declare:

  • Values and inputs supplied by people, files, services, or connectors.
  • Derivations that remain current as their dependencies change.
  • Relations and queries over ranges, collections, Frames, tables, and external data.
  • Predicates and inference over symbol properties, time, and topology.
  • Constraints and goals for validation, goal seeking, optimization, and numerical analysis.
  • State and reactions driven by conditions, schedules, and simulated time.
  • Outputs and explanations that other models, applications, and people can inspect.

Grid builds the dependency structure, recalculates affected work, and chooses the appropriate execution strategy. The source says what the model means; the runtime machinery is not part of ordinary authoring.

Spatial And Semantic Reasoning

The terms model, binding, cell, address, symbol, alias, and region have precise meanings in Grid. See concepts.md for the compact glossary.

A Grid cell is more than a box in a worksheet. It combines a reactive calculation binding with an address in the model. Grid supports several ways to reason about that address:

A1 = 100000                         # spatial name
R1C2 = 7pct                         # another coordinate notation
B2 = A1 * (1 - R1C2)               # spatial derivation
 
ListPrice = A1                     # semantic address for the same binding
DiscountRate = R1C2
NetPrice = ListPrice * (1 - DiscountRate)
 
prices = A1:D50                    # semantic binding over a region
latest = INDEX(prices, ROWS(prices), 4)

Coordinates let an author begin calculating before every concept has a durable name. A direct named reference adds a semantic alias as the model becomes understood, without inserting another calculation between the name and the cell. Neither form replaces the other: spatial references remain useful for layout, relative calculation, ranges, and repetition, while semantic names make intent clear and carry meaning beyond a particular visual arrangement.

The address space also includes qualified names (Sheet1!B2, Dataset_1!config), structured references (Sales[Revenue]), relative and neighborhood references, and temporal coordinates (A1@-1). See reference.md for the complete surface.

Values From Cells To Resident Models

The same source language works across several value shapes:

  • Scalars include numbers, exact numbers, strings, booleans, dates, durations, blanks, errors, and semantically tagged values such as currencies and units.
  • Arrays and ranges carry rectangular computation and can spill into workbook cells.
  • Objects, records, tuples, lists, maps, sets, and deques support structured and higher-order computation.
  • Relations can be queried with native SELECT expressions and may remain in resident Frames, model tables, or external query engines.
  • Large domain values such as graphs and tensors use named resident bindings and explicit projections rather than implicitly spilling opaque data into workbook cells.
  • Grammars, parser generators, parsers, parse trees, and parse results are native immutable values, as are the grammar-bound tree values they anchor: patterns, theories, algebras, transforms, translations, bounded solvers, and checked theorems; see grammars.md.
  • Symbolic variables declared with symbol compose through ordinary operators into exact symbolic expressions and relations with assumptions, derivatives, and certified solving; see symbolic-mathematics.md.

These shapes do not all have identical storage or mutation rules. Their author-visible surface is indexed in features.md, the functions.md catalog, and relational-authoring.md. Source-authored function inference, open record rows, and collection protocols are described in named-functions.md.

Reactivity, State, And Time

Ordinary formulas are dependency-driven. = establishes an eager derivation; ~= establishes a lazy derivation that resolves when read. Inputs and default/state bindings make ownership explicit where outside writes or rules are allowed.

Rules introduce deliberate change:

WHEN inventory < reorder_point THEN
  reorder_requested = TRUE
END
 
EVERY 15min SKIP MISSED THEN
  heartbeat += 1
END

Historical references and WHY expose how values changed. Simulation adds an explicit model-time lane, state cells, integrators, trajectories, and repeated experiments. External functions are identified separately from synchronous built-ins because they may create jobs, wait on outside systems, and use cache or freshness policies.

Analysis Without A Language Change

Grid calculations can grow from arithmetic into relational analysis, graph and spatial computation, optimization, differential equations, spectral linear algebra, statistics, machine learning, and simulation without exporting the model into a second programming environment. SOLVE expresses goal seeking and bounded optimization over reactive cells; native queries preserve typed relational semantics; domain operations use resident values where materializing everything into cells would be inefficient or misleading.

The author still writes values, names, expressions, constraints, and queries. Grid decides how those operations are compiled and executed.

Explanation Is Part Of The Model

Errors are values with documented propagation and recovery rules. Type tags, units, validation, strictness, and coercion diagnostics make assumptions visible. WHY traces dependencies and recent causes; relational and graph explanation surfaces report logical and physical work. Performance guidance and explicit bounds keep powerful operations predictable without making authors select low-level execution engines.

Learn Grid Through Six Ideas

Begin with Getting Started for one working model. Then learn the language in the following order. Each stage introduces one semantic idea and shows how the richer surfaces grow from it; the feature inventory is an audit index, not a curriculum.

1. Values And Expressions

Start with the values that flow through a model and the expressions that combine them.

Doc What it gives you
reference.md Literals, expressions, operators, errors, and control forms
coercion.md How mixed kinds behave under loose, warning, and strict modes
infix-operators.md The relational vocabulary expressed by Grid's infix operators
errors.md Error values, diagnostics, recovery, and contextual rewrites

2. Cells, Names, And References

Next learn how values become addressable, reactive parts of a model.

Doc What it gives you
concepts.md Model, binding, cell, symbol, alias, address, region, and resident value
assignments.md Bindings, target forms, ownership decorators, ranges, and schedules
reference.md Spatial, semantic, structured, relative, and temporal reference forms

3. Types, Units, And Predicates

Then add semantic claims about values: what they are, what refines them, and what is true of their bindings.

Doc What it gives you
reference.md Type tags, units, IS, choices, predicates, validation, and strictness
algebraic-data-types.md Payload-bearing choices, constructors, exhaustive matching, and finite recursion
coercion.md Representation validity and operator coercion boundaries
cell-metadata.md Validation and presentation contracts attached to bindings
predicates.md Unary predicate schemas plus temporal, topological, and conceptual-set facts, inference, and explanation
presentation.md Declared presentation — FORMAT, VALIDATE, ## doc notes

4. Collections And Projections

With bindings and types in place, move from scalar formulas to shaped and resident values.

Doc What it gives you
collections.md Arrays, native collection kinds, functional pipelines, updates, and contracts
relational-authoring.md Relations, Frames, native SELECT, projections, methods, and pipes
graph-authoring.md Graph schemas, paths, patterns, partitions, measures, and fixed points

5. Definitions And Modules

Once calculations compose, give repeated ideas names and share them across models.

Doc What it gives you
reference.md DEF, lambdas, choices, units, model directives, and USE imports
algebraic-data-types.md Closed payload types and constructor-pattern MATCH
functions.md Built-in function families and signatures
function-compatibility.md Compatibility names, aliases, and special forms

6. Reactive Rules And Actions

Finally, introduce intentional change, clocks, outside work, and repeated experiments after ordinary dependency-driven calculation is familiar.

Doc What it gives you
rules-and-schedules.md WHEN, EVERY, and AT triggers, actions, overrides, and state
external-functions.md Asynchronous work, freshness, jobs, and lazy resolution
simulation.md Model time, state, integrators, trajectories, and experiments

Reference And Practice

These documents support the six-stage path without defining its order.

Doc What it gives you
cookbook.md Worked recipes organized by task
style-guide.md Canonical authoring conventions
performance.md Patterns that keep recalculation predictable
symbolic-mathematics.md Native symbolic variables, exact algebra, assumptions, differentiation, solving, approximation, and proof replay
game-theory.md Declarative games, certified equilibria, direct mechanisms, allocations, and evidence
grammars.md Grammars, parsers, and grammar-bound trees: patterns, theories, algebras, transforms, translations, solvers, and checked theorems
features.md Audited inventory of every supported feature
ai-agent-guide.md Generation contract for AI authors

The catalog goes well beyond spreadsheet math: optimization (linear and mixed-integer programs, MINIMIZE/MAXIMIZE, sensitivity and IIS), differential-equation solvers (ODE_SOLVE, PDE_SOLVE_1D), spectral linear algebra (EIGEN.*, SVD.*), nonlinear solving and curve fitting (NSOLVE, CURVE_FIT), splines, and signal processing (SIGNAL.PSD, FFT). See reference.md for the family map and cookbook.md for worked examples.

Conceptual Map

  source statements

        ├── spatial and semantic bindings
        ├── expressions, queries, constraints, and rules
        └── types, units, validation, and metadata


  dependency-tracked model

        ├── reactive recalculation and state transitions
        ├── resident collections and domain values
        └── external data and scheduled work


  values, errors, diagnostics, history, and explanations

A Grid file (.grid) is a set of statements. Grid turns those statements into addressable bindings, tracks dependencies between them, evaluates formulas and queries, and applies explicit state changes when their triggers fire.

Mental Model In One Page

Read this if you want the absolute minimum needed to understand any model.

  1. A model is a set of addressable reactive bindings. A binding may use a spatial name (A1, R1C1), a semantic name (Revenue), or a qualified name (Sheet1!B2, Dataset_1!config). The ! join is a namespace specifier, not an accessor.
  2. Cells are reactive calculation bindings. A formula may reference other cells, names, ranges, collections, relations, or domain values. Cyclic dependencies are detected and reported as #CIRCULAR_REF! unless iterative calculation is enabled.
  3. Space and meaning compose. Revenue = A1 adds a semantic address for the same spatial binding; data = B1:B100 names a region. Authors can retain both forms as the model grows.
  4. Evaluation is automatic. = is eager and recomputes after relevant changes. ~= is lazy and computes when read. Grid owns dependency order and execution strategy.
  5. Type tags carry semantic meaning. A1 IS currency = 1000 says the value is currency, not just a number. Tags drive formatting, validation, and downstream consumers.
  6. Value shape matters. Scalars, arrays, collections, relations, Frames, tables, graphs, and tensors have documented composition and residency rules. Large resident values use named bindings and explicit projections.
  7. Errors are values. #N/A, #DIV/0!, #VALUE!, #REF!, #NUM!, #NAME?, #NULL!, #CALC!, #SPILL!, #TYPE!, #CIRCULAR_REF! flow through formulas. Use IFERROR, TRY, DEFAULT, or ASSERT to handle them.
  8. Arrays spill. A formula that returns an array writes into a rectangle of cells anchored at its target. Use A1# to refer to the spilled rectangle as a single value.
  9. Effects and time are explicit. External functions have separate execution contracts. WHEN, EVERY, and AT rules make state changes under declared conditions or schedules; temporal references read history.
  10. SOLVE finds inputs, not just outputs. A SOLVE statement drives a cell to a target or optimizes an objective within bounds and writes the answer to a result cell: goal seeking and optimization are first-class syntax.
  11. Models remain inspectable. Diagnostics, WHY, validation, strictness, and explanation surfaces expose meaning and execution without requiring authors to manage the runtime.

The rest of this documentation defines the exact syntax and contracts behind that model.

File Format Summary

A .grid file looks like this:

MODEL "My Model"
DESCRIPTION "What this model does."
VERSION "1.0.0"
AUTHOR "you@example.com"
TAGS "demo", "v1"
 
# Inputs
A1 is currency = 100000
A2 is percentage = 21pct
 
# Derivations
B1 is currency = A1 * (1 - A2)
B2 = B1 > 50000 THEN "ok" ELSE "small"
 
END MODEL

The header directives are all optional (the file will parse without them) but every shared model in the canonical library uses them.

Execution Is Automatic

Models do not pick an engine. The .grid source describes the computation and Grid runs it.

Older files may carry a RUNTIME directive in their header. Grid still parses it for backwards compatibility, but new models should omit it; it has no place in new model source.

How To Ask For Help

  • Looking for a function? Open functions.md and search by name or category.
  • Looking for a complete syntax checklist? Open features.md; it is audited against the parser feature registry.
  • Reviewing a large model? Read performance.md for patterns that keep recalculation predictable.
  • Got a syntax error? Check errors.md and reference.md.
  • Got #VALUE! or surprised by mixed-type behavior? Read coercion.md.
  • Don't know how to express something? Look in cookbook.md.
  • Generating code from an LLM? Read ai-agent-guide.md and feed it as system context to the agent.

Examples

The canonical examples under examples/canonical/ show complete models in increasing complexity, including foundational formulas, array analytics, text quality checks, external enrichment, rules, portfolio risk, electoral apportionment, reproducible election forecasting, and the native Graph V2 surface in 16-graph-v2-native.grid. The unified Predicate model in 17-predicate-knowledge.grid carries structured truth from model symbols into recursive rules, projects a property graph into logical facts, derives reachability, and retains the exact graph edges behind an inferred answer.

Predicate Rules And Proofs

Predicate rules add explainable truth over the model graph:

predicate releasable means
  reviewed
  AND NOT blocked
  AND EVERY dependency IS :releasable
 
ready = MUST(service IS :releasable)

Rules, natural algebraic laws, graph quantifiers, modal constraints, and WHY(query_cell) are covered in the predicate guide.

Temporal History And Provenance

Temporal references read prior values from a model's history:

B1 = A1@-1
C1 = A1@dt"2026-04-10T15:30:00Z"

A1@-N resolves the referenced cell at a prior model revision, and A1@dt"..." resolves the latest revision at or before the timestamp.

WHY(cell) explains the dependency path behind a current value, including the input cells that moved the latest result. Together, temporal references and WHY make a model easier to audit and replay from the language surface.

WHY is a semantic explanation: the target binding, its effective value, dependency lineage, and an active override are meaningful to an author. The shape of the traversal, cache details, parallel work, and execution lane are diagnostic implementation details and may change without changing the model. Likewise, an EXPLAIN report may describe a selected physical plan, but the reported plan is not a promise that future equivalent evaluations use it.

Known Limitations

These language surfaces are intentionally reserved or only partially wired today. If you hit one in production, file an issue with the concrete formula and we'll prioritize the fix.

  • External-function cache policy (access-driven). Every external function declares a cache policy (ttlMs, maxStalenessMs, refreshMode) and Grid honors it: a cached value is served while within ttlMs, refreshed (served-stale for background, withheld for blocking) once past ttlMs, and withheld-and-refreshed at maxStalenessMs. The one nuance is that refresh is evaluated on resolve, not by a standalone background timer, so a fully idle model is not refreshed until it is next resolved. See external-functions.md.

  • External functions are a fixed built-in catalog. They are not user-definable from the language surface; the built-in set is registered in Grid itself.

BESSELK/BESSELY high-precision evaluation, TEXT fraction formats (# ?/?, # ??/??), locale-aware month/day names and separators ([$-409] and [$-de-DE] tokens), and static/dynamic LEFT(N)/RIGHT(N) spatial offsets are supported.

Versioning

This documentation tracks the current Grid language surface.