bench

package
v6.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 51 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrorUnknown       = driver.ErrorKindUnknown
	ErrorSerialization = driver.ErrorKindSerialization
	ErrorDeadlock      = driver.ErrorKindDeadlock
	ErrorLockTimeout   = driver.ErrorKindLockTimeout
	ErrorTransient     = driver.ErrorKindTransient
	ErrorUnsupported   = driver.ErrorKindUnsupported
	ErrorCanceled      = driver.ErrorKindCanceled
	ErrorTimeout       = driver.ErrorKindTimeout
)
View Source
const (
	Counter metricType = iota
	Trend
	Rate
	Gauge
)

Variables

View Source
var (
	DrainNoTimeout         = Drain{/* contains filtered or unexported fields */}
	DrainHalfMinuteTimeout = Drain{/* contains filtered or unexported fields */}
)
View Source
var ErrNoRows = errors.New("query returned no rows")

Functions

func DriverDialectStem

func DriverDialectStem(t DriverTypeName) string

DriverDialectStem names the SQL asset stem an engine prefers when it is not the protocol's own, so a workload can prefer its engine-specific asset and fall back to the protocol's.

This is what makes an engine-specific file reachable at all: workloads embed their assets, and the only other way to choose one is --sql-file, which takes a path on disk. TPC-B and TPC-C ship a crdb.sql for exactly one reason — CockroachDB rejects a bare ANALYZE — and without this it could only be used by copying the asset out of the binary first.

func Fatal

func Fatal(err error) error

Fatal wraps an error with explicit run-stopping intent.

func IsFatalError

func IsFatalError(err error) bool

IsFatalError reports whether err carries a fatal workload action.

func ParseDriverType

func ParseDriverType(s string) (config.DriverType, error)

func ParseTxIsolation

func ParseTxIsolation(s string) (config.TxIsolationLevel, error)

func Retry0

func Retry0(ctx context.Context, policy RetryPolicy, fn func() error) error

Retry0 runs a void operation under policy. Error and fatal actions preserve the original error, ignore returns nil, and retry replays fn.

func RunCatalog

func RunCatalog(ctx context.Context, catalog *Catalog, name string, options RunOptions) (*report.Run, error)

RunCatalog executes one descriptor selected from an explicit catalog.

func RunTest

func RunTest(ctx context.Context, test Test, options RunOptions) (result *report.Run, err error)

RunTest observes a definition, validates inputs, then executes a fresh replay. Reports are returned as data; this function never writes report history.

Types

type Action

type Action func(context.Context, *Bench) error

Action is ordinary work independent of its execution policy.

type BeginOpts

type BeginOpts struct {
	Isolation TxIsolationName
	Name      string
}

BeginOpts selects isolation + names the tx for metrics.

type Bench

type Bench struct {
	Log Logger
	// contains filtered or unexported fields
}

Bench is a stable step-worker-scoped set of author capabilities. Workers own separate Bench values; workload state remains ordinary Go state.

func (*Bench) AddReportData

func (b *Bench) AddReportData(key, value string)

AddReportData adds or replaces one JSON value in the common report metadata. Values are copied into the final envelope and should contain only non-secret run labels.

func (*Bench) Begin

func (b *Bench) Begin(ctx context.Context, opts BeginOpts) (*Tx, error)

Begin starts a transaction.

func (*Bench) BeginTx

func (b *Bench) BeginTx(ctx context.Context, opts BeginOpts, fn func(*Tx) error) (err error)

BeginTx runs fn inside a transaction: commits on nil return, rolls back on error.

func (*Bench) CollectedMetrics

func (b *Bench) CollectedMetrics() (map[string]MetricSnapshot, error)

CollectedMetrics returns every collected metric keyed by its prefix-stripped name. Workloads call it from Teardown to post-process their own per-transaction counters and trends into a final report.

func (*Bench) Database

func (b *Bench) Database(ref DriverRef) *Database

func (*Bench) DriverTypeName

func (b *Bench) DriverTypeName() DriverTypeName

func (*Bench) Exec

func (b *Bench) Exec(ctx context.Context, sql string, args map[string]any) error

Exec runs a statement that returns no rows.

func (*Bench) ExecQuery

func (b *Bench) ExecQuery(ctx context.Context, q QueryHandle, args map[string]any) error

func (*Bench) Insert

func (b *Bench) Insert(
	ctx context.Context,
	table string,
	source gen.BatchSource,
	options ...InsertOption,
) (*InsertResult, error)

Insert streams a partitioned source through the selected database backend.

func (*Bench) Iteration

