openjd

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: 21 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 openjd implements parsing, validation, and parameter-space expansion for Open Job Description (OpenJD) job templates.

Specification version

This package targets the "jobtemplate-2023-09" specification revision, which is the version used by AWS Deadline Cloud and other OpenJD-compatible systems. The specificationVersion field in a submitted template must equal that literal string.

Usage

Parse a raw YAML or JSON submission, then validate and expand it:

tmpl, err := openjd.Parse(rawBytes, openjd.FormatYAML)
if err != nil {
    // low-level decode error (bad YAML/JSON)
}

if errs := openjd.Validate(tmpl); len(errs) > 0 {
    for _, e := range errs {
        fmt.Printf("%s: %s\n", e.Pointer, e.Message)
    }
}

for i, step := range tmpl.Steps {
    tasks, err := openjd.ExpandParameterSpace(step.ParameterSpace)
    // each task is a map[string]string of parameter name → value
}

Format strings

OpenJD format strings use double-braces to reference job or task parameters, for example: "{{Param.FrameNumber}}" or "{{Task.Param.OutputFile}}". This package records format strings verbatim; interpolation is performed later by the worker when it executes the task.

Path-mapping rules

PATH-typed job parameters and task parameters hold filesystem or S3 paths. At execution time the worker resolves them to concrete local paths using the path-mapping JSON file written into the session working directory. The parser records PATH parameters as strings; no path resolution is performed here.

Index

Constants

View Source
const (
	// MinExprSubmissionOperations / MaxExprSubmissionOperations bound
	// [ExprLimits.SubmissionOperations].
	//
	// Ceiling: exactly one order of magnitude above the default. The
	// worst-case single request measured with this dimension at 10,000 is
	// ~17 minutes of server CPU (~24 if a position spends its whole budget at
	// the worst measured rate), and no COUNTER can see that, so the only
	// honest statement about a raised value is that it lengthens that floor
	// proportionally -- at both maxima the same construction measures ~40
	// hours. Ten times is a deliberate limit on how much worse an operator can
	// make the worst request the farm can be asked to serve.
	//
	// Those figures predate EXPR sub-project H1 and are kept because they are
	// what this ceiling was chosen against. What H1 changed is that they are no
	// longer the wall-clock outcome: [ExprLimits.Deadline] stops an evaluation
	// at openjd.expr_submission_deadline (default 5s, ceiling 60s) whatever
	// they permit. The two are NOT co-sized -- 10,000 positions x 10,000
	// operations nominally permits ~17 minutes against a 60s ceiling -- so at
	// any legal configuration the deadline, not this number, is what a request
	// actually stops at.
	//
	// Floor: one order of magnitude below the default so tightening remains
	// meaningful, and ~67x above what a reference preset's expressions
	// actually spend. The measurement, re-run by
	// TestExprLimits_FloorsAcceptReferencePresets on every test run, is that
	// the most expensive single evaluation in any of the fourteen presets
	// costs 15 operations. Earlier revisions of this sentence said "two orders
	// of magnitude above the handful of operations" and then "exactly 1
	// operation -- so the headroom is 1000x"; both were measured against a
	// smaller preset set, and the ratio moves as presets are added. Trust the
	// floors paragraph at the top of this file, which the test re-measures.
	MinExprSubmissionOperations int64 = 1_000
	MaxExprSubmissionOperations int64 = 100_000

	// MinExprSubmissionMemoryBytes / MaxExprSubmissionMemoryBytes bound
	// [ExprLimits.SubmissionMemoryBytes].
	//
	// Ceiling: one order of magnitude above the default, a JUDGEMENT, and the
	// same shape as the other two catastrophe ceilings.
	//
	// WHAT THAT CEILING REALLY PERMITS is not 10 MB, and saying "10 MB of
	// live values per evaluation is as much as an operator may permit an
	// unauthenticated submission to hold" -- as an earlier revision of this
	// paragraph did -- understates it by 50x. The charge against
	// TemplateRetainedBytes lands ONCE PER let: BLOCK, after that block has
	// finished evaluating, so a single block transiently holds up to
	// maxLetBindings (50, Template Schemas section 3.6) x THIS number before
	// any counter sees it: 50 MB at the default and 500 MB at this ceiling,
	// per concurrently-resolving request. That product, not this number, is
	// what a host's RAM has to be sized against, and it is the reason this
	// ceiling is a tight multiple rather than an open range. See
	// [ExprLimits.TemplateRetainedBytes] and defaultTemplateRetainedBytes'
	// own comment in exprcheck.go, which state the same product from the
	// other end.
	//
	// It coincides with internal/openjd/expr's fixed maxStringBytes, and an
	// earlier revision mistook the coincidence for a derivation ("above it the
	// fixed guard fires first, so a larger value is inert"). Measurement
	// disproved that -- see [ExprLimits.SubmissionMemoryBytes] for the
	// construction, which holds 12 MB live with no fixed guard firing. Do not
	// re-derive this ceiling from maxStringBytes; if the argument for 10x ever
	// changes, this number is free to move with it.
	//
	// Floor: 4 KB, ~10x the live bytes a reference preset's largest expression
	// produces. That measurement -- 390 bytes, re-run by
	// TestExprLimits_FloorsAcceptReferencePresets, and stated correctly in
	// this file's own floors paragraph above -- is what the number is sized
	// from. Earlier revisions of this sentence said "three orders of magnitude
	// above the few hundred live bytes" and then "64 bytes ... ~1.8 orders";
	// both were measured against a smaller preset set, and the figure moves as
	// presets are added. Trust the floors paragraph three screens up, which
	// the test re-measures.
	MinExprSubmissionMemoryBytes int64 = 4_096
	MaxExprSubmissionMemoryBytes int64 = 10_000_000

	// MinExprTemplatePositions / MaxExprTemplatePositions bound
	// [ExprLimits.TemplatePositions].
	//
	// Ceiling: one order of magnitude above the default, for the same reason
	// as the operation ceiling — this is the other multiplicand in the
	// derived cumulative-operation ceiling, and raising BOTH to their maxima
	// multiplies that derived number by 100 (10^8 -> 10^10). Documentation
	// must say so in those words; see design spec §4 caveat 1.
	//
	// Floor: 256, roughly 8x the largest reference preset's measured 31
	// positions, and still ~40x below the default so an operator running only
	// small templates can tighten hard.
	MinExprTemplatePositions int64 = 256
	MaxExprTemplatePositions int64 = 100_000

	// MinExprTemplateRetainedBytes / MaxExprTemplateRetainedBytes bound
	// [ExprLimits.TemplateRetainedBytes] — the one POLICY bound of the four,
	// so the range is wide rather than tied to a measurement: 64 KB (about a
	// thousand small let bindings; the reference presets use no let: at all
	// and retain zero) up to 100 MB of live values from one request.
	MinExprTemplateRetainedBytes int64 = 65_536
	MaxExprTemplateRetainedBytes int64 = 100_000_000
)

The range an operator may configure each of the four to. Out-of-range values are rejected at STARTUP by internal/config's validateOpenJD, which carries its own copies of these numbers (internal/config must not import this package -- CLAUDE.md's dependency direction) and is pinned to them by internal/server's TestExprLimits_ConfigMatchesOpenJD, the one package that may import both.

The CEILINGS encode design spec §3's distinction between a catastrophe bound (a tight ceiling, tied to a measurement) and a policy bound (wide but finite). Which of the four is which, and why, is on each ExprLimits field. All three catastrophe ceilings are one order of magnitude above their default, and all three are JUDGEMENTS -- none is derived from some fixed guard firing first, which is a derivation this file offered once and had to withdraw (see ExprLimits.SubmissionMemoryBytes).

The FLOORS all come from measurement, not from taste. The fourteen reference presets in presets/sqi/ -- the templates this repo itself ships -- are measured per dimension by binary search on every run, by TestExprLimits_FloorsAcceptReferencePresets: at most 31 expression positions template-wide, and 390 live bytes with 15 operations in any single evaluation. Those three maxima are set by ffmpeg-segment-transcode-expr, the only preset doing real slice arithmetic; the render presets cost an order of magnitude less. Retained bytes are effectively zero for all fourteen -- the binary search floors that dimension at 1, so a reported "1" means "nothing measurable", not a real cost. Every floor below leaves at least 4x headroom over the worst of them (8x to 65536x in practice), so no operator can tighten a knob to a value that rejects sqi's own templates. TestExprLimits_FloorsAcceptReferencePresets re-measures that on every run rather than trusting this paragraph.

View Source
const (
	// StatusSupported means the extension is fully implemented and accepted.
	StatusSupported = "supported"
	// StatusInProgress means the extension is registered for conformance
	// scoring but is NOT accepted: some required part of it is unimplemented.
	StatusInProgress = "in-progress"
)

Extension status values. Status is the SECOND half of the registration gate: validateExtensions accepts an extension only when it is both present in the registry AND marked supported.

The split exists so that a partially-implemented extension can be present — so the conformance harness can drive it through the real parse and validate path — while production still rejects it, for a stated reason rather than because a map lookup missed.

View Source
const ExtensionEXPR = "EXPR"

ExtensionEXPR is the registry name of the OpenJD expression-language extension.

Exported for internal/scheduler, which decides per lease request whether a job needs a worker capable of phase-3 expression evaluation. It compares this name against the extension list Submitter.Submit persisted on the job row, so the test is EXACT for every job submitted since migration 00027. Rows older than that column record no list, and for those alone the scheduler falls back to scanning the raw template for these bytes -- a heuristic whose two error directions are written out in that package's exprcaps.go.

View Source
const SpecVersion = "jobtemplate-2023-09"

SpecVersion is the only specification version accepted by this package.

Variables

View Source
var (
	// TargetString is the target for a name, command, variable value or
	// embedded-file body -- any plain string-typed field.
	TargetString = expr.TString
	// TargetInt is the target for a timeout.
	TargetInt = expr.TInt
	// TargetArgItem is the target for a single entry of an args list, per
	// section 1.3.2's list-item rule: a string is one argument, None drops the
	// argument, and a list[string] flattens inline. UnionOf/OptionalOf's
	// normalization collapses OptionalOf(TString)'s own union with the
	// list[string] member into one flat three-member union rather than a
	// union nested inside a union.
	TargetArgItem = expr.UnionOf(expr.OptionalOf(expr.TString), expr.ListOf(expr.TString))
)

Target types for checkFormatString, section 1.3.2. Declared once as package-level values so call sites read as "the name field" rather than reconstructing the type at every call.

