fmtres

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 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 only known 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 extend the scope with future keys — such as Task.File.*, Env.File.*, or Session.PathMappingRulesFile — before resolving.

Index

Constants

View Source
const (
	// MinExprOperationLimit / MaxExprOperationLimit bound
	// [ExprLimits.OperationLimit].
	//
	// Floor: the SERVER's own 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 own defaults.
	//
	// TWO WAYS THAT IS LESS THAN PARITY, both real:
	//
	//  1. It is the server's DEFAULT, not the server's configured value, and
	//     E4d Task 1 made the latter configurable up to 100,000. A farm that
	//     raises openjd.expr_operation_limit and leaves a worker at this floor
	//     has a worker tighter than what the server accepts -- the same
	//     cross-binary breakage AssignmentPositions carries, which no
	//     compile-time test can see. E4d Task 3 made the server DETECT it from
	//     this worker's advertised caps and withhold EXPR work
	//     (internal/scheduler/exprcaps.go); it did not, and could not, make
	//     this floor track a server it cannot read.
	//  2. Even at parity it would not guarantee acceptance: phase 3 evaluates
	//     the same expressions against CONCRETE values and E2's Task 10
	//     measured it at ~40x phase 1's cost. That is why the DEFAULT here is
	//     100x the server's rather than equal to it.
	//
	// Ceiling: one order of magnitude above the default. Policy, not
	// catastrophe -- but not open-ended either, because nothing meters wall
	// clock and section 1.3.10 prices 256 bytes at one operation, so 10^7
	// operations is already ~2.5 GB of byte-work priced into ONE evaluation,
	// repeated per position.
	MinExprOperationLimit int64 = 10_000
	MaxExprOperationLimit int64 = 10_000_000

	// MinExprMemoryLimit / MaxExprMemoryLimit bound [ExprLimits.MemoryLimit].
	//
	// Floor: the SERVER's own 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 only had a placeholder for, so a
	// worker allowance below what the server accepted rejects after the fact.
	// It carries the SAME residual gap: the server's value is configurable up
	// to 10,000,000, so this floor tracks the server's default rather than the
	// server's setting, and the same runtime gate is what detects the
	// mismatch. See MinExprOperationLimit for the full statement.
	//
	// Ceiling: one order of magnitude above the default. This is a catastrophe
	// ceiling, and the number it really sets is the per-block structural
	// ceiling maxLetBindings (50) x this value -- 1 GB at the default, 10 GB
	// at the maximum, per concurrently-resolving task slot. An operator
	// choosing the maximum should have sized the host's RAM against that
	// product, not against this number.
	MinExprMemoryLimit int64 = 1_000_000
	MaxExprMemoryLimit int64 = 200_000_000

	// MinExprAssignmentPositions / MaxExprAssignmentPositions bound
	// [ExprLimits.AssignmentPositions].
	//
	// Floor: 2,000, just above E4c's own worked figure of 1,841 positions for
	// a generous-but-plausible real session (see [ExprLimits.AssignmentPositions]).
	// Sizing it against this repo's reference presets instead would have given
	// something near 12, which is exactly the kind of floor that lets an
	// operator tighten into per-task post-acceptance failures.
	//
	// Ceiling: 100,000, which is BOTH one order of magnitude above the default
	// AND exactly internal/openjd's MaxExprTemplatePositions. The second
	// reason is the load-bearing one: the worker's cap must be able to reach
	// the highest value an operator can legally give the server, or the
	// cross-binary relation of design spec §2 would be unsatisfiable by
	// configuration. THE INVARIANT IS >=, NOT EQUALITY -- this ceiling must
	// never fall below the server's, and that is what
	// TestTemplateBudget_WorkerCapIsNotTighter asserts. The two being equal
	// today is a value, not the rule.
	MinExprAssignmentPositions int64 = 2_000
	MaxExprAssignmentPositions int64 = 100_000

	// MinExprAssignmentRetainedBytes / MaxExprAssignmentRetainedBytes bound
	// [ExprLimits.AssignmentRetainedBytes].
	//
	// Both ends are exactly 2x their LetRetainedBytes counterparts, preserving
	// the ratio the defaults already carry (20 MB assignment-wide, 10 MB per
	// table): the assignment-wide cap should never be 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 -- that is allowed and
	// coherent (the tighter of the two simply becomes the effective one), and
	// deliberately 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,
	// i.e. the largest single value phase 2 can pass through to a binding. A
	// table must be able to hold at least one of those, and the whole-table
	// accounting (property 2 on the field) means the job's own parameters are
	// counted alongside it, so anything smaller would be a floor that rejects
	// accepted work.
	//
	// IT IS A TENTH OF THE SERVER'S DEFAULT template-wide retained-bytes
	// budget, which is not an oversight but the same shape as the operation
	// and memory floors above: they track the server's DEFAULTS and cannot
	// track its configured values. One binding is the least a table can
	// usefully hold; a server accepts a whole template's worth. A worker left
	// at this floor therefore promises nothing about even a DEFAULT server,
	// and is offered no EXPR work until either it is raised or
	// openjd.expr_template_retained_bytes is lowered to meet it. That is
	// visible -- a registration WARN naming both keys, and an unschedulable
	// reason on the task -- rather than a per-task failure after acceptance,
	// which is what internal/scheduler's fifth comparison bought.
	//
	// Ceiling: one order of magnitude above the default, and equal to
	// internal/openjd's MaxExprTemplateRetainedBytes -- which, as with
	// AssignmentPositions above, is the load-bearing half: the server
	// compares this value against openjd.expr_template_retained_bytes, so
	// this ceiling must be able to reach the highest value that key can
	// legally take, or the relation would be unsatisfiable by configuration.
	// Catastrophe bound: this is the dimension the measured 495 MB OOM lived
	// in, and 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 must not import this one -- config is the operator-facing layer, and this is the enforcement leaf) and is pinned to them by cmd/sqi-worker's TestExprLimitsBounds_MatchFmtres, the one place that may import both.

The CEILINGS encode design spec §3's distinction between a catastrophe bound (tight, tied to a measurement) and a policy bound (wide but finite, sized against what a legitimate template plausibly needs). Which of the five is which, and why, is on each ExprLimits field. All three catastrophe ceilings are one order of magnitude above their default; both policy ceilings are set from a stated relation rather than from a multiple.

The FLOORS follow one 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. That is the worst failure shape available (design spec §2 records it as a measured incident), so no floor here is sized against the smallest value this repo's own presets happen to cost. TestExprLimits_PresetCostsLeaveFloorHeadroom measures the presets on every run and fails if any of them comes within 4x of a floor.

WHAT THE FLOORS DO NOT PROMISE, stated here because an earlier revision of this paragraph claimed it and it is false: they are NOT "at least the largest value a legitimately accepted assignment could need". Two of the five (MinExprOperationLimit, MinExprMemoryLimit) are sized against the server's DEFAULTS, and E4d Task 1 -- the same wave -- made those two configurable too, up to 10x their defaults. An operator who raises openjd.expr_operation_limit to 100,000 and leaves a worker at its floor gets a worker 10x tighter than what the server accepted, which is the post-acceptance per-task failure this whole paragraph is about. Sizing these floors from the server's configured value is still impossible here (the worker does not read the server's config, and by choice does not receive it). What E4d Task 3 added is the other direction: the worker ADVERTISES its caps at registration and the server withholds EXPR work from a worker that is short in ANY compared dimension -- so the consequence of a floor that is too low for a given server is now "this host runs no EXPR jobs", not "every task of an accepted job fails here". ALL FIVE are advertised and compared: Task 3 shipped with four, and the wave's final review found the fifth (LetRetainedBytes) reachable through legal configuration and added it. The floors themselves still promise nothing about a particular server. Each affected field says so in its own comment; do not re-generalize the promise here.

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.
	//
	// WORKED CALCULATION, generous but plausible for a real session, and
	// CORRECTED by fix round 1 (post-implementation review): an EARLIER
	// version of this comment counted onEnter AND onExit as 21 positions
	// each (42/environment) -- wrong in TWO ways the fix round's other
	// change (Critical 2, session.go's resolveEnvAction) resolved together.
	// First, it undercounted: Variables is resolved at BOTH entry
	// (resolveEnvEntry) and exit (resolveEnvAction) in the pre-fix code, so
	// the real PRE-FIX charge was onEnter(21) + onExit(21) + variables
	// charged TWICE (10 + 10) + files(5) = 67, not 57. Second, and mooting
	// the first: fix round 1's Critical 2 made resolveEnvAction's teardown
	// path NOT charge this budget AT ALL (see that method's own doc comment
	// in session.go for why a budget that cannot avert the memory it is
	// charging for must not be allowed to block cleanup) -- so onExit's
	// command/args and the SECOND (exit-time) variables resolution now
	// contribute ZERO positions, not 21 or 10.
	//
	// The CURRENT, accurate calculation: one task action (command + 30 args
	// + 10 embedded files = 41, unaffected -- a task has no exit/teardown
	// counterpart) plus up to 50 environments entered in one session (no
	// structural cap on environment count exists today -- see
	// internal/openjd's own maxSteps comment for the analogous reasoning it
	// applies to steps), each environment costing ONLY its entry-side work:
	// onEnter (command + 20 args = 21) + 10 variables (entry only) + 5
	// embedded files = 36 positions. 50 x 36 = 1,800, plus the task's own 41,
	// is 1,841.
	//
	// THE VALUE IS NOT SIZED BY THAT CALCULATION ALONE. It is 10,000 because
	// internal/openjd's own template-position default is 10,000, and this cap
	// must never be the TIGHTER of the two -- raised from 5,000 by fix round 2
	// (whole-branch review, IMPORTANT 1), which found the two constants had
	// no stated relation, no test, and no mention of each other.
	//
	// E4d TASK 2 MADE BOTH SIDES CONFIGURABLE, so this constant is now only
	// the DEFAULT: the enforced value is [ExprLimits.AssignmentPositions],
	// carried on the assignment's own budget. It stays exported because
	// internal/openjd's TestTemplateBudget_WorkerCapIsNotTighter is the only
	// place that sees both sides of the relation and still needs to read it --
	// but note that with both sides configurable, that test now compares two
	// DEFAULTS and cannot see a farm whose YAML violates the relation. E4d
	// Task 3 closed that at runtime, in internal/scheduler: 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 documented heuristic, not exactly -- see
	// internal/scheduler/exprcaps.go's jobMayUseEXPR). What
	// Task 2 did was make the relation SATISFIABLE at every legal setting, by
	// giving this dimension the same ceiling as the server's (see
	// MaxExprAssignmentPositions).
	//
	// WHY THE RELATION IS LOAD-BEARING: the server charges its 10,000-position
	// template-wide budget at validate and submit; this budget is charged on
	// the WORKER, after the job exists. 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's walk already charged for the whole template. So a cap here
	// BELOW the server's is reachable by a template the server ACCEPTED: one
	// job environment with 5,000 Variables charged ~5,001 positions
	// server-side (accepted, well under 10,000) and tripped the old 5,000 cap
	// here inside session.Manager.Create -- failing EVERY task in the job,
	// one at a time, after submission, naming a budget the submitter was
	// never shown. Post-submission per-task failure is the worst available
	// place to enforce a template-shape rule; making this cap >= the server's
	// moves that rejection back to the one synchronous request that can
	// report it. Pinned by TestTemplateBudget_WorkerCapIsNotTighter
	// (internal/openjd/exprcheck_budget_test.go), which is where BOTH
	// constants are visible.
	//
	// The alternative -- keeping 5,000 here and having the server charge a
	// per-ASSIGNMENT sub-budget so the rejection happens at submit -- was
	// rejected as the larger change: the server would have to model which of
	// a template's positions land in one assignment (a task's own step plus
	// the environments that task enters), which is a partition of the walk
	// that nothing in internal/openjd computes today.
	//
	// The worked calculation above still stands as the FLOOR: 1,841 for a
	// generous real session, so 10,000 leaves ~5.4x headroom rather than the
	// ~2.7x that 5,000 gave. The wall-clock tradeoff of raising it is the
	// same one internal/openjd's own template-position limit records for the
	// server, on a host that is executing one task rather than serving an
	// API request.
	//
	// ONE ASSUMPTION IS WORTH NAMING, because a future change could void it:
	// "an assignment's positions are a subset of the template's" holds while
	// exactly one task runs per session (see this file's "Scope" section and
	// session.go's own package comment). If session reuse across tasks lands,
	// N tasks would share one budget and the subset argument becomes N x the
	// per-task share -- at which point this cap, and the test pinning it,
	// both need revisiting.
	DefaultAssignmentPositions int64 = 10_000
)

Variables

TargetArgItem is this package's own copy of exprcheck.go's identically named value -- see this file's own doc comment, above, for why a second copy exists and must be kept 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' own nil handling for the same parameter.

It does NOT evaluate the enclosing step template's block (section 3.6.2 row 1): EnvSymbols already folded those names into syms when it built the table, 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 rather than silently overwriting it.

CALL THIS AFTER RESOLVING env.Variables, not before. Section 3.6.2 row 4 grants an environment script's let: names to the script's own children -- actions and embeddedFiles -- and Variables is a sibling of Script on the parent Environment, not a descendant of it, 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, then the step script's (msg.StepScriptLet) -- mutating syms in place. This is Template Schemas section 3.6.2 row 1/2's ordering, and the reason the two blocks travel as separate wire fields rather than being concatenated: the script's block may not shadow a name the template's block already bound, which is only enforceable if the two stay distinguishable (protocol.go's own doc comment on StepTemplateLet/StepScriptLet makes the same point).

The two blocks do NOT share one table outright, mirroring checkStepExpressions (exprcheck.go) exactly rather than the simpler "evaluate both over syms" a first attempt at this function used (see stepTemplateLetScope's own doc comment for that history): the template's block is evaluated against [stepTemplateLetScope]'s NARROWER view of syms, then only the names it successfully bound are merged into the full syms before the script's block -- which DOES see the full table -- runs. A name the template's block bound is therefore visible to the script's block (and, per shadow rejection, may not be rebound by it), but a Session.*/Task.*/*.File.* symbol the template's block tried to reference is not, exactly as ScopeStepTemplate denies it server-side.

CALL THIS ONCE PER TABLE. It mutates syms by inserting every successfully bound name (both blocks') directly into it -- calling it a second time over the SAME syms makes every binding in both blocks fail the shadow check, because every name is now already present as a key. A caller that resolves more than one action/embedded-file/variable against the same task (e.g. ResolveActionExpr called once per action) must call ApplyTaskLet exactly once to build the table, then reuse that same syms for every resolution -- not call ApplyTaskLet again per resolution.

Callers pass the result of TaskSymbols as syms -- ApplyTaskLet is a SEPARATE step from building the base table, not folded into TaskSymbols itself. Two reasons: TaskSymbols has its own callers that want the base job/task/session table alone, with no let: block involved (Task 3's own tests, and TestPhase2Phase3Agreement's key-set comparison against SymbolsFor, which likewise never touches let); and the LET evaluation needs the metering options (below) that only a caller resolving pathMap can supply, which TaskSymbols itself has no reason to require.

pathMap is forwarded to ExprEvalOptions, exactly as every other phase-3 evaluator in this package requires -- see ResolveActionExpr's doc comment for why this is a plain parameter rather than a variadic opts tail: taking the raw ingredient closes off the possibility of a caller building an options value, empty or otherwise, that skips metering.

Returns a non-nil error if any binding in either block failed to evaluate (errors.Join of every failure across both blocks) -- syms still holds every binding that DID succeed, since a failed binding does not stop the walk; see this section's own doc comment for why continuing past a failure, rather than aborting, is the intended behavior.

budget is EXPR sub-project E4c's Task 4 addition: forwarded verbatim to both blocks' evalLetBindings calls, so the task's own let: retention is charged against the SAME AssignmentBudget every environment table this assignment builds shares -- see session.Session's own accessor for how the one budget object reaches every phase-3 call site for one assignment.

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 a clean, field-for-field mapping: SourcePath and DestinationPath copy verbatim, and SourcePathFormat's three wire spellings ("POSIX", "WINDOWS", "URI" -- protocol.PathMapRule's own doc comment) correspond one to one with expr.PathMapSourceFormat's three constants. convertPathMapSourceFormat's default case (an unrecognized spelling) is defensive only, exactly like EmbeddedFileName's own filename checks in fmtres.go: the assignment is server-signed, so a wire value other than the three the server ever writes is not expected in production, and falling back to PathMapPOSIX (the format that requires nothing of the text to already be structured a particular way) is the least surprising choice for a value this function cannot recognize.

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 assignment is server-signed).

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 exactly as in TaskScope. The returned map may be mutated by the caller to add additional keys 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 any other environment's and not the step's Task.File.* files (a template may declare many environments, each with its own files; mirrors internal/openjd's symbolsFor, which 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, but ONLY when env.StepEnvironment is true -- see below.
  • The ENCLOSING STEP TEMPLATE's let-bound names (msg.StepTemplateLet), again 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 -- matching EnvScope's existing, pre-EXPR behavior.

Step.Name is CONDITIONAL, unlike every other symbol here, because section 3.6.2 (and internal/openjd's own ScopeJobEnvironment/ ScopeStepEnvironment split, scope.go) grants it to a STEP environment's script but not a JOB environment's: ScopeStepEnvironment is exactly ScopeJobEnvironment plus Step.Name. protocol.AssignEnvironment. StepEnvironment is the bit that distinguishes them on the wire (assign.go sets it from which of tmpl.JobEnvironments/stepTmpl.StepEnvironments the entry came from), so this function trusts it directly rather than guessing.

FIX ROUND 2 (E4a whole-branch review, Critical 1): 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 -- not only in the script -- and section 3.6's prose 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 already implements it: checkStepExpressions passes stepLet as checkEnvironmentExpressions' outerLet, which folds it into baseSyms BEFORE anything else and therefore behind variables, embedded files, onEnter and onExit alike. Phase 3 did not, so a template phase 2 accepted with zero errors failed every task in the step with unknown symbol "<name>" at enterOne -- naming a symbol the submitter had been told was valid -- and failed teardown the same way on the exit path.

It is folded in HERE, inside the table builder, rather than exposed as a second "apply" step the caller could forget, precisely because forgetting it is the defect being fixed. That also mirrors phase 2 structurally: checkEnvironmentExpressions treats outerLet as part of the table an environment STARTS from (baseSyms := clone(outerLet); then symbolsFor's own additions), not as a let: block the environment itself evaluates. The environment's OWN let: block (section 3.6.2 row 4) remains 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 NOTHING from this: they have no enclosing step, so there is no step-template let block in scope, and sub-project E3's section 2.2 ruling plus the 7.3.1--step-name-in-job-environment-let.invalid.yaml fixture require the negative half to hold. 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: the same limits-carrier role, 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 should be called with: the assignment's own 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 own concrete Session.WorkingDirectory and Task.File.* values, and any path literal an expression writes, must agree on the SAME flavor; see exprsyms.go's own doc comment for why that is PathNative here and POSIX everywhere upstream of it), and the session's real apply_path_mapping rules translated from the assignment's wire format via ConvertPathMapRules.

This is deliberately the ONE place all four settings are assembled: EXPR sub-project E4a's Task 3 recorded expr.WithPathFormat(expr.PathNative) as "a requirement for the wiring... wherever the options are assembled" -- this function is that place, so a later caller (Task 6) cannot wire the resolvers in this file while forgetting it.

ExprEvalOptions itself is a thin wrapper over exprEvalOptionsFor with pathFlavor (this package's fixed choice, exprsyms.go); exprEvalOptionsFor takes the flavor as a parameter purely so a white-box test (expres_internal_test.go) can force a flavor other than whatever this host's runtime.GOOS-driven pathFlavor.resolve() happens to produce, and so prove expr.WithPathFormat is genuinely wired rather than merely present in source with no observable effect -- see that test's own doc comment for why a POSIX-only CI host cannot otherwise distinguish the option being set from the option having been deleted.

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 actual 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 own PathMap field, forwarded to ExprEvalOptions to build this call's options -- there is deliberately NO way to call this function without metering, the worker's native path flavor, and the session's real path-mapping rules all applying: FIX ROUND 1 (Task 4 review) replaced a variadic opts ...expr.Option parameter with this one, because a variadic tail compiles fine when the caller passes NOTHING, silently handing every evaluation expr.Eval's own unconfigured defaults (10x the operations, 5x the memory this package's own named limits choose) with no compiler error, no lint, and no test failure to catch it. Taking the raw ingredient (pathMap) rather than a pre-built []expr.Option closes that gap completely, not merely narrows it: there is no longer an options value a caller could construct, empty or otherwise, that skips metering.

ResolveActionExpr returns a descriptive 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 EXPR sub-project E4c's Task 4 addition: charges one position for the command and one for each Args entry, BEFORE resolving it, so a budget already exhausted by an earlier action/environment in this same assignment stops the walk here without doing that entry's own evaluation work. See AssignmentBudget's own doc comment for the full account. It is a REQUIRED parameter; passing nil (this package's own unit tests) charges a fresh, default-limited throwaway budget no single call can exhaust -- see [budgetOrDefault], which also documents why a production caller must not.

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 exactly 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 a descriptive 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 a descriptive 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 is not deterministic across calls -- unlike exprcheck.go's checker walk, which sorts (checkEnvironmentExpressions' own reason: reproducible ERROR pointers for a template author). This function has no author-facing position to keep stable; which variable happens to trip an already-near-exhausted budget varying run to run does not change the OUTCOME (the assignment still fails, with a budget-exceeded error either way), only which key's name appears in it.

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> currently map to the same value; path-mapped (cooked) Param values are a later task. The returned map may be mutated by the caller to add additional keys 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 SAME computation the pre-EXPR path already uses, so the two paths 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 for the negative this asymmetry is tested against.

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). These are host facts the caller supplies, exactly as they already do 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 EXPR sub-project E4d's Task 2 addition, and it is used here PURELY AS THE LIMITS CARRIER: nothing in symbol building charges positions or retained bytes (those dimensions belong to the callers that resolve fields and evaluate let: blocks), but binding a PATH parameter runs a real apply_path_mapping evaluation through [mapPathParamValue], and that evaluation must be metered by the SAME operator-configured per-evaluation limits as every other one in this package. Before Task 2 it was the one evaluator here that no budget reached, so an operator tightening the memory limit would have seen every other position honor it and this one silently keep the compiled-in default. It is a REQUIRED parameter; passing nil (this package's own unit tests) meters against the defaults -- see [budgetOrDefault], which also documents why a production caller must not.

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 this file's own package-level doc comment for the full account of what it bounds, why it is scoped per-assignment rather than per-table or process-wide, 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. Passing nil is legal and means "the built-in default limits, on a fresh throwaway ledger" -- it is what this package's own unit tests pass when the limits are not what they are testing, and it is never acceptable from a production call site. See [budgetOrDefault] for both halves of that contract and for 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 deliberately REQUIRED rather than an option: this constructor is where an assignment acquires its limits, and a caller that has operator configuration to supply but silently does not is the exact failure E4d exists to prevent. Callers with nothing to say 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, 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 own 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, matching [ChargePositions]'s own contract.

func (*AssignmentBudget) Err added in v0.3.0

func (b *AssignmentBudget) Err() error

Err returns the ONE 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.

It is how the per-evaluation and per-table numbers reach the evaluator: the resolvers build their expr.Option slice from it (ExprEvalOptions), and evalLetBindings reads LetRetainedBytes from it. Read-only, and safe without the mutex -- limits is written once by the constructor and never again.

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. No measured worker-side catastrophe is attributable to
	// this dimension: E4a's Critical 2 (50 let bindings retaining 495 MB in
	// 49 ms, an OOM-kill of sqi-worker and with it every unrelated task on the
	// host) was a MEMORY construction that "spends almost no operations", and
	// E4c's own note says an operation budget would not have caught it. What
	// this number bounds is CPU inside one evaluation, charged to the task
	// slot the assignment already occupies -- so an operator who raises it is
	// lengthening their own worst assignment, not exposing the host to a fault
	// that kills unrelated work. That is why its ceiling is sized against what
	// a legitimate template plausibly needs rather than against a measurement.
	//
	// It is nonetheless one of the two multiplicands 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. Design spec §4 caveats 1 and 3 apply to this knob on the
	// worker exactly as they do to the server's.
	OperationLimit int64

	// MemoryLimit is the section 1.3.9 live-byte budget for ONE phase-3
	// expression evaluation.
	//
	// CATASTROPHE BOUND. It is the multiplicand of the measured OOM: E4a's
	// Critical 2 measured 50 bindings of `a<i> = "x" * (Task.Param.N * 100000)`
	// retaining 495 MB in 49 ms, and recorded the structural ceiling as
	// maxLetBindings x this number = 1 GB per block -- on a shared, long-lived
	// process whose death takes every unrelated task on the host with it, and
	// which phase 2 CANNOT reject (Task.Param.N is unresolved at submission,
	// so `"x" * unresolved` costs nothing there). Raising it raises that
	// ceiling in direct proportion, per concurrently-resolving task slot,
	// which is why the ceiling below is a tight multiple of the default rather
	// than an open-ended range.
	//
	// NOTE FOR ANYONE SIZING IT: this bound and internal/openjd/expr's own
	// fixed maxStringBytes (10,000,000) are NOT the same kind of thing and the
	// default is already ABOVE it. 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 (measured). An earlier
	// revision of expres.go's own comment claimed both worker limits "sit
	// comfortably UNDER" the fixed guards;
	// that was false for this one (20,000,000 > 10,000,000) and has been
	// withdrawn.
	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 plausibly needs:
	// E4c's own worked calculation for a generous session (one task action
	// with 30 args and 10 embedded files, plus 50 entered environments at 36
	// entry-side positions each) is 1,841 positions, and the default of 10,000
	// leaves ~5.4x headroom over that. Nothing measured a catastrophe in this
	// dimension on the WORKER; the server's equivalent has one (an 84 KB
	// template of ~2,000 args entries cost 11.3 s of CPU per anonymous
	// request), but the worker 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 own template-position cap is reachable by a template
	// the server ACCEPTED -- failing every task in the job after submission,
	// naming a budget the submitter never saw. E4c pinned that with
	// TestTemplateBudget_WorkerCapIsNotTighter comparing two CONSTANTS. With
	// both sides configurable the relation became breakable through YAML, and
	// E4d Task 3 re-closed it OUTSIDE this package: this value is advertised
	// to the server in the worker's registration message
	// (protocol.ExprLimits), and internal/scheduler refuses to dispatch an
	// EXPR job to a worker whose advertised value is below the server's
	// configured one. What this file does about it is set the CEILING (below)
	// equal to the server's own ceiling, so the relation stays 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 EVERY phase-3 table this assignment builds retains,
	// summed across the task's own table and every environment's.
	//
	// CATASTROPHE BOUND -- the aggregate of the same 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 AT ANY ONE INSTANT (each
	// environment's table is a local variable that becomes GC-eligible once
	// that environment finishes resolving) -- see [AssignmentBudget]'s own doc
	// comment, which states the distinction at length. An operator sizing host
	// RAM against this number over-provisions, and sizing this number against
	// an observed RSS under-bounds it. That is design spec §4 caveat 2, and it
	// belongs in the operator documentation, not only here.
	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 one of the five: it IS the bound
	// E4a's Critical 2 added in response to the measured 495 MB / 49 ms
	// OOM construction described on MemoryLimit. Its absence is not
	// hypothetical.
	//
	// IT IS ADVERTISED AND COMPARED, against the server's TEMPLATE-wide
	// retained-bytes budget. There is no per-table quantity on the server to
	// pair it with, but a template-wide sum is a valid upper bound on any one
	// of that template's tables, and comparing against it is what closed the
	// configuration the wave's final review found: a worker at this field's
	// floor rejecting, once per task, a let: block the server had accepted.
	// internal/scheduler/exprcaps.go carries the full argument, including why
	// comparing against the server's per-EVALUATION memory limit instead
	// would have been unsound.
	//
	// TWO PROPERTIES OF THE DEFAULT WORTH KNOWING BEFORE MOVING IT, both
	// inherited unchanged from the constant it replaces (this wave changes no
	// default, by requirement):
	//
	//  1. 10,000,000 is exactly internal/openjd/expr's maxStringBytes, so the
	//     largest single string the evaluator can produce cannot be bound at
	//     all, even into an empty table (the check is retained+size > limit,
	//     and a 10,000,000-byte string measures slightly more than that once
	//     its value header is counted). E4a recorded that coincidence and said
	//     the day the limit became configurable it should not default to
	//     sitting exactly on another bound. It still does -- moving the
	//     DEFAULT is a behavior change this wave is not permitted to make.
	//     The knob is now the way out for an operator who needs one.
	//  2. The accounting measures the WHOLE table, not only let-bound names,
	//     so a job whose own parameters are large spends budget its let: block
	//     never asked for. That is deliberate (metering only let names would
	//     let a table hold parameters PLUS a full budget of bindings), and E4a
	//     said what it needed was "a knob, not a different formula". This is
	//     the knob.
	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 field means "unset, use the default" -- see [ExprLimits.orDefaults]. A NEGATIVE field means the same thing; neither can ever mean "unlimited", which is the one meaning a resource-exhaustion guard must not acquire by accident. internal/worker/config rejects an out-of-range configured value at startup, long before one could reach here.

The ranges an OPERATOR may choose from are not enforced by this type. They live in the Min/Max constants below (and are mirrored, deliberately, by internal/worker/config, which must not import this package), so that a test can set an absurd value to prove a knob is genuinely wired -- which is exactly how this wave's mutation tests work.

func DefaultExprLimits added in v0.3.0

func DefaultExprLimits() ExprLimits

DefaultExprLimits returns the five values this package used as fixed constants before E4d. A worker started with no expr: configuration meters exactly as every release before E4d did.

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 has to be what it would ENFORCE: an un-normalized zero would be published as "not advertised" while the evaluator quietly 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