func (b *Bench) Iteration() uint64

func (*Bench) LogicalOperation

func (b *Bench) LogicalOperation(fn func() error) error

LogicalOperation counts one successful logical operation, including its retries. Nested managed transactions do not double-count that operation.

func (*Bench) Query

func (b *Bench) Query(ctx context.Context, sql string, args map[string]any) (*Rows, error)

func (*Bench) QueryRow

func (b *Bench) QueryRow(ctx context.Context, sql string, args map[string]any) (Row, error)

func (*Bench) QueryValue

func (b *Bench) QueryValue[T any](ctx context.Context, sql string, args map[string]any) (T, error)

QueryValue reads one owned scalar or shallow struct. No row is ErrNoRows.

func (*Bench) QueryValues

func (b *Bench) QueryValues[T any](ctx context.Context, sql string, args map[string]any) (values []T, err error)

QueryValues collects owned scalar or shallow struct rows and closes the cursor.

func (*Bench) RawRow

func (b *Bench) RawRow(ctx context.Context, sql string, args map[string]any) (_ []any, err error)

QueryRow returns the first row (or nil if no rows).

func (*Bench) RawRows

func (b *Bench) RawRows(ctx context.Context, sql string, args map[string]any) (_ [][]any, err error)

QueryRows returns all rows (up to a large cap).

func (*Bench) RecordError

func (b *Bench) RecordError(operation string, err error)

RecordQueryError records a query-set error after the workload has decided not to retry it. The query set may continue and the run remains successful.

func (*Bench) Transaction

func (b *Bench) Transaction(
	ctx context.Context,
	options TransactionOptions,
	body func(context.Context, *Tx) error,
) error

Transaction manages transaction lifecycle and retries as one logical operation.

func (*Bench) TxRetryPolicy

func (b *Bench) TxRetryPolicy(opts TxRetryPolicyOptions) RetryPolicy

TxRetryPolicy builds a policy from this bench's driver classifier and workload overrides.

func (*Bench) Worker

func (b *Bench) Worker() int

type CaptureOptions

type CaptureOptions struct {
	Directory string
	Logs      bool
	Metrics   bool
	Interval  time.Duration
	MaxBytes  int64
}

CaptureOptions records optional streams into a caller-selected persistent root.

type Catalog

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

Catalog is an explicit set of Test values, or a live registered view.

func NewCatalog

func NewCatalog(tests ...Test) (*Catalog, error)

func RegisteredCatalog

func RegisteredCatalog() *Catalog

func (*Catalog) Describe

func (c *Catalog) Describe(name string) (Description, error)

func (*Catalog) DescribeAll

func (c *Catalog) DescribeAll() ([]Description, error)

func (*Catalog) Resolve

func (c *Catalog) Resolve(name string, inputs ParamInputs, drivers map[string]DriverConfig) (Description, error)

func (*Catalog) ResolveRun

func (c *Catalog) ResolveRun(name string, options RunOptions) (description Description, err error)

ResolveRun observes effective run inputs, including step selection, without actions. Logger, metrics export and report options do not affect discovery.

func (*Catalog) Test

func (c *Catalog) Test(name string) (Test, bool)

type Constraint

type Constraint struct {
	Kind  string `json:"kind"`
	Value any    `json:"value"`
}

Constraint describes a discoverable parameter restriction.

type Contribution

type Contribution = ReportContribution

ReportContribution is one workload-owned report result.

type CounterHandle

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

func (*CounterHandle) Add

func (c *CounterHandle) Add(ctx context.Context, value float64, labels ...Label)

type Database

type Database struct{ *Bench }

Database is a step-worker-scoped neutral facade for a named driver.

type Def

type Def struct {
	Param     ParamDeclarations
	Execution Execution
	Drivers   DriverDeclarations
	Queries   QueryFiles
	Metrics   MetricDeclarations
	Report    ReportDeclarations
	// contains filtered or unexported fields
}

Def scopes one observation or execution replay. Subspaces may be passed to ordinary helpers. Actions run only through Execution.

type Description

type Description struct {
	Name    string
	Params  []ParamSchema
	Steps   []StepDescription
	Drivers []DriverDescription
	Values  map[string]ResolvedParameter
	Metrics []MetricSchema
}

Description is a copied observation of a test, not an exhaustive runtime graph.

func Describe

func Describe(name string) (Description, error)

func DescribeAll

func DescribeAll() ([]Description, error)

func DescribeTest

func DescribeTest(test Test) (Description, error)

type Drain

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

Drain defines the grace period after a duration budget. Use named presets or DrainTimeout; an unspecified zero value is invalid.