View Source
var ErrInvalidTransition = errors.New("openjd: invalid state transition")

ErrInvalidTransition is returned when a requested step status transition is not permitted by the step state machine.

Use errors.Is to test:

err := ValidateStepTransition(from, to)
if errors.Is(err, ErrInvalidTransition) { ... }

The task state machine lives in package store, which enforces it on every status write, and carries its own store.ErrInvalidTransition.

Functions

func CancelDependents

func CancelDependents(ctx context.Context, st store.Store, jobID string) (int, []store.Task, error)

CancelDependents cancels every store.StepStatusPending step of jobID whose dependency graph includes a step that terminated unsuccessfully — that is, reached store.StepStatusFailed or store.StepStatusCanceled — and cancels each such step's store.TaskStatusPending tasks.

A pending step that depends on a failed or canceled step can never become ready (ResolveDependencies only promotes steps whose dependencies all reached completed), so it would otherwise strand forever and prevent the job from ever reaching a terminal state. Canceling it lets job-completion detection proceed.

It returns the number of steps newly canceled and the pending tasks that were transitioned to canceled (so the caller can fan those terminal task transitions out to subscribers). Each canceled task is stamped with store.FailureReasonUpstreamFailed in the same UPDATE, unless it already carries a more specific reason.

CancelDependents loops to a fixpoint: canceling a step makes it an unsuccessful dependency for its own dependents, so a single call propagates through transitive dependency chains. Calling it is idempotent — steps already past pending are skipped.

It is typically invoked by the scheduler immediately after any step transitions to failed or canceled.

func DecodeListParamValue added in v0.3.0

func DecodeListParamValue(value string) ([]any, error)

DecodeListParamValue parses a canonical list parameter value into its elements. Exported for callers that must operate on a list value's elements -- resolving loc:// URIs, building a staging manifest -- without reaching into this package's encoding.

func DeriveChunkBounds added in v0.2.0

func DeriveChunkBounds(rows []TaskParams, ps *StepParameterSpace)

DeriveChunkBounds adds "<name>.Start" and "<name>.End" keys to every row in rows for each CHUNK[INT] parameter declared in ps. Each chunk value is a contiguous integer range encoding (e.g. "1-10", "5", "1-10:2"); Start is the smallest integer in the chunk and End the largest. It is a no-op when ps is nil or declares no CHUNK[INT] parameter, and is only meaningful (and only called) when the SQI_CHUNK_BOUNDS extension is enabled. A value that fails to parse is left without derived keys — expansion has already validated ranges.

func DeriveStorageType added in v0.2.0

func DeriveStorageType(roots map[string]string) string

DeriveStorageType classifies a storage location from its roots: "s3" when every root is an S3 URI, "filesystem" when none are (or there are no roots), and "mixed" when the roots span both. The storage-location type is descriptive only — sqi keys real behavior off each root's scheme, not off this value.

func EncodeListParamValue added in v0.3.0

func EncodeListParamValue(elems []any) (string, error)

EncodeListParamValue is DecodeListParamValue's inverse, producing the same canonical form encodeListDefault does -- HTML escaping off, no trailing newline.

