cachekey

package
v1.12.0-alpha.2 Latest Latest
Warning

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

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

README

Source Cache-Key Rules

rules/a-v1.cue decides two things at once:

  1. What a SourceDefinition's CUE template may read from context. Anything not listed is rejected at vela def apply and is absent from the context a source is compiled against — so it cannot be read even where admission is disabled.
  2. How a cache key is assembled from those reads.

A source's key is never authored. Infer derives it from what the template actually reads, and Stamp writes the result into the definition's $internal: block. Admission re-derives it and rejects a mismatch, so the block cannot be edited by hand.

For the other half of context — what an Application's $(context.x) expressions may read — see ../sourceexpr/README.md. The two files are routinely confused; that README opens with the distinction.

Architecture

  • rules/a-v1.cue — the rules. One file per version; all are embedded.
  • rules.go — loads and hashes them (LoadRules, LoadRulesByHash, policyHash).
  • infer.go — derives the key dimensions from a template's reads.
  • stamp.go — writes the $internal: block.
  • expression.go — assembles the key expression from the dimensions.
  • surfaces.go — which surfaces can supply a set of fields (SurfacesSupporting, CheckSurface, MissingOn).
  • key_validation.go — validates a stamped key against a re-derivation.

The assembled identity

<definition>[-<readable segments...>]-<hash>

The hash covers every value the template reads and carries uniqueness on its own. Segments are cosmetic — they exist so an operator can grep, and an empty one is simply dropped. segment: true therefore says nothing about correctness.

keyed: {
	cluster: {order: 2, segment: true}     // inlined and hashed
	clusterVersion: order: 3               // hashed only - a struct has no rendered form
	appLabels: {order: 10, indexed: true}  // read by literal key: appLabels["team"]
}
Option Means
order position in the key; dimensions come out in this sequence, not alphabetically
segment: true inline the value in the readable prefix as well as hashing it
indexed: true the read carries a literal key, and that key's value is what contributes

Inline only what is always renderable — a Kubernetes-style name. Not a struct (clusterVersion), not a free-form value (label and annotation values may contain characters legal there and illegal in an object name), and not something legitimately empty in normal operation (appRevision before the first revision, replicaKey outside the replication policy), which would leave a blank segment.

Readable implies keyed

There is no "a template may read this, but it does not affect the key". If a template reads a value, that value must contribute, or two different values share one cache entry and the cache is wrong.

What you can choose is whether it is inlined. A hash-only field separates entries correctly without lengthening the key. That is the right answer for anything not worth grepping.

A read costs a cache entry per distinct value. That is the cost of reading one, not of listing it here — a template that does not read a field is unaffected by its presence.

Changing the rules

Before release the version rule does not bite: nothing outside this repository has ever been stamped, so edit a-v1.cue in place and regenerate. After release, add a new file alongside it — a definition stamped with one version's hash loads that version's rules, so the old file must remain for as long as any definition references it.