func DrainTimeout

func DrainTimeout(duration time.Duration) Drain

type DriverConfig

type DriverConfig struct {
	Kind                  DriverTypeName   `json:"kind,omitempty"`
	URL                   string           `json:"url,omitempty"`
	DefaultInsertMethod   InsertStrategy   `json:"defaultInsertMethod,omitempty"`
	BulkSize              *int32           `json:"bulkSize,omitempty"`
	Postgres              *PostgresConfig  `json:"postgres,omitempty"`
	SQL                   *SQLConfig       `json:"sql,omitempty"`
	CaCertFile            *string          `json:"caCertFile,omitempty"`
	AuthToken             *string          `json:"authToken,omitempty"`
	ServiceAccountKeyFile *string          `json:"serviceAccountKeyFile,omitempty"`
	AuthUser              *string          `json:"authUser,omitempty"`
	AuthPassword          *string          `json:"authPassword,omitempty"`
	TLSInsecureSkipVerify *bool            `json:"tlsInsecureSkipVerify,omitempty"`
	Recording             *record.Recorder `json:"-"`
}

DriverConfig supplies soft defaults or explicit host configuration. Secrets are consumed by backends, never emitted by driver discovery.

func DriverConfiguration

func DriverConfiguration(c *config.DriverConfig) DriverConfig

DriverConfiguration converts implementation-facing configuration into a copied neutral host input. Backend implementations need not be imported by authors.

type DriverDeclarations

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

func (*DriverDeclarations) Declare

func (d *DriverDeclarations) Declare(name string, defaults DriverConfig) DriverRef

func (*DriverDeclarations) QueryTimeout

func (d *DriverDeclarations) QueryTimeout(timeout time.Duration)

type DriverDescription

type DriverDescription struct {
	Name string         `json:"name"`
	Kind DriverTypeName `json:"kind"`
}

DriverDescription is secret-free authored driver metadata.

type DriverRef

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

DriverRef identifies a named declaration in one definition replay.

func (DriverRef) Kind

func (r DriverRef) Kind() DriverTypeName

func (DriverRef) Name

func (r DriverRef) Name() string

func (DriverRef) SupportsInsert

func (r DriverRef) SupportsInsert(method InsertStrategy) bool

type DriverTypeName

type DriverTypeName string
const (
	DriverPostgres  DriverTypeName = "postgres"
	DriverMySQL     DriverTypeName = "mysql"
	DriverPicodata  DriverTypeName = "picodata"
	DriverYDB       DriverTypeName = "ydb"
	DriverNoop      DriverTypeName = "noop"
	DriverCSV       DriverTypeName = "csv"
	DriverRecording DriverTypeName = "recording"

	// Engines that speak another driver's protocol under their own name. Each is a
	// kind of its own because it selects its own SQL asset and transaction defaults.
	DriverCRDB     DriverTypeName = "crdb"
	DriverYugabyte DriverTypeName = "yugabyte"
	DriverTiDB     DriverTypeName = "tidb"
)

func DriverTypeNameOf

func DriverTypeNameOf(t config.DriverType) DriverTypeName

DriverTypeNameOf reverse-maps the driver enum to the authoring string name.

type ErrorAction

type ErrorAction uint8

ErrorAction is workload policy for one classified driver error.

const (
	ErrorActionError ErrorAction = iota
	ErrorActionRetry
	ErrorActionIgnore
	ErrorActionFatal
)

type ErrorActionMap

type ErrorActionMap map[driver.ErrorKind]ErrorAction

ErrorActionMap maps database-independent error kinds to workload actions.

func DefaultErrorActions

func DefaultErrorActions() ErrorActionMap

DefaultErrorActions returns safe transaction defaults. Contention and transient failures retry; everything else remains an error.

type ErrorFacts

type ErrorFacts = driver.ErrorFacts

ErrorKind and ErrorFacts expose backend-neutral classification, not concrete errors.

type ErrorKind

type ErrorKind = driver.ErrorKind

ErrorKind and ErrorFacts expose backend-neutral classification, not concrete errors.

type Execution

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

Execution observes or executes steps immediately in ordinary Go order.

func (*Execution) Enabled

func (e *Execution) Enabled(name string) bool

Enabled checks selection without recording or executing a step.

func (*Execution) Err

func (e *Execution) Err() error

func (*Execution) Step

func (e *Execution) Step(name string, action Action, options ...StepOption) Result

type FatalError

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

FatalError marks an error that must stop the whole scenario.

func (*FatalError) Error

func (e *FatalError) Error() string

func (*FatalError) Unwrap

