requel

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

requel

Reproducible data-science functions for agents.

requel (as in RQL, out loud) is a runtime and a small compiler for describing what an agent is allowed to ask of your data. You write .rql files, commit them to a git repository, compile governed SQL and retrieval entrypoints, and compose those entrypoints into Functions that run against your real data systems.


The problem

Ask an agent for last quarter's revenue by region. It joins orders to order_items to reach a line-item filter, sums net_revenue, and hands you $4.2M.

The number is wrong. The join multiplied every order by its line-item count, so a three-line order was counted three times. Nothing failed. The SQL was valid, the number was plausible, and the agent had no way to notice. SQL will not tell you that a join changed the grain of your table.

Agents rarely fail by crashing. They fail by being confident and wrong in a shape indistinguishable from being confident and right. requel's answer is a language that refuses:

$ requel render queries/fanout.rql --params '{}'
error[RQL3001]: fan-out hazard: aggregate over `warehouse.orders` joins
row-multiplying edge `warehouse.order_items` (join_many). SUM/COUNT over a
multiplied row set inflates results.
  --> queries/fanout.rql:14:1
    |
 14 |     m = aggregate(at = orders, sql = sql("SUM(o.net_revenue) AS revenue"))
    | ^
  --> queries/fanout.rql:13:1   related: row-multiplying edge declared here
  help: pre-aggregate at its own grain in a subquery, use COUNT(DISTINCT <pk>)
        style metrics, or wrap the metric with allow_fanout("<why the numbers
        are still correct>", frag)

The query does not run. There is no number to be confidently wrong about. If the fan-out is deliberate, you say so in the file, and that sentence lands in a pull request diff where a human reads it:

m = allow_fanout(reason = "revenue weighted per item on purpose", frag = m)

The escape hatch exists, and taking it leaves a record a reviewer can see.


What it refuses

requel's analysis pass knows the grain of every relation and the cardinality of every edge between them, so it judges what a join does to your numbers before a warehouse ever sees the query.

  • Inflation (RQL3001, above). An aggregate crossing a row-multiplying edge.
  • Deflation (RQL3019), the twin nobody writes a check for. An INNER join silently deletes fact rows with no match on the other side, so the total shrinks and looks fine. Warned before the execute confirmation prompt and recorded on the run's audit line, so it is findable afterwards.
  • Nullability (RQL3037). Predicate evaluation is two-valued, so filtering on a nullable column drops the rows that cannot answer, turning unknown into excluded silently and in one direction.
  • Access. A relation declares who may read it, once, beside the table it protects:
accounts = relation(
    backing = "warehouse.accounts",
    key = ["id"],
    guard = lambda a: (
        sql("{}.tenant_id = {}", a, ctx.attrs.tenant_id)
        if "tenant_viewer" in ctx.roles or "tenant_admin" in ctx.roles
        else fail_closed("accounts requires tenant_admin or tenant_viewer")
    ),
)

Every query touching accounts inherits the guard, including inside subqueries, where the predicate lands in that scope's WHERE clause:

$ requel render queries/acct_view.rql --params '{}' --context tenant-viewer.json
SELECT a.id FROM warehouse.accounts a WHERE (a.tenant_id = $1)
-- binds:
--   1: $1 (string) = t-9

$ requel render queries/acct_view.rql --params '{}' --context anonymous.json
error[RQL2001]: accounts requires tenant_admin or tenant_viewer

Fail-closed is the default and the empty guard is refused, so "no roles" cannot resolve to "no restriction". An agent cannot forget the tenant filter, because writing it was never the agent's job.


How a request becomes a query

A repository is a layered vocabulary, and each directory has one job:

relations/    physical tables, their keys, and their access guards
objects/      the domain vocabulary: dimensions, metrics, filters, edges
queries/      typed entrypoints that read one governed target
concepts/     reusable, project-authored definitions an agent composes
functions/    public multi-step investigations

An object declares meaning once, so every query built on it inherits the same definitions, including the ones that are policy as much as schema:

Customer = object.make(
    name = "Customer",
    backing = customers,
    properties = {
        "id": prop("integer"),
        "region": prop("string"),
        "email": prop("string", nullable = True),
    },
    dimensions = [
        {"key": "region", "expr": lambda a: sql("{}.region", a)},
        {
            "key": "email",
            "expr": lambda a: sql("{}.email", a) if "pii_reader" in ctx.roles else sql("'***'"),
            "doc": "Customer email. Redacted to '***' unless the caller carries pii_reader.",
        },
    ],
    joins = [{
        "name": "region",
        "cardinality": "one",
        "on": lambda self, other: sql("{}.region = {}.code", self, other),
    }],
)

object.make always declares a keyed nominal type with a closed property contract. An analytical registry with no instance API uses semantic.make instead and does not appear in the operational object catalog.

A declared edge is an offer. Nothing is joined until an entrypoint names the route, and then only the hops the caller's request actually needs:

params(
    metrics    = Set(Order.metric_keys, default = []),
    dimensions = Set(Order.dimension_keys + Customer.dimension_keys + Region.dimension_keys, default = []),
    filters    = List(FilterInput, default = []),
    limit      = Int(default = 1000),
)

def query(p):
    return view.make(
        base = Order, base_alias = "o",
        joins = [
            {"edge": "customer", "object": Customer, "alias": "c"},
            {"edge": "region", "of": "c", "object": Region, "alias": "rg"},
        ],
        metrics = p.metrics, dimensions = p.dimensions, filters = p.filters,
        limit = {"n": p.limit, "max": 50000},
    )

Ask for a Region dimension and you get both hops, because the region table is only reachable through the customer table:

SELECT rg.manager AS "Region.manager", SUM(o.net_revenue) AS revenue
FROM warehouse.orders o
JOIN warehouse.customers c ON o.customer_id = c.id
JOIN warehouse.regions rg ON c.region = rg.code
GROUP BY rg.manager LIMIT 1000

Ask for a Customer dimension and the region table is absent entirely. Each route is assembled per request, and the caller never spells a join.

Caller values become binds. Authored literals inline, caller data parameterizes; a ' OR 1=1 -- in a context attribute arrives as $1. The same fragment lowers to PostgreSQL, Snowflake, BigQuery, ClickHouse, or DuckDB, because the dialect is a property of the connector.


Functions

A function is a bounded, read-only DAG. Its leaves are governed entrypoints; its interior is a closed set of pure transforms: project, filter, join, group, sort, take, derive, classify, annotate, distinct, require_complete. There is no arbitrary computation in the middle, which is what makes a plan something you can review and re-derive.

def query(p):
    protein_hits = function.call(
        name = "protein_hits",
        entrypoint = "/queries/blastp_subject_hits.rql",
        target = "homology",
        params = {"sequence": p.protein_sequence},
    )
    families = from_dual_method(protein_hits, nucleotide_hits, top_n = p.top_n)
    return function.make(
        output = families,
        result_kind = "amr_method_corroboration_evidence",
        doc = "Protein-level AMR family support with translated-nucleotide corroboration.",
    )

Completeness is tracked, and a truncated search cannot support an absence claim. Every result carries is_complete and, when it is false, incomplete_reasons naming which step was short and why. A function concluding "the second method did not corroborate this" is refused outright if that method's results were truncated, because the missing family might be in the rows that were dropped. The runtime knows the difference between "we looked and found nothing" and "we stopped looking".

Every plan is re-derived by an independent verifier. A second implementation with its own graph walk, schema projection, and information-flow rules recomputes the compiled plan and refuses it on any disagreement. A new operation has to be written twice, by construction.

Concepts declare their contracts. function.requires states what a concept needs of the node it is handed; function.provides states what it returns. Hand a concept a node missing a column and you are refused at your call site, naming the missing column and listing what the node does have.


Built for agents

  • requel inspect returns an entrypoint's typed contract as JSON Schema plus x-rql-* extensions: every parameter, every selectable metric and dimension, every filter key with its permitted operators and enumerated values, every result column with its type, nullability, documentation, and closed label set. An agent generates against the contract instead of guessing at your schema.
  • requel explain is the security summary: which relations an entrypoint reaches, which are guarded and which are explicitly UNGUARDED, which edges drop rows, which fan-outs were acknowledged and why. An unprotected relation is named as unprotected, so the fact a reviewer needs most is never left to an absent heading.
  • api.txt is a committed manifest of everything your repository promises callers. requel surface --check compares it as a compatibility judgment: widening asks you to regenerate, while withdrawing a filter value or retyping a parameter is a break that exits with a distinct code and has to be announced with a deprecation first.
  • Examples are the tests. Every entrypoint carries example() blocks pinning the rendered SQL, the compiled plan, the produced rows, or the diagnostic code it must refuse with. requel test runs them and --update rewrites the goldens.
  • requel serve hosts the runtime over MCP or HTTP. Identity is resolved at launch, by the operator: pinned binds one identity to the process, signed verifies a host-signed token per call. The model never chooses whose data it reads.

Rendering, linting, testing and inspecting need no credentials at all. The warehouse is only required to execute, and execution is read-only, capped, attributed with a comment header identifying the entrypoint, and logged as a structured audit line.


Getting started

curl -fsSL https://rafflesia.ai/requel.sh | sh

The installer verifies the download's sha256, and verifies the release's build-provenance attestation as well when the gh CLI is available; --strict makes that mandatory. Every release artifact is signed through Sigstore and bound to the function that built it, so you can check any binary yourself:

gh attestation verify "$(command -v requel)" --repo Rafflesia-ai/requel

Building from source works too. The CLI is a single static, zero-cgo binary:

go -C app build -o ../requel ./cmd/requel

Then:

requel init my-ontology       # scaffold a repo that passes its own checks
requel connect warehouse --dsn-env WAREHOUSE_DSN --schemas 'public'
requel scaffold db --from-lock    # draft relations and objects offline
requel test                       # run every example block
requel verify                     # the full offline gate

Rafflesia Databases use the same function with a provider-aware ClickHouse connector:

[project]
dialect = "clickhouse"

[connectors.rafflesia]
driver = "rafflesia"
dsn_env = "RAFFLESIA_DSN"

The DSN is the managed HTTPS native-SQL endpoint with the connection response's default_database as its path (for example /rafflesia_catalog). Requel verifies the service view in that database when it connects, then uses the ordinary ClickHouse catalog and query path. Rafflesia Ontology exports release-pinned backings such as uniprot_swissprot.proteins__r_2026_02_2026_06_10; _current views are for interactive convenience, not reproducible research.

Command What it does
inspect typed contract of an entrypoint, for agents
explain reviewer/agent security summary
render compile to SQL for given params, binds or inline
execute render, then run read-only against a connector
test run example blocks; --update rewrites goldens
lint static checks; --probe-schema diffs against the snapshot
surface the callable surface (api.txt) and its compatibility check
diff rendered delta vs. a base revision, for pull requests
serve host the runtime over MCP or HTTP
doctor what this checkout can do right now, and what each gap needs

Embed the compiler

Applications that own execution and operational state import librequel directly:

model, diagnostics := requel.LoadModel(ctx, modelFS, "requel.toml", options)
plan, diagnostic := model.CompileObjectList(ctx, requel.ObjectListRequest{
    ObjectType: "Order",
    Limit:      100,
    Options: requel.CompileOptions{RelationBindings: map[string]string{
        "data.orders": `pg_temp."orders"`,
    }},
})

The library opens no connector and executes no SQL. A host owns transactions, credentials, identity, approvals, mutation, and audit persistence. Trusted HostModule declarations extend the model with operational vocabulary, while SourceDecorator wraps object sources with host authorization. Relation placement occurs during compilation, so plan.Fingerprint covers the exact SQL shape and physical relation placement the host executes while redacting caller and context bind values; plan.Dependencies still names logical model relations. PostgreSQL object and dataset filters and ordering give declared strings one explicit text COLLATE "C" contract, so a host may preserve those semantics across source refinement and local evaluation.

There is no post-compilation SQL rewriting API. See examples/embed for the smallest complete in-memory host.


Design

  • Locality of behavior. A semantic unit should be understandable from that unit and the files it imports. It is why a guard lives in relations/, beside the table it protects.
  • Authored fragments are trusted; parameters are not. Caller values cannot become SQL structure; only authored fragments introduce SQL logic. This is a taint bit on every string, and it is the single rule that makes it safe to let a model author queries at all.
  • Transparent over compiled. Sanitized interpolation and lambdas, in place of a query compiler that hides its reasoning, so what you read is what renders.
  • No new DSL. .rql files are Starlark, the Python dialect from Bazel. Models already write it fluently; editors already highlight it. More importantly it is hermetic: no I/O, no clock, no network, no ambient state, so the same inputs produce the same plan on every machine, forever. Determinism here is a language property that the runtime enforces for you.
  • Deliberately small. A dozen function operations and one closed predicate vocabulary. Arithmetic, casts and conditional expressions are out of scope on purpose: they belong in a reviewed entrypoint's SQL, where the schema snapshot, the persona matrix and the analysis pass all reach them. A small vocabulary is what makes a plan re-derivable by a second implementation, and what keeps an agent from having a large surface to be wrong on.
  • Composable by interface. Adding a target means implementing an interface. Today: PostgreSQL, Supabase, Rafflesia Databases, Snowflake, BigQuery, ClickHouse, DuckDB, MongoDB, turbopuffer, and BLAST-family homology search. The governance spine (typed parameters, guards, the closed operator set, row caps, completeness, audit) is shared across all of them, so a new integration inherits it.
  • Files in git. Every governance artifact is a committed file a reviewer watches change: the SQL goldens, the plan goldens, api.txt, the persona matrix recording what each caller's guard evaluates to, the schema lockfile. requel diff leads with what moved ("this guard edit flips analyst from a tenant predicate to DENIED"), so a reviewer reads a sentence instead of simulating a lambda, and requel verify is the offline gauntlet a pull request has to pass.

Tools such as TextQL share the premise that an agent should do real research across governed data instead of answering one question at a time, and reading around the space (including ontology-as-a-repo formats like .tql) was part of how the shape of an RQL repository was chosen.


License

Apache License 2.0. Open source, with no field-of-use restriction: use, modify and redistribute requel — including inside a commercial product or service — subject to the license's attribution and notice terms (keep the copyright notice, the license text, and the NOTICE file with any copy you redistribute, and state significant changes you made). It carries an express patent grant from every contributor, which terminates for a party that brings a patent claim against the software.

Third-party dependencies keep their own licenses. All are permissive (Apache-2.0 / BSD / MIT) except github.com/go-sql-driver/mysql, which is MPL-2.0 (file-level copyleft, unmodified here).

Documentation

Overview

Package requel is the embeddable, read-only RQL compiler.

A Model loads one ontology repository and exposes its catalog, object graph, callable contracts, and deterministic compilation boundary. The package does not open connectors or execute the plans it produces; hosts retain ownership of transactions, credentials, auditing, scheduling, and transport.

Index

Constants

View Source
const (
	FunctionString    = functionruntime.StringType
	FunctionInteger   = functionruntime.IntegerType
	FunctionNumber    = functionruntime.NumberType
	FunctionBoolean   = functionruntime.BooleanType
	FunctionDate      = functionruntime.DateType
	FunctionTimestamp = functionruntime.TimestampType
	FunctionDecimal   = functionruntime.DecimalType
)
View Source
const (
	// APIVersion identifies the supported Go embedding contract independently
	// from the standalone application's release version.
	APIVersion = "requel.go.v2"
	// LangVersion is the RQL language version implemented by this compiler.
	LangVersion = engine.LangVersion
	// StdVersion is the bundled RQL standard-library version.
	StdVersion = engine.StdVersion
	// CatalogVersion identifies the serialized catalog contract.
	CatalogVersion = engine.CatalogVersion
	// PlanVersion identifies every serialized plan produced by this package.
	PlanVersion = "requel.plan.v2"
)
View Source
const (
	ObjectAnd       = engine.ObjectAnd
	ObjectOr        = engine.ObjectOr
	ObjectNot       = engine.ObjectNot
	ObjectPredicate = engine.ObjectPredicate
)

Variables

This section is empty.

Functions

func EvaluatePredicate added in v0.3.0

func EvaluatePredicate(predicate Predicate, row map[string]any) (bool, error)

EvaluatePredicate evaluates the shared closed predicate IR. It intentionally exposes no arbitrary callback, reflection, or code execution facility.

func FindAndLoad

func FindAndLoad(start string) (*Model, *Diagnostic)

FindAndLoad finds the nearest requel.toml at or above start and loads it.

func Load

func Load(root string) (*Model, *Diagnostic)

Load validates a repository and builds its strict capability catalog without opening a connector.

func LoadModel

func LoadModel(ctx context.Context, modelFS fs.FS, manifestPath string, options LoadOptions) (*Model, Diagnostics)

LoadModel snapshots a repository supplied as an fs.FS into compiler-owned immutable memory. manifestPath identifies requel.toml inside that filesystem; its directory becomes the confined model root.

func LoadWithOptions

func LoadWithOptions(root string, options LoadOptions) (*Model, *Diagnostic)

LoadWithOptions loads a model with a closed trusted host-module set.

func PredicateText added in v0.3.0

func PredicateText(predicate Predicate) string

PredicateText renders the shared closed predicate IR for catalogs, review explanations, and audit output. It never evaluates or interpolates code.

Types

type ActionContract added in v0.3.0

type ActionContract struct {
	Name         string `json:"name"`
	Label        string `json:"label,omitempty"`
	Description  string `json:"description,omitempty"`
	DeniedReason string `json:"denied_reason,omitempty"`
	// Target and Creates are mutually exclusive: an action acts on an
	// existing row of Target, or births a record of Creates.
	Target  string        `json:"target,omitempty"`
	Creates string        `json:"creates,omitempty"`
	Inputs  []ActionInput `json:"inputs"`
	// Reads names target properties the effects and predicates may see.
	Reads []string `json:"reads"`
	// The declared effect envelope, default-deny. Writes members are
	// "Object.property" and name declared writable properties; Schedules
	// members name declared actions; Emits and Invokes name host
	// vocabularies the host validates against its own registries.
	Emits           []string `json:"emits"`
	Writes          []string `json:"writes"`
	Schedules       []string `json:"schedules"`
	Invokes         []string `json:"invokes"`
	AllowedForShape string   `json:"allowed_for_shape"`
	// The row predicates' declared shapes — always, never, or conditional —
	// never their verdicts, which are questions about data.
	AllowedIfShape      string `json:"allowed_if_shape"`
	RequiresReviewShape string `json:"requires_review_shape"`
	// AllowedIf and RequiresReview carry the structured predicate tree when
	// the declaration used the closed vocabulary (shape "structured"), with
	// a deterministic text rendering beside each: the tree is
	// host-evaluable without Starlark, the text is what a reviewer reads.
	// Opaque function predicates leave these empty.
	AllowedIf          *ActionPredicate `json:"allowed_if,omitempty"`
	AllowedIfText      string           `json:"allowed_if_text,omitempty"`
	RequiresReview     *ActionPredicate `json:"requires_review,omitempty"`
	RequiresReviewText string           `json:"requires_review_text,omitempty"`
	CorrelationFrom    string           `json:"correlation_from,omitempty"`
	// Dependencies names every object type this contract touches — its
	// subject, its writes targets, and its reference inputs — deduplicated
	// and sorted, so impact analysis over an object includes the constructs
	// that mutate it, not only the ones that read it.
	Dependencies []string `json:"dependencies"`
	File         string   `json:"file"`
	Line         int      `json:"line"`
}

ActionContract is one compiled action declaration: the reviewable description of a governed write, produced by `action.make` and validated against the object catalog it references. It is a declaration, not an operation — Requel performs no host operation, so the catalog states what an action is and its pure renderer can only return inert intents. The host owns authorization, planning, reviews, execution and the record of what happened; this contract is the one authoritative description of what it is running.

type ActionEffect added in v0.3.0

type ActionEffect = engine.ActionEffect

type ActionInput added in v0.3.0

type ActionInput struct {
	Name         string   `json:"name"`
	Type         string   `json:"type"`
	IsNullable   bool     `json:"is_nullable,omitempty"`
	ObjectType   string   `json:"object_type,omitempty"`
	Reads        []string `json:"reads,omitempty"`
	Doc          string   `json:"doc,omitempty"`
	Label        string   `json:"label,omitempty"`
	Labels       []string `json:"labels,omitempty"`
	Format       string   `json:"format,omitempty"`
	DefaultValue any      `json:"default,omitempty"`
	HasDefault   bool     `json:"has_default,omitempty"`
	Minimum      *float64 `json:"min,omitempty"`
	Maximum      *float64 `json:"max,omitempty"`
}

ActionInput is one declared scalar, typed object reference, or bounded object-set input.

type ActionObjectRef added in v0.3.0

type ActionObjectRef = engine.ActionObjectRef

ActionObjectRef and ActionEffect are inert values returned by pure action rendering. Requel cannot resolve, authorize, persist, or execute either.

type ActionPredicate added in v0.3.0

type ActionPredicate struct {
	Kind     string            `json:"kind"`
	Column   string            `json:"column,omitempty"`
	Op       string            `json:"op,omitempty"`
	Value    any               `json:"value,omitempty"`
	Input    string            `json:"input,omitempty"`
	Children []ActionPredicate `json:"children,omitempty"`
}

ActionPredicate is one node of the closed predicate vocabulary — compare | all | any | not — over the subject's properties, with literal or declared caller-input operands. A host evaluates the tree directly; the catalog renders it as deterministic text.

type ActionVocabulary added in v0.3.0

type ActionVocabulary struct {
	Events      []string `json:"events"`
	Connections []string `json:"connections"`
}

ActionVocabulary names the host capabilities action contracts may reference: declared event kinds and declared outbound connections.

type Bind

type Bind struct {
	Ordinal int    `json:"ordinal"`
	Type    string `json:"type"`
	Value   any    `json:"value"`
}

Bind is one driver argument in ordinal order.

type Call

type Call struct {
	Entrypoint string         `json:"entrypoint"`
	Params     map[string]any `json:"params,omitempty"`
	Principal  Principal      `json:"principal,omitempty"`
	Now        time.Time      `json:"now,omitempty"`
	// Dialect overrides the repository dialect for hosts that deliberately
	// execute against another compatible engine. Empty uses requel.toml.
	Dialect string `json:"dialect,omitempty"`
	// RelationBindings is trusted, compile-local physical placement. Compiled
	// SQL contains these addresses while plan provenance remains logical.
	RelationBindings map[string]string `json:"-"`
}

Call is one invocation of a governed RQL entrypoint.

type CanonicalCell

type CanonicalCell struct {
	Kind  CanonicalKind
	Value any
}

type CanonicalKind

type CanonicalKind string

CanonicalKind is the closed, driver-independent value union accepted by the semantic decoder. Hosts adapt database values into this union; all object, property, identity, and cardinality rules remain in Requel.

const (
	CanonicalNull      CanonicalKind = "null"
	CanonicalString    CanonicalKind = "string"
	CanonicalInteger   CanonicalKind = "integer"
	CanonicalNumber    CanonicalKind = "number"
	CanonicalDecimal   CanonicalKind = "decimal"
	CanonicalBoolean   CanonicalKind = "boolean"
	CanonicalDate      CanonicalKind = "date"
	CanonicalTimestamp CanonicalKind = "timestamp"
	CanonicalJSON      CanonicalKind = "json"
)

type CanonicalRow

type CanonicalRow []CanonicalCell

type Catalog

type Catalog struct {
	Object                string              `json:"object"`
	Version               string              `json:"version"`
	DefinitionFingerprint string              `json:"definition_fingerprint"`
	Project               CatalogProject      `json:"project"`
	Entrypoints           []CatalogEntrypoint `json:"entrypoints"`
	Relations             []CatalogRelation   `json:"relations"`
	Namespaces            []CatalogNamespace  `json:"namespaces"`
	Connectors            []CatalogConnector  `json:"connectors"`
	Targets               []CatalogTarget     `json:"targets"`
	AllowedFlows          []string            `json:"allowed_flows"`
	CapabilityEdges       []CatalogEdge       `json:"capability_edges"`
	Objects               []ObjectType        `json:"objects"`
	Actions               []ActionContract    `json:"actions,omitempty"`
	ObjectGraph           *Graph              `json:"object_graph"`
}

Catalog is the complete, generated capability catalog for one model. It is a transport-neutral value: no connector handle or runtime readiness state can appear in it.

type CatalogConnector

type CatalogConnector struct {
	Name    string `json:"name"`
	Driver  string `json:"driver"`
	Kind    string `json:"kind"`
	Dialect string `json:"dialect,omitempty"`
}

type CatalogEdge

type CatalogEdge struct {
	From     string `json:"from"`
	FromKind string `json:"from_kind"`
	To       string `json:"to"`
	ToKind   string `json:"to_kind"`
	Kind     string `json:"kind"`
	Step     string `json:"step,omitempty"`
	Target   string `json:"target,omitempty"`
}

type CatalogEntrypoint

type CatalogEntrypoint struct {
	File                string         `json:"file"`
	Kind                string         `json:"kind"`
	Doc                 string         `json:"doc,omitempty"`
	ContractFingerprint string         `json:"contract_fingerprint"`
	Contract            map[string]any `json:"contract"`
}

type CatalogNamespace

type CatalogNamespace struct {
	Name        string   `json:"name"`
	Guarded     bool     `json:"guarded"`
	Pinned      bool     `json:"pinned"`
	Doc         string   `json:"doc,omitempty"`
	Entrypoints []string `json:"entrypoints"`
}

type CatalogProject

type CatalogProject struct {
	Name     string `json:"name"`
	Dialect  string `json:"dialect"`
	Language string `json:"language"`
	Std      string `json:"stdlib"`
}

type CatalogRelation

type CatalogRelation struct {
	Backing string   `json:"backing"`
	Key     []string `json:"key"`
	Guarded bool     `json:"guarded"`
	File    string   `json:"file"`
	Line    int      `json:"line"`
}

type CatalogTarget

type CatalogTarget struct {
	Name      string `json:"name"`
	Connector string `json:"connector"`
	Driver    string `json:"driver"`
	Kind      string `json:"kind"`
}

type CompileOptions

type CompileOptions struct {
	SourceDecorator SourceDecorator
	// RelationBindings is trusted, compile-local physical placement. It is
	// applied before the compiler calculates the returned plan fingerprint.
	RelationBindings map[string]string
}

type CompiledFunction added in v0.3.0

type CompiledFunction struct {
	// contains filtered or unexported fields
}

CompiledFunction is an immutable executable handle. Its representation stays private so compiler/runtime package moves do not become host API changes.

func (*CompiledFunction) Contract added in v0.3.0

func (compiled *CompiledFunction) Contract() FunctionContract

func (*CompiledFunction) Execute added in v0.3.0

func (compiled *CompiledFunction) Execute(ctx context.Context, options FunctionExecution) (*FunctionRun, *FunctionError)

type ComposedEdge

type ComposedEdge struct {
	From        string   `json:"from"`
	Name        string   `json:"name"`
	To          string   `json:"to,omitempty"`
	Hops        []ViaHop `json:"hops"`
	Cardinality string   `json:"cardinality,omitempty"`
	Optional    bool     `json:"optional"`
	GuardChain  []string `json:"guard_chain"`
	File        string   `json:"file"`
	Line        int      `json:"line"`
	Unresolved  string   `json:"unresolved,omitempty"`
}

type DatasetColumn

type DatasetColumn = engine.DatasetColumn

DatasetColumn is one column in a host-declared raw-source contract.

type DatasetListRequest

type DatasetListRequest struct {
	Dataset          string
	Relation         string
	Key              []string
	Columns          []DatasetColumn
	Select           []string
	Filter           *ObjectFilter
	Sort             []ObjectSort
	Limit            int
	Offset           int
	IncludeTotal     bool
	Dialect          string
	RelationBindings map[string]string `json:"-"`
}

DatasetListRequest is a bounded inspection query over a closed dataset contract. Dataset, Relation, Key, and Columns are trusted host structure; Select, Filter, Sort, Limit, and Offset may originate with a caller.

type DatasetQueryPlan

type DatasetQueryPlan struct {
	Version      string         `json:"version"`
	Dataset      string         `json:"dataset"`
	ModelHash    string         `json:"model_hash"`
	Fingerprint  string         `json:"fingerprint"`
	Dependencies []string       `json:"dependencies"`
	Columns      []ObjectColumn `json:"columns"`
	Rows         SQLPlan        `json:"rows"`
	Count        *SQLPlan       `json:"count,omitempty"`
	Limit        int            `json:"limit"`
	Offset       int            `json:"offset"`
}

DatasetQueryPlan is ready for execution by a host-owned transaction.

type DecodedObjectRow

type DecodedObjectRow struct {
	Ref    ObjectRef      `json:"ref"`
	Values map[string]any `json:"values"`
}

type DecodedResult

type DecodedResult struct {
	ObjectType string             `json:"object_type"`
	Rows       []DecodedObjectRow `json:"rows"`
	HasMore    bool               `json:"has_more"`
}

type DerivedRelationPlan

type DerivedRelationPlan struct {
	Version      string   `json:"version"`
	Relation     string   `json:"relation"`
	ModelHash    string   `json:"model_hash"`
	Fingerprint  string   `json:"fingerprint"`
	Dependencies []string `json:"dependencies"`
	Query        SQLPlan  `json:"query"`
}

DerivedRelationPlan is immutable SQL ready for a host-owned transaction. Dependencies retain logical model identities; Query contains the physical placement supplied for this compilation.

type DerivedRelationRequest

type DerivedRelationRequest struct {
	Relation           string
	Query              string
	AvailableRelations []string
	Dialect            string
	File               string
	RelationBindings   map[string]string `json:"-"`
}

DerivedRelationRequest asks Requel to validate and compile one trusted, host-authored read-only relation. AvailableRelations is the complete logical namespace the host permits this query to read.

type Diagnostic

type Diagnostic = engine.Diagnostic

Diagnostic is one stable, source-anchored compiler finding.

type Diagnostics

type Diagnostics []*Diagnostic

Diagnostics is a deterministic collection of compiler findings.

type Dimension

type Dimension struct {
	Key   string `json:"key"`
	Type  string `json:"type"`
	Label string `json:"label,omitempty"`
	Doc   string `json:"doc,omitempty"`
}

type Filterable

type Filterable struct {
	Key       string   `json:"key"`
	Type      string   `json:"type"`
	Operators []string `json:"operators"`
	Values    []string `json:"values,omitempty"`
	Doc       string   `json:"doc,omitempty"`
}

type FunctionColumnLabel added in v0.3.0

type FunctionColumnLabel = functionruntime.ColumnLabel

type FunctionColumnType added in v0.3.0

type FunctionColumnType = functionruntime.ColumnType

FunctionColumnType is the closed scalar type vocabulary accepted at a function terminal boundary.

type FunctionContract added in v0.3.0

type FunctionContract struct {
	Entrypoint            string             `json:"entrypoint"`
	ResultKind            string             `json:"result_kind"`
	Cardinality           string             `json:"cardinality"`
	Doc                   string             `json:"doc,omitempty"`
	DefinitionFingerprint string             `json:"definition_fingerprint"`
	PlanFingerprint       string             `json:"plan_fingerprint"`
	Targets               []string           `json:"targets"`
	DataFlows             []FunctionDataFlow `json:"data_flows"`
	Reads                 []TerminalRead     `json:"reads"`
	OutputSchema          FunctionSchema     `json:"output_schema"`
	MaxRows               int                `json:"max_rows"`
}

FunctionContract is the stable, detached description an embedding host needs to authorize and prepare a function run. It contains no executable DAG.

type FunctionDataFlow added in v0.3.0

type FunctionDataFlow struct {
	From    string   `json:"from"`
	To      string   `json:"to"`
	Columns []string `json:"columns"`
}

type FunctionError added in v0.3.0

type FunctionError = functionruntime.Error

type FunctionExecution added in v0.3.0

type FunctionExecution struct {
	AllowedTargets map[string]bool
	AllowedFlows   map[string]bool
	MaxRows        int
	Terminal       FunctionTerminalExecutor
	Now            func() time.Time
	NewID          func(prefix string) string
	OnStep         func(FunctionTerminalCall, FunctionStepRun, *FunctionTable, error)
}

type FunctionIncompleteReason added in v0.3.0

type FunctionIncompleteReason = functionruntime.IncompleteReason

type FunctionOrder added in v0.3.0

type FunctionOrder = functionruntime.Order

type FunctionProvenance added in v0.3.0

type FunctionProvenance = functionruntime.StepProvenance

type FunctionResultColumn added in v0.3.0

type FunctionResultColumn = functionruntime.ResultColumn

type FunctionRun added in v0.3.0

type FunctionRun = functionruntime.Run

type FunctionSchema added in v0.3.0

type FunctionSchema = functionruntime.Schema

type FunctionStepRun added in v0.3.0

type FunctionStepRun = functionruntime.StepRun

type FunctionTable added in v0.3.0

type FunctionTable = functionruntime.Table

type FunctionTerminalCall added in v0.3.0

type FunctionTerminalCall struct {
	Node       string         `json:"node"`
	Target     string         `json:"target"`
	Entrypoint string         `json:"entrypoint"`
	Security   string         `json:"security"`
	Reads      []TerminalRead `json:"reads"`
	Schema     FunctionSchema `json:"schema"`
	MaxRows    int            `json:"max_rows"`
	Params     map[string]any `json:"params"`
}

FunctionTerminalCall is the complete contract for one host-executed leaf. The host receives logical addresses and typed parameters, never the function DAG itself.

type FunctionTerminalExecutor added in v0.3.0

type FunctionTerminalExecutor func(context.Context, FunctionTerminalCall) (*FunctionTerminalResult, error)

type FunctionTerminalResult added in v0.3.0

type FunctionTerminalResult struct {
	Table    *FunctionTable
	Evidence map[string]any
}

type Graph

type Graph struct {
	Objects       []GraphObject       `json:"objects"`
	Edges         []GraphEdge         `json:"edges"`
	ComposedEdges []ComposedEdge      `json:"composed_edges"`
	Pairs         []GraphPair         `json:"pairs"`
	UnboundEdges  []UnboundEdge       `json:"unbound_edges"`
	Unresolved    []UnresolvedBinding `json:"unresolved_bindings"`
	MaxDepth      int                 `json:"max_depth"`
	Truncated     bool                `json:"truncated"`
}

Graph is the statically derived object and edge graph for one model.

type GraphEdge

type GraphEdge struct {
	From        string `json:"from"`
	Edge        string `json:"edge"`
	To          string `json:"to"`
	Cardinality string `json:"cardinality"`
	Optional    bool   `json:"optional"`
	Guarded     bool   `json:"guarded"`
	Backing     string `json:"backing,omitempty"`
	Source      string `json:"source"`
	DeclFile    string `json:"decl_file"`
	DeclLine    int    `json:"decl_line"`
	BindFile    string `json:"bind_file,omitempty"`
	BindLine    int    `json:"bind_line,omitempty"`
}

type GraphObject

type GraphObject struct {
	Name    string `json:"name"`
	Backing string `json:"backing,omitempty"`
	Guarded bool   `json:"guarded"`
	File    string `json:"file"`
	Line    int    `json:"line"`
}

type GraphPair

type GraphPair struct {
	From      string      `json:"from"`
	To        string      `json:"to"`
	Ambiguous bool        `json:"ambiguous"`
	Paths     []GraphPath `json:"paths"`
}

type GraphPath

type GraphPath struct {
	Hops        []GraphEdge `json:"hops"`
	Cardinality string      `json:"cardinality"`
	Optional    bool        `json:"optional"`
	GuardChain  []string    `json:"guard_chain"`
	Named       []string    `json:"named,omitempty"`
}

type Guard

type Guard struct {
	Relation  string `json:"relation"`
	Predicate string `json:"predicate"`
}

Guard documents one row-policy predicate injected by the compiler.

type HostModule

type HostModule struct {
	Namespace  string
	ABIVersion string
	Exports    starlark.StringDict
}

HostModule is the stable embedding boundary for trusted operational declarations. Model code imports it as host:<namespace>; exports never enter the global compiler scope. Requel evaluates declarations but never executes operational effects or owns their state.

type LoadOptions

type LoadOptions struct {
	HostModules []HostModule
	// ActionVocabulary is the host capability catalog: the event kinds and
	// outbound connection names the host's registries declare, injected at
	// load so the emits/invokes halves of action effect envelopes validate
	// beside the rest of the contract. Names only — URLs, credentials, SQL,
	// and handler implementations never enter the model. nil leaves those
	// members to the host's own validation.
	ActionVocabulary *ActionVocabulary
}

type Metric

type Metric struct {
	Key            string   `json:"key"`
	ResultType     string   `json:"result_type"`
	Doc            string   `json:"doc,omitempty"`
	ExactGrain     []string `json:"exact_grain"`
	Additivity     string   `json:"additivity"`
	AdditivityNote string   `json:"additivity_note,omitempty"`
}

type Model

type Model struct {
	// contains filtered or unexported fields
}

Model is an immutable semantic definition from the host's point of view. Reloading is explicit: construct a new Model and atomically replace the old one. Each compilation still uses a fresh hermetic Starlark evaluation.

func (*Model) ActionAllowed added in v0.3.0

func (m *Model) ActionAllowed(name string, ref ActionObjectRef, target, input map[string]any) (bool, error)

ActionAllowed evaluates the model's pure row eligibility predicate. The host must resolve and authorize ref before calling it; this method grants no capability and performs no lookup or mutation.

func (*Model) ActionAllowedFor added in v0.3.0

func (m *Model) ActionAllowedFor(name string, principal Principal) (bool, error)

ActionAllowedFor evaluates optional semantic actor eligibility after the embedding host has independently granted the action capability.

func (*Model) ActionContract added in v0.3.0

func (m *Model) ActionContract(name string) (*ActionContract, bool)

ActionContract returns one compiled action declaration by exact case-sensitive name.

func (*Model) ActionContracts added in v0.3.0

func (m *Model) ActionContracts() []ActionContract

ActionContracts returns every compiled action declaration in deterministic name order.

func (*Model) ActionRequiresReview added in v0.3.0

func (m *Model) ActionRequiresReview(name string, ref ActionObjectRef, target, input map[string]any) (bool, error)

ActionRequiresReview evaluates the model's pure review predicate. A host may independently require review; the model result can never waive that platform policy.

func (*Model) Catalog

func (m *Model) Catalog() *Catalog

Catalog returns a detached copy so callers cannot mutate the model's cached definition through slices or maps.

func (*Model) CatalogHash

func (m *Model) CatalogHash() string

CatalogHash identifies the immutable catalog derived from the source.

func (*Model) Compile

func (m *Model) Compile(ctx context.Context, call Call) (*Plan, *Diagnostic)

Compile evaluates, checks, and lowers one call. It performs no external I/O beyond reading the already selected ontology repository and never executes the returned plan.

func (*Model) CompileDatasetList

func (m *Model) CompileDatasetList(ctx context.Context, request DatasetListRequest) (*DatasetQueryPlan, *Diagnostic)

CompileDatasetList compiles raw-source inspection through Requel's object predicate, ordering, identifier, bind, and lowering machinery. It never opens or executes against the declared relation.

func (*Model) CompileDerivedRelation

func (m *Model) CompileDerivedRelation(ctx context.Context, request DerivedRelationRequest) (*DerivedRelationPlan, *Diagnostic)

CompileDerivedRelation owns read-only validation, deterministic-function validation, dependency discovery, and compile-local relation placement. It performs no I/O and never executes the returned statement.

func (*Model) CompileFunction added in v0.3.0

func (m *Model) CompileFunction(ctx context.Context, call Call) (*CompiledFunction, *Diagnostic)

CompileFunction compiles and independently verifies a function entrypoint, then returns the narrow read-only execution seam.

func (*Model) CompileObjectAggregate

func (m *Model) CompileObjectAggregate(ctx context.Context, request ObjectAggregateRequest) (*ObjectAggregatePlan, *Diagnostic)

CompileObjectAggregate compiles a bounded aggregate over the same effective object source used by list, get, and traversal.

func (*Model) CompileObjectGet

func (m *Model) CompileObjectGet(ctx context.Context, request ObjectGetRequest) (*ObjectQueryPlan, *Diagnostic)

CompileObjectGet compiles an exact typed-key lookup with a two-row bound so the host can distinguish not-found, one row, and a violated key contract.

func (*Model) CompileObjectKeyProbe

func (m *Model) CompileObjectKeyProbe(ctx context.Context, request ObjectKeyProbeRequest) (*ObjectKeyProbePlan, *Diagnostic)

CompileObjectKeyProbe compiles a bounded duplicate-key integrity check over the same authorized, decorated effective relation as normal object reads.

func (*Model) CompileObjectList

func (m *Model) CompileObjectList(ctx context.Context, request ObjectListRequest) (*ObjectQueryPlan, *Diagnostic)

CompileObjectList compiles a generic object page without opening a database.

func (*Model) CompileObjectTraversal

func (m *Model) CompileObjectTraversal(ctx context.Context, request ObjectTraversalRequest) (*ObjectQueryPlan, *Diagnostic)

CompileObjectTraversal compiles a governed traversal as a single SQL plan. It neither reads the source row first nor infers paths between object types.

func (*Model) DeploymentHash

func (m *Model) DeploymentHash() string

DeploymentHash identifies the compiler and standard-library semantics.

func (*Model) EvaluateOperationalModules

func (m *Model) EvaluateOperationalModules(ctx context.Context, paths []string) *Diagnostic

EvaluateOperationalModules evaluates trusted .star declarations in one Requel loader session. They may load .rql object modules and host modules, but receive no filesystem, database, network, clock, or compiler handle.

func (*Model) Graph

func (m *Model) Graph() *Graph

Graph returns a detached copy of the model's statically derived object graph.

func (*Model) Hash

func (m *Model) Hash() string

Hash returns the definition fingerprint stamped into every compiled plan.

func (*Model) Inspect

func (m *Model) Inspect(entrypoint string) (map[string]any, *Diagnostic)

Inspect returns the typed callable contract of one entrypoint.

func (*Model) MaxRows added in v0.3.0

func (m *Model) MaxRows() int

MaxRows is the repository-wide authored ceiling for result-bearing query assets. Embedding hosts enforce it while consuming driver rows, before a decoder or function runtime can retain an oversized result.

func (*Model) Object

func (m *Model) Object(name string) (*ObjectType, bool)

Object returns one nominal object contract by exact case-sensitive name.

func (*Model) Objects

func (m *Model) Objects() []ObjectType

Objects returns every nominal object contract in deterministic name order.

func (*Model) RenderAction added in v0.3.0

func (m *Model) RenderAction(name string, ref ActionObjectRef, target, input map[string]any) ([]ActionEffect, error)

RenderAction evaluates the authored pure effects function and returns a closed execution-neutral intent list after enforcing the declaration's default-deny envelope. Requel has no API capable of applying the result.

func (*Model) Root

func (m *Model) Root() string

Root returns the source directory used by Load. Models created with LoadModel are filesystem-free and return an empty string.

func (*Model) SourceHash

func (m *Model) SourceHash() string

SourceHash identifies the normalized model inputs. Tiny's model_hash is exactly this value.

type ObjectAggregateMeasure

type ObjectAggregateMeasure struct {
	Name     string
	Op       string
	Property string
}

type ObjectAggregatePlan

type ObjectAggregatePlan struct {
	Version            string         `json:"version"`
	ObjectType         string         `json:"object_type"`
	ModelHash          string         `json:"model_hash"`
	Fingerprint        string         `json:"fingerprint"`
	Dependencies       []string       `json:"dependencies"`
	DependencyCoverage string         `json:"dependency_coverage"`
	Columns            []ObjectColumn `json:"columns"`
	Rows               SQLPlan        `json:"rows"`
	SourceAccesses     []SourceAccess `json:"source_accesses"`
}

func (*ObjectAggregatePlan) Decode

func (p *ObjectAggregatePlan) Decode(rows []CanonicalRow) ([]map[string]any, *Diagnostic)

Decode validates an aggregate result against its generated scalar schema. Aggregate rows are ordinary typed result rows, never object instances.

type ObjectAggregateRequest

type ObjectAggregateRequest struct {
	ObjectType string
	Filter     *ObjectFilter
	GroupBy    []string
	Measures   []ObjectAggregateMeasure
	Limit      int
	Principal  Principal
	Now        time.Time
	Dialect    string
	Options    CompileOptions
}

type ObjectColumn

type ObjectColumn = engine.ObjectColumn

type ObjectDisplay

type ObjectDisplay struct {
	Primary   string `json:"primary,omitempty"`
	Secondary string `json:"secondary,omitempty"`
}

type ObjectExprOp

type ObjectExprOp = engine.ObjectExprOp

type ObjectFilter

type ObjectFilter = engine.ObjectFilter

type ObjectGetRequest

type ObjectGetRequest struct {
	ObjectType string
	Key        string
	Select     []string
	Principal  Principal
	Now        time.Time
	Dialect    string
	Options    CompileOptions
}

type ObjectKeyProbePlan

type ObjectKeyProbePlan struct {
	Version            string   `json:"version"`
	ObjectType         string   `json:"object_type"`
	Key                []string `json:"key"`
	ModelHash          string   `json:"model_hash"`
	Fingerprint        string   `json:"fingerprint"`
	Dependencies       []string `json:"dependencies"`
	DependencyCoverage string   `json:"dependency_coverage"`
	Rows               SQLPlan  `json:"rows"`
}

type ObjectKeyProbeRequest

type ObjectKeyProbeRequest struct {
	ObjectType string
	Principal  Principal
	Now        time.Time
	Dialect    string
	Options    CompileOptions
}
type ObjectLink struct {
	Name        string   `json:"name"`
	From        string   `json:"from"`
	To          string   `json:"to"`
	Cardinality string   `json:"cardinality"`
	IsOptional  bool     `json:"is_optional"`
	IsComposed  bool     `json:"is_composed"`
	IsGuarded   bool     `json:"is_guarded"`
	Hops        []ViaHop `json:"hops,omitempty"`
}

type ObjectListRequest

type ObjectListRequest struct {
	ObjectType   string
	Select       []string
	Filter       *ObjectFilter
	Sort         []ObjectSort
	Limit        int
	Offset       int
	IncludeTotal bool
	Principal    Principal
	Now          time.Time
	Dialect      string
	Options      CompileOptions
}

ObjectListRequest is a generic governed read over one nominal object type.

type ObjectQueryPlan

type ObjectQueryPlan struct {
	Version            string            `json:"version"`
	ObjectType         string            `json:"object_type"`
	SchemaHash         string            `json:"schema_hash"`
	ModelHash          string            `json:"model_hash"`
	Fingerprint        string            `json:"fingerprint"`
	Dependencies       []string          `json:"dependencies"`
	DependencyCoverage string            `json:"dependency_coverage"`
	Columns            []ObjectColumn    `json:"columns"`
	Rows               SQLPlan           `json:"rows"`
	Count              *SQLPlan          `json:"count,omitempty"`
	Limit              int               `json:"limit"`
	Offset             int               `json:"offset"`
	Cardinality        ResultCardinality `json:"cardinality"`
	SourceAccesses     []SourceAccess    `json:"source_accesses"`
}

ObjectQueryPlan contains the page and matching count statements compiled from one normalized request. Hosts execute both in one repeatable-read transaction.

func (*ObjectQueryPlan) Decode

func (p *ObjectQueryPlan) Decode(rows []CanonicalRow) (DecodedResult, *Diagnostic)

Decode validates a driver-independent result against the exact compiled contract and constructs nominally typed object rows. It is deterministic and performs no I/O.

type ObjectRef

type ObjectRef struct {
	ObjectType string `json:"object_type"`
	Key        string `json:"key"`
}

type ObjectSort

type ObjectSort = engine.ObjectSort

type ObjectTraversalRequest

type ObjectTraversalRequest struct {
	SourceType   string
	SourceKey    string
	Edge         string
	Select       []string
	Filter       *ObjectFilter
	Sort         []ObjectSort
	Limit        int
	Offset       int
	IncludeTotal bool
	Principal    Principal
	Now          time.Time
	Dialect      string
	Options      CompileOptions
}

ObjectTraversalRequest follows one named direct or composed ontology edge from one exact source object. Edge names are model-authored capabilities; callers cannot submit arbitrary object pairs or join predicates.

type ObjectType

type ObjectType struct {
	Name               string        `json:"name"`
	Label              string        `json:"label,omitempty"`
	Description        string        `json:"description,omitempty"`
	Group              string        `json:"group,omitempty"`
	Backing            string        `json:"backing"`
	IsDerived          bool          `json:"is_derived"`
	Dependencies       []string      `json:"dependencies"`
	DependencyCoverage string        `json:"dependency_coverage"`
	SchemaHash         string        `json:"schema_hash"`
	Key                []string      `json:"key"`
	Display            ObjectDisplay `json:"display"`
	Properties         []Property    `json:"properties"`
	Links              []ObjectLink  `json:"links"`
	Dimensions         []Dimension   `json:"dimensions"`
	Metrics            []Metric      `json:"metrics"`
	Filterables        []Filterable  `json:"filterables"`
	File               string        `json:"file"`
	Line               int           `json:"line"`
}

ObjectType is one nominal object type and its closed instance contract.

func (ObjectType) Property

func (o ObjectType) Property(name string) (Property, bool)

Property returns one declared public property by exact name.

type ObjectTypeValue

type ObjectTypeValue = engine.ObjectTypeValue

ObjectTypeValue is the immutable nominal Starlark value returned by object.make and accepted by trusted host declarations.

type Plan

type Plan struct {
	Version        string          `json:"version"`
	Kind           PlanKind        `json:"kind"`
	Entrypoint     string          `json:"entrypoint"`
	ModelHash      string          `json:"model_hash"`
	Fingerprint    string          `json:"fingerprint"`
	SQL            *SQLPlan        `json:"sql,omitempty"`
	Retrieval      json.RawMessage `json:"retrieval,omitempty"`
	Function       json.RawMessage `json:"function,omitempty"`
	Relations      []string        `json:"relations"`
	Guards         []Guard         `json:"guards"`
	Warnings       []Warning       `json:"warnings"`
	ResultSchema   json.RawMessage `json:"result_schema,omitempty"`
	SourceAccesses []SourceAccess  `json:"source_accesses"`
}

Plan is the immutable output of compilation. SQL plans carry driver-ready text and arguments. Retrieval and function plans carry their canonical JSON wire documents so an embedding host does not depend on compiler internals.

func (*Plan) Decode

func (p *Plan) Decode(rows []CanonicalRow) ([]map[string]any, *Diagnostic)

Decode validates ordinary authored-entrypoint rows. It never tags them as objects; nominal identity is reserved for generated object plans.

func (*Plan) ResultColumns

func (p *Plan) ResultColumns() ([]ObjectColumn, *Diagnostic)

ResultColumns returns the detached, closed scalar contract for an authored entrypoint. It lets a host adapt driver values without learning semantic validation rules.

type PlanKind

type PlanKind string

PlanKind identifies the external executor a compiled plan needs.

const (
	PlanSQL       PlanKind = "sql"
	PlanRetrieval PlanKind = "retrieval"
	PlanFunction  PlanKind = "function"
)

type Predicate added in v0.3.0

type Predicate = functionruntime.Predicate

type PredicateOperand added in v0.3.0

type PredicateOperand = functionruntime.Operand

type Principal

type Principal struct {
	Subject string         `json:"subject,omitempty"`
	Roles   []string       `json:"roles,omitempty"`
	Attrs   map[string]any `json:"attrs,omitempty"`
}

Principal is trusted context supplied by the embedding host. It is separate from Call.Params because callers may choose parameters but must never choose their own identity, roles, tenancy attributes, or clock.

type Property

type Property struct {
	Name       string   `json:"name"`
	Type       string   `json:"type"`
	IsKey      bool     `json:"is_key"`
	IsNullable bool     `json:"is_nullable"`
	IsWritable bool     `json:"is_writable"`
	IsComputed bool     `json:"is_computed"`
	MaskRole   string   `json:"mask_role,omitempty"`
	Doc        string   `json:"doc,omitempty"`
	Label      string   `json:"label,omitempty"`
	Labels     []string `json:"labels,omitempty"`
	Format     string   `json:"format,omitempty"`
}

func (Property) Decode

func (p Property) Decode(cell CanonicalCell) (any, *Diagnostic)

Decode validates one canonical value against this property's complete scalar, nullability, label, and format contract.

type ResultCardinality

type ResultCardinality string
const (
	CardinalityPage            ResultCardinality = "page"
	CardinalityAtMostOneObject ResultCardinality = "at_most_one_object"
)

type SQLPlan

type SQLPlan struct {
	Dialect string `json:"dialect"`
	Text    string `json:"text"`
	Args    []any  `json:"args"`
	Binds   []Bind `json:"binds"`
}

SQLPlan is ready for a host-owned database transaction.

type SourceAccess added in v0.3.0

type SourceAccess = engine.SourceAccess

type SourceDecorationRequest

type SourceDecorationRequest struct {
	Object     ObjectType
	Alias      string
	Authorized SourcePlan
}

type SourceDecorator

type SourceDecorator interface {
	DecorateObjectSource(SourceDecorationRequest) (SourceWrapper, *Diagnostic)
}

type SourcePlan

type SourcePlan struct {
	// contains filtered or unexported fields
}

SourcePlan is an opaque authorized object source. A trusted decorator may wrap it, but cannot inspect, construct, replace, duplicate, or omit it.

type SourceWrapper

type SourceWrapper struct {
	Before    string
	After     string
	Binds     []Bind
	Relations []string
}

SourceWrapper is the stable trusted-host authorization seam. The compiler inserts Authorized exactly once between Before and After. Each {{bind}} marker consumes one typed Bind in order.

type TerminalRead added in v0.3.0

type TerminalRead = functionruntime.TerminalRead

type UnboundEdge

type UnboundEdge struct {
	From        string `json:"from"`
	Edge        string `json:"edge"`
	Cardinality string `json:"cardinality"`
	Optional    bool   `json:"optional"`
	File        string `json:"file"`
	Line        int    `json:"line"`
}

type UnresolvedBinding

type UnresolvedBinding struct {
	Edge   string `json:"edge"`
	Base   string `json:"base,omitempty"`
	Object string `json:"object,omitempty"`
	Reason string `json:"reason"`
	File   string `json:"file"`
	Line   int    `json:"line"`
}

type ViaHop

type ViaHop struct {
	Edge  string `json:"edge"`
	Alias string `json:"alias"`
}

type Warning

type Warning struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

Warning is a non-fatal semantic finding attached to a plan.

Directories

Path Synopsis
connectors module
Package devkit contains source-authoring operations built on the Requel compiler.
Package devkit contains source-authoring operations built on the Requel compiler.
examples
embed command
Command embed is the smallest complete Requel host.
Command embed is the smallest complete Requel host.
internal
ast
Package ast defines the abstract syntax tree for the `sql"…"` fragment surface.
Package ast defines the abstract syntax tree for the `sql"…"` fragment surface.
audit
Package audit builds warehouse-side attribution for executed queries (backlog item 6).
Package audit builds warehouse-side attribution for executed queries (backlog item 6).
buildinfo
Package buildinfo owns process build metadata shared by the compiler's diagnostics and the standalone runtime.
Package buildinfo owns process build metadata shared by the compiler's diagnostics and the standalone runtime.
compiler
Package rql implements RQL — a Starlark-hosted, governed SQL renderer — and the engine behind the `requel` CLI.
Package rql implements RQL — a Starlark-hosted, governed SQL renderer — and the engine behind the `requel` CLI.
correlation
Package correlation mints the opaque identifiers that tie one unit of work together across the two records the runtime keeps of it: the accountable audit trail and the operational telemetry.
Package correlation mints the opaque identifiers that tie one unit of work together across the two records the runtime keeps of it: the accountable audit trail and the operational telemetry.
ctxsign
Package ctxsign verifies the signed context tokens of blueprint 02 §5.2.
Package ctxsign verifies the signed context tokens of blueprint 02 §5.2.
diag
Package diag defines the stable diagnostic model: codes, severities, spans, and both human and JSON rendering.
Package diag defines the stable diagnostic model: codes, severities, spans, and both human and JSON rendering.
function
Package function defines and executes RQL's target-neutral, read-only evidence function plan.
Package function defines and executes RQL's target-neutral, read-only evidence function plan.
functioncheck
Package functioncheck is an intentionally independent verifier for canonical rql.function.v1 documents.
Package functioncheck is an intentionally independent verifier for canonical rql.function.v1 documents.
lexer
Package lexer tokenizes the `sql"…"` fragment surface.
Package lexer tokenizes the `sql"…"` fragment surface.
manifest
Package manifest holds the shared shape of requel.toml (blueprint 09 §2) — the connector/driver taxonomy and the [observability] validation that the connector layer and the RQL runtime both consult.
Package manifest holds the shared shape of requel.toml (blueprint 09 §2) — the connector/driver taxonomy and the [observability] validation that the connector layer and the RQL runtime both consult.
personas
Package personas parses the persona file that `requel explain --personas` and `requel explain --personas` accept.
Package personas parses the persona file that `requel explain --personas` and `requel explain --personas` accept.
render
Package render lowers a final Fragment to SQL text plus a bind list, in bind or inline mode, with dialect-specific placeholders and literals (blueprint 01 §6.3, 04 §5).
Package render lowers a final Fragment to SQL text plus a bind list, in bind or inline mode, with dialect-specific placeholders and literals (blueprint 01 §6.3, 04 §5).
retrievalcheck
Package retrievalcheck is the retrieval target's independent oracle (blueprint 16 §9): a second derivation of the query body from the same pre-lowering inputs, sharing no code with the engine's lowering.
Package retrievalcheck is the retrieval target's independent oracle (blueprint 16 §9): a second derivation of the query body from the same pre-lowering inputs, sharing no code with the engine's lowering.
value
Package value defines the runtime values shared by the render layer, including the Fragment type that carries SQL parts, bind values, and analysis metadata (blueprint 01, 03 §1).
Package value defines the runtime values shared by the render layer, including the Fragment type that carries SQL parts, bind values, and analysis metadata (blueprint 01, 03 §1).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL