fmtres

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package fmtres resolves OpenJD "{{...}}" format strings on the worker, where the session working directory, and therefore Session.WorkingDirectory, is known only at run time.

The server resolves loc:// URIs and the job-parameter space before dispatching an assignment (see internal/scheduler/assign.go); this package performs the remaining, worker-local substitution of format-string references in command lines, argument lists, and environment-variable values.

Scopes

Two resolution contexts exist, matching the OpenJD specification:

  • Task-action context (a step's onRun command and args) exposes Param.<n> / RawParam.<n> (job parameters), Task.Param.<n> / Task.RawParam.<n> (task parameters), and Session.WorkingDirectory.
  • Environment-action context (an environment's onEnter/onExit actions and its variable values) exposes Param.<n> / RawParam.<n> and Session.WorkingDirectory, but not Task.Param.*: environments are session-scoped and entered once, not per task.

TaskScope and EnvScope return a fmtstring.MapScope (a plain map) so callers can add keys, such as Task.File.* or Env.File.*, before resolving.

Index

Constants

View Source
const (
	// MinExprOperationLimit / MaxExprOperationLimit bound
	// [ExprLimits.OperationLimit].
	//
	// Floor: the server's default per-evaluation operation budget
	// (internal/openjd's defaultSubmissionOperations, 10,000). Below that, a
	// worker would reject at execution an expression the server type-checked
	// at submit under its defaults.
	//
	// That falls short of parity in two ways:
	//
	//  1. It is the server's default, not its configured value, which can be
	//     up to 100,000. A worker at this floor on a farm that raised
	//     openjd.expr_operation_limit is tighter than what the server accepts;
	//     the server detects this from the worker's advertised caps and
	//     withholds EXPR work (internal/scheduler/exprcaps.go).
	//  2. Even at parity acceptance is not guaranteed: phase 3 evaluates the
	//     same expressions against concrete values, which cost more than
	//     phase 1's placeholders. That is why the default here is 100x the
	//     server's.
	//
	// Ceiling: one order of magnitude above the default. A policy bound, but
	// finite: nothing meters wall clock and section 1.3.10 prices 256 bytes at
	// one operation, so 10^7 operations is ~2.5 GB of byte-work in one
	// evaluation, repeated per position.
	MinExprOperationLimit int64 = 10_000
	MaxExprOperationLimit int64 = 10_000_000

	// MinExprMemoryLimit / MaxExprMemoryLimit bound [ExprLimits.MemoryLimit].
	//
	// Floor: the server's default per-evaluation memory budget
	// (internal/openjd's defaultSubmissionMemoryBytes, 1,000,000), for the
	// same reason as the operation floor: a phase-3 evaluation holds the
	// concrete value a phase-2 evaluation had only a placeholder for, so a
	// worker allowance below what the server accepted rejects after the fact.
	// The same gap applies: the server's value is configurable up to
	// 10,000,000, this floor tracks the server's default, and the same
	// runtime gate detects a mismatch (see MinExprOperationLimit).
	//
	// Ceiling: one order of magnitude above the default. A catastrophe
	// ceiling; the number it sets is the per-block structural ceiling
	// maxLetBindings (50) x this value, 1 GB at the default and 10 GB at the
	// maximum, per concurrently resolving task slot. An operator choosing the
	// maximum should size the host's RAM against that product.
	MinExprMemoryLimit int64 = 1_000_000
	MaxExprMemoryLimit int64 = 200_000_000

	// MinExprAssignmentPositions / MaxExprAssignmentPositions bound
	// [ExprLimits.AssignmentPositions].
	//
	// Floor: 2,000, slightly above the 1,841 positions of a generous real session
	// (see [ExprLimits.AssignmentPositions]). A floor sized against this
	// repository's presets would be near 12, low enough to let an operator
	// tighten into per-task failures after acceptance.
	//
	// Ceiling: 100,000, one order of magnitude above the default and equal to
	// internal/openjd's MaxExprTemplatePositions. The worker's cap must be able
	// to reach the highest value an operator can legally give the server, or
	// the relation worker cap >= server cap would be unsatisfiable by
	// configuration. The invariant is >=: this ceiling must never fall below
	// the server's, which TestTemplateBudget_WorkerCapIsNotTighter asserts.
	MinExprAssignmentPositions int64 = 2_000
	MaxExprAssignmentPositions int64 = 100_000

	// MinExprAssignmentRetainedBytes / MaxExprAssignmentRetainedBytes bound
	// [ExprLimits.AssignmentRetainedBytes].
	//
	// Both ends are 2x their LetRetainedBytes counterparts, the ratio the
	// defaults carry (20 MB assignment-wide, 10 MB per table), so the
	// assignment-wide cap is not the tighter of the two merely because an
	// operator moved one end of one range. An operator may still configure it
	// tighter than the per-table cap; the tighter one then applies. That is not
	// rejected at load, because tightening is the safe direction and a
	// cross-field rule would make one knob's legal range depend on another's
	// value.
	MinExprAssignmentRetainedBytes int64 = 2_000_000
	MaxExprAssignmentRetainedBytes int64 = 200_000_000

	// MinExprLetRetainedBytes / MaxExprLetRetainedBytes bound
	// [ExprLimits.LetRetainedBytes].
	//
	// Floor: 1,000,000, one server-default evaluation's worth of live bytes,
	// the largest single value phase 2 can pass through to a binding. A table
	// must be able to hold one of those, and with whole-table accounting
	// (property 2 on the field) the job's parameters are counted alongside
	// it, so a smaller floor would reject accepted work.
	//
	// It is a tenth of the server's default template-wide retained-bytes
	// budget: like the operation and memory floors, it tracks a server
	// default it cannot read. One binding is the least a table can hold; a
	// server accepts a whole template's worth. A worker at this floor is
	// offered no EXPR work, even by a default server, until it is raised or
	// openjd.expr_template_retained_bytes is lowered to meet it. That shows as
	// a registration warning naming both keys and an unschedulable reason on
	// the task, because internal/scheduler compares this dimension too.
	//
	// Ceiling: one order of magnitude above the default, and equal to
	// internal/openjd's MaxExprTemplateRetainedBytes: the server compares this
	// value against openjd.expr_template_retained_bytes, so this ceiling must
	// reach that key's highest legal value or the relation would be
	// unsatisfiable by configuration. A catastrophe bound: the worst case an
	// operator can hand a host is this value plus one in-flight evaluation's
	// MemoryLimit, per table, per concurrent task slot.
	MinExprLetRetainedBytes int64 = 1_000_000
	MaxExprLetRetainedBytes int64 = 100_000_000
)

The range an operator may configure each of the five to. Out-of-range values are rejected at startup by internal/worker/config's validateExpr, which carries its own copies of these numbers (that package is the operator-facing layer and must not import this enforcement leaf) and is pinned to them by cmd/sqi-worker's TestExprLimitsBounds_MatchFmtres, the one place that may import both.

The ceilings distinguish a catastrophe bound (tight) from a policy bound (wide but finite, sized against what a legitimate template needs); each ExprLimits field says which it is. The three catastrophe ceilings are one order of magnitude above their default; the two policy ceilings are set from a stated relation.

The floors follow a principle that does not apply on the server: a limit tightened too far on a worker rejects work after the job was accepted, once per task, naming a budget the submitter never saw. So no floor here is sized against the smallest value this repository's presets cost. TestExprLimits_PresetCostsLeaveFloorHeadroom fails if any preset comes within 4x of a floor.

The floors do not promise "at least the largest value a legitimately accepted assignment could need". MinExprOperationLimit and MinExprMemoryLimit are sized against the server's defaults, and those two are configurable on the server up to 10x their defaults: a server with openjd.expr_operation_limit at 100,000 and a worker at its floor gives a worker 10x tighter than what the server accepted. The worker does not read or receive the server's configuration, so the check runs the other way: the worker advertises all five caps at registration, and the server withholds EXPR work from a worker that is short in any compared dimension. A floor too low for a given server therefore means "this host runs no EXPR jobs", not "every task of an accepted job fails here". The floors promise nothing about a particular server; each affected field says so.

View Source
const (
	// DefaultAssignmentPositions is the default cap on the number of
	// format-string positions (command, one Args entry, one embedded file, one
	// variable value) one assignment's phase-3 evaluation may resolve, summed
	// across the task's own table and every environment's.
	//
	// It is 10,000 because internal/openjd's template-position default is
	// 10,000, and this cap must never be the tighter of the two. The positions
	// one assignment resolves (its own step action and embedded files, plus
	// every job and step environment the session enters) are a subset of the
	// positions the server already charged for the whole template at validate
	// and submit. A cap here below the server's is reachable by a template the
	// server accepted: one job environment with 5,000 Variables charges ~5,001
	// positions server-side and would trip a 5,000 cap here inside
	// session.Manager.Create, failing every task in the job after submission
	// with a budget the submitter never saw. Keeping this cap >= the server's
	// leaves the rejection to the submit request, where it can be reported.
	//
	// The enforced value is [ExprLimits.AssignmentPositions], carried on the
	// assignment's budget; this constant is the default. It is exported for
	// internal/openjd's TestTemplateBudget_WorkerCapIsNotTighter
	// (exprcheck_budget_test.go), which compares the two defaults and cannot
	// see a farm whose configuration violates the relation. internal/scheduler
	// enforces the relation at runtime: the configured value is advertised to
	// the server at registration, and an EXPR job is not dispatched to a
	// worker whose value is below the server's (that gate identifies an EXPR
	// job by a heuristic; see internal/scheduler/exprcaps.go's jobMayUseEXPR).
	// The relation is satisfiable at every legal setting because this
	// dimension has the same ceiling as the server's (see
	// MaxExprAssignmentPositions).
	//
	// For scale, a generous real session needs about 1,841 positions: one task
	// action (command + 30 args + 10 embedded files = 41) plus 50 environments,
	// each charging only its entry-side work (onEnter command + 20 args = 21,
	// 10 variables, 5 embedded files = 36). Teardown charges nothing.
	//
	// The subset relation holds while exactly one task runs per session (see
	// the "Scope" section above and session.go's package comment). If sessions
	// were reused across tasks, N tasks would share one budget and this cap,
	// with the test pinning it, would need revisiting.
	DefaultAssignmentPositions int64 = 10_000
)

Variables

TargetArgItem is this package's copy of exprcheck.go's identically named value. See the comment at the top of this file for why a second copy exists; it must stay in step with the original.

Functions

func AddFileVars

func AddFileVars(scope fmtstring.MapScope, prefix string, files []protocol.EmbeddedFile, workDir string) error

AddFileVars sets "<prefix>.<name>" in scope to the absolute on-disk path of each embedded file's materialized location (filepath.Join(workDir, filename), where filename is derived via EmbeddedFileName). prefix is "Task.File" or "Env.File"; the key uses each file's Name. workDir is the absolute session working directory, so the resulting values are absolute paths.

If two files share the same Name, the later entry overwrites the earlier in the scope (last-wins); callers should ensure unique names upstream.

AddFileVars returns an error naming the offending file when a filename is invalid. The scope is mutated in place.

func ApplyEnvLet added in v0.3.0

func ApplyEnvLet(
	env *protocol.AssignEnvironment, syms expr.MapSymbols, pathMap []protocol.PathMapRule, budget *AssignmentBudget,
) error

ApplyEnvLet is ApplyTaskLet's environment counterpart: it evaluates env's own script let: block (AssignEnvironment.Let, Template Schemas section 3.6.2 row 4) over syms, mutating it in place. A nil env is a no-op returning nil, matching EnvSymbols' nil handling.

It does not evaluate the enclosing step template's block (section 3.6.2 row 1): EnvSymbols already folded those names into syms, so they are visible here, and per section 3.6 a binding in this block that tries to rebind one of them is rejected by the shadow check.

Call this after resolving env.Variables. Section 3.6.2 row 4 grants an environment script's let: names to the script's children (actions and embeddedFiles), and Variables is a sibling of Script on the parent Environment, not a descendant, so a variable value may not see them. Phase 2 encodes that by checking Variables against baseSyms before cloning it into scriptSyms and binding the block (checkEnvironmentExpressions, exprcheck.go); phase 3 encodes it by ordering the two calls, since it mutates one table rather than cloning.

Callers pass the result of EnvSymbols as syms. See ApplyTaskLet for pathMap and budget.

func ApplyTaskLet added in v0.3.0

func ApplyTaskLet(
	msg *protocol.AssignMsg, syms expr.MapSymbols, pathMap []protocol.PathMapRule, budget *AssignmentBudget,
) error

ApplyTaskLet evaluates a task's phase-3 let: bindings over syms, the step template's block (msg.StepTemplateLet) first and then the step script's (msg.StepScriptLet), mutating syms in place. This is Template Schemas section 3.6.2 row 1/2's ordering. The two blocks travel as separate wire fields because the script's block may not shadow a name the template's block bound, which is enforceable only while they stay distinguishable (see protocol.go's doc comment on StepTemplateLet/StepScriptLet).

As in checkStepExpressions (exprcheck.go), the two blocks do not share one table: the template's block is evaluated against [stepTemplateLetScope]'s narrower view of syms, then only the names it bound are merged into the full syms before the script's block, which sees the full table, runs. A name the template's block bound is visible to the script's block (and may not be rebound by it), but a Session.*/Task.*/*.File.* symbol the template's block tried to reference is not, as ScopeStepTemplate denies it server-side.

Call this once per table. It inserts every bound name from both blocks into syms, so a second call over the same syms makes every binding fail the shadow check. A caller resolving more than one action, embedded file or variable for the same task calls ApplyTaskLet once to build the table and reuses that syms for every resolution.

Callers pass the result of TaskSymbols as syms. ApplyTaskLet is separate from TaskSymbols for two reasons: some callers want the base job/task/session table alone (TaskSymbols' tests, and TestPhase2Phase3Agreement's key-set comparison against SymbolsFor, which never touches let); and let evaluation needs pathMap for its metering options, which TaskSymbols does not otherwise require.

pathMap is forwarded to ExprEvalOptions, as for every other phase-3 evaluator in this package; see ResolveActionExpr's doc comment for why it is a plain parameter rather than a variadic opts tail.

It returns a non-nil error if any binding in either block failed (errors.Join of every failure across both blocks); syms still holds every binding that succeeded, since a failed binding does not stop the walk (see the section comment above).

budget is forwarded to both blocks' evalLetBindings calls, so the task's let: retention is charged against the same AssignmentBudget every environment table of this assignment shares; see session.Session's accessor for how the budget reaches every phase-3 call site.

func ConvertPathMapRules added in v0.3.0

func ConvertPathMapRules(rules []protocol.PathMapRule) []expr.PathMapRule

ConvertPathMapRules converts the assignment's wire-format path-mapping rules (protocol.PathMapRule, JSON-shaped for the OpenJD pathmapping-1.0 file) into expr.PathMapRule, the type expr.WithPathMapping accepts.

The conversion is field for field: SourcePath and DestinationPath copy verbatim, and SourcePathFormat's three wire spellings ("POSIX", "WINDOWS", "URI"; see protocol.PathMapRule's doc comment) correspond one to one with expr.PathMapSourceFormat's three constants. convertPathMapSourceFormat's default case (an unrecognized spelling) is defensive, like EmbeddedFileName's filename checks in fmtres.go: the server builds the assignment and writes only those three, and PathMapPOSIX, which assumes no particular structure in the text, is the fallback.

func EmbeddedFileName

func EmbeddedFileName(f protocol.EmbeddedFile) (string, error)

EmbeddedFileName computes the on-disk filename for an embedded file: it uses f.Filename when set, falling back to f.Name. Filenames containing path separators or null bytes are rejected to prevent directory traversal (a defense-in-depth check, since the server builds the assignment).

This is the single source of truth for the materialized filename, shared by the embedded-file writer and by AddFileVars, so the path placed into Task.File.* / Env.File.* matches exactly where the file is written.

func EnvScope

func EnvScope(jobParams map[string]string, workDir, pathMapFile string, hasPathMap bool) fmtstring.MapScope

EnvScope builds the format-string scope for an environment action (an environment's onEnter/onExit command and args) and for environment variable values.

Unlike TaskScope, the environment scope does not expose Task.Param.* / Task.RawParam.*: environments are session-scoped and entered once, not per task. jobParams are exposed as Param.<n> and RawParam.<n>; workDir is exposed as Session.WorkingDirectory. pathMapFile and hasPathMap populate Session.PathMappingRulesFile / Session.HasPathMappingRules as in TaskScope. The caller may add keys to the returned map before resolving.

func EnvSymbols added in v0.3.0

func EnvSymbols(
	msg *protocol.AssignMsg, env *protocol.AssignEnvironment, workDir, pathMapFile string, hasPathMap bool,
	budget *AssignmentBudget,
) (expr.MapSymbols, error)

EnvSymbols builds the phase-3 EXPR symbol table for one environment's actions (onEnter/onExit) and variable values. It exposes:

  • Param.<name> / RawParam.<name>, exactly as TaskSymbols.
  • Env.File.<name>, one path per entry in env.EmbeddedFiles: this environment's own files, not another environment's and not the step's Task.File.* files (a template may declare many environments, each with its own files; internal/openjd's symbolsFor takes the specific *Environment for the same reason).
  • Session.WorkingDirectory, Session.PathMappingRulesFile (only when hasPathMap), Session.HasPathMappingRules.
  • Job.Name, from msg.JobName.
  • Step.Name, from msg.StepName, only when env.StepEnvironment is true (see below).
  • The enclosing step template's let-bound names (msg.StepTemplateLet), also only when env.StepEnvironment is true (see below).

It does not expose Task.Param.*/Task.RawParam.*/Task.File.*: environments are session-scoped and entered once, not per task, as in EnvScope.

Step.Name is conditional because section 3.6.2 (and internal/openjd's ScopeJobEnvironment/ScopeStepEnvironment split, scope.go) grants it to a step environment's script but not a job environment's: ScopeStepEnvironment is ScopeJobEnvironment plus Step.Name. protocol.AssignEnvironment.StepEnvironment distinguishes them on the wire (assign.go sets it from whether the entry came from tmpl.JobEnvironments or stepTmpl.StepEnvironments), and this function trusts it.

msg.StepTemplateLet is evaluated and folded in here, for a step environment only. Template Schemas section 3.6.2 row 1 makes a <StepTemplate>.let binding's names available in stepEnvironments, hostRequirements, parameterSpace and script, and section 3.6 states the same rule from the other side ("a let binding in a <StepTemplate>'s stepEnvironments cannot shadow a binding from that step's let block"). Phase 2 implements it too: checkStepExpressions passes stepLet as checkEnvironmentExpressions' outerLet, which folds it into baseSyms before anything else, so it is visible to variables, embedded files, onEnter and onExit alike. Without it here, a template phase 2 accepted would fail every task in the step with unknown symbol "<name>" at enterOne, and fail teardown the same way.

It is folded in inside the table builder rather than exposed as a second "apply" step the caller could forget. That matches phase 2: checkEnvironmentExpressions treats outerLet as part of the table an environment starts from (baseSyms := clone(outerLet), then symbolsFor's additions), not as a let: block the environment evaluates. The environment's own let: block (section 3.6.2 row 4) is a separate, later step, ApplyEnvLet, because section 3.6.2 places the environment's Variables between the two, and phase 2's ordering there is observable.

Job environments get none of this: they have no enclosing step, so no step-template let block is in scope, and the OpenJD conformance fixture 7.3.1--step-name-in-job-environment-let.invalid.yaml requires that. env.StepEnvironment is the same bit Step.Name keys off, for the same reason.

An error is returned when an embedded file's Name/Filename is invalid (see EmbeddedFileName), when a PATH parameter's value cannot be mapped, or when any step-template let: binding fails to parse or evaluate. See TaskSymbols for budget, which carries the limits here for the same reason (a job PATH parameter is bound here too).

func ExprEvalOptions added in v0.3.0

func ExprEvalOptions(lim ExprLimits, pathMap []protocol.PathMapRule) []expr.Option

ExprEvalOptions builds the []expr.Option every phase-3 evaluation in this package is called with: the assignment's metering (lim's OperationLimit/MemoryLimit; a zero ExprLimits normalizes to the defaults above, so there is no unmetered spelling), the evaluation's path flavor (pathFlavor, exprsyms.go's expr.PathNative: the worker runs on the host a task executes on, so its concrete Session.WorkingDirectory and Task.File.* values, and any path literal an expression writes, must agree on one flavor; see exprsyms.go's doc comment for why that is PathNative here and POSIX upstream), and the session's apply_path_mapping rules translated from the assignment's wire format via ConvertPathMapRules.

This is the one place these settings are assembled, so a caller cannot use the resolvers in this file without expr.WithPathFormat(expr.PathNative).

It wraps exprEvalOptionsFor with pathFlavor. exprEvalOptionsFor takes the flavor as a parameter so a white-box test (expres_internal_test.go) can force a flavor other than the one this host's pathFlavor.resolve() produces, proving expr.WithPathFormat is wired; on a POSIX-only CI host the option being set and the option being absent are otherwise indistinguishable.

func ResolveAction

func ResolveAction(action *protocol.Action, scope fmtstring.Scope) (*protocol.Action, error)

ResolveAction returns a copy of action with its Command and every Args entry resolved against scope. All other fields (TimeoutSeconds, Cancelation) are copied unchanged. A nil action returns (nil, nil).

ResolveAction returns a descriptive error — naming the offending reference — if any reference is malformed or names a variable the scope does not provide. The input action is never mutated.

func ResolveActionExpr added in v0.3.0

func ResolveActionExpr(
	action *protocol.Action, syms expr.MapSymbols, pathMap []protocol.PathMapRule, budget *AssignmentBudget,
) (*protocol.Action, error)

ResolveActionExpr is ResolveAction's EXPR-aware counterpart: it returns a copy of action with Command resolved via resolveFormatStringExpr and every Args entry resolved via resolveArgItemExpr (see that function's doc comment for why one entry may become zero, one, or several arguments). All other fields (TimeoutSeconds, Cancelation) are copied unchanged. A nil action returns (nil, nil).

syms is the phase-3 symbol table (TaskSymbols or EnvSymbols); pathMap is the assignment's PathMap field, forwarded to ExprEvalOptions to build this call's options, so every call applies metering, the worker's native path flavor and the session's path-mapping rules. It takes pathMap rather than a variadic opts ...expr.Option parameter: a variadic tail compiles when the caller passes nothing, handing every evaluation expr.Eval's unconfigured defaults (10x the operations and 5x the memory of this package's limits) with nothing to catch it. Taking pathMap rather than a pre-built []expr.Option means no options value a caller could construct skips metering.

ResolveActionExpr returns an error naming the offending field if any reference is malformed, evaluates to an error, or names a symbol syms does not provide. The input action is never mutated.

budget is charged one position for the command and one for each Args entry, before resolving it, so a budget already exhausted earlier in the assignment stops the walk without evaluating that entry. See AssignmentBudget. It is required; nil (passed by this package's unit tests) charges a fresh, default-limited throwaway budget. See [budgetOrDefault], which also documents why a production caller must not pass nil.

func ResolveEmbeddedFiles

func ResolveEmbeddedFiles(files []protocol.EmbeddedFile, scope fmtstring.Scope) ([]protocol.EmbeddedFile, error)

ResolveEmbeddedFiles returns copies of files with each file's Data resolved against scope. All other fields (Name, Filename, Runnable, EndOfLine) are copied unchanged. A nil slice returns (nil, nil).

ResolveEmbeddedFiles returns a descriptive error — naming the offending file and reference — when a file's data is malformed or names a variable the scope does not provide. The input slice and its elements are never mutated.

func ResolveEmbeddedFilesExpr added in v0.3.0

func ResolveEmbeddedFilesExpr(
	files []protocol.EmbeddedFile, syms expr.MapSymbols, pathMap []protocol.PathMapRule, budget *AssignmentBudget,
) ([]protocol.EmbeddedFile, error)

ResolveEmbeddedFilesExpr is ResolveEmbeddedFiles' EXPR-aware counterpart: it returns copies of files with each file's Data resolved via resolveFormatStringExpr (TargetString: an embedded file's body is always one string, never subject to TargetArgItem's list-item rule). All other fields (Name, Filename, Runnable, EndOfLine) are copied unchanged. A nil slice returns (nil, nil).

See ResolveActionExpr for syms/pathMap/budget. ResolveEmbeddedFilesExpr returns an error naming the offending file when a file's data is malformed, evaluates to an error, or names a symbol syms does not provide. The input slice and its elements are never mutated.

func ResolveVars

func ResolveVars(vars map[string]string, scope fmtstring.Scope) (map[string]string, error)

ResolveVars returns a copy of vars with every value resolved against scope. Keys are copied unchanged. A nil map returns (nil, nil).

ResolveVars returns a descriptive error — naming both the offending variable key and the reference — if any value is malformed or names a variable the scope does not provide. The input map is never mutated.

func ResolveVarsExpr added in v0.3.0

func ResolveVarsExpr(
	vars map[string]string, syms expr.MapSymbols, pathMap []protocol.PathMapRule, budget *AssignmentBudget,
) (map[string]string, error)

ResolveVarsExpr is ResolveVars' EXPR-aware counterpart: it returns a copy of vars with every value resolved via resolveFormatStringExpr. Keys are copied unchanged. A nil map returns (nil, nil).

See ResolveActionExpr for syms/pathMap/budget. ResolveVarsExpr returns an error naming the offending variable key if any value is malformed, evaluates to an error, or names a symbol syms does not provide. The input map is never mutated.

Keys are iterated in map order, which varies between calls. exprcheck.go's checker walk sorts, to give a template author reproducible error pointers; this function has no such position to keep stable. Which variable trips a nearly exhausted budget can vary run to run, but the assignment fails with a budget-exceeded error either way; only the key named in it changes.

func TaskScope

func TaskScope(jobParams, taskParams map[string]string, workDir, pathMapFile string, hasPathMap bool) fmtstring.MapScope

TaskScope builds the format-string scope for a task action (a step's onRun command and args).

jobParams are the job-level parameter values (exposed as Param.<n> and RawParam.<n>); taskParams are the per-task parameter values (exposed as Task.Param.<n> and Task.RawParam.<n>); workDir is the session working directory (exposed as Session.WorkingDirectory).

pathMapFile is the absolute path to the written OpenJD path-mapping file and hasPathMap reports whether the assignment carries any path-mapping rules; they populate Session.HasPathMappingRules ("true"/"false") and, when hasPathMap is true, Session.PathMappingRulesFile (otherwise that key is absent).

Param.<n> and RawParam.<n> map to the same value; Param values are not path-mapped here. The caller may add keys to the returned map before resolving.

func TaskSymbols added in v0.3.0

func TaskSymbols(
	msg *protocol.AssignMsg, workDir, pathMapFile string, hasPathMap bool, budget *AssignmentBudget,
) (expr.MapSymbols, error)

TaskSymbols builds the phase-3 EXPR symbol table for a task action (a step's onRun command, args, and embedded files). It exposes:

  • Param.<name> / RawParam.<name>, typed from msg.JobParameterTypes and concretized from msg.JobParameters.
  • Task.Param.<name> / Task.RawParam.<name>, typed from msg.ParameterTypes and concretized from msg.Parameters.
  • Task.File.<name>, one path per entry in msg.EmbeddedFiles, at its materialized on-disk location under workDir (via AddFileVars, the computation the non-EXPR path uses, so the two cannot diverge).
  • Session.WorkingDirectory, Session.PathMappingRulesFile (only when hasPathMap), Session.HasPathMappingRules.
  • Job.Name, Step.Name, from msg.JobName/msg.StepName.

It does not expose Env.File.* (see EnvSymbols for that family, and TestTaskSymbols_ExcludesEnvFile).

workDir is the absolute session working directory; pathMapFile is the absolute path to the written OpenJD path-mapping JSON file (meaningful only when hasPathMap is true). The caller supplies these host facts, as for TaskScope.

An error is returned only when an embedded file's Name/Filename is invalid (see EmbeddedFileName) or when a PATH parameter's value cannot be mapped.

budget is used here only to carry the limits: symbol building charges no positions or retained bytes (the callers that resolve fields and evaluate let: blocks do), but binding a PATH parameter runs an apply_path_mapping evaluation through [mapPathParamValue], which must be metered by the same operator-configured per-evaluation limits as every other evaluation in this package. It is required; nil (passed by this package's unit tests) meters against the defaults. See [budgetOrDefault], which also documents why a production caller must not pass nil.

Types

type AssignmentBudget added in v0.3.0

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

AssignmentBudget bounds the cumulative section 1.3.9/1.3.10 cost phase-3 evaluation may charge against one assignment. See the comment at the top of this file for what it bounds, why it is scoped per assignment, and how concurrency figures into the constants above.

Use NewAssignmentBudget to create one; every phase-3 entry point in this package (TaskSymbols, EnvSymbols, ApplyTaskLet, ApplyEnvLet, ResolveActionExpr, ResolveEmbeddedFilesExpr, ResolveVarsExpr) takes one as a required trailing parameter. nil means "the built-in default limits, on a fresh throwaway ledger"; this package's unit tests pass it when the limits are not under test, and production call sites must not. See [budgetOrDefault] for both halves of that contract and the guard that enforces the second.

func NewAssignmentBudget added in v0.3.0

func NewAssignmentBudget(lim ExprLimits) *AssignmentBudget

NewAssignmentBudget returns a fresh, unspent AssignmentBudget metered by lim. A zero ExprLimits (or any individually unset field) normalizes to the defaults (see [ExprLimits.orDefaults]); it never means "unlimited".

The parameter is required rather than an option: this constructor is where an assignment acquires its limits, and a caller that forgot to supply its operator configuration would meter by the defaults instead. Callers with nothing to supply pass ExprLimits{}.

func (*AssignmentBudget) ChargePositions added in v0.3.0

func (b *AssignmentBudget) ChargePositions(n int64, where string) error

ChargePositions charges n additional format-string positions, naming where as the position that exhausted the budget if this call is the one that does. It returns a non-nil error (the same error on every call once the budget is spent, in either dimension) when the caller may not do the work those positions represent.

func (*AssignmentBudget) ChargeRetainedBytes added in v0.3.0

func (b *AssignmentBudget) ChargeRetainedBytes(n int64, where string) error

ChargeRetainedBytes charges n additional retained bytes (one let: binding's expr.SizeOf), naming where as the position that exhausted the budget if this call is the one that does. n <= 0 is a no-op that still reports the budget's current state, as in [ChargePositions].

func (*AssignmentBudget) Err added in v0.3.0

func (b *AssignmentBudget) Err() error

Err returns the error recording why the budget tripped, or nil if it never did.

func (*AssignmentBudget) Limits added in v0.3.0

func (b *AssignmentBudget) Limits() ExprLimits

Limits returns the normalized ExprLimits this budget meters against.

The resolvers build their expr.Option slice from it (ExprEvalOptions), and evalLetBindings reads LetRetainedBytes from it. It needs no mutex: limits is written once by the constructor.

type ExprLimits added in v0.3.0

type ExprLimits struct {
	// OperationLimit is the section 1.3.10 operation budget for one phase-3
	// expression evaluation.
	//
	// Policy bound. It bounds CPU inside one evaluation, charged to the task
	// slot the assignment already occupies, so raising it lengthens the
	// operator's own worst assignment without exposing the host to a fault
	// that kills unrelated work. Memory-heavy let: constructions spend almost
	// no operations, so this budget does not bound them; MemoryLimit and
	// LetRetainedBytes do. Its ceiling is sized against what a legitimate
	// template needs.
	//
	// It is one of the two factors in the derived cumulative bound for an
	// assignment (AssignmentPositions x OperationLimit), and nothing here
	// bounds wall clock: section 1.3.10 prices 256 bytes at one operation, so
	// a raised value buys proportionally more byte-heavy work per position.
	// The same applies to the server's operation limit.
	OperationLimit int64

	// MemoryLimit is the section 1.3.9 live-byte budget for one phase-3
	// expression evaluation.
	//
	// Catastrophe bound. A let: block of maxLetBindings (50) bindings such as
	// `a<i> = "x" * (Task.Param.N * 100000)` can retain up to maxLetBindings x
	// this number, 1 GB per block at the default, in a shared, long-lived
	// process whose death ends every task on the host. Phase 2 cannot reject
	// it (Task.Param.N is unresolved at submission, so `"x" * unresolved`
	// costs nothing there). Raising this value raises that ceiling in
	// proportion, per concurrently resolving task slot, so the ceiling below
	// is a tight multiple of the default.
	//
	// This bound and internal/openjd/expr's fixed maxStringBytes (10,000,000)
	// measure different things, and the default is above maxStringBytes.
	// maxStringBytes bounds one produced string; section 1.3.9's meter bounds
	// the sum of live values and recurses into containers, so a list of two
	// 9 MB strings holds 18,000,128 bytes live with no fixed guard firing.
	MemoryLimit int64

	// AssignmentPositions is how many format-string positions (a command, one
	// args entry, one embedded file, one variable value) one assignment may
	// resolve, summed across the task's own symbol table and every environment
	// table the session enters.
	//
	// Policy bound, sized against what a real session needs: a generous
	// session (one task action with 30 args and 10 embedded files, plus 50
	// entered environments at 36 entry-side positions each) resolves 1,841
	// positions, and the default of 10,000 leaves ~5.4x headroom. The worker,
	// unlike the server's API, is neither anonymous nor synchronous.
	//
	// It carries a cross-binary relation this package cannot check: an
	// assignment's positions are a subset of its template's, so a value here
	// below the server's template-position cap is reachable by a template the
	// server accepted, failing every task in the job after submission with a
	// budget the submitter never saw. TestTemplateBudget_WorkerCapIsNotTighter
	// compares the two defaults; because both sides are configurable, the
	// relation is enforced outside this package. This value is advertised to
	// the server in the worker's registration message (protocol.ExprLimits),
	// and internal/scheduler does not dispatch an EXPR job to a worker whose
	// advertised value is below the server's configured one. This file sets
	// the ceiling (below) equal to the server's ceiling, so the relation is
	// satisfiable at every value an operator can legally give the server.
	AssignmentPositions int64

	// AssignmentRetainedBytes is the cumulative section 1.3.9 size of every
	// let-bound value retained by every phase-3 table this assignment builds,
	// summed across the task's own table and every environment's.
	//
	// Catastrophe bound: the aggregate of the mechanism MemoryLimit and
	// LetRetainedBytes bound per evaluation and per table. Without it, a
	// session entering N environments could allocate N x LetRetainedBytes over
	// the course of entry with every individual table compliant.
	//
	// It measures cumulative allocation across one session's entry-time
	// evaluation, not peak live retention (each environment's table is a
	// local variable that becomes GC-eligible once that environment finishes
	// resolving); see [AssignmentBudget]'s doc comment. Sizing host RAM
	// against this number over-provisions, and sizing this number against an
	// observed RSS under-bounds it.
	AssignmentRetainedBytes int64

	// LetRetainedBytes is the total section 1.3.9 size of everything one
	// phase-3 symbol table holds live, measured across every let: block
	// evaluated into it.
	//
	// Catastrophe bound, and the most direct of the five against the let:
	// construction described on MemoryLimit.
	//
	// It is advertised and compared against the server's template-wide
	// retained-bytes budget. The server has no per-table quantity to pair it
	// with, but a template-wide sum is an upper bound on any one of that
	// template's tables, and comparing against it keeps a worker at this
	// field's floor from rejecting, once per task, a let: block the server
	// accepted. internal/scheduler/exprcaps.go gives the full argument,
	// including why comparing against the server's per-evaluation memory
	// limit would be unsound.
	//
	// Two properties of the default to know before changing it:
	//
	//  1. 10,000,000 is internal/openjd/expr's maxStringBytes, so the largest
	//     single string the evaluator can produce cannot be bound, even into
	//     an empty table (the check is retained+size > limit, and a
	//     10,000,000-byte string measures slightly more once its value header
	//     is counted). An operator who needs to bind such a string raises
	//     this knob.
	//  2. The accounting measures the whole table, not only let-bound names,
	//     so a job with large parameters spends budget its let: block never
	//     asked for. Metering only let names would let a table hold its
	//     parameters plus a full budget of bindings; this knob is the
	//     adjustment.
	LetRetainedBytes int64
}

ExprLimits is the worker's phase-3 expression budget, as five numbers.

They split into two per-evaluation bounds (OperationLimit, MemoryLimit: what one expression may cost, section 1.3.10 and section 1.3.9), one per-table bound (LetRetainedBytes: what one phase-3 symbol table may hold live), and two per-assignment bounds (AssignmentPositions, AssignmentRetainedBytes: summed across every table one assignment builds).

A zero or negative field means "unset, use the default" (see [ExprLimits.orDefaults]); no value means "unlimited". internal/worker/config rejects an out-of-range configured value at startup.

This type does not enforce the ranges an operator may choose from. They live in the Min/Max constants below (mirrored by internal/worker/config, which must not import this package), so a test can set an out-of-range value to prove a knob is wired.

func DefaultExprLimits added in v0.3.0

func DefaultExprLimits() ExprLimits

DefaultExprLimits returns the default value of each of the five limits, the values a worker started with no expr: configuration meters by.

func (ExprLimits) Normalized added in v0.3.0

func (l ExprLimits) Normalized() ExprLimits

Normalized is the exported form of [ExprLimits.orDefaults]. The worker advertises its caps to the server at registration (protocol.ExprLimits), and what it advertises must be what it enforces: an un-normalized zero would be published as "not advertised" while the evaluator used the default. internal/worker/registration is the caller.

Jump to

Keyboard shortcuts

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