func (e *FatalError) Unwrap() error

type FinalSnapshot

type FinalSnapshot = ReportContext

ReportContribution is one workload-owned report result.

type GaugeHandle

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

func (*GaugeHandle) Set

func (g *GaugeHandle) Set(ctx context.Context, value float64, labels ...Label)

type HistogramHandle

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

func (*HistogramHandle) Record

func (h *HistogramHandle) Record(ctx context.Context, value float64, labels ...Label)

type InsertOption

type InsertOption interface {
	// contains filtered or unexported methods
}

func InsertMethod

func InsertMethod(m InsertStrategy) InsertOption

func LoadWorkers

func LoadWorkers(n int) InsertOption

type InsertResult

type InsertResult struct {
	Rows    int64
	Elapsed time.Duration
}

Insert runs a driver.InsertRequest through the benchmark driver. It wires progress tracking and metrics while streaming workload-authored gen.BatchSource rows. InsertResult contains neutral insertion measurements.

type InsertStrategy

type InsertStrategy int

func (InsertStrategy) String

func (m InsertStrategy) String() string

type Label

type Label struct {
	Name  string
	Value string
}

Label is one finite, declared metric dimension.

func LabelValue

func LabelValue(name, value string) Label

type Logger

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

Logger is a concurrency-safe structured logger. Logging does not choose an execution outcome; return an error or Fatal to change control flow.

func LoggerFromBackend

func LoggerFromBackend(log *zap.Logger) Logger

LoggerFromBackend adapts implementation-side logging without exposing it in run requests.

func NewLogger

func NewLogger(output io.Writer) Logger

NewLogger writes structured JSON records to a caller-owned writer.

func (Logger) Debug

func (l Logger) Debug(message string, fields ...any)

func (Logger) Error

func (l Logger) Error(message string, fields ...any)

func (Logger) Info

func (l Logger) Info(message string, fields ...any)

func (Logger) Warn

func (l Logger) Warn(message string, fields ...any)

func (Logger) With

func (l Logger) With(fields ...any) Logger

With returns a logger with copied additional fields.

type MetricDeclarations

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

MetricDeclarations registers typed instruments during definition.

func (*MetricDeclarations) Counter

func (d *MetricDeclarations) Counter(name string, opts ...MetricOption) *CounterHandle

func (*MetricDeclarations) Gauge

func (d *MetricDeclarations) Gauge(name string, opts ...MetricOption) *GaugeHandle

func (*MetricDeclarations) Histogram

func (d *MetricDeclarations) Histogram(name string, opts ...MetricOption) *HistogramHandle

func (*MetricDeclarations) Rate

func (d *MetricDeclarations) Rate(name string, opts ...MetricOption) *RateHandle

type MetricOption

type MetricOption interface {
	// contains filtered or unexported methods
}

MetricOption supplies discoverable metric units, description, or label values.

func Bounds

func Bounds(values ...float64) MetricOption

Bounds sets explicit histogram boundaries in declared unit.

func LabelValues

func LabelValues(name string, values ...string) MetricOption

func MetricDescription

func MetricDescription(description string) MetricOption

func Unit

func Unit(unit string) MetricOption

type MetricSchema

type MetricSchema struct {
	Name        string              `json:"name"`
	Kind        string              `json:"kind"`
	Unit        string              `json:"unit,omitempty"`
	Description string              `json:"description,omitempty"`
	Bounds      []float64           `json:"bounds,omitempty"`
	Labels      map[string][]string `json:"labels"`
}

MetricSchema is copied instrument metadata for discovery.

type MetricSnapshot

type MetricSnapshot struct {
	Total   float64
	Count   uint64
	Sum     float64
	Bounds  []float64
	Buckets []uint64
}

MetricSnapshot is a read-only copy of one metric's accumulated values at a run. Counter and Gauge metrics report Total; Trend histograms report Count, Sum, and the bucket layout (Bounds/BucketCounts) so callers can derive quantiles without retaining every raw observation.

type MetricsConfig

type MetricsConfig struct {
	GRPCEndpoint       string
	HTTPEndpoint       string
	HTTPPath           string
	Headers            string
	Insecure           bool
	Prefix             string
	ServiceVersion     string
	RunID              string
	ResourceAttributes map[string]string

	// OnSummary receives the final collected metrics snapshot once per Run,
	// right before the text summary is printed. Optional; programmatic
	// consumers (stroppy baseline) read structured numbers here.
	OnSummary func(map[string]report.Metric)

	// Quiet suppresses the final text summary. Programmatic consumers that
	// read OnSummary render their own report.
	Quiet bool

	// SummaryWriter receives the final text summary. Nil uses os.Stderr.
	SummaryWriter io.Writer
}

