workload

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 5 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 workload holds the parts of workload management (#399, ADR 0014) that are pure policy: the default capacities and the rule that a missing per-engine row falls back to them. The admission workflow and the API use these values; nothing here talks to the database or to Temporal.

Index

Constants

View Source
const AdmissionThrottleSignal = "set-throttle"

AdmissionThrottleSignal is the signal that sets the adaptive gate. It lives here (not in the workflows package) so the Lens poll activity, which cannot import workflows, can send it.

Variables

This section is empty.

Functions

func AdmissionWorkflowID

func AdmissionWorkflowID(engineID string) string

AdmissionWorkflowID is the id of an engine's admission workflow (#399). The workflows package re-exports it from here so the activity and the workflow agree without an import cycle.

func AnyDDL

func AnyDDL(statements []string) bool

AnyDDL reports whether any statement of a script is a DDL (#580).

func ClampToMax

func ClampToMax(class, ceiling queryengine.WorkloadClass) queryengine.WorkloadClass

ClampToMax caps a class so it is never more important than ceiling: it returns ceiling when class outranks it, and class otherwise (#546).

func ClassRank

func ClassRank(class queryengine.WorkloadClass) int

ClassRank orders the classes by priority: interactive is the most important (0) and background the least (2). An unknown class ranks last.

func Defaults

func Defaults(engineClass string) map[queryengine.WorkloadClass]Capacity

Defaults returns the conservative capacity of every class for an engine class ("direct" or "federated"). A federated engine is Trino today, so its defaults are Trino's. A missing row in engine_queue_capacity means these.

func EncodeRuleMatch

func EncodeRuleMatch(m RuleMatch) ([]byte, error)

EncodeRuleMatch encodes a match for storage. Keys with a zero value are omitted so the database CHECK accepts the object.

func IsDDL

func IsDDL(sql string) bool

IsDDL reports whether sql is a data-definition statement. The caller passes one statement, already split by the engine dialect (#580).

func IsSelect

func IsSelect(sql string) bool

IsSelect reports whether sql is a statement a cost estimate can be had for: a SELECT or a CTE that starts with WITH. Other statements (including VALUES and TABLE) never get an EXPLAIN (#550).

func TrinoPlanCost

func TrinoPlanCost(plan []byte) (int64, bool)

TrinoPlanCost returns the largest estimated byte count a Trino EXPLAIN (FORMAT JSON) plan reports (#550). ok is false when the plan carries no estimate (missing statistics), so classification falls through to the next step. Any `*InputSizeInBytes` key counts, case-insensitively, including the `processedInputSizeInBytes` newer Trino versions emit (#591).

func Validate

func Validate(rg ResourceGroups) error

Validate checks the document's structural invariants: one root group, every subgroup named and reachable through the root, every selector pointing at an existing group, and no negative limit (0 is a closed class). It is the gate the caller runs before writing the document anywhere.

Types

type AdaptiveThresholds

type AdaptiveThresholds struct {
	// QueuedQueries throttles when the cluster's queued queries exceed it.
	QueuedQueries int
	// BlockedQueries throttles when queries held by locks/contention exceed it.
	BlockedQueries int
	// MemoryHeadroom throttles when free/total memory falls below it (0..1).
	MemoryHeadroom float64
}

AdaptiveThresholds are the conservative defaults of the adaptive gate. A zero field disables that trigger.

func DefaultAdaptiveThresholds

func DefaultAdaptiveThresholds() AdaptiveThresholds

DefaultAdaptiveThresholds are the shipped defaults: the queued-query gate is the primary trigger (#551); the blocked and memory gates catch saturation that the queue length does not show (#579).

func (AdaptiveThresholds) Throttled

func (t AdaptiveThresholds) Throttled(p ClusterPressure) (bool, string)

Throttled reports whether the snapshot crosses a threshold, and the reason stored on the gate. The triggers are evaluated in a fixed order so the reason is deterministic.

type AdmissionThrottle

type AdmissionThrottle struct {
	Throttled bool
	Reason    string
}

AdmissionThrottle is the adaptive gate's mode and why it changed.

type Capacity

type Capacity struct {
	MaxRunning     int
	MaxQueued      int
	QueueTimeout   time.Duration
	RuntimeTimeout time.Duration
}

Capacity is how one (engine, class) queue is allowed to run and wait.

QueueTimeout bounds the *wait* before a run enters the engine; RuntimeTimeout bounds how long it may *execute* once admitted. The second is what stops a background run that waited 24h from being killed by the global statement timeout after 30 minutes.

func Resolve

func Resolve(engineClass string, class queryengine.WorkloadClass, configured *Capacity) Capacity

Resolve returns the configured capacity when one exists, otherwise the engine class's default for that workload class. A configured row may leave the runtime bound unset (NULL); it then falls back to the default. The schema forbids 0, so 0 is unambiguously "unset".

type ClusterPressure

type ClusterPressure struct {
	QueuedQueries    int
	BlockedQueries   int
	TotalMemoryBytes *int64
	FreeMemoryBytes  *int64
}

ClusterPressure is the slice of the latest cluster snapshot the gate reads.

type Decision

type Decision struct {
	Class  queryengine.WorkloadClass
	Reason string
	// Weight is the fairness weight of the run within its class. Rules may set
	// it; it is 1 otherwise (#546).
	Weight int
	// MaxClass is the most important class a later step (the user downgrade)
	// may assign. Empty means no rule capped it (#546).
	MaxClass queryengine.WorkloadClass
}

Decision is the class a run gets and the step that chose it. The reason is stored on the execution and shown in its details.

func Classify

func Classify(origin Origin) Decision

Classify is the first classification step: background work gets the background class, everything a person waits for is interactive. Admin rules, cost routing and the user downgrade are later steps and come after this.

func Decide

func Decide(origin Origin, in RuleInput, rules []Rule) Decision

Decide classifies a run: origin first, then the ordered, enabled rules (first match wins), then the default (#399, #546). Rules can override the origin's class, which is how an admin moves a retriever's DDL or a heavy workspace (#580 lands the DDL/export refinements). Cost routing and the user downgrade are later steps.

func MatchRule

func MatchRule(in RuleInput, rules []Rule) (Decision, bool)

MatchRule returns the first enabled rule that matches, and whether one did (#546). Callers use it to know whether a rule decides the class before they pay for a cost estimate (#550).

type Origin

type Origin string

Origin is where a run came from. Classification looks at it before any admin rule (#399, ADR 0014).

const (
	// OriginEditor is a Run from the SQL workbench.
	OriginEditor Origin = "editor"
	// OriginAgent is a run made by an agent principal.
	OriginAgent Origin = "agent"
	// OriginExplore is a compiled Explore query or an Explore preview.
	OriginExplore Origin = "explore"
	// OriginRetriever is a retriever refresh.
	OriginRetriever Origin = "retriever"
	// OriginMetadata is metadata introspection through an engine.
	OriginMetadata Origin = "metadata"
	// OriginMaintenance is Iceberg maintenance.
	OriginMaintenance Origin = "maintenance"
	// OriginExport is a user export of a result set as a run.
	OriginExport Origin = "export"
	// OriginDownload is a user download of a stored result as a run.
	OriginDownload Origin = "download"
	// OriginBI is a statement through the BI gateway (ADR 0017).
	OriginBI Origin = "bi"
)

func (Origin) Valid

func (o Origin) Valid() bool

Valid reports whether o is one of the known origins.

type ResourceGroups

type ResourceGroups struct {
	RootGroups []RootGroup `json:"rootGroups"`
	Selectors  []Selector  `json:"selectors"`
}

ResourceGroups is the generated Trino resource-groups.json document.

func Generate

func Generate(classes map[queryengine.WorkloadClass]Capacity, ceiling *int) ResourceGroups

Generate renders the document. ceiling, when non-nil and positive, becomes the root hardConcurrencyLimit. A class whose capacity is 0 (MaxRunning == 0) is closed: it keeps its subgroup and selector with a hardConcurrencyLimit of 0, so Trino holds its runs (up to maxQueued) as Baleia's own queue would, instead of the catch-all routing them into an open class's capacity (#635).

type RootGroup

type RootGroup struct {
	Name                 string     `json:"name"`
	SoftMemoryLimit      string     `json:"softMemoryLimit"`
	HardConcurrencyLimit *int       `json:"hardConcurrencyLimit,omitempty"`
	SubGroups            []SubGroup `json:"subGroups"`
}

RootGroup is the single `baleia` group that owns the per-class subgroups.

type Rule

type Rule struct {
	ID       string
	Position int
	Enabled  bool
	Match    RuleMatch
	Class    queryengine.WorkloadClass
	MaxClass queryengine.WorkloadClass
	Weight   int
}

Rule is one ordered, admin-managed workload rule (#539, #546): the in-memory form of a workload_rules row.

type RuleInput

type RuleInput struct {
	WorkspaceID  string
	TeamID       string
	Role         string
	UserID       string
	AgentID      string
	EngineID     string
	Origin       Origin
	SavedQueryID string
	Statements   int
	// DDL marks a data-definition statement: it is never demoted to background
	// by origin alone (#580).
	DDL bool
	// CostHeavy is set by the caller when the engine's cost estimate exceeds
	// its threshold (#550).
	CostHeavy bool
}

RuleInput is the run being classified (#546).

type RuleMatch

type RuleMatch struct {
	WorkspaceID   string
	TeamID        string
	Role          string
	UserID        string
	AgentID       string
	EngineID      string
	Origin        Origin
	SavedQueryID  string
	MinStatements int
	MaxStatements int
}

RuleMatch is the closed set of match fields (#539). A zero field does not constrain the run; every non-zero field must match.

func ParseRuleMatch

func ParseRuleMatch(raw []byte) (RuleMatch, error)

ParseRuleMatch decodes a workload_rules.match column. An empty object is a catch-all rule.

type Selector

type Selector struct {
	ClientTags []string `json:"clientTags,omitempty"`
	Group      string   `json:"group"`
}

Selector routes a session to a group. The empty ClientTags selector is the catch-all, so it is always last.

type SubGroup

type SubGroup struct {
	Name                 string `json:"name"`
	HardConcurrencyLimit int    `json:"hardConcurrencyLimit"`
	MaxQueued            int    `json:"maxQueued"`
}

SubGroup is one class's queue, with its concurrency and queued limits.

Directories

Path Synopsis
Package resourcegroups publishes the generated Trino resource-group document (#598) into the tables Trino's database resource group manager reads (#599).
Package resourcegroups publishes the generated Trino resource-group document (#598) into the tables Trino's database resource group manager reads (#599).
publish
Package publish writes the generated Trino resource-group document through the narrow Writer surface the store implements (ADR 0020).
Package publish writes the generated Trino resource-group document through the narrow Writer surface the store implements (ADR 0020).

Jump to

Keyboard shortcuts

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