plancontract

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package plancontract evaluates structural Cloud Spanner query plan contracts.

The package intentionally works on an already-built plan report projection: it does not parse DDL, analyze SQL with the GoogleSQL frontend, or start an emulator/Omni backend. Callers are responsible for collecting QueryPlan data and normalizing PlanNode operators before invoking this package.

Index

Constants

View Source
const (
	StatusPass         = "pass"
	StatusFail         = "fail"
	StatusNotEvaluated = "not_evaluated"

	FileVersionV1Alpha = "v1alpha-plan-contracts"
	EvaluatorVersionV1 = "v1"

	StabilityNormalized = "normalized_operator"
	StabilityRawPlan    = "raw_query_plan"

	EvaluationModeNone       = "none"
	EvaluationModeReportOnly = "report_only"
	EvaluationModeCheck      = "check"

	FailureKindViolation             = "violation"
	FailureKindClassificationUnknown = "classification_unknown"
	ReasonTargetNotFound             = "target_not_found"
	ReasonTargetError                = "target_error"
)
View Source
const (
	IdentifierPattern = `[A-Za-z_][A-Za-z0-9_]*`
	TargetIDPattern   = `^query/` + IdentifierPattern + `(#inner)?$`
)

Variables

This section is empty.

Functions

func AddCheckWarnings

func AddCheckWarnings(summary *EvaluationSummary, evaluations []Evaluation)

AddCheckWarnings mutates summary with warnings that only apply to --check.

func AddDerivedOperatorFamilyCounts

func AddDerivedOperatorFamilyCounts(counts map[string]int)

AddDerivedOperatorFamilyCounts updates count-only umbrella families in counts.

func CheckFailureCount

func CheckFailureCount(evaluations []Evaluation) int

CheckFailureCount counts failed or not-evaluated contracts.

func ConcreteOperatorFamilies

func ConcreteOperatorFamilies() []string

ConcreteOperatorFamilies returns operator families that can appear directly in normalized_operators[].family. Derived umbrella families such as explicit_sort and blocking_operator are intentionally omitted.

func EnvironmentWarnings

func EnvironmentWarnings(report Report) []string

EnvironmentWarnings returns warnings that affect contract interpretation.

func KnownOperatorFamilies

func KnownOperatorFamilies() []string

KnownOperatorFamilies returns all normalized operator families.

func KnownOperatorFamily

func KnownOperatorFamily(family string) bool

KnownOperatorFamily reports whether family is a supported normalized family.

func ObservedOperatorFamilies

func ObservedOperatorFamilies(operators []Operator) []string

func OperatorFamily

func OperatorFamily(node *spannerpb.PlanNode) string

func OperatorFamilyCounts

func OperatorFamilyCounts(operators []Operator) map[string]int

OperatorFamilyCounts returns a complete zero-filled operator family count map.

func OperatorFamilyCountsOrEmpty

func OperatorFamilyCountsOrEmpty(counts map[string]int) map[string]int

OperatorFamilyCountsOrEmpty returns a complete zero-filled copy of counts.

func OperatorMetadataString

func OperatorMetadataString(node *spannerpb.PlanNode, key string) string

func OperatorTreeDigest

func OperatorTreeDigest(plan *spannerpb.QueryPlan) string

func OptimizerPinningWarnings

func OptimizerPinningWarnings(report Report) []string

OptimizerPinningWarnings returns environment warnings related to optimizer pinning.

func PredefinedNames

func PredefinedNames() []string

PredefinedNames returns all predefined contract names.

func Scope

func Scope(scope string) string

Scope returns the canonical contract scope string.

func TargetID

func TargetID(queryName, scope string) string

TargetID returns the canonical contract target ID for a query name and scope.

func ViolationCount

func ViolationCount(evaluations []Evaluation) int

ViolationCount counts failed rule results.

func ZeroOperatorFamilyCounts

func ZeroOperatorFamilyCounts() map[string]int

ZeroOperatorFamilyCounts returns a complete zero-filled operator family map.

Types

type ApplyResult

type ApplyResult struct {
	FileVersion      string
	EvaluatorVersion string
	Evaluations      []Evaluation
	Summary          EvaluationSummary
}

ApplyResult contains contract evaluation output fields.

func Evaluate

func Evaluate(report Report, contracts File) (ApplyResult, error)

Evaluate evaluates contracts against a plan report projection.

type BackendIdentity

type BackendIdentity struct {
	Kind        string `json:"kind" yaml:"kind"`
	Version     string `json:"version" yaml:"version"`
	ImageDigest string `json:"image_digest" yaml:"image_digest"`
	Source      string `json:"source" yaml:"source"`
}

BackendIdentity identifies the backend that produced the plan.