type ParamDeclarations

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

ParamDeclarations owns declaration, resolution, and copied provenance.

func (ParamDeclarations) Bool

func (p ParamDeclarations) Bool(name string, fallback bool, description string, opts ...ParamOption) (bool, ParamInfo)

func (ParamDeclarations) BoolVar

func (p ParamDeclarations) BoolVar(
	dst *bool,
	name string,
	fallback bool,
	description string,
	opts ...ParamOption,
) ParamInfo

func (ParamDeclarations) Declare

func (p ParamDeclarations) Declare[T any](
	name string,
	fallback T,
	description string,
	opts ...ParamOption,
) (T, ParamInfo)

Declare resolves a supported scalar type immediately. Invalid declarations or winning inputs panic with ValidationError; application boundaries return it.

func (ParamDeclarations) Duration

func (p ParamDeclarations) Duration(
	name string,
	fallback time.Duration,
	description string,
	opts ...ParamOption,
) (time.Duration, ParamInfo)

func (ParamDeclarations) DurationVar

func (p ParamDeclarations) DurationVar(
	dst *time.Duration,
	name string,
	fallback time.Duration,
	description string,
	opts ...ParamOption,
) ParamInfo

func (ParamDeclarations) Float64

func (p ParamDeclarations) Float64(
	name string,
	fallback float64,
	description string,
	opts ...ParamOption,
) (float64, ParamInfo)

func (ParamDeclarations) Float64Var

func (p ParamDeclarations) Float64Var(
	dst *float64,
	name string,
	fallback float64,
	description string,
	opts ...ParamOption,
) ParamInfo

func (ParamDeclarations) Int

func (p ParamDeclarations) Int(name string, fallback int, description string, opts ...ParamOption) (int, ParamInfo)

func (ParamDeclarations) Int64

func (p ParamDeclarations) Int64(
	name string,
	fallback int64,
	description string,
	opts ...ParamOption,
) (int64, ParamInfo)

func (ParamDeclarations) Int64Var

func (p ParamDeclarations) Int64Var(
	dst *int64,
	name string,
	fallback int64,
	description string,
	opts ...ParamOption,
) ParamInfo

func (ParamDeclarations) IntVar

func (p ParamDeclarations) IntVar(
	dst *int,
	name string,
	fallback int,
	description string,
	opts ...ParamOption,
) ParamInfo

func (ParamDeclarations) String

func (p ParamDeclarations) String(name, fallback, description string, opts ...ParamOption) (string, ParamInfo)

func (ParamDeclarations) StringVar

func (p ParamDeclarations) StringVar(dst *string, name, fallback, description string, opts ...ParamOption) ParamInfo

func (ParamDeclarations) Uint64

func (p ParamDeclarations) Uint64(
	name string,
	fallback uint64,
	description string,
	opts ...ParamOption,
) (uint64, ParamInfo)

func (ParamDeclarations) Uint64Var

func (p ParamDeclarations) Uint64Var(
	dst *uint64,
	name string,
	fallback uint64,
	description string,
	opts ...ParamOption,
) ParamInfo

func (ParamDeclarations) Var

func (p ParamDeclarations) Var[T any](
	dst *T,
	name string,
	fallback T,
	description string,
	opts ...ParamOption,
) ParamInfo

type ParamInfo

type ParamInfo struct {
	Name     string
	Source   ParamSource
	Spelling string
}

ParamInfo is copied provenance for one resolved declaration.

func (ParamInfo) Explicit

func (p ParamInfo) Explicit() bool

type ParamInputs

type ParamInputs struct {
	CLI            map[string]string
	RunConfig      map[string]json.RawMessage
	WorkloadConfig map[string]json.RawMessage
}

ParamInputs contains explicitly supplied typed inputs. Environment is read only for declared parameter names; unrelated process variables are ignored.

type ParamOption

type ParamOption interface {
	// contains filtered or unexported methods
}

ParamOption modifies declaration metadata and optional constraints.

func Aliases

func Aliases(names ...string) ParamOption

Aliases adds alternate parameter names with the same flag/env/config projections.

func DerivedDefault

func DerivedDefault(description string) ParamOption

DerivedDefault describes a contextual fallback instead of a fixed schema value.

func Max

func Max[T ~int | ~int64 | ~uint64 | ~float64](value T) ParamOption

func Min

func Min[T ~int | ~int64 | ~uint64 | ~float64](value T) ParamOption