The round trip is CANONICAL-IN, CANONICAL-OUT, not universally byte-identical: encoding what DecodeListParamValue just decoded from an already-canonical value reproduces the same bytes, but a JSON round trip normalizes whitespace, number spelling (1.0 -> 1), and \u escapes. A SUBMITTED value is exactly the case where that matters -- BindJobParameters carries it verbatim, never canonicalizing it -- so decoding and re-encoding a non-canonical submitted value (e.g. to splice in a resolved loc:// URI) can change its bytes even though every element's value is unchanged.

func ExtractJobLevelLocRefs

func ExtractJobLevelLocRefs(tmpl *JobTemplate) []string

ExtractJobLevelLocRefs returns the deduplicated set of location names referenced at job scope only — job-parameter defaults and job environments. Step references are intentionally excluded; use ExtractStepLocRefs for those.

func ExtractStepLocRefs

func ExtractStepLocRefs(st StepTemplate) []string

ExtractStepLocRefs returns the deduplicated set of location names referenced in a single step (its script, environments, and parameter space range lists).

func ExtractTemplateLocRefs

func ExtractTemplateLocRefs(tmpl *JobTemplate) []string

ExtractTemplateLocRefs returns the deduplicated set of location names referenced anywhere in the given job template (command args, environment variables, embedded file data, and task/job parameter defaults).

Only the location names are returned; use ExtractLocRefs when the full LocRef details are needed.

func IsListParamTypeName added in v0.3.0

func IsListParamTypeName(declared string) bool

IsListParamTypeName reports whether a declared type NAME is one of RFC 0007's list types. It takes a string rather than a JobParamType because callers outside this package hold the type as the text the assignment carries.

func IsS3Root added in v0.2.0

func IsS3Root(root string) bool

IsS3Root reports whether root is an S3 object-store root — i.e. it begins with the lowercase "s3://" scheme. Uppercase "S3://" is intentionally NOT treated as S3 (it is a filesystem path), matching JoinPath's forward-slash rule.

func JoinPath

func JoinPath(root, relPath string) string

JoinPath joins a resolved root with the relative path portion of a loc:// URI. relPath includes the leading slash (or is empty).

For S3 roots (e.g. "s3://bucket/prefix"), path separators are kept as "/". For filesystem roots, the OS-appropriate separator is used.

func ResolveDependencies

func ResolveDependencies(ctx context.Context, st store.Store, jobID string) (int, error)

ResolveDependencies inspects every step of jobID and promotes any store.StepStatusPending step whose declared dependencies have all reached store.StepStatusCompleted to store.StepStatusReady, then transitions all of that step's store.TaskStatusPending tasks to store.TaskStatusReady.

It returns the number of steps newly promoted to ready.

Calling ResolveDependencies is idempotent: steps that are already past pending are skipped. It is typically invoked by the scheduler immediately after any step transitions to store.StepStatusCompleted.

Steps with an empty DependsOn list are always eligible. In normal operation such steps are created with store.StepStatusReady by Submitter.Submit, so they will simply be skipped here. If a no-dep step is somehow in pending state, ResolveDependencies will promote it correctly.

Note: ResolveDependencies considers only a single pass through the step list. Call it again if the first pass unblocked a step whose promotion might unblock further steps in the same job.

func ResolveLocURIs

func ResolveLocURIs(s string, resolve func(name, relPath string) (string, error)) (string, error)

ResolveLocURIs replaces every loc:// URI in s with the concrete path returned by resolve(locationName, relPath). relPath includes the leading slash; it is empty when the URI is a bare "loc://name" reference.

resolve is called once per unique URI occurrence; if resolve returns an error the function aborts and returns the error.

func ResolveParameterSpaceParams

func ResolveParameterSpaceParams(
	tmpl *JobTemplate, step *StepTemplate, ps *StepParameterSpace, jobParams map[string]string,
	budget ...*templateBudget,
) (*StepParameterSpace, ValidationErrors)

ResolveParameterSpaceParams returns a new *StepParameterSpace with every {{Param.<name>}} and {{RawParam.<name>}} reference in RangeExpr and RangeList entries substituted with the corresponding value from jobParams.

Both "Param.<name>" and "RawParam.<name>" resolve to the same bound string value — path mapping is worker-side and out of scope at submit time.

tmpl is the job template ps was parsed from, and step is the step template ps belongs to (nil is allowed for both, and a nil tmpl is treated the same as an extension-less template). They exist on this signature for exactly three things, all gated on tmpl.hasExtension("EXPR"):

  • deciding whether a whole-field RangeExpr that is a LONE {{...}} expression (fmtstring.LoneRef — the entire field is one reference, no surrounding text) is section 1.3.12's extended range form and should be EVALUATED into a value rather than substituted as plain text — and, for every other shape (a RangeList entry, or a RangeExpr/RangeString that is literal text or has a reference embedded in surrounding text), whether each embedded {{...}} is read as an EXPRESSION (evaluated, expr.TAny, rendered to text) rather than a bare dotted-identifier lookup (resolveFormatStringExpr, resolveRangeListEntry);
  • building the phase-2 ScopeJob symbol table that evaluation runs against, with jobParams already bound concrete — Submitter.prepareTemplate's step 2d re-check runs the identical construction over the identical map, so a range expression this package resolves and the one checkTemplateExpressions already accepted read the same job-parameter values the same way;
  • evaluating step's OWN let: block and merging the names it binds into that table, which is what section 3.6.2 row 1 grants a step template's let: at the parameterSpace position. Both halves are shared with the checker rather than reimplemented (exprcheck.go's stepLetSymbols and rangeScopeSymbols), because them being built separately is exactly how they drifted: before EXPR sub-project E4b's whole-branch review this function passed no step at all, so a step-level let: ["base = 10"] with range: "{{ [base, base + 1] }}" validated at upload, passed the phase-2 re-check, and then failed HERE with unknown symbol "base" — a symbol the checker had just certified.

A nil tmpl, or one that does not declare EXPR, takes exactly the base-spec substitution path this function has always taken — see [resolveRangeExprField]'s own doc comment for why that matters and how it is proven. step is read only on the EXPR path, so a base-spec caller may pass nil for it freely.

The input ps is never mutated; a fresh struct (with a new slice of TaskParamDefinition values) is always returned on success.

If ps is nil, (nil, nil) is returned immediately.

On a malformed reference, an unknown variable, or (EXPR-declared only) an expression evaluation error — at the whole-field RangeExpr, an individual RangeList entry, or an embedded reference within either — a ValidationError is accumulated with a pointer of the form

/parameterSpace/taskParameterDefinitions/<i>/range
/parameterSpace/taskParameterDefinitions/<i>/range/<j>   (RangeList entry j)

A malformed or unevaluatable entry in step's own let: block is reported the same way, at pointer /let/<i> — the checker has already rejected it by the time production reaches here, but reporting it directly beats letting every range expression that referenced the failed binding fail with a misleading "unknown symbol" instead.

A WALL-CLOCK DEADLINE (ExprLimits.Deadline, carried on budget) is the one evaluation failure that is NOT reported that way. It is recorded on the budget instead ([templateBudget.recordDeadline]), which stops the walk and is read back by the caller through [templateBudget.deadline]; this function then returns a nil parameter space, because a partly-resolved one is indistinguishable from a complete one. Every one of this function's evaluation sites -- step's let: block, the whole-field range, and each RangeList entry -- routes through recordDeadline before converting anything, so there is no position at which "the server gave up" can reach the API as "your template is invalid".

All task-parameter definitions are inspected before returning so callers receive a complete error list in one round-trip UNLESS the template-wide budget (below) trips first, in which case the walk stops early -- see that paragraph.

budget is EXPR sub-project E4c's Task 4 addition, corrected by fix round 1 (post-implementation review, Critical 1): an optional [templateBudget] shared across EVERY STEP's ResolveParameterSpaceParams call for THE SAME SUBMISSION (submit.go's prepareTemplate builds one -- resolverBudget -- and Submit's step loop threads the same object into every step). It is deliberately NOT the same object as checkExpressionsAtSubmit's own budget, even though this function resolves the identical range positions and let bytes checkTemplateExpressions already charged (checkParameterSpaceExpressions, exprcheck.go) for the same submission: fix round 1 found that sharing ONE budget between the two silently HALVED the effective cap for those classes, so a template ValidateWithOptions (phase 1) accepted could be rejected by Submit (phase 2) purely because two walks were drawing from one pool -- exactly the "fail purely on accumulated cost, with no way for the submitter to see why" failure mode design spec §3.1 exists to prevent, one level down from where Task 3 closed it for phase 1 vs. phase 2. §3.1 sanctions two budgets per request; this function's budget is the resolver's own. See TestSubmit_ValidateAcceptsMustNotRejectOnBudgetAlone (resolve_budget_test.go) for the constructions that proved the bug and now prove the fix, and TestPhase2Budget_CheckerAndResolverHaveIndependentBudgets for the unit-level version.

Sharing IS still correct, and unchanged, ACROSS STEPS within one budget: a many-step submission's cumulative resolver cost is bounded together, exactly as a many-step template's cumulative checker cost already is (design spec §3's "one budget per phase" reasoning, applied here to "one budget per WALK per phase" instead of "one budget per phase" outright).

Omitting budget (as every pre-Task-4 caller does) gives this call its own fresh, throwaway allowance -- see [templateBudgetOrFresh] -- which is harmless: no legitimate single call comes close to either dimension's cap on its own.

The budget is consulted, and charged, ONLY on the EXPR-enabled path: a template that does not declare EXPR takes the exact base-spec substitution this function has always performed, byte for byte, with no budget interaction of any kind -- matching every other EXPR-only behavior this function gates on exprEnabled.

func ResolveRoot

func ResolveRoot(locationName string, roots map[string]string, computeLocation string) (string, error)

ResolveRoot returns the concrete root path for locationRoots given a compute location name. It prefers the compute-location-specific root, falls back to "default", and returns an error if neither is present.

func SymbolsFor added in v0.3.0

func SymbolsFor(
	tmpl *JobTemplate, step *StepTemplate, env *Environment, scope Scope, params map[string]string,
) expr.MapSymbols

SymbolsFor is the exported counterpart of symbolsFor, for the one caller outside this package that needs to drive the SAME phase-1/phase-2 symbol-table construction this package uses internally: internal/worker/fmtres's phase-3 "agreement" test (EXPR sub-project E4a), which proves the worker's own phase-3 table types a template's declared parameters identically to this package's phase-2 table -- the design spec's own claim that phases 1-3 are "the same walk with a different table" gets its sharpest test here, and that test needs the REAL phase-2 table, not a hand-reconstructed approximation of it.

This is a direct, unwrapped call -- see symbolsFor's own doc comment for the full contract (what step/env/params being nil means, and the scope gating).

func ValidLocationName

func ValidLocationName(name string) bool

ValidLocationName reports whether name is a referenceable storage-location name — i.e. one that a loc:// URI can address. Names containing whitespace, "/", or quotes are rejected because the loc:// parser cannot match them.

func ValidS3Root added in v0.2.0

func ValidS3Root(root string) bool

ValidS3Root reports whether root is a well-formed s3://bucket[/prefix] URI: it must carry the s3:// scheme, a non-empty bucket segment, and no whitespace in that bucket segment. The optional key prefix after the first "/" is not constrained (object keys are permissive across providers).

func ValidateStepTransition

func ValidateStepTransition(from, to store.StepStatus) error

ValidateStepTransition returns nil if transitioning a step from old to new status is permitted by the state machine, or a descriptive error wrapping ErrInvalidTransition otherwise.

Types

type Action

type Action struct {
	// Command is the executable (may be a format string).
	Command string
	// Args is the optional argument list (each entry may be a format string).
	Args []string
	// ArgsSet records whether the key was present, so a declared but empty
	// list is distinguishable from an omitted one.
	ArgsSet bool
	// TimeoutSeconds, when > 0, limits how long the action may run.
	TimeoutSeconds int
	// TimeoutSet records whether the key was present, so an explicit
	// "timeout: 0" (illegal) is distinguishable from an omitted one (legal).
	TimeoutSet bool
	// Cancelation describes how to stop a running action.
	Cancelation *CancelationMethod
}

Action is an executable command run as part of a step or environment script.

type AmountRequirement

type AmountRequirement struct {
	// Name is the capability name (e.g. "amount.worker.vcpu").
	Name string
	// Min and Max bound the acceptable range.  Nil means no bound.
	// Stored as strings for lossless round-tripping of int and float values.
	Min *string
	Max *string
}

AmountRequirement is a single quantifiable host capability requirement.

type AttributeRequirement

type AttributeRequirement struct {
	// Name is the capability name (e.g. "attr.worker.os.family").
	Name string
	// AnyOf requires the host attribute to match at least one value.
	AnyOf []string
	// AllOf requires the host attribute to match all listed values.
	AllOf []string
}

AttributeRequirement is a categorical host capability requirement.

type CancelationMethod

type CancelationMethod struct {
	// Mode selects the cancelation strategy.
	Mode CancelationMode
	// NotifyPeriodSeconds is the delay between SIGTERM and SIGKILL when Mode is
	// [CancelModeNotifyThenTerminate].  0 means use the spec default (120s for
	// onRun actions, 30s for others).
	NotifyPeriodSeconds int
	// NotifyPeriodSet records whether the key was present, so an explicit zero
	// is distinguishable from an omitted field.
	NotifyPeriodSet bool
}

CancelationMethod configures how a running Action is canceled.

type CancelationMode

type CancelationMode string

CancelationMode is the cancelation strategy for an Action.

const (
	// CancelModeTerminate sends SIGKILL / TerminateProcess immediately.
	CancelModeTerminate CancelationMode = "TERMINATE"
	// CancelModeNotifyThenTerminate sends SIGTERM first, then SIGKILL after
	// NotifyPeriodSeconds.
	CancelModeNotifyThenTerminate CancelationMode = "NOTIFY_THEN_TERMINATE"
)

type ControlType added in v0.2.0

type ControlType string

ControlType is the OpenJD base-spec userInterface control for a job parameter.

const (
	// ControlLineEdit is a single-line text input.
	ControlLineEdit ControlType = "LINE_EDIT"
	// ControlMultilineEdit is a multi-line text input.
	ControlMultilineEdit ControlType = "MULTILINE_EDIT"
	// ControlDropdownList is a dropdown; requires allowedValues.
	ControlDropdownList ControlType = "DROPDOWN_LIST"
	// ControlCheckBox is a two-state checkbox; requires exactly two allowedValues.
	ControlCheckBox ControlType = "CHECK_BOX"
	// ControlHidden hides the parameter from the generated form.
	ControlHidden ControlType = "HIDDEN"
	// ControlSpinBox is a numeric spinner; valid only on INT/FLOAT.
	ControlSpinBox ControlType = "SPIN_BOX"
	// ControlChooseInputFile is a browse-for-an-existing-file dialog; PATH only.
	ControlChooseInputFile ControlType = "CHOOSE_INPUT_FILE"
	// ControlChooseOutputFile is a browse-for-an-output-file dialog; PATH only.
	ControlChooseOutputFile ControlType = "CHOOSE_OUTPUT_FILE"
	// ControlChooseDirectory is a browse-for-a-directory dialog; PATH only.
	ControlChooseDirectory ControlType = "CHOOSE_DIRECTORY"

	// ControlLineEditList edits a list of free-text values; LIST[STRING] only.
	ControlLineEditList ControlType = "LINE_EDIT_LIST"
	// ControlSpinBoxList edits a list of numbers; LIST[INT] and LIST[FLOAT].
	ControlSpinBoxList ControlType = "SPIN_BOX_LIST"
	// ControlCheckBoxList edits a list of booleans; LIST[BOOL] only.
	ControlCheckBoxList ControlType = "CHECK_BOX_LIST"
	// ControlChooseInputFileList browses for existing files; LIST[PATH] only.
	ControlChooseInputFileList ControlType = "CHOOSE_INPUT_FILE_LIST"
	// ControlChooseOutputFileList browses for output files; LIST[PATH] only.
	ControlChooseOutputFileList ControlType = "CHOOSE_OUTPUT_FILE_LIST"
	// ControlChooseDirectoryList browses for directories; LIST[PATH] only.
	ControlChooseDirectoryList ControlType = "CHOOSE_DIRECTORY_LIST"
)

type EmbeddedFile

type EmbeddedFile struct {
	// Name is the identifier used to reference this file.
	Name string
	// Filename is the on-disk name; if empty the worker generates one.
	Filename string
	// FilenameSet records whether the key was present, so an explicitly empty
	// filename is distinguishable from an omitted one.
	FilenameSet bool
	// Data is the file content (may contain format-string references).
	Data string
	// Type is the file-type discriminator.  In jobtemplate-2023-09 the only
	// allowed value is [EmbeddedFileTypeText].  Empty means absent; validation
	// rejects it as required.
	Type EmbeddedFileType
	// Runnable, when true, sets the file's execute permission.
	Runnable bool
	// EndOfLine is "AUTO", "LF", or "CRLF".  Empty means "AUTO".
	EndOfLine string
}

EmbeddedFile is a plain-text file embedded directly in the job template. The worker materializes it to the session working directory before running the associated actions.

type EmbeddedFileType

type EmbeddedFileType string

EmbeddedFileType is the type discriminator for an EmbeddedFile. In jobtemplate-2023-09 the only allowed value is EmbeddedFileTypeText. An empty value means the field was absent in the source document.

const (
	// EmbeddedFileTypeText is the only supported embedded-file type in
	// jobtemplate-2023-09.  It means the file contains UTF-8 plain text.
	EmbeddedFileTypeText EmbeddedFileType = "TEXT"
)

type Environment

type Environment struct {
	// Name is unique within its containing list.
	Name string
	// Description is optional documentation.
	Description string
	// Script defines the onEnter and onExit actions.
	Script *EnvironmentScript
	// Variables are environment variables set for all actions in the session.
	Variables map[string]string
}

Environment is an OpenJD environment block used at the job or step level. Environments are entered once per session and exited in reverse order.

type EnvironmentActions

type EnvironmentActions struct {
	OnEnter *Action
	OnExit  *Action
}

EnvironmentActions are the lifecycle hooks for an Environment. OnEnter is required by the OpenJD spec; only OnExit is optional.

type EnvironmentScript

type EnvironmentScript struct {
	// EmbeddedFiles are plain-text files materialized before actions run.
	EmbeddedFiles []EmbeddedFile
	// EmbeddedFilesSet records whether the key was present, so a declared but
	// empty list is distinguishable from an omitted one.
	EmbeddedFilesSet bool
	// Let holds the raw <LetBinding> strings of this element's let: block
	// (Template Schemas 3.6). The "name = expression" text is parsed during
	// validation, not here, so a malformed binding reports as a
	// ValidationError with a JSON pointer rather than a decode error without
	// one.
	Let []string
	// LetSet records whether the key was present, so a declared but empty
	// list is distinguishable from an omitted one -- 3.6 constrains a
	// DEFINED let: block to at least one element.
	LetSet bool
	// Actions holds the onEnter and onExit lifecycle hooks.
	Actions EnvironmentActions
}

EnvironmentScript holds the runnable actions for an Environment.

type ExprLimits added in v0.3.0

type ExprLimits struct {
	// SubmissionOperations is the section 1.3.10 operation budget for ONE
	// expression evaluation at submission time.
	//
	// CATASTROPHE BOUND. It is one of the two multiplicands in the derived
	// cumulative-operation ceiling (TemplatePositions x SubmissionOperations)
	// and it scales the measured worst-case wall clock of a single request
	// directly: the worst single request measured on this branch is ~17
	// minutes of server CPU at the default 10,000 (E4d's whole-branch review;
	// E4c's ~9.5 minutes came from a payload that leaves a third of the
	// budget unspent), because op-cheap byte-heavy work over the ~900 KB
	// SubmissionMemoryBytes allows to be live spends only a few thousand of
	// those 10,000 operations for tens of milliseconds -- measured, a regex
	// (re_findall) 3,519 for ~50 ms, a case mapping (.title()) 7,034 for
	// ~57 ms, and that same regex twice inside a comprehension 7,048 for
	// ~103 ms; an earlier revision gave ~3,500 operations for the first two
	// alike. Doubling this number roughly doubles that floor, which is why
	// internal/config caps it at one order of magnitude above the default
	// rather than leaving it open-ended.
	//
	// SUPERSEDED BY EXPR SUB-PROJECT H1 -- an earlier revision of the sentence
	// above closed with "Nothing in this package measures TIME, so the only
	// lever on the worst case is this count and the position count." The first
	// half stopped being true 90 lines below, where [ExprLimits.Deadline] now
	// sits, and the second half was the structural reason H1 had to exist at
	// all. A wall-clock backstop (openjd.expr_submission_deadline, default 5s)
	// now stops an evaluation directly, so RAISING THIS NUMBER IS FAR LESS OF A
	// LEVER ON ELAPSED TIME THAN IT LOOKS: at the default deadline a request is
	// cut off at 5s whatever the ~17-minute figure permits. Raise it because a
	// template's expressions genuinely need more operations, not to buy time --
	// and read the deadline's own limits before concluding the ceiling here is
	// what bounds the worst case.
	SubmissionOperations int64

	// SubmissionMemoryBytes is the section 1.3.9 live-byte budget for ONE
	// expression evaluation at submission time.
	//
	// CATASTROPHE BOUND, with a ceiling of one order of magnitude above the
	// default -- the same shape, and the same reasoning, as
	// SubmissionOperations and TemplatePositions. It is what bounds the live
	// string a single evaluation can hold, and therefore how much byte-heavy,
	// operation-cheap work one position can be asked to do.
	//
	// AN EARLIER REVISION OF THIS COMMENT CLAIMED THE CEILING WAS NOT A
	// JUDGEMENT CALL -- that internal/openjd/expr's fixed maxStringBytes
	// (10,000,000) would fire first above it, making a larger value inert.
	// THAT IS FALSE, and it was disproved by measurement in E4d Task 1's
	// review: maxStringBytes bounds ONE PRODUCED STRING, while section
	// 1.3.9's meter bounds the SUM of live values and recurses into
	// containers. `["a"*4000000, "b"*4000000, "c"*4000000]` holds 12,000,192
	// live bytes with no fixed guard firing -- each string is 4 MB, three
	// elements is nowhere near maxElements -- so it is rejected at a 10 MB
	// limit and ACCEPTED at 20 MB. Raising this knob is not inert; it permits
	// proportionally more live memory per evaluation on an unauthenticated
	// path. The number is unchanged; only the reason for it is, and the
	// reason had to change because a false one invites exactly the raise it
	// claimed was harmless.
	SubmissionMemoryBytes int64

	// TemplatePositions is how many expression positions ONE
	// checkTemplateExpressions walk may check.
	//
	// CATASTROPHE BOUND. It is the other multiplicand in the derived
	// cumulative-operation ceiling, and it is the bound that made the walk
	// safe to run at all: before it existed an 84 KB template of ~2,000 args
	// entries cost 11.3 s of CPU per anonymous request, with nothing but the
	// 4 MiB body size bounding it.
	//
	// It also carries a CROSS-BINARY relation the server cannot check on its
	// own: internal/worker/fmtres's MaxAssignmentPositions bounds the same
	// quantity on the host, an assignment's positions are a subset of its
	// template's, and a worker cap BELOW this value is reachable by a template
	// this package ACCEPTED -- failing every task in the job after submission
	// instead of failing the one request that could have reported it. E4c
	// pinned that with TestTemplateBudget_WorkerCapIsNotTighter comparing two
	// CONSTANTS; making both sides configurable made the relation breakable
	// through YAML, which no compile-time test can see. E4d Task 3 closed that
	// at RUNTIME rather than here: workers advertise their caps at
	// registration and internal/scheduler refuses to dispatch an EXPR job to
	// one that is tighter than the value this field carried at acceptance
	// (internal/scheduler/exprcaps.go). Nothing about that gate makes a
	// tighter worker safe -- it makes it visibly unused for EXPR work instead
	// of silently failing every task.
	TemplatePositions int64

	// TemplateRetainedBytes is how many bytes every let: block in the template
	// may cumulatively RETAIN across one walk -- summed over the whole call,
	// not reset per block. Every other position discards its result; let is
	// the only construct that keeps one.
	//
	// POLICY BOUND, and the only one of the four. Its absence did not produce
	// a measured catastrophe on its own: E3's 6.9 GB / 1.45 s construction was
	// closed by enforcing maxLetBindings at the evaluator (making a single
	// block's cost O(cap)), and a block's transient ceiling is already
	// maxLetBindings x SubmissionMemoryBytes regardless of what this number
	// says. What this bounds is the SUM across many individually-compliant
	// blocks, which a template with many steps can legitimately grow -- so an
	// operator with an unusual workload has a real reason to move it, in
	// either direction, and internal/config gives it a wide but finite range
	// rather than a ceiling tied to a measurement.
	TemplateRetainedBytes int64

	// Deadline, when non-zero, is an absolute wall-clock time after which
	// evaluation stops with [expr.ErrDeadlineExceeded].
	//
	// IT IS NOT ONE OF THE FOUR. Unlike every other field here it is
	// per-REQUEST rather than operator configuration -- it is computed at the
	// top of one submission from the configured duration, so two requests
	// arriving a second apart carry different values. It is also not a
	// VALIDITY bound: the four numbers above decide whether a template is
	// INVALID (a 422), while this decides only whether this server keeps
	// working on it (a 503). See [ValidateWithBudget].
	//
	// It lives on this struct because this struct is already the budget bundle
	// threaded to every evaluation, and adding a parameter to
	// [ExprLimits.evalOptions] would touch its ~25 call sites to no benefit.
	// It is deliberately EXEMPT from [ExprLimits.orDefaults]' "<= 0 means
	// unset, use the default" rule, which has no meaning for a time: the zero
	// time means NO deadline, and that is the default.
	//
	// BEING PER-REQUEST, IT MUST NEVER BE SET ON A LONG-LIVED ExprLimits.
	// [SubmitterOptions.ExprLimits] is the trap: it is read once at server boot
	// into a [Submitter] reused for every subsequent submission, so a deadline
	// stored there is a single absolute instant that every later request is
	// measured against -- accepting nothing at all once it passes. See that
	// field's own comment for what the submission path needs instead.
	Deadline time.Time
}

ExprLimits bounds what one submitted template may spend inside the EXPR expression checker: the four operator-configurable numbers of sub-project E4d, lifted out of package constants so an operator can size them, plus sub-project H1's per-request ExprLimits.Deadline.

The four numbers split into two per-EVALUATION bounds (SubmissionOperations, SubmissionMemoryBytes -- what ONE expression position may cost, section 1.3.10 and section 1.3.9 respectively) and two per-WALK bounds (TemplatePositions, TemplateRetainedBytes -- what the WHOLE template may cost across one checkTemplateExpressions call). See each field's own comment, and the long rationale blocks in exprcheck.go that each field's DEFAULT still carries.

The fifth field is none of those things and is documented as such on itself: it is per-REQUEST rather than operator configuration, it measures TIME rather than counting anything, and it decides whether this server keeps working (503) rather than whether the template is valid (422). It rides on this struct because this struct is the bundle already threaded to every evaluation. Phrases like "the four" below mean the four numbers, and deliberately exclude it.

A ZERO field means "unset, use the default" -- see [ExprLimits.orDefaults]. That is deliberate and it is what keeps every existing ValidateOptions{EnforceLimits: ...} literal in this repo (and every caller that has no operator configuration to offer, e.g. internal/product's ValidateTemplate) behaving byte for byte as it did before this type existed. It also means a NEGATIVE value is not silently accepted as "unlimited": orDefaults treats anything <= 0 as unset, and internal/config's validateOpenJD 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 here -- they live in internal/config (MinOpenJDExpr*/MaxOpenJDExpr*) and are rejected at load, because internal/config is the layer that owns operator-facing policy and this package must stay importable from it-free code. This type accepts any positive value so that a test can deliberately set an absurd one to prove a knob is wired (which is exactly how this wave's mutation tests work).

func DefaultExprLimits added in v0.3.0

func DefaultExprLimits() ExprLimits

DefaultExprLimits returns the four values this package used as fixed constants before E4d, and which internal/config's OpenJDConfig defaults to. A server started with no expression-limit configuration behaves 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], for the one production caller outside this package that needs the values a walk would ACTUALLY enforce rather than the ones a config literal happens to carry: internal/scheduler compares them against each worker's advertised EXPR caps before dispatching an EXPR job (EXPR sub-project E4d Task 3). Comparing an un-normalized zero would report a shortfall of "0", i.e. no shortfall at all, in every dimension the caller left unset.

type Extension added in v0.2.0

type Extension struct {
	// Name is the OpenJD extension identifier, matching [A-Z_0-9]{3,128}.
	Name string
	// Origin is official (upstream OpenJD) or vendor (sqi-defined).
	Origin Origin
	// Status is the implementation status, e.g. "supported".
	Status string
	// Summary is a one-line description.
	Summary string
	// DocPath points at the extension's contribution doc, repo-relative.
	DocPath string
}

Extension is one entry in the supported-extension registry.

func LookupExtension added in v0.2.0

func LookupExtension(name string) (Extension, bool)

LookupExtension returns the registry entry for name and whether it exists.

type Format

type Format int

Format identifies the wire format of a raw template submission.

const (
	// FormatYAML means the raw bytes are YAML.
	FormatYAML Format = iota
	// FormatJSON means the raw bytes are JSON.
	FormatJSON
)

type HostRequirements

type HostRequirements struct {
	// Amounts are quantifiable requirements such as CPUs, RAM, or software slots.
	Amounts []AmountRequirement
	// Attributes are categorical requirements such as OS or CPU architecture.
	Attributes []AttributeRequirement
}

HostRequirements declares the worker capabilities required by a step.

type ItemConstraint added in v0.3.0

type ItemConstraint struct {
	// AllowedValues enumerates the only acceptable element values.
	AllowedValues []string
	// AllowedValuesSet records whether the key was PRESENT, for the same
	// reason [JobParameter.AllowedValuesSet] does: a declared list must hold
	// at least one value, but omitting it entirely is legal, and both decode
	// to an empty slice.
	AllowedValuesSet bool
	// MinValue and MaxValue bound a numeric element. Stored as strings for
	// lossless round-tripping, as on [JobParameter].
	MinValue *string
	MaxValue *string
	// MinLength and MaxLength bound a string-like element's length or — when
	// this constraint describes an inner LIST — that list's element count.
	MinLength *int
	MaxLength *int
	// Item constrains the elements of an inner list. Non-nil only for
	// LIST[LIST[INT]]; nil at the innermost level.
	Item *ItemConstraint
}

ItemConstraint constrains the ELEMENTS of a LIST[*] job parameter, and — one level deeper, through its own Item field — the elements of the inner lists of a LIST[LIST[INT]].

It mirrors the type nesting so each level reuses the same property names as the equivalent scalar type: MinLength/MaxLength for string-like items, MinValue/MaxValue for numeric ones (RFC 0007, "Nested Item Constraints", which records that the rejected alternative was flat names like minItemValue — abandoned because LIST[LIST[INT]] would have needed minItemIntValue).

Which fields are LEGAL at a given level depends on the element type and is enforced by validation, not here: the decoder's job is to record what the template said so that an error can name it.

Nesting is capped at one level, matching the RFC's own limit of list[list[T]] and no deeper.

type JobParamType

type JobParamType string

JobParamType is the discriminator for a JobParameter.

const (
	// JobParamTypeInt is a 64-bit integer parameter.
	JobParamTypeInt JobParamType = "INT"
	// JobParamTypeFloat is a decimal (float64) parameter.
	JobParamTypeFloat JobParamType = "FLOAT"
	// JobParamTypeString is an arbitrary UTF-8 string parameter.
	JobParamTypeString JobParamType = "STRING"
	// JobParamTypePath is a filesystem or S3 path parameter.
	JobParamTypePath JobParamType = "PATH"

	// JobParamTypeBool is a boolean parameter. Unlike every other type it
	// forbids allowedValues: restricting a two-valued domain to one value
	// carries no meaning (RFC 0007, <JobBoolParameterDefinition>).
	JobParamTypeBool JobParamType = "BOOL"
	// JobParamTypeRangeExpr is an <IntRangeExpr> string parameter, e.g.
	// "1-100:2,200". Its default is validated with the SPEC's permissive range
	// policy, not internal/openjd's stricter one -- see
	// validateRangeExprParamConstraints for why the two differ here.
	JobParamTypeRangeExpr JobParamType = "RANGE_EXPR"

	// JobParamTypeListString is a list of strings. Like every list type its
	// default is stored as canonical JSON in [JobParameter.Default]; see
	// paramjson.go for that encoding and for why a list value does not get a
	// typed field of its own.
	JobParamTypeListString JobParamType = "LIST[STRING]"
	// JobParamTypeListPath is a list of paths. It is the only list type whose
	// RawParam form differs from its Param form (list[string] rather than
	// list[path]), because path mapping applies per element.
	JobParamTypeListPath JobParamType = "LIST[PATH]"
	// JobParamTypeListInt is a list of 64-bit integers.
	JobParamTypeListInt JobParamType = "LIST[INT]"
	// JobParamTypeListFloat is a list of decimals.
	JobParamTypeListFloat JobParamType = "LIST[FLOAT]"
	// JobParamTypeListBool is a list of booleans, each accepting the same
	// spellings as [JobParamTypeBool].
	JobParamTypeListBool JobParamType = "LIST[BOOL]"
	// JobParamTypeListListInt is a list of lists of integers -- the deepest
	// nesting RFC 0007 allows. Its identified use case is programmatic (graph
	// adjacency lists), which is why the RFC gives it no user-interface
	// control of its own beyond HIDDEN.
	JobParamTypeListListInt JobParamType = "LIST[LIST[INT]]"
)

type JobParameter

type JobParameter struct {
	// Name is the parameter identifier; must match [A-Za-z_][A-Za-z0-9_]*.
	Name string
	// Type discriminates INT / FLOAT / STRING / PATH.
	Type JobParamType
	// Description is optional documentation shown in UI elements.
	Description string
	// Default is the value used when the submitter does not provide one.
	// Stored as a string regardless of Type to avoid lossy conversion.
	// Nil means no default (parameter is required).
	Default *string
	// AllowedValues, when non-nil, enumerates the only acceptable values.
	AllowedValues []string
	// AllowedValuesSet records whether the key was PRESENT in the template.
	// "allowedValues: null" and "allowedValues: []" both decode to an empty
	// slice, which is indistinguishable from the key being absent — but the
	// spec allows omitting the list entirely while requiring a declared one to
	// hold at least one value.
	AllowedValuesSet bool
	// MinValue / MaxValue constrain INT and FLOAT parameters.
	// Stored as strings for lossless round-tripping.
	MinValue *string
	MaxValue *string
	// MinLength / MaxLength constrain STRING and PATH parameters.
	MinLength *int
	MaxLength *int
	// ObjectType narrows how the PATH value is interpreted: FILE or DIRECTORY.
	// Empty means absent; the spec default is DIRECTORY.
	// Only valid for PATH parameters; validation rejects it on other types.
	ObjectType PathObjectType
	// DataFlow describes the data-flow direction of the PATH value.
	// Empty means absent; the spec default is NONE.
	// Only valid for PATH parameters; validation rejects it on other types.
	DataFlow PathDataFlow
	// UserInterface carries optional OpenJD base-spec presentation hints.
	// Nil when the parameter declares no userInterface object.
	UserInterface *ParameterUserInterface
	// FileFilters are the file-type choices offered by a CHOOSE_*_FILE dialog.
	// Only valid on PATH parameters; validation rejects them on other types.
	FileFilters []PathFileFilter
	// FileFilterDefault is the filter selected when the dialog opens.
	// Only valid on PATH parameters. Nil when absent.
	FileFilterDefault *PathFileFilter
	// Item constrains the ELEMENTS of a LIST[*] parameter. Nil for a scalar
	// type, or when the template declares no item: block.
	Item *ItemConstraint
}

JobParameter is one entry in JobTemplate.ParameterDefinitions.

type JobTemplate

type JobTemplate struct {
	// SpecificationVersion must equal [SpecVersion].
	SpecificationVersion string

	// Name is the human-readable job name.  Required; may contain format-string
	// references such as "Render {{Param.SceneName}}".
	Name string

	// Description is an optional free-form description (no functional effect).
	Description string

	// Extensions is the optional list of named OpenJD feature extensions to
	// enable (e.g. "feature-bundle-1").
	Extensions []string
	// ExtensionsSet records whether the key was present, so a declared but
	// empty list is distinguishable from an omitted one.
	ExtensionsSet bool
	// UnknownFields are top-level keys the schema does not define. Carried from
	// the decoder so validation can reject them; the spec's job template is a
	// closed object.
	UnknownFields []string

	// PathTranslation is the parsed SQI_PATH_TRANSLATION extension block, or nil
	// when the extension is not declared.
	PathTranslation *PathTranslation

	// ParameterDefinitions declares the job-level parameters that submitters
	// must or may provide.  Parameter names must be unique.
	ParameterDefinitions []JobParameter
	// ParameterDefinitionsSet records whether the key was present, so a
	// declared but empty list is distinguishable from an omitted one.
	ParameterDefinitionsSet bool

	// JobEnvironments are environments that wrap every session in this job.
	// They are entered in order and exited in reverse order.
	JobEnvironments []Environment

	// Steps is the ordered list of step definitions.  At least one step is
	// required.
	Steps []StepTemplate
}

JobTemplate is the root document of an OpenJD submission.

func Parse

func Parse(data []byte, f Format) (*JobTemplate, error)

Parse decodes raw YAML or JSON bytes into a JobTemplate. It returns a low-level decode error for malformed documents; call Validate afterward to check semantic correctness.

type LocRef

type LocRef struct {
	// LocationName is the symbolic storage-location name (e.g. "nas_shows").
	LocationName string
	// RelPath is the path portion after the location name, including the
	// leading slash, or empty for a bare root reference (e.g. "loc://nas_shows").
	RelPath string
	// Raw is the full original URI string.
	Raw string
}

LocRef is a single named-location reference extracted from a template string.

func ExtractLocRefs

func ExtractLocRefs(s string) []LocRef

ExtractLocRefs scans s for all loc:// URI occurrences and returns them in order of appearance. Duplicates are not deduplicated.

type Origin added in v0.2.0

type Origin string

Origin distinguishes an upstream OpenJD extension from one defined by sqi.

const (
	// OriginOfficial marks an extension defined by the upstream OpenJD spec.
	OriginOfficial Origin = "official"
	// OriginVendor marks an extension defined by sqi. Vendor extension names
	// MUST carry the SQI_ prefix so they can never collide with a future
	// official OpenJD name; if upstreamed, the prefix is dropped and the entry
	// flips to OriginOfficial (the "promotion path").
	OriginVendor Origin = "vendor"
)

type ParameterUserInterface added in v0.2.0

type ParameterUserInterface struct {
	// Control selects the input widget.
	Control ControlType
	// Label is the human-readable field label.
	Label string
	// GroupLabel groups related fields in the generated form.
	GroupLabel string
	// Decimals sets the precision for a SPIN_BOX on a FLOAT parameter.
	Decimals *int
	// SingleStepDelta is the increment a SPIN_BOX applies per step. Held as a
	// string so validation can tell an integer from a float: an INT parameter's
	// delta must itself be an integer.
	SingleStepDelta *string
	// LabelSet and GroupLabelSet record whether the key was PRESENT in the
	// template, as opposed to merely empty. Both fields are optional, but an
	// explicitly empty one is invalid, and the string alone cannot tell the two
	// apart.
	LabelSet      bool
	GroupLabelSet bool
}

ParameterUserInterface is the OpenJD base-spec userInterface hint object on a job parameter. It is presentation metadata consumed by submission UIs; the server parses, validates, and carries it but does not act on it.

type PathDataFlow

type PathDataFlow string

PathDataFlow is the dataFlow discriminator for a PATH JobParameter. An empty value means the field was not set; the OpenJD spec default when absent is NONE. Only valid on PATH parameters.

const (
	// PathDataFlowNone means the path has no specific data-flow direction.
	// This is the spec default when dataFlow is absent.
	PathDataFlowNone PathDataFlow = "NONE"
	// PathDataFlowIn means the path is read as input by the job.
	PathDataFlowIn PathDataFlow = "IN"
	// PathDataFlowOut means the path is written as output by the job.
	PathDataFlowOut PathDataFlow = "OUT"
	// PathDataFlowInOut means the path is both read and written.
	PathDataFlowInOut PathDataFlow = "INOUT"
)

type PathDelivery added in v0.2.0

type PathDelivery struct {
	Kind PathDeliveryKind
	// Pattern is the flag template for DeliveryCommandFlags (uses {src}/{dest}).
	Pattern string
	// Variable is the environment variable name for DeliveryEnvironment.
	Variable string
}

PathDelivery is one enabled delivery plus its optional settings.

func DefaultPathDeliveries added in v0.2.0

func DefaultPathDeliveries() []PathDelivery

DefaultPathDeliveries is the implicit delivery set used when the extension is not declared: today's automatic behavior (swap in place + translation file).

type PathDeliveryKind added in v0.2.0

type PathDeliveryKind string

PathDeliveryKind identifies one path-delivery mechanism of the SQI_PATH_TRANSLATION extension.

const (
	// DeliverySwapInPlace substitutes concrete paths into the command/args.
	DeliverySwapInPlace PathDeliveryKind = "swap_in_place"
	// DeliveryTranslationFile writes the OpenJD pathmapping-1.0 file.
	DeliveryTranslationFile PathDeliveryKind = "translation_file"
	// DeliveryCommandFlags appends per-pair flags rendered from Pattern.
	DeliveryCommandFlags PathDeliveryKind = "command_flags"
	// DeliveryEnvironment sets Variable to the joined src=dest pairs.
	DeliveryEnvironment PathDeliveryKind = "environment"
	// DeliveryStageLocally copies inputs to worker-local scratch.
	DeliveryStageLocally PathDeliveryKind = "stage_locally"
)

type PathFileFilter added in v0.3.0

type PathFileFilter struct {
	// Label names the filter in the chooser dialog. Unlike a parameter's
	// userInterface label/groupLabel, this field has no enforced length cap.
	Label string
	// Patterns are the glob patterns the filter matches; at least one required.
	Patterns []string
}

PathFileFilter is one named file type offered by an input or output file chooser dialog, e.g. {label: "Image Files", patterns: ["*.png", "*.exr"]}. It is presentation metadata: the server parses, validates, and carries it but never acts on it.

type PathObjectType

type PathObjectType string

PathObjectType is the objectType discriminator for a PATH JobParameter. An empty value means the field was not set; the OpenJD spec default when absent is DIRECTORY. Only valid on PATH parameters.

const (
	// PathObjectTypeFile means the path refers to a regular file.
	PathObjectTypeFile PathObjectType = "FILE"
	// PathObjectTypeDirectory means the path refers to a directory.
	// This is the spec default when objectType is absent.
	PathObjectTypeDirectory PathObjectType = "DIRECTORY"
)

type PathTranslation added in v0.2.0

type PathTranslation struct {
	Deliveries []PathDelivery
}

PathTranslation is the parsed SQI_PATH_TRANSLATION block.

type Scope added in v0.3.0

type Scope int

Scope identifies the symbol environment of a template position: which symbols exist there, and whether the position runs on a worker host.

This is the SINGLE declaration of scope in the package. It has two consumers, which is the whole point:

  • The EXPR path builds a typed symbol table from it, so a reference to a symbol the scope does not expose fails as an unknown symbol from the evaluator rather than from a second, parallel mechanism.
  • The base-spec path keeps prefix-matching, against prefixes DERIVED from this declaration (derivedPrefixes) rather than a hand-maintained list.

Before E2 the base-spec prefixes were three literals in validate.go. Keeping them AND an EXPR scope model would put scope knowledge in two places, which is the shape of a drift this program has already been bitten by once.

const (
	// ScopeJob is a submission-time position with no session or task context:
	// the job's own name, host requirements, and a step's parameter space.
	ScopeJob Scope = iota
	// ScopeJobEnvironment is a job-level environment's script and variables.
	ScopeJobEnvironment
	// ScopeStepEnvironment is a step-level environment's script and variables.
	// It differs from ScopeJobEnvironment by exactly one symbol, Step.Name,
	// which is EXPR-only -- see derivedPrefixes.
	ScopeStepEnvironment
	// ScopeStepScript is a step script's actions and embedded files.
	ScopeStepScript
	// ScopeStepTemplate is a step template's own let: block (Template Schemas
	// section 3.6.2 row 1), evaluated at submission before any host exists.
	// It is not derivable from any other scope: ScopeJob is the closest
	// (also submission-time) but exposes neither Job.Name nor Step.Name,
	// while this scope needs both -- and unlike every host-context scope it
	// gets no Session.*, no Task.* and no Env.File.*. Appended at the end so
	// the four scopes above keep their existing values.
	ScopeStepTemplate
)

func (Scope) IsHostContext added in v0.3.0

func (s Scope) IsHostContext() bool

IsHostContext reports whether expressions in this scope are evaluated on a worker host, where session state exists.

It gates the host-context-only functions. The specification does NOT commit to a single such function: its FunctionLibrary.with_host_context() enables "host-only functions like apply_path_mapping()" (wiki 2026-02-Expression-Language.md:514). apply_path_mapping is the only one in sqi's registry today because it is the only function that reads session state; the gate is a set (hostOnlyFunctions, exprcheck.go) rather than a name comparison so a second entrant costs one edit. (RFC 0005's "Host-Context Function Availability" states the rule at more length, but the RFC is the proposal behind the specification, not the specification -- see hostOnlyFunctions' own comment.)

This is deliberately an explicit positive list of the host-context scopes, not a negation of the non-host ones. A negation (originally "s != ScopeJob") is an every-scope-but-this-one claim: it is correct only for as long as every scope added later happens to be a host context, which is not a property Go's type system -- or anything else -- enforces. A positive list fails CLOSED: a sixth scope that nobody adds a case for here is simply not a host context, and apply_path_mapping stays unavailable there until someone deliberately decides otherwise. ScopeStepTemplate is the case that exposed the negation as wrong -- it is not ScopeJob, so "s != ScopeJob" would have silently granted it host-only functions despite section 3.6.2 row 1 placing it at submission time, before any host exists.

func (Scope) String added in v0.3.0

func (s Scope) String() string

type StepActions

type StepActions struct {
	// OnRun is executed once per task.
	OnRun Action
}

StepActions holds the lifecycle actions for tasks of a step.

type StepDependency

type StepDependency struct {
	// DependsOn is the name of the prerequisite step.
	DependsOn string
}

StepDependency names a step that must reach store.StepStatusCompleted before this step's tasks may be scheduled.

type StepParameterSpace

type StepParameterSpace struct {
	// TaskParameterDefinitions declares all task parameters.  1–16 entries.
	TaskParameterDefinitions []TaskParamDefinition
	// Combination is an optional expression that controls how parameter ranges
	// are combined.  Identifiers connected with * form a Cartesian product;
	// identifiers grouped in parentheses (A,B,C) are zipped (association).
	// When nil, all parameters are joined with *.
	Combination *string
}

StepParameterSpace defines the multidimensional task parameter space for a step. Expanding it via ExpandParameterSpace yields one TaskParams per task.

type StepScript

type StepScript struct {
	// EmbeddedFiles are plain-text files written to disk before each action.
	EmbeddedFiles []EmbeddedFile
	// EmbeddedFilesSet records whether the key was present, so a declared but
	// empty list is distinguishable from an omitted one.
	EmbeddedFilesSet bool
	// Let holds the raw <LetBinding> strings of this element's let: block
	// (Template Schemas 3.6). The "name = expression" text is parsed during
	// validation, not here, so a malformed binding reports as a
	// ValidationError with a JSON pointer rather than a decode error without
	// one.
	Let []string
	// LetSet records whether the key was present, so a declared but empty
	// list is distinguishable from an omitted one -- 3.6 constrains a
	// DEFINED let: block to at least one element.
	LetSet bool
	// Actions holds the task lifecycle hooks.
	Actions StepActions
}

StepScript is the executable definition attached to a StepTemplate.

type StepTemplate

type StepTemplate struct {
	// Name identifies this step; must be unique within the job.
	Name string
	// Description is optional documentation.
	Description string
	// Script is the executable definition of the step's tasks.
	Script *StepScript
	// StepEnvironments are per-step environments entered after job environments.
	StepEnvironments []Environment
	// StepEnvironmentsSet records whether the key was present, so a declared
	// but empty list is distinguishable from an omitted one.
	StepEnvironmentsSet bool
	// ParameterSpace defines the task parameter combinations for this step.
	// Nil means the step produces exactly one task with no parameters.
	ParameterSpace *StepParameterSpace
	// HostRequirements declares the host capabilities required by this step.
	HostRequirements *HostRequirements
	// Dependencies lists the steps that must complete before this one starts.
	Dependencies []StepDependency
	// DependenciesSet records whether the key was present, so a declared but
	// empty list is distinguishable from an omitted one.
	DependenciesSet bool
	// Let holds the raw <LetBinding> strings of this element's let: block
	// (Template Schemas 3.6). The "name = expression" text is parsed during
	// validation, not here, so a malformed binding reports as a
	// ValidationError with a JSON pointer rather than a decode error without
	// one.
	Let []string
	// LetSet records whether the key was present, so a declared but empty
	// list is distinguishable from an omitted one -- 3.6 constrains a
	// DEFINED let: block to at least one element.
	LetSet bool
}

StepTemplate defines one step within a JobTemplate.

type SubmitOptions

type SubmitOptions struct {
	// FarmID is the farm this job belongs to. Required.
	FarmID string
	// QueueID is the queue this job is placed in. Required.
	QueueID string
	// Owner is the human responsible for the job (e.g. artist login name).
	Owner string
	// Submitter is the authenticated identity that placed the job (e.g. a
	// service account or API token owner). May differ from Owner.
	Submitter string
	// Priority overrides the default priority (50). Values ≤ 0 are treated as
	// the default.
	Priority int
	// Project is an optional label for grouping jobs in the UI and API.
	Project string
	// Name overrides the job name. When empty, the template's own name
	// (tmpl.Name) is used. Lets callers (e.g. product submissions) give each
	// job a distinct, human-meaningful name without editing the template.
	Name string
	// Parameters holds the caller-supplied values for job-level parameters
	// declared in the template's parameterDefinitions.  Keys are parameter
	// names; values are raw strings.  Missing entries are filled from each
	// parameter's Default; parameters with neither a supplied value nor a
	// default produce a [SubmitValidationError].
	Parameters map[string]string
	// MaxAttempts, RetryDelaySeconds, and FailureLimit are optional per-job
	// retry overrides. Nil means inherit (queue -> farm -> server default).
	MaxAttempts       *int
	RetryDelaySeconds *int
	FailureLimit      *int
	// Deadline, when non-zero, is an absolute wall-clock time after which this
	// submission's expression evaluation stops and [Submitter.Submit] returns
	// an error wrapping [expr.ErrDeadlineExceeded] -- EXPR sub-project H1's
	// backstop.
	//
	// It lives HERE, on the per-call options, and not on
	// [SubmitterOptions.ExprLimits], because it is an ABSOLUTE instant and a
	// Submitter is built once at server boot: a deadline stored there would be
	// one instant computed at boot, failing every submission that arrived
	// after it, forever. Compute it per request from the operator's configured
	// DURATION (config's openjd.expr_submission_deadline) at the top of the
	// handler -- internal/api does exactly that.
	//
	// The zero value -- what every caller but a submission handler passes --
	// means no deadline and costs the evaluator nothing.
	//
	// A breach is NOT a *SubmitValidationError. That type is the client-fault
	// channel; a wall-clock stop is this server giving up on a template that
	// might be perfectly valid, so the two must stay tellable apart by
	// errors.Is/errors.As at the HTTP boundary (503, not 422).
	Deadline time.Time

	// DependsOn lists the IDs of upstream jobs this job must wait for (whole-job
	// cross-job dependencies). Each must already exist and be in the same farm;
	// none may already be failed or canceled. When any is not yet completed, the
	// job is created in store.JobStatusBlocked with all tasks held pending.
	DependsOn []string
}

SubmitOptions carries the caller-supplied metadata attached to a job at submission time. All fields are optional except FarmID and QueueID.

type SubmitResult

type SubmitResult struct {
	// Job is the persisted job row, including the verbatim raw template.
	Job store.Job
	// Steps holds the persisted step rows in template order.
	Steps []store.Step
	// Tasks holds all persisted task rows across all steps.
	Tasks []store.Task
	// BoundParameters is the fully-resolved name→value map produced by
	// [BindJobParameters].  Defaults from the template are merged in; every
	// declared parameter is guaranteed to have an entry here.
	// Later tasks ({{Param.*}} resolution, worker carry) consume this map.
	BoundParameters map[string]string
}

SubmitResult is returned by Submitter.Submit and holds every persisted row created during submission.

type SubmitValidationError

type SubmitValidationError struct {
	// Cause is the underlying parse, validation, or storage-location error.
	Cause error
}

SubmitValidationError is returned by Submitter.Submit when the job template fails to parse, fails OpenJD validation, or references storage locations that are not registered or lack the required root coverage.

The REST layer maps this error type to HTTP 422 (Unprocessable Entity) via errors.As so that callers get a precise status code regardless of how the underlying error message is phrased.

func (*SubmitValidationError) Error

func (e *SubmitValidationError) Error() string

func (*SubmitValidationError) Unwrap

func (e *SubmitValidationError) Unwrap() error

type Submitter

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

Submitter handles the full OpenJD submission pipeline: parse, validate, expand the parameter space, persist the normalized job/step/task rows alongside the verbatim raw template, and enforce storage-location coverage.

Create one with NewSubmitter or NewSubmitterWithOptions and reuse it across requests.

func NewSubmitter

func NewSubmitter(st store.Store) *Submitter

NewSubmitter returns a Submitter backed by st with default options (EnforceLimits: true). The store must implement store.StorageLocationStore (which store.Store always does) so that named-location references in submitted templates can be validated at submission time.

func NewSubmitterWithOptions

func NewSubmitterWithOptions(st store.Store, opts SubmitterOptions) *Submitter

NewSubmitterWithOptions returns a Submitter backed by st with the supplied options. Use this when the caller needs to control SubmitterOptions.EnforceLimits based on operator configuration.

func (*Submitter) Submit

func (s *Submitter) Submit(
	ctx context.Context,
	rawTemplate string,
	format store.TemplateFormat,
	opts SubmitOptions,
) (*SubmitResult, error)

Submit parses rawTemplate, validates it, expands each step's parameter space into concrete tasks, and persists:

  • one store.Job row containing rawTemplate verbatim
  • one store.Step row per step in the template
  • one store.Task row per element of the parameter-space expansion

Steps whose DependsOn list is empty start in store.StepStatusReady; steps with dependencies start in store.StepStatusPending. Tasks inherit their step's initial status.

Everything one submission creates — the job row, its cross-job dependency edges, every step and every task — is written by a single store.JobStore.CreateJobSubmission call, which is atomic on both store backends. A failure at any point therefore leaves nothing behind: there is no orphaned pending job for a sweep to reap, and no job missing the steps that failed to write (which checkJobCompletion, deriving job status from the steps that exist, would have reported completed).

Expansion runs to completion before that write, so a template that cannot expand never reaches the store at all. That also bounds what a breach of [maxTasksPerJob] costs: an over-cap job is rejected during expansion, so it neither materializes its rows nor writes any.

type SubmitterOptions

type SubmitterOptions struct {
	// EnforceLimits controls whether quantitative OpenJD limit checks are run
	// during validation.  Mirrors [ValidateOptions.EnforceLimits].
	// Defaults to true when using [NewSubmitter].
	EnforceLimits bool

	// ExprLimits carries the operator-configured EXPR expression limits
	// (sub-project E4d) into BOTH phases this pipeline runs: phase 1, through
	// the [ValidateOptions] prepareTemplate builds, and phase 2, through the
	// two [templateBudget]s it allocates for checkExpressionsAtSubmit and for
	// every step's ResolveParameterSpaceParams call.
	//
	// The zero value means "use the defaults" ([ExprLimits.orDefaults]), so
	// [NewSubmitter] and every existing SubmitterOptions literal keep the
	// pre-E4d behavior unchanged.
	//
	// DO NOT SET [ExprLimits.Deadline] HERE. It is the one field of ExprLimits
	// that is per-REQUEST rather than operator configuration -- an ABSOLUTE
	// time, not a duration -- and this struct is read exactly once, by
	// [NewSubmitterWithOptions] at server boot, into a Submitter that is reused
	// for the process's whole life. Both phase-2 budgets are built from that
	// stored copy (prepareTemplate's checkerBudget and resolverBudget), so a
	// deadline set here would be one absolute instant computed at boot: every
	// submission arriving after it would fail with expr.ErrDeadlineExceeded
	// forever, and every submission before it would get a budget shrinking
	// toward zero. It is also the shortest-looking way to satisfy H1's Task 3,
	// which is why this warning is here rather than left to be discovered.
	//
	// The deadline lives on the per-call path instead, and already does:
	// [SubmitOptions.Deadline], threaded through [Submitter.prepareTemplate]
	// and copied onto the ExprLimits behind phase 1's [ValidateWithBudget]
	// call and behind both phase-2 budgets. internal/api computes it from the
	// configured DURATION at the top of each request.
	//
	// As the code stands a Deadline set here is INERT rather than harmful --
	// every one of those three copies overwrites the field with the request's
	// own value, zero included -- but that is a property of three call sites,
	// not a guarantee, and the failure it would cause if one of them stopped
	// overwriting is silent and total. Leave it zero.
	ExprLimits ExprLimits
}

SubmitterOptions carries optional configuration for a Submitter.

type TaskChunks

type TaskChunks struct {
	// DefaultTaskCount is the number of INT values to group per task.
	DefaultTaskCount int
	// TargetRuntimeSeconds is parsed and carried but not acted on. The spec
	// permits this explicitly: "A scheduler can ignore this, or dynamically
	// adjust the chunk task count to be closer to this value."
	TargetRuntimeSeconds *int
	// RangeConstraint is "CONTIGUOUS" or "NONCONTIGUOUS"; required, validated
	// in [validateChunks].
	RangeConstraint string
}

TaskChunks configures chunked task grouping for a CHUNK[INT] parameter.

type TaskParamDefinition

type TaskParamDefinition struct {
	// Name is the parameter identifier.
	Name string
	// Type discriminates INT / FLOAT / STRING / PATH / CHUNK[INT].
	Type TaskParamType
	// RangeExpr holds the raw range string for INT and CHUNK[INT] parameters
	// when the template uses range expression syntax (e.g. "1-100:2").
	// Exactly one of RangeExpr or RangeList is set for each definition.
	//
	// Under the EXPR extension, section 1.3.12 extends this field for EVERY
	// type (not only INT/CHUNK[INT]): a whole-field `range: "{{ <expr> }}"`
	// decodes here the same way for any type — parse.go's decoder does not
	// distinguish by type — so a STRING or FLOAT definition can carry a
	// non-nil RangeExpr too, holding a lone expression that evaluates to a
	// list. ResolveParameterSpaceParams (resolve.go) is what converts that
	// case into RangeList, clearing RangeExpr, before expand.go ever sees it
	// — expandTaskParam only ever consults RangeExpr for INT/CHUNK[INT].
	RangeExpr *string
	// RangeList holds the explicit value list for all other types, and also for
	// INT/CHUNK[INT] when the template provides an array of values.
	RangeList []string
	// Chunks is non-nil only for CHUNK[INT] parameters.
	Chunks *TaskChunks
}

TaskParamDefinition is one parameter declaration in a StepParameterSpace.

type TaskParamType

type TaskParamType string

TaskParamType is the discriminator for a TaskParamDefinition.

const (
	// TaskParamTypeInt is an integer task parameter.
	TaskParamTypeInt TaskParamType = "INT"
	// TaskParamTypeFloat is a float task parameter.
	TaskParamTypeFloat TaskParamType = "FLOAT"
	// TaskParamTypeString is a string task parameter.
	TaskParamTypeString TaskParamType = "STRING"
	// TaskParamTypePath is a path task parameter.
	TaskParamTypePath TaskParamType = "PATH"
	// TaskParamTypeChunkInt is a chunked integer task parameter that groups
	// multiple frame values into a single task.
	TaskParamTypeChunkInt TaskParamType = "CHUNK[INT]"
)

type TaskParams

type TaskParams map[string]string

TaskParams is one materialized row from a step's parameter-space expansion. Keys are parameter names; values are their string representations. An empty map means the step has no parameters (produces a single task).

func ExpandParameterSpace

func ExpandParameterSpace(ps *StepParameterSpace) ([]TaskParams, error)

ExpandParameterSpace materializes a step's parameter space into the concrete set of task parameter maps that the scheduler will use to create individual tasks.

When ps is nil the step has a zero-dimensional parameter space: a single task is produced with an empty TaskParams map.

The combination expression (if provided) controls how parameter ranges are joined:

  • Identifiers separated by * form a Cartesian product (outer join).
  • Identifiers grouped in parentheses (A,B,C) are zipped (inner join / association). All parameters in a group must have the same range length.

If no combination expression is provided, all parameters are joined with *.

This entry point charges no job-wide budget ([maxTasksPerJob]): it expands ONE step, and a single step is already bounded by [maxTasksPerStep], which is the same number. The submission pipeline calls [expandParameterSpace] with a per-job budget instead, because only a caller that walks a whole template can see the sum.

type ValidateOptions

type ValidateOptions struct {
	// EnforceLimits gates quantitative limit checks: maximum name lengths,
	// element counts, etc.
	//
	// When false those checks are skipped — useful in operator environments
	// that predate strict limit enforcement and cannot yet update all templates.
	//
	// NOTE: the quantitative limit checks live in [validateLimits] (and the
	// helpers it calls). Every limit check MUST be guarded by opts.EnforceLimits
	// and belong to validateLimits — do not scatter gated checks elsewhere.
	// Structural correctness checks belong in the always-run path instead:
	// [validateHostRequirements] is the host-requirement half, deliberately
	// separate from [validateHostRequirementLimits]. Reserved-capability value
	// checks ([validateReservedAmounts], [validateReservedAttributes]) are
	// value-domain correctness, not a size or count cap, so they run from
	// [validateHostRequirements] unconditionally too.
	// Resource-exhaustion guards (e.g. the [maxRangeValues] cap in
	// parseIntRangeExpr, the [maxTasksPerStep] cap in ExpandParameterSpace,
	// and [parameterSpaceOverCaps] gating the expression walk in this
	// function) are NOT limit checks: they always apply, regardless of this
	// flag. [parameterSpaceOverCaps] is the one most likely to confuse,
	// because it REUSES maxTaskParameterDefinitions and maxTaskParamValues --
	// the same two constants [validateParameterSpaceLimits] checks under this
	// very flag -- for a different question (should the walk run) than the
	// gated check asks (should the template be rejected for its size); see
	// both functions' doc comments.
	EnforceLimits bool

	// ExprLimits is the operator-configured bound on what this template's EXPR
	// expression walk may spend — EXPR sub-project E4d. The zero value means
	// "use the defaults", so every caller that has no operator configuration
	// to offer (internal/product's ValidateTemplate, this package's own tests,
	// the conformance harness) keeps the exact pre-E4d behavior by omitting
	// it.
	//
	// It reaches every consumption point through the walk's own
	// [templateBudget]; see [ExprLimits] for what each of the four bounds and
	// for which of them an operator may move how far.
	ExprLimits ExprLimits

	// Deadline, when non-zero, is an absolute wall-clock time after which the
	// expression walk stops and [ValidateWithBudget] returns a non-nil error
	// wrapping [expr.ErrDeadlineExceeded].
	//
	// It is a BACKSTOP, not a budget. The deterministic limits in ExprLimits
	// decide whether a template is VALID; this decides only whether this
	// server keeps working on it, and the same template would validate on an
	// idle machine. That is why it cannot be reported as a ValidationError,
	// and why reading it needs [ValidateWithBudget]: [ValidateWithOptions]
	// discards the channel it arrives on, so setting this field there stops
	// the walk without telling the caller why.
	//
	// Zero -- the default, and what every caller but the submission path uses
	// -- means no deadline and costs nothing: the meter short-circuits before
	// reading any clock.
	Deadline time.Time
}

ValidateOptions controls optional validation behavior passed to ValidateWithOptions.

type ValidationError

type ValidationError struct {
	// Pointer is a JSON Pointer (RFC 6901) to the offending field, e.g.
	// "/steps/0/dependencies/0/dependsOn".
	Pointer string
	// Message is a human-readable description of the problem.
	Message string
}

ValidationError is a single validation failure with a JSON-pointer path to the offending field.

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors is the result of Validate: a slice of zero or more errors.

func BindJobParameters

func BindJobParameters(params []JobParameter, provided map[string]string) (map[string]string, ValidationErrors)

BindJobParameters resolves each declared job parameter to a concrete string value, validates every value against its type and constraints, and returns the fully-bound name→value map.

Resolution order per declared parameter:

  1. provided[name] — the caller-supplied value, if present.
  2. p.Default — the template default, if the parameter has one.
  3. Required-but-missing error: the parameter has neither a supplied value nor a default.

Any key in provided that does not match a declared parameter name produces an "unknown parameter" error. All errors are accumulated before returning so callers receive a complete problem list in one round-trip.

Pointer conventions:

  • Unknown provided key → /parameterValues/<name>
  • Required-but-missing → /parameterDefinitions/<name>
  • Type / constraint err → /parameterValues/<name>

AllowedValues comparison:

  • INT — both value and each allowed entry are parsed as int64; "01" and "1" are considered equal.
  • FLOAT — both parsed as float64; "1.00" and "1.0" are considered equal.
  • STRING / PATH — exact string comparison.

On success, returns the resolved map and nil errors. On failure, returns (nil, errors).

func Validate

func Validate(t *JobTemplate) ValidationErrors

Validate performs semantic validation of a parsed JobTemplate and returns all detected problems. An empty slice means the template is valid.

Validations performed:

  • specificationVersion must equal SpecVersion
  • name must not be empty
  • at least one step is required
  • job parameter names must be unique and match the identifier pattern
  • job parameter type must be INT, FLOAT, STRING, or PATH
  • step names must be unique and non-empty
  • each step dependency must reference a declared step name
  • step dependency graph must be acyclic
  • task parameter names within a step must be unique
  • task parameter types must be INT, FLOAT, STRING, PATH, or CHUNK[INT]
  • INT/CHUNK[INT] range expressions must be parseable
  • combination expression must reference only declared task parameter names

Validate is a thin wrapper around ValidateWithOptions with ValidateOptions.EnforceLimits set to true.

func ValidateWithBudget added in v0.3.0

func ValidateWithBudget(t *JobTemplate, opts ValidateOptions) (ValidationErrors, error)

ValidateWithBudget is ValidateWithOptions plus a wall-clock backstop.

It returns the same ValidationErrors, plus an error that is non-nil ONLY when opts.Deadline passed mid-walk, in which case it wraps expr.ErrDeadlineExceeded. That second channel exists because the two outcomes mean different things to a caller: ValidationErrors say the template is INVALID and become a 422, while a deadline says this server gave up and becomes a 5xx. A deadline is non-deterministic — the same body would validate on an idle machine — so reporting it as a validation error would make acceptance depend on machine load.

When the error is non-nil the ValidationErrors are INCOMPLETE by definition: the walk stopped early, so a position that would have failed may not have been reached. Callers must not present them as a verdict.

Everything after the expression walk still runs when the deadline passed. The remaining checks are deterministic, expression-free and bounded by template size, so finishing them costs no meaningful time and leaves the caller a more complete (though still incomplete) picture if it wants to log one.

func ValidateWithOptions

func ValidateWithOptions(t *JobTemplate, opts ValidateOptions) ValidationErrors

ValidateWithOptions is like Validate but accepts a ValidateOptions value so callers can control optional validation behavior — currently whether quantitative limit checks are enforced.

Existing callers should continue to use Validate; this entry point is for the submission pipeline where the operator may disable limit enforcement via config.

It is ValidateWithBudget with the deadline channel discarded, and that is safe by construction: without ValidateOptions.Deadline set, that error is always nil. Every caller that does not set a deadline — which is every caller but the submission path — keeps its exact previous behavior. A caller that DOES set one gets a walk that stops but no way to learn that it did, so use ValidateWithBudget instead.

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

Directories

Path Synopsis
Package expr reads and evaluates the OpenJD EXPR extension's expression language.
Package expr reads and evaluates the OpenJD EXPR extension's expression language.
Package fmtstring resolves Open Job Description (OpenJD) format strings.
Package fmtstring resolves Open Job Description (OpenJD) format strings.
Package intrange implements the OpenJD base specification's <IntRangeExpr> grammar (2023-09 Template Schemas, section 3.4.1.1.1): the succinct "1,3,7-10:2" form used for frame ranges.
Package intrange implements the OpenJD base specification's <IntRangeExpr> grammar (2023-09 Template Schemas, section 3.4.1.1.1): the succinct "1,3,7-10:2" form used for frame ranges.

Jump to

Keyboard shortcuts

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