type Contract

type Contract struct {
	Name   string      `json:"name" yaml:"name"`
	Target string      `json:"target" yaml:"target"`
	Use    []string    `json:"use,omitempty" yaml:"use,omitempty"`
	Forbid []Predicate `json:"forbid,omitempty" yaml:"forbid,omitempty"`
	CEL    string      `json:"cel,omitempty" yaml:"cel,omitempty"`
}

Contract describes one user-authored plan contract.

type Diagnostic

type Diagnostic struct {
	ID      string `json:"id" yaml:"id"`
	Message string `json:"message" yaml:"message"`
}

Diagnostic records plan normalization or classification warnings.

func ClassificationWarnings

func ClassificationWarnings(operators []Operator) []Diagnostic

type Evaluation

type Evaluation struct {
	Name      string       `json:"name" yaml:"name"`
	Query     string       `json:"query,omitempty" yaml:"query,omitempty"`
	TargetID  string       `json:"target_id" yaml:"target_id"`
	Scope     string       `json:"scope,omitempty" yaml:"scope,omitempty"`
	Status    string       `json:"status" yaml:"status"`
	Reason    string       `json:"reason,omitempty" yaml:"reason,omitempty"`
	Error     string       `json:"error,omitempty" yaml:"error,omitempty"`
	Stability Stability    `json:"stability" yaml:"stability"`
	Results   []RuleResult `json:"results,omitempty" yaml:"results,omitempty"`
}

Evaluation is the result for one Contract.

type EvaluationSummary

type EvaluationSummary struct {
	Status              string   `json:"status" yaml:"status"`
	Contracts           int      `json:"contracts" yaml:"contracts"`
	Passed              int      `json:"passed" yaml:"passed"`
	Failed              int      `json:"failed" yaml:"failed"`
	NotEvaluated        int      `json:"not_evaluated" yaml:"not_evaluated"`
	EnvironmentWarnings []string `json:"environment_warnings" yaml:"environment_warnings"`
}

EvaluationSummary summarizes all contract evaluations.

func Summarize

func Summarize(evaluations []Evaluation) EvaluationSummary

Summarize summarizes contract evaluation results.

type File

type File struct {
	Version   string     `json:"version" yaml:"version"`
	Contracts []Contract `json:"contracts" yaml:"contracts"`
}

File is the top-level plan contract YAML document.

func ReadFile

func ReadFile(path string) (File, error)

ReadFile reads and validates a plan contract YAML file.

type Operator

type Operator struct {
	Index               int32          `json:"index" yaml:"index"`
	DisplayName         string         `json:"display_name" yaml:"display_name"`
	Family              string         `json:"family" yaml:"family"`
	ExecutionMethod     string         `json:"execution_method,omitempty" yaml:"execution_method,omitempty"`
	IteratorType        string         `json:"iterator_type,omitempty" yaml:"iterator_type,omitempty"`
	ScanMethod          string         `json:"scan_method,omitempty" yaml:"scan_method,omitempty"`
	ScanFormat          string         `json:"scan_format,omitempty" yaml:"scan_format,omitempty"`
	ScanType            string         `json:"scan_type,omitempty" yaml:"scan_type,omitempty"`
	ScanTarget          string         `json:"scan_target,omitempty" yaml:"scan_target,omitempty"`
	SeekableKeySize     string         `json:"seekable_key_size,omitempty" yaml:"seekable_key_size,omitempty"`
	JoinType            string         `json:"join_type,omitempty" yaml:"join_type,omitempty"`
	JoinConfiguration   string         `json:"join_configuration,omitempty" yaml:"join_configuration,omitempty"`
	CallType            string         `json:"call_type,omitempty" yaml:"call_type,omitempty"`
	DistributionTable   string         `json:"distribution_table,omitempty" yaml:"distribution_table,omitempty"`
	SubqueryClusterNode string         `json:"subquery_cluster_node,omitempty" yaml:"subquery_cluster_node,omitempty"`
	SpoolName           string         `json:"spool_name,omitempty" yaml:"spool_name,omitempty"`
	FullScan            bool           `json:"full_scan,omitempty" yaml:"full_scan,omitempty"`
	ChildIndexes        []int32        `json:"child_indexes" yaml:"child_indexes"`
	DescendantIndexes   []int32        `json:"descendant_indexes" yaml:"descendant_indexes"`
	SubtreeFamilyCounts map[string]int `json:"subtree_family_counts" yaml:"subtree_family_counts"`
}

Operator is the normalized operator view used by stable predefined contracts.

func NormalizeOperators

func NormalizeOperators(plan *spannerpb.QueryPlan) []Operator

type OperatorEdge