Min and Max apply inclusive numeric or duration bounds.

func OneOf

func OneOf[T comparable](values ...T) ParamOption

OneOf restricts a declaration to the supplied comparable values.

type ParamSchema

type ParamSchema struct {
	Name               string
	Flag               string
	Scope              ParamScope
	Type               ParamType
	Description        string
	Default            any
	DefaultDescription string
	Env                string
	Config             string
	Aliases            []string
	Constraints        []Constraint
}

ParamSchema describes one declaration without requiring execution.

type ParamScope

type ParamScope string

ParamScope identifies the typed configuration object owning a parameter.

const (
	ParamScopeRun      ParamScope = "run"
	ParamScopeWorkload ParamScope = "workload"
)

type ParamSource

type ParamSource string

ParamSource identifies the winning input channel.

const (
	ParamSourceDefault    ParamSource = "default"
	ParamSourceCLI        ParamSource = "cli"
	ParamSourceProcessEnv ParamSource = "process-env"
	ParamSourceConfig     ParamSource = "config"
)

type ParamType

type ParamType string

ParamType is a discoverable parameter value type.

const (
	ParamTypeString   ParamType = "string"
	ParamTypeBool     ParamType = "bool"
	ParamTypeInt      ParamType = "int"
	ParamTypeInt64    ParamType = "int64"
	ParamTypeUint64   ParamType = "uint64"
	ParamTypeFloat64  ParamType = "float64"
	ParamTypeDuration ParamType = "duration"
)

type Policy

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

Policy is an immutable execution budget. A zero Policy is invalid.

func ConstantWorkers

func ConstantWorkers(workers int, duration time.Duration, drain Drain) Policy

ConstantWorkers stops new invocations at duration and drains existing ones.

func SelectExecutor

func SelectExecutor(mode string, candidates ...Policy) Policy

SelectExecutor chooses an already-validated policy; invalid selection panics.

func SharedIterations

func SharedIterations(workers int, count int64) Policy

SharedIterations runs count invocations distributed across workers.

func TryConstantWorkers

func TryConstantWorkers(workers int, duration time.Duration, drain Drain) (Policy, error)

func TrySharedIterations

func TrySharedIterations(workers int, count int64) (Policy, error)

func (Policy) Mode

func (p Policy) Mode() string

func (Policy) Workers

func (p Policy) Workers() int

type PostgresConfig

type PostgresConfig = config.PostgresConfig

type QueryFiles

type QueryFiles struct{}

QueryFiles loads ordinary workload-owned filesystems with local overrides.

func (QueryFiles) Load

func (QueryFiles) Load(files fs.FS, filename string) (*SQL, error)

func (QueryFiles) Override

func (QueryFiles) Override(filename string) (*SQL, error)

Override reads only the explicit filename; missing overrides never use embedded data.

type QueryHandle

type QueryHandle struct {
	Name string
	Text string
}

QueryHandle preserves immutable query identity alongside its text.

type RateHandle

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

func (*RateHandle) Record

func (r *RateHandle) Record(ctx context.Context, value bool, labels ...Label)

type ReportContext

type ReportContext struct {
	Metrics      map[string]MetricSnapshot
	Series       map[string]report.Metric
	Steps        []report.Step
	Measurements map[string]float64
	Status       report.Status
	// contains filtered or unexported fields
}

ReportContext contains final run data available to workload contributors.

func (ReportContext) Diagnostic

func (c ReportContext) Diagnostic(message string) string

Diagnostic formats a report diagnostic without configured credentials.

type ReportContribution

type ReportContribution struct {
	Status report.WorkloadReportStatus
	Reason string
	Data   any
}

type ReportContributor

type ReportContributor func(ReportContext) (ReportContribution, error)

ReportContributor builds one independently versioned workload payload after teardown and final metric collection.

type ReportDeclarations

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

ReportDeclarations owns optional independently versioned workload payloads.

func (*ReportDeclarations) Contribute

func (r *ReportDeclarations) Contribute(kind string, schema int, contributor ReportContributor)

func (*ReportDeclarations) Metadata

func (r *ReportDeclarations) Metadata(key, value string)

func (*ReportDeclarations) Put

func (r *ReportDeclarations) Put(kind string, schema int, value any)

Put copies a directly computed payload at publication time.

func (*ReportDeclarations) Render

func (r *ReportDeclarations) Render(kind string, renderer ReportRenderer)

type ReportOptions

type ReportOptions struct {
	StroppyVersion string
	BuildDigest    string
	RunID          string
	Metadata       map[string]string
}

ReportOptions provides report identity owned by the calling application.