To edit in place:

  1. Edit keyed:. Give the field an order, and segment: true only if it is always renderable and worth grepping.

  2. Run the tests. TestStampedRulesHashHasNotMoved will fail and tell you the new hash. It exists so an accidental edit is a failing test rather than a mismatch discovered against a cluster.

  3. Restamp every generated definition. The stamped annotation is definition.oam.dev/cache-key-rules:

    grep -rl '<old-hash>' examples/ | xargs sed -i '' 's/<old-hash>/<new-hash>/g'
    

    Adding fields does not change existing keys: a template that does not read the new field keeps its $internal: block byte-for-byte. Only the annotation moves.

  4. Update the pinned constant in TestStampedRulesHashHasNotMoved.

  5. Apply every definition against a running controller. This is the real proof — admission re-derives the stamp and rejects a mismatch, so acceptance means the restamp is correct:

    for f in charts/vela-core/definitions/*.yaml; do kubectl apply -f "$f"; done
    

Comments do not affect the hash — it covers the decoded keyed map alone — so documenting a field is free.

A keyed field must exist in the registry

TestKeyedFieldsExistInTheContextRegistry enforces two things: the field is declared in sourceexpr/context.cue, and it is offered by at least one surface that resolves a source.

At least one, not all. A field offered by only some surfaces is the point — it is what restricts where a source reading it may be consumed:

Field A source reading it is consumable from
appName, namespace, cluster, … everywhere
componentName, componentType components, traits
traitType traits
stepName, stepType workflow steps
policyName, policyType policies that render resources

Zero surfaces is the error: the field would be absent at render on every path, so no source could ever use it. policyRevisionName is the shape of that mistake — it is in the registry, but only on policy-app, which renders before the appfile exists and so resolves no sources.

That restriction is enforced per binding at Application admission and shown by vela def show before anything is applied.

What the tests enforce

Test Enforces
TestStampedRulesHashHasNotMoved the hash matches what generated definitions carry
TestKeyedFieldsExistInTheContextRegistry every keyed field exists and is reachable
TestKeyExpressionInlinesOnlySegments only segment: true fields reach the readable prefix
TestKeyInputsRecordEveryDimension $internal.keyInputs matches the inferred dimensions
TestUnsupportedContextIsOneMessage an unlisted field is rejected by name, pointing at properties
TestSurfaceSpecificFieldsRestrict surface-specific fields genuinely narrow consumption

Documentation

Overview

Package cachekey derives a SourceDefinition's cache key from the context its template reads.

The key is generated at build time by `vela def` and validated at admission, so nothing infers at reconcile time: the controller evaluates the generated expression exactly as it would an authored one.

Policy - which fields count, in what order - lives in an embedded CUE file whose hash is the version identity. Mechanism lives here.

Index

Constants

View Source
const InternalField = "$internal"

InternalField is the block holding everything the tooling generates, kept apart from the authored storage: block so that what a user may edit needs no explaining: one block is theirs, the other is not.

The $ prefix follows the convention CueX already uses for $params and $returns. A leading underscore would be the CUE idiom for "internal", but hidden fields are dropped from exported output, and these have to stay visible - GitOps diffs them and admission re-derives them.

View Source
const (
	// KeyField is the generated cache key, inside InternalField.
	KeyField = "key"
)
View Source
const KeyInputsField = "keyInputs"

KeyInputsField is the generated sibling of the key, inside InternalField: the values the resolver folds into the identity hash. It is recorded rather than re-derived so that inference stays a build-time concern, and so the resolver hashes exactly what the template reads rather than, say, every label on the object.

View Source
const MaxCacheKeyLen = 253

MaxCacheKeyLen is the Kubernetes object-name limit. A resolved storage key becomes the name of the backing Config object, so it must fit.

View Source
const RulesAnnotation = "definition.oam.dev/cache-key-rules"

RulesAnnotation records which inference policy generated a definition's cache key. Validation loads the rules with this hash rather than the current ones, so changing inference never invalidates a definition already generated.

View Source
const RulesVersionAnnotation = "definition.oam.dev/cache-key-rules-version"

RulesVersionAnnotation records the readable name of the same policy. The hash above is what validation looks up; this is for whoever is reading the object and wants to know which policy applied without computing anything.

Variables

This section is empty.

Functions

func CheckSurface

func CheckSurface(fields []string, surface string) error

CheckSurface reports why a source reading these fields cannot resolve on a surface, or nil if it can.

func InvalidCacheKeyChars

func InvalidCacheKeyChars(s string) string

InvalidCacheKeyChars returns a comma-separated list of the distinct disallowed characters in s, or "" when every character is permitted.

func KeyExpression

func KeyExpression(definitionName string, dims []Dimension, rules *Rules) (string, error)

KeyExpression renders the CUE expression that becomes storage.key.

This is the *readable prefix* of the cache identity, not the whole of it. The resolver appends a hash covering every value the template reads, and that hash carries uniqueness on its own - so a segment here is cosmetic, and one that resolves to nothing can be dropped without two identities colliding.

Only fields the rules mark as segments are inlined: those that always render to a Kubernetes name. A struct, a label value that may contain a dot, or a field that is legitimately empty contributes to the hash instead, which is what removes the need for a sentinel or a default.

Length is not checked here: the expression is static text, and how long it resolves to is only knowable once the interpolation has values.

func KeyInputs

func KeyInputs(dims []Dimension) []string

KeyInputs names every value the identity hash must cover, in key order.

The resolver hashes exactly this set. Hashing more - every label on the object, say - would change the identity whenever GitOps stamped an unrelated annotation and leave the cache permanently cold; hashing less would let two bindings that differ in an unrecorded input share an entry.

func MissingOn

func MissingOn(fields []string, surface string) []string

MissingOn names the context fields a surface cannot supply, as an author wrote them - context.componentName, not componentName.

Exported alongside CheckSurface because a caller reporting per surface already knows which surface it is asking about, so the sentence CheckSurface builds ends in a clause it would only have to strip back off.

func RequiredContext

func RequiredContext(template string) ([]string, error)

RequiredContext returns the context fields a source template reads.

Derived from the template rather than read back from $internal.keyInputs, so it cannot disagree with what the resolver will actually ask for - the same reason admission re-derives the key instead of trusting the stamped one.

func SurfacesSupporting

func SurfacesSupporting(fields, surfaces []string) []string

SurfacesSupporting returns the surfaces that can supply every field, out of those given.

func ValidateCacheKey

func ValidateCacheKey(key string) error

ValidateCacheKey checks that a resolved SourceDefinition storage key can be used as the name of the backing Config object.

Keys are not sanitised automatically: an interpolated value that produces an illegal name is a definition-authoring error, and silently rewriting it would change the cache identity — and therefore which Applications share an entry.

The admission webhook applies this to statically-known keys; the resolver applies it again once interpolation has produced a concrete value.

func Verify

func Verify(definitionName, template, rulesHash string) error

Verify re-derives the cache key from a stored template and checks the key the template carries matches it.

This is the admission-side half of the contract. The CLI writes the key, but nothing stops a stored object being edited or written by hand, so the key is re-derived rather than trusted.

rulesHash names the policy that produced the key, taken from the object's annotation. It is used in preference to the current rules so that changing inference does not invalidate definitions already generated and committed - which matters because GitOps re-applies them continuously. An empty hash means the object was not produced by `vela def`, and the current rules apply: the key still has to be right, just by today's policy.

Types

type Dimension

type Dimension struct {
	// Field is the context field, e.g. "cluster".
	Field string
	// Index is the literal key for an indexed read, e.g. the label name in
	// context.appLabels["team"]. Empty for a plain field.
	Index string
	// contains filtered or unexported fields
}

Dimension is one context value a cache key is built from.

func Infer

func Infer(template string, rules *Rules) ([]Dimension, error)

Infer returns the context dimensions a template's resolution depends on, in the order they contribute to the key.

The whole template is scanned, not just output:. A value reaches the output through aliases and helper fields, and deciding which reads actually influence it is not tractable - so a read anywhere counts. Over-inclusion costs a narrower cache; under-inclusion serves one consumer another's data.

func (Dimension) String

func (d Dimension) String() string

String renders a dimension the way the tests and error messages name it: "cluster", or "appLabels[team]".

type Rules

type Rules struct {
	// Hash identifies this policy. It is stamped onto generated definitions and
	// used to load the same rules again when validating them.
	Hash string
	// Version is a readable name for the same policy, declared in the rules file
	// so it cannot drift from the content it names. Stamped alongside the hash
	// for whoever is reading an annotation rather than computing one.
	Version string
	// contains filtered or unexported fields
}

Rules is one version of the inference policy, identified by the hash of the file it was loaded from.

func LoadRules

func LoadRules() (*Rules, error)

LoadRules returns the current rules - the latest file in the embedded set.

func LoadRulesByHash

func LoadRulesByHash(hash string) (*Rules, error)

LoadRulesByHash returns the rules with the given hash, for validating a definition generated against an earlier policy. A missing hash is an error rather than a fallback: silently validating against different rules than the ones used to generate would defeat the point of recording it.

func Stamp

func Stamp(definitionName, template string) (string, *Rules, error)

Stamp writes the inferred cache key into a SourceDefinition template and returns it alongside the hash of the rules used.

A key already present is accepted when it matches what inference produces and rejected when it does not. Accepting a match is what lets a definition round-trip: `vela def get` emits the stored template, key included, so rejecting any key at all would break get, edit, apply. Rejecting a mismatch rather than overwriting it keeps the author's belief about how their source is cached from being silently corrected.

So there is one rule for both the authored CUE and the applied object: the key equals what inference produces, and is written for you when absent.

It is idempotent - the generated key is not itself read when inferring - so re-stamping an already stamped template yields the same bytes. That matters because a re-apply of an unchanged definition must not show a diff.

func (*Rules) Fields

func (r *Rules) Fields() []string

Fields returns every readable context field, in key order. The resolver builds a source's context from this, so a field that is not keyed is not merely rejected - it is absent, and cannot be read even where admission is disabled.

Jump to

Keyboard shortcuts

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