Skip to main content

Component Models

Go Reference Go Reference

Package model defines the document format of a configuration-defined component model (go-kure/launcher#1261). A model is a YAML document. It declares inputs, computes values with CEL, and lists the parts (components and traits) that a component of the model type expands to. A user can add a component type without writing Go. kurel build loads models from a package’s models/ directory and from --model files (see the kurel CLI reference). Loading models there relies on the evaluation budget: every call that copies a value pays for it, including format, sort and reverse. The budget bounds the work of an evaluation, and not the memory it allocates in total (see “What the budgets bound”).

This release step covers the format, the CEL environment and the evaluation of one expression. model.Load decodes a document and checks its shape. It does not compile or run any expression. model.Compile compiles every expression of a loaded model against the environment below, and Compiled.Eval runs one of them. Compiled.Expand builds the components of the parts and binds the outputs that a later part reads. model.Registry registers a model as a component type, and its rule lowers a component of that type into the parts. The emit hook and the limits of a whole build are in. A trait a model writes on a part is resolved like an authored one: Rule implements oam.AuthoredTraitEmitter, so the engine merges the capability rendering into it, refuses a missing binding and a platform-reserved value, and records the consumed capability. The hostile corpus is in too: rule_hostile_expr_test.go for the limits of one expression and rule_hostile_build_test.go for the limits of one build.

Document

apiVersion: launcher.gokure.dev/v1alpha1
kind: Model
metadata:
  name: webapp.acme.example   # <name>.<domain>
  version: v2                 # v<major>[.<minor>[.<patch>]]
spec:
  celEnv: "1"
  inputs:
    image: {type: string, required: true}
    replicas: {type: integer, default: 2}
  values:
    - name: full
      expr: "${inputs.image + ':latest'}"
  outputs:
    deployment: "${parts.app.name}"   # the record the model publishes under `deployment`
  parts:
    - id: app
      type: deployment.apps@v1
      properties:
        replicas: "${inputs.replicas}"
      traits:
        - type: expose.launcher.gokure.dev@v1
          properties: {port: 80}
FieldRule
apiVersion, kindlauncher.gokure.dev/v1alpha1 and Model.
metadata.name<name>.<domain>. It must have a domain, so a model never takes the name of a Kubernetes kind. It follows the type identity grammar in pkg/oam (oam.ValidateTypeIdentity).
metadata.versionv<major>, v<major>.<minor> or v<major>.<minor>.<patch>. A short version is exact: v2 is v2.0.0.
spec.celEnvRequired. It must be "1". The value names a fixed set of CEL functions, so a model means the same later.
spec.inputsMap of input name to oam.PropertySchema. Each name is a CEL identifier. Each schema has a type or types. A schema may set additionalPropertiesSchema, the schema of the values of an object’s open keys, on an object only; the loader checks it as it checks properties and items. A schema may not set boundedBy, at any depth, additionalPropertiesSchema included, an empty list included: a bound is published where a test holds it, and nothing holds one a model states (go-kure/launcher#1580).
spec.valuesOrdered list of {name, expr}. A value reads inputs and earlier values only. Each name is a CEL identifier and is unique.
spec.outputsRequired: the key must be there, and a model with no outputs (left out, or null) is refused when it is registered, naming the model. outputs: {} says the model publishes nothing. Otherwise a map of output key to exactly one ${ } hole that is one read of the name of a record of a part, ${ parts.<id>.name } or ${ parts.<id>.<key>.name } (see parts[].id); text around the hole, a computed name, a read of a record itself and a part with when or forEach are refused when the model compiles, and the error names spec.outputs.<key> and the two forms. A key is a CEL identifier and is neither name nor kind. The model publishes each as an output of its own component, with the kind and the name its part publishes: a model part in another model reads it as parts.<id>.<key>.name. The build holds each against the component the part emitted. Computed outputs are not supported: a string carries no provenance, so the build could not tell two objects of one name apart.
spec.exclusiveOptional list of groups {keys: [a, b]} of top-level input names, of which a component sets at most one. The shape and the rules are those of an exclusive group of an input’s properties (oam.ExclusiveGroup): at least two keys, each a declared input, no key in two groups, no key required. A group’s own required is refused at load, naming spec.exclusive[i].required: the engine enforces at most one at the top level of a component and does not enforce “exactly one”. The model publishes the groups (oam.ExclusivePropertiesProvider), so the engine refuses a component that sets two keys of a group, naming both: ValidateAuthoredProperties (which kurel build runs) refuses an authored component before any part is evaluated, and the lowering refuses a component another model emits before it lowers it. Transform alone does not run the authored check, for a model or for any handler. Where the emitted model publishes outputs and the part that emits it has no forEach, the outer model’s expansion asks for them first, and that query renders the model, so a part that fails when it is evaluated is reported before the group is refused; the group is refused all the same. A part with forEach is not queried, so the group is refused before the model is rendered. A group is checked on what the author wrote, so an input that only has a default does not count as set, and a null counts as not set. HandlerSchemas().Exclusive lists the groups.
spec.partsAt least one part. A model that expands to nothing is an error.
parts[].idA CEL identifier, unique in the model. A later part reads the outputs of the part as records. The part’s own object is parts.<id>.name, and every other output the part declares is a record under its key, parts.<id>.<key>.name: for a postgresql part, parts.<id>.cluster.name, parts.<id>.app_secret.name and parts.<id>.rw_service.name. Only the name of a record can be read: parts.<id>, a record without .name, and any other field fail when Expand runs, and the error names the site, the read and what the part declares. A part reads only an earlier part, and never a part with forEach. An earlier part with a when is read only where its when holds (see parts[].when). A read of any other part, or of the part itself, fails when the model compiles, and the error names the site and the part. A key the part does not declare fails when Expand runs, and the error names the site, the part and the key.
parts[].type, traits[].typeA full identity, name@version. A short name and a missing version are refused.
parts[].whenOptional. Exactly one ${ } hole that gives a bool. The part is emitted only when it is true. It does not see the loop variable. A later part reads this part only where the when holds, and Compile checks it, so a model that registers is safe for every input set. Two places qualify: the true branch of a conditional whose test holds every top-level && term of the when (for when: ${ inputs.db }, a whole value is ${ inputs.db ? parts.db.name : null }, and text around a hole is host-${ inputs.db ? parts.db.name : 'none' }, which gives host-none when the part is skipped, because null in text is an error, see “Null” below; inputs.db && inputs.x also holds it), and any site of a part whose own when holds them, except that when itself. Terms are compared as CEL text, ignoring parentheses and order: a when built from a comprehension holds nothing, and a conditional inside the body of a comprehension or a cel.bind grants nothing (its range and its initializer are outside that scope, so a conditional there grants as usual). Any other read is refused when the model compiles, and so is a read of a part whose when can give null: an optional input read as it is, in a conditional or not, or a value that holds one. Write inputs.x == true. The check reads the text of the when and fails closed: a chain of &&, a comparison, `
parts[].traits[].whenOptional. The same form as parts[].when: exactly one ${ } hole that gives a bool, compiled with the same checks and with the same scope, so it does not see the loop variable and reads an earlier part that has a when only where that part’s own when holds. The trait is emitted on the component only when it is true; a trait whose when is false is left out, its properties are not evaluated, and the component is emitted either way. A null is false. The error of a bad when names spec.parts[i].traits[j].when. In a part with forEach the when is evaluated once for each instance and gives the same answer each time.
parts[].forEachOptional {as, in}. in is exactly one ${ } hole that gives a list. as is the loop variable, a CEL identifier. A filter per element goes in in.
parts[].name, properties, annotationsOptional. Strings may hold ${ } expressions. name is a string template.

A string that is exactly one ${ expr } keeps the CEL type of the result. A string with ${ } inside is a string template. $${ writes a literal ${. So $$${X} writes $${X}, the form that Flux post-build variable substitution turns into a literal ${X} where it runs over the object. values[].expr, when and forEach.in take exactly one hole and no other text. Load stores all these strings as written and compiles none of them.

Loading is always strict. An unknown field fails with its name and line. There is no extends and no patches. A file with more than one YAML document is refused. YAML anchors, aliases to an anchor defined earlier and merge keys (<< as a mapping key) are refused with their line, because they hide duplicate keys. The same text << as a value is the string << and loads. An alias whose anchor is not defined earlier in the document is refused by the YAML parser, with its own error and no line. Each entry of types must be a known type name, so types: [""] is refused. A union needs at least two different scalar types (string, integer, number or boolean), at every depth of a schema. So types: [string], types: [string, string] and types: [string, object] are refused. These are the union rules of the shared validator in pkg/oam. A malformed exclusive group on any node of an input schema is refused too, with the path of that node: a group of fewer than two keys, a key the node does not declare, a key in two groups, a Required key, or groups on a node that is not an object. These are the group rules of the same validator. A schema may set atLeastOne on an object: groups {keys: [a, b]} of its properties of which a value sets at least one, an empty array not counted (oam.AtLeastOneGroup); a malformed one is refused the same way. There is no spec.atLeastOne: the engine enforces no “at least one” on the top level of an authored component, which is why spec.exclusive refuses required. A schema may set requiredWhen on a property of an object: {key, equals}, the property being required while the sibling key is set, or set to equals (a string or a boolean). The loader refuses a malformed rule with the path of the object: a key the object does not declare, the property itself, a required property, or an equals of another type than the key’s or outside its enum. It refuses a requiredWhen on a node that is no property of an object (an input itself, an array’s items, an additionalPropertiesSchema), which has no sibling to name. A null entry in a list of strings or of objects with fixed fields is refused with its path, because YAML would drop it. Examples are types, values, parts, traits, exclusive and the keys of an exclusive group. A list of free-form items keeps its nulls. Examples are enum and any list inside a default or inside the properties of a part or a trait. In a free-form value, such as a default, the keys of a mapping must differ after YAML resolves them, so {1: a, 01: b}, {true: a, True: b} and {0.0: a, -0.0: b} are refused. In every map whose keys Load decodes into Go strings, two keys that decode to the same string are also refused. Examples are the inputs, the properties, gatedPaths and valueGatedPaths (at both levels) of a schema, the properties of a part or a trait, and the annotations. The YAML decoder refuses two keys with the same spelling. Load also refuses two keys with different spelling that decode to one string, such as image and !!binary aW1hZ2U=. Keys that decode to different strings, such as 1 and 01, stay apart. In such a map, a null key is skipped with its value, as yaml.v3 skips it. A null key is written ~, null, Null, NULL or with the !!null tag. Two null keys with different spelling, such as ~ and null, are no duplicate. Two null keys with the same spelling are refused by the YAML decoder, like any two keys with the same spelling. The checks of decoded values do not look at the value under a null key. The refusal of anchors, aliases and merge keys reads the whole document before the decoding, so it applies under a null key too. The path in an error names a key as it decodes: !!binary aW1hZ2U= appears as image.

CEL environment (celEnv: "1")

The environment is the CEL standard library plus three extension libraries. Each library has a pinned version, because cel-go defaults every library to its newest version and a model would then change meaning on an upgrade. The versions are ext.Strings 5, ext.Lists 3 and ext.Bindings 1. A golden file lists every function and overload of the environment. A test fails when the list changes. No other library is available, so math, sets and the encoders are refused.

The golden file pins what the environment holds. Some names in it start with @: cel.@block, @in, @not_strictly_false and @sortByAssociatedKeys. CEL source cannot spell an identifier with @, so a model cannot call them. Macros reach them. The function __not_strictly_false__ is declared but disabled. So are _in_ and in, the legacy names of the in operator. The type checker refuses a call of a disabled function in source, and only the runtime binding of a macro or an operator uses it. The in operator itself works through @in, so x in list and k in map compile. The golden file marks each disabled function [disabled], so a change of that state fails the test.

A variable has a type from the input schema. inputs.<name> has the type of its schema. An object input is map(string, dyn) and a types union is dyn. A list inside an object input is therefore dyn. self.name and self.application are strings. values.<name> has the type of its expression. A value reads inputs and earlier values only.

A comment in a hole runs from // to the end of the line, as in CEL. A } or a quote inside a comment does not close the hole and does not open a string. A comment with no newline after it runs to the end of the text, so the hole is not closed.

The same text is not a comment inside a string, a bytes literal or an escaped identifier. These forms may hold //: single, double and triple quoted strings, the raw form of each (r'...'), the bytes form of each (b'...', br'...') and an identifier in backticks, such as {'a//b': 1}.`a//b`. An escaped identifier ends at the next backtick. It holds no quote, brace or new line, so one that is not closed before the end of the line or text leaves the hole not closed.

An optional input has no default and is not required. It is null when absent. Test it with inputs.x == null. has(inputs.x) is refused, because an input is a variable and not a map field. A null input in an operator or a method call, such as inputs.x + 'a', compiles and fails at run time.

A key of an object input is tested with in: 'key' in inputs.obj, and 'key' in inputs.obj ? inputs.obj.key : null reads it. inputs.obj.key == null is not the same test: it fails with no such key: key when the key is absent, and is true only when the key is present with a null value.

A value that is exactly one reference to an input or to an earlier value has the declared type of that reference. If the input is optional, the value is also nullable, so values.x == null compiles. Any other expression has the type that the checker reports. The checker drops the nullable wrapper of a list or map result, so inputs.tags + [] is not nullable. It keeps the wrapper of a scalar result, so cel.bind(x, inputs.nick, x) with an optional string nick is still nullable. A local name values in a cel.bind or a comprehension hides the model values inside its scope, as in CEL.

Four rules keep an expression deterministic and bounded:

  • A comprehension (map, filter, exists, all and the like) ranges over a list only. A map has no fixed key order. A dyn value has no known element type.
  • The function dyn() is refused, because it hides a type from the rule above.
  • An expression has at most 4096 code points, a parser recursion depth of 64 and 10000 nodes. The node limit is a defensive bound. No input was found that reaches it under the size limit, and that is not proven.
  • A bind nests at most 8 deep. The limit counts every macro that expands to a bind, not only the cel.bind calls you write. In celEnv 1 these are cel.bind and sortBy. Chained sortBy calls nest, because the target of each call is the initializer of the bind before it. So [1].sortBy(x, x) repeated 9 times is refused, and so are 4 cel.bind calls around 5 sortBy calls. The optMap and optFlatMap macros expand to a bind too, and celEnv 1 does not load them.

The four numbers are start values. Raising a limit later breaks no model. Lowering one can.

Evaluation

model.Compile(m) compiles every expression site of a loaded model. Compiled.Eval(path, scope) runs one site and returns the Go value, the actual cost and an error. A site is named by its path: spec.values[0].expr, spec.parts[0].when, spec.parts[0].forEach.in, spec.parts[0].name, spec.parts[0].properties.a.b, spec.parts[0].properties.list[1], spec.parts[0].traits[0].properties.a and spec.parts[0].annotations.k. Every string in properties, in traits[].properties and in annotations is a site, with or without a hole. An unknown path is an error.

Two sites never share a path. A key that holds a dot or a bracket can write the path of another property, such as a.b beside a: {b: ...}, or a[0] beside a list a. The model is refused when it compiles, and the error names the path. A free-form map whose keys are not all strings, which YAML gives for a key such as 1 or true, is read like any other map. The text of the key is the path segment, so the key 1 gives .1. The integer key 1 and the string key "1" give one path, so a map that holds both is refused.

Compile returns the first failure, which wraps ErrInvalid and names the site. The order is the values, then for each part: when, forEach.in, name, the properties (keys sorted at every level), for each trait its when and then its properties, and the annotations. The scope of a site is the inputs, self, the earlier values, the earlier parts that have no forEach (parts.<id>; one with a when only where its when holds) and, for name, the properties, the traits and the annotations of a forEach part, the loop variable. when (of a part and of a trait) and forEach.in do not see the loop variable. The loop variable has the element type of forEach.in.

Parts. Compiled.Expand(tr, scope, naming, partName) evaluates the values, then each part in document order. A part whose when is false emits nothing, and a trait whose when is false is not put on its component. A part with forEach emits one component for each element. A part without a name takes its id. After it builds a part that has no forEach, Expand asks the Transformer for the outputs of that component (ComponentOutputsNamed, with naming as the Naming hook) and stores each as a record under the part id: the part’s own object (key object) is name, and every other output is a record {name} under its key. A part that its when skips gets no query and no record. A later part reads parts.<id>.name or parts.<id>.<key>.name, so the name follows an authored object name and the Naming hook, as the name of the built object does. The Go API keeps the whole answer (oam.Output: key, kind, name). tr must declare the type identities of the parts (registry.DeclareTypes): a type that does not resolve declares no output, so a read of it fails as an undeclared key. Eval takes the same records in Scope.Parts, and it refuses a key that is not there with the same error. Expand reads the inputs and self from the scope and sets the other fields itself. partName turns the name of a part into the name of its component. The lowering rule passes the name allocator here. A nil partName keeps the name. More than 50 components in one call fail with model.ErrLimit. The count comes after when and forEach. Expand checks no trait against a capability and runs no transform.

Manifest inlines. Compiled.ManifestInlines(tr, scope, naming, partName, timeout) evaluates the inline property of every manifests part and returns the text for each, as ManifestInline (Part, Index, Inline), in part order and then element order. It evaluates without emitting, and it judges nothing: what to make of the text is the caller’s. It runs the expansion of Expand with the when of every part treated as true, so a part whose when is false is evaluated and returned, and a later part that reads it finds it bound. It runs under the limits of one build, from a budget of its own: 500 parts, 10,000,000 cost units, 1 MiB of properties and a deadline of timeout (BuildTimeout, one second, where timeout is zero; a negative one is refused). Those limits stop it whatever scope.Ctx holds, and scope.Ctx, where set, stops it too. A part with no inline (one that sets a url) gives no entry, and an inline that is not a string is refused. A failure returns no output. naming is the Naming hook of the build, and the outputs of a part are asked as an emit asks them, about a member the model emits, so a read of parts.<id>.name holds the name an emit gives. It applies no image policy: an image reference is held to no level, so a part that an emit under a stricter level would refuse does not stop the call. Three limits, each fail-closed:

  • A when that guards its own expressions (when: inputs.db != null over ${ inputs.db.name }) makes the whole call fail when db is null, because the expression runs unguarded. What that means is the caller’s to decide.
  • The limits count the parts whose when is false, so a model that emits within them can be refused here.
  • Index is the element of forEach and reads 0 for a part with no forEach.

Lowering

model.NewRegistry(tr) returns a registry for one Transformer. Register(m) compiles the model and refuses it in these cases.

  • The type of the model is already declared, or the Transformer refuses to declare it. The error names the model.
  • The name of the model or its short name (the first label of its name) is a plain type name that a handler or a lowering rule is registered under, and no declared type claims that name. An identity resolves before a plain name, so the model would be built in that type’s place. The error names the model and the plain name. A short name that a declared type claims is not refused: the reference resolves, or is reported ambiguous. The other order is refused too: Transformer.RegisterComponent, RegisterAuthoredComponent and RegisterComponentLowering panic on a plain name that a declared type already claims as its short name, and definition.Register returns an error.
  • The model has no spec.outputs (left out, or null). The error names the model. outputs: {} registers a model that publishes nothing.
  • A part type or a trait type is not declared on the Transformer. The error names the path of the part or the trait. A model can name only a model registered before it, so no cycle exists.
  • The models nest more than 4 deep. A model with no model part has depth 1. The depth is read from the rules the Transformer holds, so it counts a model that another registry registered. The error names the model.

Then Register registers the rule and declares the type of the model. The Transformer checks the declaration first (Transformer.CheckComponentTypes), so a refused model leaves nothing registered.

A component of the model type lowers into the components of its parts.

  • An input that the component does not set, or sets to an explicit null, takes its default. self.name is the component name and self.application is the name of its document.
  • A part is named <component>-<part>. The name allocator of the run gives it, so two parts that want one name fail the build, and the error names the name.
  • The model publishes its spec.outputs (oam.OutputProvider): the rule renders the model once on the allocator of the query and answers each output as the record of one of its parts, forwarded under the key of the output (oam.OutputDecl.ForwardOf, ForwardKey). A consumer reads parts.<id>.<key>.name of a model part as it reads one of a built-in type. The build then holds each against the component the part emitted, asked as a consumer asks it, and refuses a build in which the two differ, naming the model component, the output and the part. A model with outputs: {} renders nothing for the query.
  • The model forwards the endpoints of its parts (oam.NamedEndpointProvider), so a connection can name a model component as its target and a consumer builds its connection graph from the model as from a typed component. The rule renders the model once on the allocator of the query and asks the Transformer for the endpoints of each component the render emitted (Transformer.ComponentEndpointsWithin), as it asks for their outputs: a part is asked as a consumer would ask the part’s own component, under the name the build gives it and under the Naming hook of the run. The endpoints come in part order, a part that declares none adds none, and a model whose parts declare none declares none, so a connection to it is refused as before. Two parts that declare an endpoint of one name fail the query, and the error names the model component, both parts and the endpoint name. The pods of every part carry the label of the authored component, so a platform keys the egress and endpoint-ingress peers of a model application by the component it wrote (TransformContext.EgressPeers, IngressPeers): the NetworkPolicy synthesis reads the peers of the authored component when the part’s own name has none. Every part gets its own egress policy, which selects its own pods. Endpoint ingress is read for the model component as a whole: where any part has peers under its own name only those parts get policies and the authored component’s list is ignored, and where none has, the authored list is served by the first part by name. A peers key that is the emitted name of one component’s part and the authored name of another component refuses the build.
  • parts.<id>.name and parts.<id>.<key>.name read the name that the build gives, under the Naming hook of the run where one is set (LoweringContext.NamingHook). The hook sees the name of the document as it stands in that round. The lowering rule emits a kind part (a Secret or a ConfigMap), and the build names its object after the part and never asks the hook for it. So the rule’s read does not ask the hook for the role object either. A part that is itself a lowering rule (a model, for one) keeps the whole hook, because the build gives it to that rule. A direct Expand keeps the hook, because a later Transform asks it.
  • The rule tells the TransformContext.EmitHook of the run about each component it emits, with the model, the part, the type as written, the name, the properties and the traits the part emitted. Each trait has its type as written and its evaluated properties, in the order of the part, and a trait whose when is false is not reported. The traits are told as the model emitted them, before the capability merge. Every map, slice and array in the properties and the traits is copied. A pointer or a struct in them is not followed: what it refers to is shared, so a hook must not change that. The rule tells the hook after the whole render succeeded, so a render that fails reports nothing. A direct Expand calls no hook: its components are not emitted by a build. A hook error fails the build and names the model and the part.
  • Traits on a model component are not supported. A trait on a component of a model type is refused with model.ErrTraitsUnsupported, whether the document wrote it or an outer model wrote it in the traits: of a part that is itself a model. The error names the component, the model and the trait type. A model has many parts, so no part is the one such a trait belongs to, and the rule would otherwise drop it without a word.
  • A part type and a trait type stay as the model wrote them. The engine resolves an identity to the registered name after each round, as it does for an authored component. A plain name that a handler or a rule is registered under stays as written. A model that emits no component is refused with model.ErrInvalid.

The rule enforces the limits of a render and of a build, and Register enforces the nesting depth. One render gives at most 50 components, and the models nest at most 4 deep.

Limits of a whole build. A build is one Transform. Every model render in it spends from one budget that the run keeps, so two builds on one rule never share it. A limit that is broken fails the build with model.ErrLimit and names the limit.

LimitValueWhat countsWhere it is checked
MaxBuildParts500Components that all renders of the build give, after when and forEachBefore the parts of a forEach are built
MaxBuildCost10,000,000Actual CEL cost units that all expressions of the build spentAfter each expression
MaxBuildPropertyBytes1 MiBThe size as JSON of the properties of the components and of their traits that the build emittedAfter each render
BuildTimeout1 s, or TransformContext.ModelBuildTimeout where the caller sets itTime from the first model render of the buildBefore and after each expression, and inside a long comprehension

A caller sets the time limit of its builds in TransformContext.ModelBuildTimeout: zero keeps the default BuildTimeout, a positive value replaces it, and a negative value is refused when the transform (or LowerRaws) starts. The limit holds for every render of a build, the query for the outputs of a component that the transform makes included, and a refusal names the limit that was in force. It holds inside a transform only: a query for the outputs of a model component made outside one (ComponentOutputs, ComponentOutputsNamed) renders under its own budget and keeps the default, because neither function takes a transform context. The other limits of a build are constants.

The byte limit is a proxy and is named for what it measures: the size of the emitted properties. launcher puts no limit on the size of a build’s rendered YAML: a Transform returns the cluster and not its YAML, so a caller that writes the output bounds it where it needs a bound. kurel build writes its output with no such bound. The deadline stops a long comprehension through the context of the evaluation (Scope.Ctx; a nil context reads as context.Background()), and the program checks it every 100 steps of the comprehension. The stop is cooperative: one long call of a function and a compile are not interrupted, and memory is not bounded. The deadline starts at the first model render of the build and not at the start of the Transform. A direct Expand or Eval has no build and so no build limit. The deadline can bind long before the cost limit: on a loaded development host, one expression of 700,000 cost units (lists.range(50000).map(i, i)) ran for about 2.8 s. The tests of the hostile builds (rule_hostile_build_test.go) set each limit against a control under it: 510 parts against 459 across nested models, 100,000 parts against 50 in one render, one input byte more than fits in 1 MiB against the longest input that fits, and a build of about 3,000 units against one of about 4,500 for the cost sum, which runs at a lowered limit of 3,500. At the real limit they show only that a build of slow expressions fails with a limit error, at the deadline or at the cost, whichever comes first. One long comprehension is stopped while it runs, by a clock that leaves the evaluation 2 ms, and a short build of the same model on a later clock then builds. A build of eight such comprehensions on the real clock is skipped on a host that is fast enough to pass it, because a pass shows nothing about the deadline.

Result. A string that is exactly one hole gives the value with its type: int64, uint64, float64, bool, string, []byte, []any (in order), map[string]any or nil. A string with text around a hole, or with several holes, gives a string. A []byte result is a copy: a write to it does not change the next result of the site. A map key must be a string. The compile check reads the type of the result and refuses a map whose key type is not a string, at every site that gives a value: a property, a value and a forEach.in list (a map in its elements included). A map literal with a key of another type, such as {1: 'a', 'b': 'c'}, has the key type dyn, which the check cannot read. Such a map compiles and fails when the site is evaluated, with the same words: map keys must be strings.

Text. Inside text a hole must give a string, an int, a uint, a double or a bool. A list, a map or a dyn value is refused when the model compiles (“not allowed in text”). The type of a dyn value is not known when the model compiles, so even a dyn value that holds a string is refused: write string(x) around it. A double takes the form of CEL string(x): 1.0 gives 1, 0.1 gives 0.1, 100000000.0 gives 1e+08, 1e21 gives 1e+21, -0.0 gives -0. A bool gives true or false. Text and a number or a bool do not join with +: 'a' + 1.0 is a compile error, and 'a' + string(1.0) works.

Null. A single hole keeps null: the result is nil and a property with a null value stays null downstream, no key is dropped. An input that is absent from Scope.Inputs is null. Null in mixed text is an error that names the site, never the text null and never an empty string.

Numbers. A NaN or an infinity has no place in a document. A single hole, or a list or map inside it, that holds one fails with ErrNonFinite, and so does a double of that kind in text. An explicit string(1.0 / 0.0) is text and is not refused: the author asked for the conversion.

Map keys. A key in properties, in traits[].properties and in annotations is literal text. A key that holds ${ is refused when the model compiles, whether it is a hole or the escape $${.

Cost. One hole has a cost limit of 1,000,000. An evaluation that spends more fails with ErrCostLimit, which names the site and the limit. The cost of a site is the sum of its holes. The charge by size stops a replace, a join or a format that would build a result of more than 1,000,000 bytes before it builds it (a test pins each). lists.range(1000000) is stopped by the cost limit. A list of more than 1,000,000 elements is refused by cel-go, which has its own cap for lists.range, and not by the cost limit. The charge by size (see “Charge by size”) also bounds every value.

Format. A format is refused before it runs when the most its arguments can print passes 1,000,000 bytes. The bound is the length of the format string, plus the length of each string or bytes argument (twice it when the format string holds an x, for %x), 420 for a double, 64 for a timestamp, a duration or a type, 20 for every other scalar (130 when the format string has a clause with a precision, %f, %b or %o, which print a number in more digits), 4 for each list element and 6 for each map entry. A list or map argument is walked as a tree. The walk spends one step of the comparison budget (1,000,000 values for one evaluation) for each value it reads, so a shared nest is never walked in full and a loop of calls cannot walk without limit. The bound is above the real size, so a format whose real result is within that slack of 1,000,000 bytes can be refused though it would fit. The result and the errors are those of cel-go.

Comparisons and flatten. The cost does not bound a comparison of nested lists that share their elements: cel-go compares them element by element at every depth and charges the outer length only, so d == d on four levels of shared lists of 200 elements reports a cost of 8,739 and runs for about a minute (go-kure/launcher#1451). The flatten of the lists extension (version 3) has the same flaw: it copies every element it reaches and charges the outer length times the depth. So the evaluation replaces five calls, ==, !=, in, distinct and flatten, with versions that count the values they visit: a list, a map, a list element and a map value are one step each, and a string or bytes value costs one more step for each 1,024 bytes it holds, because cel-go compares it by its content. A map comparison reads every key, also after one differs, because cel-go gives the keys in Go map order and an early stop would make a stop by the budget depend on that order. All of them in one site evaluation share a budget of 1,000,000 steps with the charge by size. It also replaces join, only for its error: the join of a list that holds a non-string fails in cel-go with an error built from the text of the whole list, which prints every shared child and reached 7 GB, so the replacement names the type of the element and prints no value. That join does not spend the budget. A site that needs more fails with ErrCostLimit, which names the site. The stop holds even where CEL would drop the error, as in (a == b) || true: the evaluation checks the budget when the program ends. A comparison or flatten of more than 1,000,000 values is refused even where stock cel-go finishes it: d == d on four levels of shared lists of 50 elements holds 6.25 million values, and cel-go answers it in about 0.2 s. Every other call gives what cel-go gives, with the cost cel-go reports: a test compares 52 expressions with cel-go’s own result and cost. The first four calls are every caller of Equal that a model reaches in cel-go v0.33.2, read again at v0.33.4 with no new caller, and in the pinned extension versions, flatten is the one list function that copies nested elements under the legacy cost tracker, and join is the one call whose error prints a nested value. A test reads the cel-go version and fails on another one, so that the calls are read again when cel-go moves. Since v0.33 each cel-go node reports its own cost from its own Exec, so every replacement node reports its cost to the cost tracker of the evaluation with the operands and the result that cel-go’s node would pass.

Charge by size. cel-go charges a call by the length of its operands and reads the cost after the call returns, so a value that many places share, or a call that builds a big output from small operands, ran below the cost limit (go-kure/launcher#1461). The evaluation now charges every call result and every identifier read by size, against the same budget of 1,000,000 steps as the comparisons. A string or bytes value costs one step for each 1,024 bytes. No string or bytes value may hold more than 1,000,000 bytes, and no list or map more than 1,000,000 elements: a value at the cap is allowed, and a value over it stops the evaluation with ErrCostLimit. A list or a map costs nothing more, because cel-go charges a call by the element count of its operands where it knows the overload. Three calls copy what their operands hold and pay for it themselves. cel-go charges a sort or a reverse one step when the type does not pick one overload (a dyn element for sort, a dyn receiver for reverse, because a string has a reverse too), and the lists extension then never reads the elements. A reverse of a list pays one step for each element, after it ran: it cannot fail on a list, and one copy holds at most 1,000,000 elements. A sort or sortBy of n keys pays n times the number of bits of n, about n log2 n, which is the number of comparisons it makes. Its keys also cost the bytes of the string and bytes elements they hold, because a sort compares them by content. So one sort of a list whose type is not fully known when the model compiles holds at most 62,500 elements, where nothing else in the evaluation spends: 62,500 keys have 16 bits and pay 1,000,000 steps (a test pins 62,500 and 62,501). cel-go charges a sort of a known type by the square of its length and refuses it far below that, and the cost limit refuses a sortBy of that length too. A format copies the strings inside its argument list, which no read has charged, so it pays the most its arguments can print (see “Format”), one step for each 1,024 bytes. sort and format pay before they run, so a call that fails after it worked, in xs.sort() == [] || true, is paid for too. join checks that every element is a string before it writes the first byte, so a join that fails copies nothing, and it checks its buffer before each write, against the bytes that the next write adds (the first element has no separator before it). replace is replaced by a version that computes the size of its result from the number of matches and stops before it builds a result over the cap. indexOf and lastIndexOf are replaced by a version that refuses a search before it runs when cel-go would charge it over the cost limit: cel-go runs two nested loops and charges one tenth of a step for each pair of characters, but only after the call returns, so a string of 1,000,000 bytes and a search text of 500,000 ran 250 billion comparisons first. matches has the same replacement, in its member and its global form: cel-go charges the length of the string times a quarter of the length of the pattern, only after the match ran, so a string of 100,000 bytes and a pattern of 40,000 that an input holds ran for minutes. Each replacement gives the result and the cost that cel-go gives for every call under that limit. An identifier that is the key of an index, as in m[k], is charged by its size at every lookup, because cel-go reads it through the attribute and not as a value. So is every other key attribute, such as m[c ? k : k] and m[(xs + [])[0]]: the key is resolved once, and the cost that the evaluation reports does not change. A map comparison charges the length of each key. &&, ||, the conditional and the comprehensions are not calls, so they stay lazy: a branch that does not run is not charged. A value over the cap is refused even where stock cel-go finishes it. A test names a class for every function of the pinned environment, so that a new cel-go version fails two lists and not one. The wrapper of an identifier read skips a node that cel-go already watches, and it finds that node by the name of an unexported cel-go type. Without the skip, cel-go reports one more step of cost for each index or select on a computed value. Three rows of the comparison test guard the name: [1, 1.0][0] == [1, 1.0][1], [1u, 1][0] == [1u, 1][1] and [[1], {'a': 1}][0] == [[1], {'a': 1}][1] must report the cost of cel-go (25, 25 and 105, and 27, 27 and 107 without the skip). A cel-go version that renames the type fails them.

What the budgets bound. A call that copies or compares the contents of a value pays for them, also when it fails afterwards, and a test pins each such call found so far (sort, sortBy, reverse, join, replace, format, the comparisons, flatten and the keys of a result copy). A test runs every function of the environment that takes a list, with == and !=, on a list whose type is not fully known or on operands that make it fail, and fails on a new one that has no row. The size of a successful format result is bounded by the check above.

The budgets bound the work of an evaluation, not the memory it allocates in total. A step pays for about 1,024 bytes, so an evaluation reads about 1 GB of strings before the budget stops it, and a call can allocate several times what it reads. These figures are totals over a whole evaluation, and not memory held at once, and the race detector raises some of them. Three loops over a string of 999,990 bytes, each run until the budget refused it (a development host, without the race detector, the largest heap sampled every 2 ms):

LoopAllocated in totalLargest sampled heap
A format that copies the string and then fails2,946 MB48 MB
A reverse of the string, its type unknown2,443 MB35 MB
A getHours with the string as its time zone7,897 MB48 MB

A build also has a deadline, which stops a long comprehension (see “Limits of a whole build”). A direct Eval has none. One call is not interrupted, and no limit bounds the memory an evaluation holds.

Result size. The Go copy of a single-hole result holds at most 1,000,000 units, counted at every depth. A list element or a map entry is one unit, and so is each byte of a bytes value. A map key costs a further unit for each 1,024 bytes, twice, because the copy hashes it to read the entry and to insert it. The copy is made after the evaluation. An expression can share one list or one bytes value in many places at a small cost, and the copy counts it once for each place. So the cost limit does not bound the copy. A result over the limit fails with ErrCostLimit, which names the site. A string or a map key in the result, at any depth, holds at most 1,000,000 bytes, as a string read by name does: an input that nests a longer one fails when the result exports it. A comparison that only reads such an input is charged by its size against the budget and exports nothing.

Cache. Cache.Compile keeps a compiled site under the model identity (Model.Key()), the site path and the template text. A second compile of a model reuses the sites. The same text at another path, or in a model of another identity, is another entry, because its types differ. An identity names one definition: a changed model under the same identity must use a new cache. A Compiled and a Cache are safe for concurrent use.

API

CallDoes
model.Compile(m)Compiles every expression site of m with a cache of its own.
(*Cache).Compile(m)The same, with a shared cache from model.CreateCache(). Len() counts the cached sites.
(*Compiled).Eval(path, scope)Runs one site. Returns the Go value, the actual cost and an error.
(*Compiled).Expand(tr, scope, naming, partName)Builds the components of the parts in document order and binds parts.<id>.name and parts.<id>.<key>.name from Transformer.ComponentOutputsNamed. It runs no transform.
(*Compiled).ManifestInlines(tr, scope, naming, partName, timeout)Returns the evaluated inline of every manifests part with each when treated as true, under the limits of one build. It emits nothing and judges nothing.
model.NewRegistry(tr)Returns a registry for one Transformer.
(*Registry).Register(m)Compiles m, refuses it as the Lowering section says, then registers its rule and declares its type.
(*Registry).RegisterLazy(m, source)Register for a model that ships with the program: every check but the compile is made now, and the expressions compile once, at the first build that uses the model (sync.Once, safe for concurrent first use). A model that does not compile fails that build, and every later one, with source in the error. The caller proves the model compiles, as pkg/oam/shipped does with a test that compiles each embedded model.
(*Registry).Rule(key)Returns the rule registered under a Key(), or nil.
(*Rule).LowerComponent(comp, lctx)Lowers a component of the model type into the components of its parts.
(*Rule).Outputs(comp, lctx)Answers the records of spec.outputs as forwarded outputs (oam.OutputProvider).
(*Rule).EndpointsNamed(comp, lctx)Answers the endpoints of the parts, in part order, as the endpoints of the model component (oam.NamedEndpointProvider).
model.Load(data)Decodes one document and checks it. A failure of a decoded document wraps model.ErrInvalid and names the field, for example spec.parts[1].id. A YAML, apiVersion or kind failure does not wrap it. A YAML type error, such as a list where a string belongs, names the line of the field and not its path. An explicit tag that does not fit its value, such as !!bool notabool, names its line too, when one tagged value is at fault; with two or more, the error has no line.
(*Model).Identity()The model identity as written in metadata.
(*Model).Key()The identity with the version in the canonical form (name@v2.0.0). The registry returns a version as it was registered, so compare and store this form (oam.TypeID.Canonical).

Load returns the first failure. The YAML, apiVersion and kind checks come first. Then come the null and duplicate-key checks, the metadata, spec.celEnv, the inputs in alphabetical order of their names (a Go map keeps no document order), the values and the parts in document order, then the output keys in alphabetical order.