type ReportRenderer

type ReportRenderer func(io.Writer, json.RawMessage) error

ReportRenderer writes human output from the same finalized contribution payload.

type ResolvedParameter

type ResolvedParameter struct {
	Value any
	Info  ParamInfo
}

ResolvedParameter is a copied effective value and provenance.

type Result

type Result struct {
	Status StepStatus
	Err    error
}

Result is a copied outcome; modifying it cannot change execution.

type RetryDecision

type RetryDecision struct {
	Action       ErrorAction
	Facts        driver.ErrorFacts
	DelaySeconds float64
}

RetryDecision records the classified facts and resolved action for one error.

type RetryOptions

type RetryOptions = TxRetryPolicyOptions

RetryOptions is the workload-owned retry configuration.

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts int
	Classify    func(error) driver.ErrorFacts
	Actions     ErrorActionMap
	OnRetry     func(attempt int, err error, decision RetryDecision)
	// contains filtered or unexported fields
}

RetryPolicy combines driver classification with workload-owned actions.

func (RetryPolicy) Retries added in v6.2.1

func (p RetryPolicy) Retries(err error) bool

Retries reports whether the policy would make another attempt after err. A workload that runs its own loop asks this rather than re-deriving a verdict the driver already gave.

type Row

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

Row is owned query data. Cursor Row values are views until the next advance; Copy returns an independent row suitable for retention.

func (Row) At

func (r Row) At[T any](index int) (T, error)

func (Row) Columns

func (r Row) Columns() []string

func (Row) Copy

func (r Row) Copy() Row

func (Row) Float64

func (r Row) Float64(column string) (float64, error)

func (Row) Get

func (r Row) Get[T any](column string) (T, error)

func (Row) Int64

func (r Row) Int64(column string) (int64, error)

func (Row) IsNull

func (r Row) IsNull(column string) (bool, error)

func (Row) String

func (r Row) String(column string) (string, error)

func (Row) Values

func (r Row) Values() []any

type Rows

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

Rows is a streaming cursor. Close returns terminal iteration/finalization errors.

func (*Rows) Close

func (r *Rows) Close() error

func (*Rows) Err

func (r *Rows) Err() error

func (*Rows) Next

func (r *Rows) Next() bool

func (*Rows) Row

func (r *Rows) Row() Row

type RunDefaults

type RunDefaults struct {
	Workers    int
	Iterations int64
	Duration   time.Duration
	Drain      Drain
}

RunDefaults supplies ordinary defaults for the optional standard parameter bundle.

type RunOptions

type RunOptions struct {
	Drivers map[string]DriverConfig
	Params  ParamInputs
	Steps   []string
	NoSteps []string
	Logger  Logger
	Metrics *MetricsConfig
	Report  *ReportOptions
	Capture *CaptureOptions
}

RunOptions is explicit input for one fresh observation/execution operation.

type RunSettings

type RunSettings struct {
	Executor     string
	Workers      int
	Iterations   int64
	Duration     time.Duration
	Drain        Drain
	QueryTimeout time.Duration
}

RunSettings contains resolved values, with no hidden engine override.

func RunParameters

func RunParameters(p *ParamDeclarations, defaults RunDefaults) RunSettings

RunParameters is optional sugar over individual parameter declarations.

func (RunSettings) Policy

func (s RunSettings) Policy() Policy

type SQL

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

SQL is a parsed SQL file split into named sections and the named/anonymous queries within each. Drivers bind :name parameters, so parsing keeps only section/query markers and full-line comment stripping.

func ParseSQL

func ParseSQL(content string) *SQL

ParseSQL parses SQL text into sections (the string form of LoadSQL, for inline SQL).

func (*SQL) Lookup

func (s *SQL) Lookup(section, name string) (QueryHandle, bool)

func (*SQL) Names

func (s *SQL) Names(section string) []string

Names returns the query names of a section in file order. Workloads with a flat query file (no sections) keep every query under the empty section name "".

func (*SQL) Query

func (s *SQL) Query(section, query string) (string, bool)

Query returns the SQL text of one named query within a section.

func (*SQL) Require

func (s *SQL) Require(section, name string) QueryHandle

func (*SQL) Section

func (s *SQL) Section(name string) []string

Section returns the SQL text of every query in a section (anonymous queries included). Empty slice if the section is absent (callers treat missing as no-op).

type SQLConfig

type SQLConfig = config.SQLConfig

type StepDescription

type StepDescription struct {
	Name     string `json:"name"`
	Executor string `json:"executor"`
	Workers  int    `json:"workers"`
	Measured bool   `json:"measured"`
}