type OperatorEdge struct {
	ParentIndex int32  `json:"parent_index" yaml:"parent_index"`
	ChildIndex  int32  `json:"child_index" yaml:"child_index"`
	Type        string `json:"type,omitempty" yaml:"type,omitempty"`
	Variable    string `json:"variable,omitempty" yaml:"variable,omitempty"`
}

OperatorEdge records a PlanNode parent-child edge.

func NormalizeOperatorEdges

func NormalizeOperatorEdges(plan *spannerpb.QueryPlan) []OperatorEdge

type Optimizer

type Optimizer struct {
	Requested OptimizerEnvironment `json:"requested" yaml:"requested"`
	Effective OptimizerEffective   `json:"effective" yaml:"effective"`
}

Optimizer records requested and effective optimizer settings.

type OptimizerEffective

type OptimizerEffective struct {
	Version           string `json:"version" yaml:"version"`
	StatisticsPackage string `json:"statistics_package" yaml:"statistics_package"`
}

OptimizerEffective is the observed optimizer environment.

type OptimizerEnvironment

type OptimizerEnvironment struct {
	Version           string `json:"version" yaml:"version"`
	StatisticsPackage string `json:"statistics_package" yaml:"statistics_package"`
}

OptimizerEnvironment is the requested optimizer environment.

type Predicate

type Predicate struct {
	OperatorFamily string `json:"operator_family" yaml:"operator_family"`
	MaxCount       int    `json:"max_count,omitempty" yaml:"max_count,omitempty"`
}

Predicate forbids an operator family above MaxCount.

type Query

type Query struct {
	TargetID             string
	Name                 string
	Catalog              string
	Scope                string
	Kind                 string
	Status               string
	SQLSHA256            string
	DDLSHA256            string
	OperatorTreeSHA256   string
	OperatorFamilies     []string
	OperatorFamilyCounts map[string]int
	NormalizedOperators  []Operator
	OperatorEdges        []OperatorEdge
	Error                string
	OptimizerNotPinned   bool
	PlanEnvironmentNotes []string
	ClassificationNotes  []Diagnostic
	RawPlan              *spannerpb.QueryPlan
}

Query is the per-query contract evaluator input projection.

func FindTarget

func FindTarget(report Report, targetID string) (Query, bool)

FindTarget finds a query by canonical contract target ID.

type Remediation

type Remediation struct {
	Kind       string `json:"kind" yaml:"kind"`
	AppliesTo  string `json:"applies_to,omitempty" yaml:"applies_to,omitempty"`
	Confidence string `json:"confidence,omitempty" yaml:"confidence,omitempty"`
	AutoFix    bool   `json:"auto_fix" yaml:"auto_fix"`
	Message    string `json:"message" yaml:"message"`
}

Remediation describes a possible follow-up when a contract fails.

type Report

type Report struct {
	Backend         string
	BackendIdentity BackendIdentity
	Optimizer       Optimizer
	Queries         []Query
}

Report is the contract evaluator input projection.

type RuleResult

type RuleResult struct {
	Rule                   string        `json:"rule,omitempty" yaml:"rule,omitempty"`
	Source                 string        `json:"source,omitempty" yaml:"source,omitempty"`
	Predefined             string        `json:"predefined,omitempty" yaml:"predefined,omitempty"`
	Expression             string        `json:"expression,omitempty" yaml:"expression,omitempty"`
	OperatorFamily         string        `json:"operator_family,omitempty" yaml:"operator_family,omitempty"`
	Status                 string        `json:"status" yaml:"status"`
	FailureKind            string        `json:"failure_kind,omitempty" yaml:"failure_kind,omitempty"`
	DiagnosticID           string        `json:"diagnostic_id,omitempty" yaml:"diagnostic_id,omitempty"`
	ObservedCount          int           `json:"observed_count,omitempty" yaml:"observed_count,omitempty"`
	MaxCount               int           `json:"max_count,omitempty" yaml:"max_count,omitempty"`
	MatchedOperatorIndexes *[]int32      `json:"matched_operator_indexes,omitempty" yaml:"matched_operator_indexes,omitempty"`
	Remediation            []Remediation `json:"remediation,omitempty" yaml:"remediation,omitempty"`
}

RuleResult is the result for one expanded contract rule.

type Stability

type Stability struct {
	Tier                 string   `json:"tier" yaml:"tier"`
	Reasons              []string `json:"reasons" yaml:"reasons"`
	CheckRecommended     bool     `json:"check_recommended" yaml:"check_recommended"`
	ReplayableFromReport bool     `json:"replayable_from_report" yaml:"replayable_from_report"`
}

Stability classifies the robustness of a contract rule.

Jump to

Keyboard shortcuts

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