StepDescription describes one encountered step, not every possible Go branch.

type StepOption

type StepOption interface {
	// contains filtered or unexported methods
}

func Always

func Always(timeout time.Duration) StepOption

Always allows a reached, selected action to run after failure with a detached cleanup context. It does not bypass step filters or register a finalizer.

func Measure

func Measure() StepOption

Measure includes a once-only step in throughput measurement.

func Use

func Use(ref DriverRef) StepOption

Use selects the default database for this step.

type StepStatus

type StepStatus string

StepStatus describes an immediate step outcome.

const (
	Observed            StepStatus = "observed"
	Completed           StepStatus = "completed"
	CompletedWithErrors StepStatus = "completed_with_errors"
	Skipped             StepStatus = "skipped"
	Blocked             StepStatus = "blocked"
	Failed              StepStatus = "failed"
	Canceled            StepStatus = "canceled"
)

type Test

type Test struct {
	Name   string
	Define func(*Def) error
	// Source publishes package-relative files or a complete project for ejection.
	// Nil means unpublished.
	Source fs.FS
	// SourcePackage is the original import path of a package-relative publication.
	SourcePackage string
}

Test is an ordinary definition value. Mutable run state belongs inside Define.

func Lookup

func Lookup(name string) (Test, bool)

func Register

func Register(test Test) Test

Register stores a value copy and returns it. Importable packages normally call Register from init; declaration-time registration is also supported.

type TransactionOptions

type TransactionOptions struct {
	Name      string
	Isolation TxIsolationName
	Retry     TxRetryPolicyOptions
}

TransactionOptions combines identity, isolation and opt-in whole-body retry.

type Tx

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

Tx is the transaction handle (sugar over driver.Tx; NONE mode delegates to the driver).

func (*Tx) Commit

func (t *Tx) Commit(ctx context.Context) error

func (*Tx) Exec

func (t *Tx) Exec(ctx context.Context, sql string, args map[string]any) error

func (*Tx) ExecQuery

func (t *Tx) ExecQuery(ctx context.Context, q QueryHandle, args map[string]any) error

func (*Tx) Query

func (t *Tx) Query(ctx context.Context, sql string, args map[string]any) (*Rows, error)

func (*Tx) QueryRow

func (t *Tx) QueryRow(ctx context.Context, sql string, args map[string]any) (Row, error)

func (*Tx) QueryValue

func (t *Tx) QueryValue[T any](ctx context.Context, sql string, args map[string]any) (T, error)

func (*Tx) QueryValues

func (t *Tx) QueryValues[T any](ctx context.Context, sql string, args map[string]any) (values []T, err error)

func (*Tx) RawRow

func (t *Tx) RawRow(ctx context.Context, sql string, args map[string]any) (_ []any, err error)

func (*Tx) RawRows

func (t *Tx) RawRows(ctx context.Context, sql string, args map[string]any) (_ [][]any, err error)

func (*Tx) Rollback

func (t *Tx) Rollback(ctx context.Context) error

type TxIsolationName

type TxIsolationName string
const (
	IsoDBDefault       TxIsolationName = "db_default"
	IsoReadUncommitted TxIsolationName = "read_uncommitted"
	IsoReadCommitted   TxIsolationName = "read_committed"
	IsoRepeatableRead  TxIsolationName = "repeatable_read"
	IsoSerializable    TxIsolationName = "serializable"
	IsoConn            TxIsolationName = "conn"
	IsoNone            TxIsolationName = "none"
)

type TxRetryPolicyOptions

type TxRetryPolicyOptions struct {
	MaxAttempts      int
	Idempotent       bool
	Actions          ErrorActionMap
	BaseDelaySeconds float64
	MaxDelaySeconds  float64
	OnRetry          func(attempt int, err error, decision RetryDecision)
}

TxRetryPolicyOptions configures Bench.TxRetryPolicy.

type VU

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

VU is the per-VU execution context for a Go workload. It carries per-iteration ctx + identity; sinks live on root. Step tag and iteration counters are read by the metrics layer and exposed to workloads via Bench.

func (*VU) Context

func (v *VU) Context() context.Context

func (*VU) VUID

func (v *VU) VUID() uint64

type ValidationError

type ValidationError struct {
	Operation string
	Cause     error
}

ValidationError identifies invalid author declarations or configuration. Convenience APIs panic with this value; application boundaries return it as an error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Directories

Path Synopsis
Package testkit runs ordinary workloads without a database or report history.
Package testkit runs ordinary workloads without a database or report history.

Jump to

Keyboard shortcuts

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