runtime

package
v0.0.0-...-ff88eae Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotImplemented       = errors.New("evaluation for this node type not implemented")
	ErrNotFound             = errors.New("identifier not found")
	ErrInternalFuncNotFound = errors.New("internal function not found")
	ErrUnsupportedType      = errors.New("unsupported type for operation")
	ErrInvalidType          = errors.New("invalid type")
)
View Source
var BoolType = decl.BoolType
View Source
var BoolValue = decl.BoolValue
View Source
var FloatType = decl.FloatType
View Source
var FloatValue = decl.FloatValue
View Source
var IntType = decl.IntType
View Source
var IntValue = decl.IntValue
View Source
var NewNewExpr = decl.NewNewExpr
View Source
var NewValue = decl.NewValue
View Source
var Nil = decl.Nil
View Source
var StrType = decl.StrType
View Source
var StringValue = decl.StringValue
View Source
var TupleValue = decl.TupleValue
View Source
var TypeTagFuture = decl.TypeTagFuture

Functions

func AssertLogContains

func AssertLogContains(t *testing.T, logs string, expected string)

AssertLogContains checks that logs contain expected message

func AssertNoLogErrors

func AssertNoLogErrors(t *testing.T, logs string)

AssertNoLogErrors checks that no ERROR level logs were produced

func CaptureLog

func CaptureLog(t *testing.T, level LogLevel) (*bytes.Buffer, func())

CaptureLog captures log output during test execution Returns the captured output and a cleanup function

func Debug

func Debug(format string, args ...any)

Debug logs a debug message using the global logger

func Error

func Error(format string, args ...any)

Error logs an error message using the global logger

func FlowEval

func FlowEval(component, method string, inputRate float64, context *FlowContext) map[string]float64

FlowEval computes outbound traffic rates from a given component.method at inputRate Returns map of {downstreamComponent.method: outputRate}

func GetDefaultFlowStrategy

func GetDefaultFlowStrategy() string

GetDefaultFlowStrategy returns the name of the default flow strategy

func Info

func Info(format string, args ...any)

Info logs an info message using the global logger

func ListFlowStrategies

func ListFlowStrategies() map[string]StrategyInfo

ListFlowStrategies returns all registered flow strategies

func NewComponentInstance

func NewComponentInstance(id string, file *FileInstance, compDecl *ComponentDecl) (comp *ComponentInstance, result Value, err error)

NewComponentInstance creates a new component instanceof the given type.

func QuietTest

func QuietTest(t *testing.T) func()

QuietTest disables logging for the duration of a test Usage: defer QuietTest(t)()

func RegisterFlowNativeMethod

func RegisterFlowNativeMethod(name string, info *FlowNativeMethodInfo)

RegisterFlowNativeMethod registers a native method for flow analysis

func RegisterFlowStrategy

func RegisterFlowStrategy(name string, strategy FlowStrategy) error

RegisterFlowStrategy registers a new flow evaluation strategy

func RunCallInBatches

func RunCallInBatches(system *SystemInstance, obj, method string, nbatches, batchsize int, numworkers int, onBatch func(batch int, batchVals []Value)) (results [][]Value)

func RunTestCall

func RunTestCall(system *SystemInstance, env *Env[Value], obj, method string, ncalls int)

func SetLogLevel

func SetLogLevel(level LogLevel)

SetLogLevel sets the global log level

func SolveSystemFlows

func SolveSystemFlows(entryPoints map[string]float64, context *FlowContext) map[string]float64

SolveSystemFlows performs iterative fixed-point computation for system-wide flows with back-pressure

func SolveSystemFlowsPreservingPaths

func SolveSystemFlowsPreservingPaths(entryPoints map[string]float64, context *FlowContext) map[string]float64

SolveSystemFlowsPreservingPaths performs convergence analysis while preserving existing flow paths

func SolveSystemFlowsWithGenerators

func SolveSystemFlowsWithGenerators(generators []GeneratorEntryPoint, context *FlowContext) map[string]float64

SolveSystemFlowsWithGenerators performs flow analysis with per-generator tracking

func TestLogLevel

func TestLogLevel(t *testing.T, level LogLevel) func()

TestLogLevel sets log level for a specific test Useful for debugging individual tests

func VerboseTest

func VerboseTest(t *testing.T) func()

VerboseTest enables debug logging if test is run with -v flag

func Warn

func Warn(format string, args ...any)

Warn logs a warning message using the global logger

Types

type Aggregator

type Aggregator interface {
	Eval(eval *SimpleEval, env *Env[Value], currTime *core.Duration, futures []Value) (result Value, returned bool)
}

type AllPathsTraceData

type AllPathsTraceData struct {
	TraceID string    `json:"trace_id"`
	Root    TraceNode `json:"root"`
}

AllPathsTraceData represents the complete execution tree (matches proto structure)

type AnalyzeDecl

type AnalyzeDecl = decl.AnalyzeDecl

type ArrivalRateUpdate

type ArrivalRateUpdate struct {
	Component string  `json:"component"`
	Method    string  `json:"method"`
	Rate      float64 `json:"rate"`
}

ArrivalRateUpdate represents a request to update a component method's arrival rate

type AssignmentStmt

type AssignmentStmt = decl.AssignmentStmt

type BinaryExpr

type BinaryExpr = decl.BinaryExpr

type BlockStmt

type BlockStmt = decl.BlockStmt

type CallExpr

type CallExpr = decl.CallExpr

type CaseExpr

type CaseExpr = decl.CaseExpr

type CaseStmt

type CaseStmt = decl.CaseStmt

type ComponentDecl

type ComponentDecl = decl.ComponentDecl

type ComponentDeclBodyItem

type ComponentDeclBodyItem = decl.ComponentDeclBodyItem

Slices for lists

type ComponentInstance

type ComponentInstance struct {
	ObjectInstance

	// The specs about the component
	ComponentDecl *ComponentDecl
	// contains filtered or unexported fields
}

The runtime instance of a component. This could be Native or a UserDefined component

func (*ComponentInstance) GetArrivalRate

func (ci *ComponentInstance) GetArrivalRate(methodName string) float64

GetArrivalRate returns the arrival rate for a specific method. Returns -1 if the component doesn't support arrival rates (infinite bandwidth).

func (*ComponentInstance) GetFlowPattern

func (c *ComponentInstance) GetFlowPattern(method string, inputRate float64) components.FlowPattern

func (*ComponentInstance) GetTotalArrivalRate

func (ci *ComponentInstance) GetTotalArrivalRate() float64

GetTotalArrivalRate returns the sum of all method arrival rates. Returns -1 if the component doesn't support arrival rates.

func (*ComponentInstance) GetUtilizationInfo

func (ci *ComponentInstance) GetUtilizationInfo() []components.UtilizationInfo

GetUtilizationInfo returns utilization information for this component and its children. For SDL components, it aggregates info from all child components that support utilization tracking.

func (*ComponentInstance) ID

func (c *ComponentInstance) ID() string

func (*ComponentInstance) Initializer

func (ci *ComponentInstance) Initializer() (blockStmt *BlockStmt, err error)

A component declaration contains instantiations of components, params, methods etc Specifically when a component is initialized in initializers it is important to not be bound by order. This method compiles the System into a set of statements that can be executed so that all components are intantiated first and then their properties/params are set.

func (*ComponentInstance) NeighborsFromMethod

func (ci *ComponentInstance) NeighborsFromMethod(methodName string) []*NeighborMethod

Returns all the neighbouring component+method from a given component method

func (*ComponentInstance) SetArrivalRate

func (ci *ComponentInstance) SetArrivalRate(methodName string, rate float64) error

SetArrivalRate sets the arrival rate for a specific method on this component. For native components, this delegates to the native implementation if supported. For SDL components, stores the rate internally. Returns nil on success (even if component doesn't support arrival rates).

type ComponentMethod

type ComponentMethod struct {
	Component string `json:"component"`
	Method    string `json:"method"`
}

ComponentMethod identifies a component and method

type DefaultLogger

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

DefaultLogger implements the Logger interface

func NewLogger

func NewLogger(output io.Writer, level LogLevel) *DefaultLogger

NewLogger creates a new logger instance

func (*DefaultLogger) Debug

func (l *DefaultLogger) Debug(format string, args ...any)

Debug logs a debug message

func (*DefaultLogger) Error

func (l *DefaultLogger) Error(format string, args ...any)

Error logs an error message

func (*DefaultLogger) GetLevel

func (l *DefaultLogger) GetLevel() LogLevel

GetLevel returns the current log level

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(format string, args ...any)

Info logs an info message

func (*DefaultLogger) SetLevel

func (l *DefaultLogger) SetLevel(level LogLevel)

SetLevel sets the minimum log level

func (*DefaultLogger) Warn

func (l *DefaultLogger) Warn(format string, args ...any)

Warn logs a warning message

type DistributeExpr

type DistributeExpr = decl.DistributeExpr

type Duration

type Duration = float64

type Edge

type Edge struct {
	ID            string    `json:"id"`
	NextNode      TraceNode `json:"next_node"`
	Label         string    `json:"label"`
	IsAsync       bool      `json:"is_async"`
	IsReverse     bool      `json:"is_reverse"`
	Probability   string    `json:"probability"`
	Condition     string    `json:"condition"`
	IsConditional bool      `json:"is_conditional"`
}

Edge represents a transition from one node to another (matches proto structure)

type EnumDecl

type EnumDecl = decl.EnumDecl

type Env

type Env[T any] = decl.Env[T]

type ErrorCollector

type ErrorCollector = loader.ErrorCollector

type ExecutionTracer

type ExecutionTracer struct {
	Events []*TraceEvent
	// contains filtered or unexported fields
}

ExecutionTracer records the execution flow of a single simulation run.

func NewExecutionTracer

func NewExecutionTracer() *ExecutionTracer

NewExecutionTracer creates a new tracer.

func (*ExecutionTracer) Enter

func (t *ExecutionTracer) Enter(ts core.Duration, kind TraceEventKind, comp *ComponentInstance, method *MethodDecl, args ...string) int64

Enter logs the entry into a function or block. It returns the ID of the newly created event.

func (*ExecutionTracer) Exit

func (t *ExecutionTracer) Exit(ts core.Duration, duration core.Duration, comp *ComponentInstance, method *MethodDecl, retVal Value, err error)

Exit logs the exit from a function or block.

func (*ExecutionTracer) PopParent

func (t *ExecutionTracer) PopParent()

PopParent removes the most recent event ID from the stack.

func (*ExecutionTracer) PushParentID

func (t *ExecutionTracer) PushParentID(id int64)

PushParentID manually pushes a parent ID onto the stack. Used by the aggregator to set the context for evaluating futures.

func (*ExecutionTracer) SetRuntime

func (t *ExecutionTracer) SetRuntime(runtime *Runtime)

SetRuntime sets the runtime reference for metrics processing

type ExpectStmt

type ExpectStmt = decl.ExpectStmt

type ExpectationsDecl

type ExpectationsDecl = decl.ExpectationsDecl

type Expr

type Expr = decl.Expr

type ExprBase

type ExprBase = decl.ExprBase

type ExprStmt

type ExprStmt = decl.ExprStmt

type FileDecl

type FileDecl = decl.FileDecl

type FileInstance

type FileInstance struct {
	Runtime *Runtime
	Decl    *FileDecl
	// contains filtered or unexported fields
}

Runtime information about a Filedecl and its initial environment

func NewFileInstance

func NewFileInstance(r *Runtime, file *FileDecl) *FileInstance

func (*FileInstance) Env

func (f *FileInstance) Env() *Env[Value]

func (*FileInstance) GetComponentDecl

func (f *FileInstance) GetComponentDecl(name string) (*ComponentDecl, error)

GetComponentDecl returns the ComponentDecl for the given name even if it is an import by resolving to the original source

func (*FileInstance) GetEnumDecl

func (f *FileInstance) GetEnumDecl(name string) (*EnumDecl, error)

GetEnumDecl returns the EnumDecl for the given name even if it is an import by resolving to the original source

func (*FileInstance) NewSystem

func (f *FileInstance) NewSystem(systemName string, init bool) (*SystemInstance, core.Duration)

Initialize a new system with the given name. Returns nil if system name is invalid If init is true then the initializer commands are also run for the system along with a new env that is created and set for the System as it's "initial" environment which will be used for all further system/method invocations

type FlowAnalysisResult

type FlowAnalysisResult struct {
	Strategy   string               `json:"strategy"`
	Status     FlowStatus           `json:"status"`
	Iterations int                  `json:"iterations,omitempty"`
	System     string               `json:"system"`
	Generators []GeneratorConfigAPI `json:"generators"`
	Flows      FlowData             `json:"flows"`
	Warnings   []string             `json:"warnings,omitempty"`
}

FlowAnalysisResult contains the results of flow analysis

func EvaluateFlowStrategy

func EvaluateFlowStrategy(strategyName string, system *SystemInstance, generators []GeneratorConfigAPI) (*FlowAnalysisResult, error)

EvaluateFlowStrategy runs flow analysis with the specified strategy

type FlowComparisonResult

type FlowComparisonResult struct {
	Strategy1   string               `json:"strategy1"`
	Strategy2   string               `json:"strategy2"`
	Differences []FlowRateDifference `json:"differences"`
	Similarity  float64              `json:"similarity"` // 0.0 to 1.0
}

FlowComparisonResult represents a comparison between two flow analyses

type FlowContext

type FlowContext struct {
	System     *SystemDecl            // SDL system definition
	Parameters map[string]interface{} // Current parameter values (hitRate, poolSize, etc.)

	// Back-pressure and convergence tracking
	ArrivalRates   map[string]float64 // Current arrival rates per component.method
	SuccessRates   map[string]float64 // Current success rates per component.method
	ServiceTimes   map[string]float64 // Service times per component.method (seconds)
	ResourceLimits map[string]int     // Pool sizes, capacities per component

	// Native component instances for FlowAnalyzable interface
	NativeComponents map[string]components.FlowAnalyzable // component name -> FlowAnalyzable instance

	// Cycle handling configuration
	MaxRetries           int      // Limit exponential growth (recommended: 50)
	ConvergenceThreshold float64  // Fixed-point iteration threshold (recommended: 0.01)
	MaxIterations        int      // Maximum fixed-point iterations (recommended: 10)
	CallStack            []string // Detect infinite recursion

	// Current calling component context for dependency resolution
	CurrentComponent string // Component currently being analyzed

	// Variable outcome tracking for conditional flow analysis
	VariableOutcomes map[string]float64 // variable name -> success rate (for method-local analysis)

	// Traffic generators and their flows (NEW ARCHITECTURE)
	Generators      map[string]*GeneratorConfig `json:"generators"`      // ID -> generator config
	GeneratorFlows  map[string][]FlowPath       `json:"generatorFlows"`  // GeneratorID -> flow paths
	AggregatedFlows map[string]float64          `json:"aggregatedFlows"` // "comp.method" -> total RPS

	// Flow order tracking for visualization (LEGACY - will be replaced)
	FlowOrder int                     // Current flow order counter
	FlowPaths map[string]FlowPathInfo // flowKey -> path info for visualization

	// Generator-specific flow tracking (LEGACY - will be replaced)
	CurrentGeneratorID string            // ID of the generator currently being analyzed
	GeneratorFlowOrder map[string]int    // Per-generator flow order counters
	GeneratorColors    map[string]string // Generator ID -> color mapping
	// contains filtered or unexported fields
}

FlowContext holds the system state and configuration for flow evaluation

func NewFlowContext

func NewFlowContext(system *SystemDecl, parameters map[string]interface{}) *FlowContext

NewFlowContext creates a new FlowContext with sensible defaults

func (*FlowContext) AddGenerator

func (fc *FlowContext) AddGenerator(id, name, target string, rate float64) error

AddGenerator adds a new traffic generator to the flow context

func (*FlowContext) GetActiveGenerators

func (fc *FlowContext) GetActiveGenerators() []*GeneratorConfig

GetActiveGenerators returns all enabled generators

func (*FlowContext) GetAggregatedFlows

func (fc *FlowContext) GetAggregatedFlows() map[string]float64

GetAggregatedFlows returns total flow rates per component.method

func (*FlowContext) GetFlowMetrics

func (fc *FlowContext) GetFlowMetrics() FlowMetrics

GetFlowMetrics returns flow statistics for monitoring

func (*FlowContext) GetGenerator

func (fc *FlowContext) GetGenerator(id string) (*GeneratorConfig, bool)

GetGenerator retrieves a generator by ID

func (*FlowContext) GetGeneratorFlows

func (fc *FlowContext) GetGeneratorFlows(generatorID string) []FlowPath

GetGeneratorFlows returns flows originating from a specific generator

func (*FlowContext) RemoveGenerator

func (fc *FlowContext) RemoveGenerator(id string) error

RemoveGenerator removes a traffic generator from the flow context

func (*FlowContext) Reset

func (fc *FlowContext) Reset()

Reset clears all flow state while preserving generators

func (*FlowContext) SetNativeComponent

func (fc *FlowContext) SetNativeComponent(name string, component components.FlowAnalyzable)

SetNativeComponent registers a native component for flow analysis

func (*FlowContext) SetResourceLimit

func (fc *FlowContext) SetResourceLimit(component string, limit int)

SetResourceLimit sets the resource limit for a component

func (*FlowContext) UpdateGenerator

func (fc *FlowContext) UpdateGenerator(id string, rate float64, enabled bool) error

UpdateGenerator modifies an existing generator

func (*FlowContext) Validate

func (fc *FlowContext) Validate() error

Validate checks flow context consistency

type FlowData

type FlowData struct {
	Edges          []FlowEdgeAPI          `json:"edges"`
	ComponentRates map[string]float64     `json:"componentRates"`
	Metadata       map[string]interface{} `json:"metadata"`
}

FlowData contains the flow analysis data

type FlowEdge

type FlowEdge struct {
	FromComponent *ComponentInstance
	FromMethod    string
	ToComponent   *ComponentInstance
	ToMethod      string
	Rate          float64
}

FlowEdge represents a flow connection between two component methods

type FlowEdgeAPI

type FlowEdgeAPI struct {
	From ComponentMethod `json:"from"`
	To   ComponentMethod `json:"to"`
	Rate float64         `json:"rate"`
}

FlowEdgeAPI represents a flow between two component methods (API version)

type FlowEdgeMap

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

FlowEdgeMap tracks all flow edges in the system

func NewFlowEdgeMap

func NewFlowEdgeMap() *FlowEdgeMap

NewFlowEdgeMap creates a new empty FlowEdgeMap

func (*FlowEdgeMap) AddEdge

func (fem *FlowEdgeMap) AddEdge(fromComp *ComponentInstance, fromMethod string, toComp *ComponentInstance, toMethod string, rate float64)

AddEdge adds a flow edge to the map

func (*FlowEdgeMap) Clear

func (fem *FlowEdgeMap) Clear()

Clear removes all edges

func (*FlowEdgeMap) GetEdges

func (fem *FlowEdgeMap) GetEdges() []FlowEdge

GetEdges returns all flow edges

type FlowMetrics

type FlowMetrics struct {
	TotalRPS     float64            `json:"totalRPS"`     // Total system RPS
	ComponentRPS RateMap            `json:"componentRPS"` // RPS per component instance
	GeneratorRPS map[string]float64 `json:"generatorRPS"` // RPS per generator (still string-based for generator IDs)
}

FlowMetrics represents flow statistics for monitoring

type FlowNativeMethodInfo

type FlowNativeMethodInfo struct {
	// Whether this method induces delay
	HasDelay bool

	// Function to extract delay from AST arguments during flow analysis
	// Returns 0 if delay cannot be determined statically
	ExtractDelay func(args []Expr) core.Duration

	// Whether this method makes external calls (affects flow)
	HasOutflows bool

	// Static outflows if known (e.g., a native logging service)
	// Map of "component.method" -> rate multiplier
	Outflows map[string]float64
}

FlowNativeMethodInfo describes flow and timing characteristics of a native method

func GetFlowNativeMethodInfo

func GetFlowNativeMethodInfo(methodName string) *FlowNativeMethodInfo

GetFlowNativeMethodInfo returns flow analysis info for a native method Returns nil if not registered (caller should use default behavior)

type FlowPath

type FlowPath struct {
	From        string  `json:"from"`        // Source component.method
	To          string  `json:"to"`          // Target component.method
	Rate        float64 `json:"rate"`        // Flow rate (RPS)
	Order       float64 `json:"order"`       // Execution order (supports decimals)
	Condition   string  `json:"condition"`   // Condition expression (e.g., "!(cached)")
	Probability float64 `json:"probability"` // Condition probability [0,1]
	GeneratorID string  `json:"generatorId"` // Which generator originated this flow
}

FlowPath represents a single flow between components with attribution

type FlowPathInfo

type FlowPathInfo struct {
	Order       float64 // Execution order (supports decimals for conditional paths)
	Condition   string  // Condition expression if this is a conditional path
	Probability float64 // Probability of this path being taken
	GeneratorID string  // ID of the generator that originated this flow
	Color       string  // Color for visualization (based on generator)
}

FlowPathInfo tracks information about a flow path for visualization (LEGACY - will be replaced by FlowPath)

type FlowRateDifference

type FlowRateDifference struct {
	Component string  `json:"component"`
	Method    string  `json:"method"`
	Rate1     float64 `json:"rate1"`
	Rate2     float64 `json:"rate2"`
	Delta     float64 `json:"delta"`
	Percent   float64 `json:"percent"` // Percentage difference
}

FlowRateDifference represents a difference in flow rates between strategies

type FlowScope

type FlowScope struct {
	Outer            *FlowScope
	SysEnv           *Env[Value]
	CurrentComponent *ComponentInstance
	CurrentMethod    *MethodDecl
	ArrivalRates     RateMap
	SuccessRates     RateMap
	CallStack        []*ComponentInstance
	FlowEdges        *FlowEdgeMap

	// Variable outcome tracking for conditional flow analysis
	VariableOutcomes map[string]float64
}

FlowScope manages the runtime context for flow evaluation

func NewFlowScope

func NewFlowScope(sysEnv *Env[Value]) *FlowScope

NewFlowScope creates a new root flow scope

func (*FlowScope) ApplyToComponents

func (fs *FlowScope) ApplyToComponents() error

ApplyToComponents applies the calculated arrival rates to the actual components by calling SetArrivalRate on each component instance

func (*FlowScope) GetVariable

func (fs *FlowScope) GetVariable(name string) (Value, bool)

GetVariable retrieves a variable from the current or outer scopes

func (*FlowScope) GetVariableOutcome

func (fs *FlowScope) GetVariableOutcome(varName string) (float64, bool)

GetVariableOutcome retrieves the tracked success rate for a variable

func (*FlowScope) IsInCallStack

func (fs *FlowScope) IsInCallStack(component *ComponentInstance) bool

IsInCallStack checks if a component is already in the call stack (cycle detection)

func (*FlowScope) Pop

func (fs *FlowScope) Pop() *FlowScope

Pop returns the parent scope

func (*FlowScope) Push

func (fs *FlowScope) Push(component *ComponentInstance, method *MethodDecl) *FlowScope

Push creates a new nested scope for entering a component method

func (*FlowScope) ResolveTarget

func (fs *FlowScope) ResolveTarget(target string) (*ComponentInstance, string)

ResolveTarget resolves a target string like "db.Query" to component instance and method This will use the current environment to look up component instances

func (*FlowScope) SetVariable

func (fs *FlowScope) SetVariable(name string, value Value)

SetVariable sets a variable in the current scope

func (*FlowScope) TrackVariableOutcome

func (fs *FlowScope) TrackVariableOutcome(varName string, successRate float64)

TrackVariableOutcome records the success rate of a variable (for conditional evaluation)

type FlowState

type FlowState struct {
	Strategy        string             `json:"strategy"`
	AppliedAt       string             `json:"appliedAt,omitempty"`
	Rates           map[string]float64 `json:"rates"`
	ManualOverrides map[string]float64 `json:"manualOverrides,omitempty"`
}

FlowState represents the current flow analysis state

type FlowStatus

type FlowStatus string

FlowStatus indicates the status of flow analysis

const (
	FlowStatusConverged FlowStatus = "converged"
	FlowStatusPartial   FlowStatus = "partial"
	FlowStatusFailed    FlowStatus = "failed"
)

type FlowStrategy

type FlowStrategy interface {
	// Evaluate performs flow analysis given system and generators
	Evaluate(system *SystemInstance, generators []GeneratorConfigAPI) (*FlowAnalysisResult, error)

	// GetInfo returns metadata about this strategy
	GetInfo() StrategyInfo

	// IsAvailable checks if this strategy can be used
	IsAvailable() bool
}

FlowStrategy defines the interface for different flow evaluation strategies

func GetFlowStrategy

func GetFlowStrategy(name string) (FlowStrategy, error)

GetFlowStrategy retrieves a registered flow strategy

type ForStmt

type ForStmt = decl.ForStmt

type Frame

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

func NewFrame

func NewFrame(outer *Frame) *Frame

NewFrame creates a new frame nested within an outer one.

func (*Frame) AddFuture

func (f *Frame) AddFuture(name string, future *Future)

AddFuture registers metadata for a future started in this frame. Called when evaluating a 'go var = ...' statement/expression.

func (*Frame) Get

func (f *Frame) Get(name string) (Value, bool)

Get retrieves a value by name, checking the current frame first, then recursively checking outer frames.

func (*Frame) GetFuture

func (f *Frame) GetFuture(name string) (*Future, bool)

GetFuture retrieves future metadata associated with a name, checking current and outer frames.

func (*Frame) Set

func (f *Frame) Set(name string, value Value)

Set defines or updates a value in the *current* frame's locals map. Use this for function parameters, let bindings, etc., within the current scope.

func (*Frame) String

func (f *Frame) String() string

String representation for debugging (optional but helpful).

type Future

type Future struct {
	// The frame from which this future was called
	CallerFrame *Frame

	// Has the Await been called on this
	Awaited bool
}

A future that was spawned in side a frame

type FutureValue

type FutureValue = decl.FutureValue

type GeneratorConfig

type GeneratorConfig struct {
	ID      string                 `json:"id"`      // Unique identifier (e.g., "load1")
	Name    string                 `json:"name"`    // Human-readable name
	Target  string                 `json:"target"`  // Method target (e.g., "server.Lookup")
	Rate    float64                `json:"rate"`    // Requests per second
	Enabled bool                   `json:"enabled"` // Whether generator is active
	Options map[string]interface{} `json:"options"` // Extensible config
}

GeneratorConfig represents a traffic generator specification

type GeneratorConfigAPI

type GeneratorConfigAPI struct {
	ID        string  `json:"id"`
	Component string  `json:"component"`
	Method    string  `json:"method"`
	Rate      float64 `json:"rate"`
}

GeneratorConfigAPI represents a traffic generator configuration for the Flow API This is the API-friendly version (uses component names, not instances)

type GeneratorEntryPoint

type GeneratorEntryPoint struct {
	Target      string  // component.method target
	Rate        float64 // requests per second
	GeneratorID string  // generator identifier
}

GeneratorEntryPoint represents an entry point with generator information (LEGACY)

type GeneratorEntryPointRuntime

type GeneratorEntryPointRuntime struct {
	Component   *ComponentInstance // Component instance
	Method      string             // Method name
	Rate        float64            // requests per second
	GeneratorID string             // generator identifier
}

GeneratorEntryPointRuntime represents an entry point with runtime component instance

type GoExpr

type GoExpr = decl.GoExpr

type GroupInfo

type GroupInfo struct {
	GroupStart int32  `json:"group_start"`
	GroupEnd   int32  `json:"group_end"`
	GroupLabel string `json:"group_label"`
	GroupType  string `json:"group_type"`
}

GroupInfo allows flexible grouping of edges with labels (matches proto structure)

type IDGen

type IDGen interface {
	NextID(class string) string
}

type IdentifierExpr

type IdentifierExpr = decl.IdentifierExpr

type IfStmt

type IfStmt = decl.IfStmt

type ImportDecl

type ImportDecl = decl.ImportDecl

type InitStmt

type InitStmt struct {
	From     *InitStmt
	Pos      Location
	Attrib   string
	CompInst *ComponentInstance // this should be From.CompInst.Attrib.  If From == nil then this is a System level component
}

type InstanceDecl

type InstanceDecl = decl.InstanceDecl

type LetStmt

type LetStmt = decl.LetStmt

type LiteralExpr

type LiteralExpr = decl.LiteralExpr

type Location

type Location = decl.Location

type LogLevel

type LogLevel int

LogLevel represents the severity of a log message

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
	LogLevelOff
)

func GetLogLevel

func GetLogLevel() LogLevel

GetLogLevel returns the current global log level

func ParseLogLevel

func ParseLogLevel(s string) (LogLevel, error)

ParseLogLevel parses a string into a LogLevel

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of a log level

type Logger

type Logger interface {
	Debug(format string, args ...any)
	Info(format string, args ...any)
	Warn(format string, args ...any)
	Error(format string, args ...any)
	SetLevel(level LogLevel)
	GetLevel() LogLevel
}

Logger interface for structured logging

type MemberAccessExpr

type MemberAccessExpr = decl.MemberAccessExpr

type MethodDecl

type MethodDecl = decl.MethodDecl

type MethodValue

type MethodValue = decl.MethodValue

type NativeMethod

type NativeMethod func(eval *SimpleEval, env *Env[Value], currTime *core.Duration, args ...Value) (result Value, returned bool)

type NativeObject

type NativeObject interface {
	Set(name string, value Value) error
	Get(name string) (Value, bool)
}

type NativeWrapper

type NativeWrapper struct {
	Name        string
	NativeValue any
}

func (*NativeWrapper) Get

func (n *NativeWrapper) Get(name string) (val Value, ok bool)

GetParam for native components is tricky. How do we map a Go field back to an Value? Option 1: Don't support GetParam directly for native components via the interface. Option 2: Use reflection, get the Go field value, wrap it in LeafNode/VarState. (Complex) Let's go with Option 2 for now, but only for simple types.

func (*NativeWrapper) Set

func (n *NativeWrapper) Set(name string, value Value) error

SetParam sets the evaluated parameter value for this instance. For DSL components, this sets an Value. For Native components, it is upto the component to manage the value of the Value

type NeighborMethod

type NeighborMethod struct {
	Component  *ComponentInstance
	MethodName string
}

type Node

type Node = decl.Node

type NodeInfo

type NodeInfo = decl.NodeInfo

type ObjectInstance

type ObjectInstance struct {
	// Where the component is defined
	File *FileInstance

	// Whether the component is native or not
	// For native components, parameters, dependencies and methods are handled
	// natively via interface methods
	IsNative       bool
	NativeInstance NativeObject

	// Initial env for this instance
	Env *Env[Value]
	// contains filtered or unexported fields
}

Objects are general items with parameters, components and methods We have 2 methods in our system so far - Components and Methods

func NewObjectInstance

func NewObjectInstance(file *FileInstance, nativeValue NativeObject) ObjectInstance

func (*ObjectInstance) Get

func (ci *ObjectInstance) Get(name string) (Value, bool)

func (*ObjectInstance) Set

func (ci *ObjectInstance) Set(name string, value Value) error

=================== SetParam sets the evaluated parameter value for this instance. For DSL components, this sets an Value. For Native components, it is upto the component to manage the value of the Value

type OptionsDecl

type OptionsDecl = decl.OptionsDecl

type ParamDecl

type ParamDecl = decl.ParamDecl

type PathTraversal

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

PathTraversal performs breadth-first traversal to discover all possible execution paths

Current limitations:

  • Control flow dependencies are not properly represented. All method calls within a method are shown as sibling edges rather than showing sequential/conditional relationships. For example, if a method calls A, then conditionally calls B or C, this will show A, B, and C as three sibling edges rather than A followed by a choice between B and C.

func NewPathTraversal

func NewPathTraversal(l *loader.Loader) *PathTraversal

NewPathTraversal creates a new path traversal engine

func (*PathTraversal) TraceAllPaths

func (pt *PathTraversal) TraceAllPaths(currentCompName string, compDecl *ComponentDecl, methodName string, maxDepth int32) (*AllPathsTraceData, error)

TraceAllPaths performs breadth-first traversal starting from the given component.method

type RateMap

type RateMap map[*ComponentInstance]map[string]float64

RateMap tracks flow rates per component instance and method

func FlowEvalRuntime

func FlowEvalRuntime(component *ComponentInstance, method string, inputRate float64, scope *FlowScope) RateMap

FlowEvalRuntime computes outbound traffic rates from a given component instance and method Returns RateMap of downstream component instances and their methods with rates

func NewRateMap

func NewRateMap() RateMap

NewRateMap creates a new empty RateMap

func SolveSystemFlowsRuntime

func SolveSystemFlowsRuntime(generators []GeneratorEntryPointRuntime, scope *FlowScope) RateMap

SolveSystemFlowsRuntime performs flow analysis using runtime component instances This implements a two-phase approach: 1. Flow propagation through the component graph 2. Iterative back-pressure adjustment until convergence

func (RateMap) AddFlow

func (rm RateMap) AddFlow(component *ComponentInstance, method string, rate float64)

AddFlow adds or updates the flow rate for a component method

func (RateMap) Clear

func (rm RateMap) Clear()

Clear removes all entries from the RateMap

func (RateMap) Copy

func (rm RateMap) Copy() RateMap

Copy creates a deep copy of the RateMap

func (RateMap) GetComponentRate

func (rm RateMap) GetComponentRate(component *ComponentInstance) float64

GetComponentRate returns the sum of all method rates for a specific component

func (RateMap) GetRate

func (rm RateMap) GetRate(component *ComponentInstance, method string) float64

GetRate returns the flow rate for a component method

func (RateMap) GetTotalRate

func (rm RateMap) GetTotalRate() float64

GetTotalRate returns the sum of all rates in the map

func (RateMap) SetRate

func (rm RateMap) SetRate(component *ComponentInstance, method string, rate float64)

SetRate sets the exact rate for a component method (replacing any existing value)

type RefValue

type RefValue = decl.RefValue

type ReturnStmt

type ReturnStmt = decl.ReturnStmt

type Runtime

type Runtime struct {
	Loader        *loader.Loader
	NativeObjects []any
	// contains filtered or unexported fields
}

func NewRuntime

func NewRuntime(loader *loader.Loader) (r *Runtime)

func (*Runtime) AvailableSystems

func (r *Runtime) AvailableSystems() (out map[string]*SystemDecl)

Get all available system declarations across all file instnces as a map

func (*Runtime) BatchSetParams

func (r *Runtime) BatchSetParams(system *SystemInstance, paramPaths []string, newValues []decl.Value, oldValues map[string]decl.Value) (err error)

func (*Runtime) CreateAggregator

func (r *Runtime) CreateAggregator(name string, aggParams []Value) Aggregator

func (*Runtime) CreateNativeComponent

func (r *Runtime) CreateNativeComponent(compDecl *ComponentDecl) NativeObject

func (*Runtime) GetParam

func (r *Runtime) GetParam(system *SystemInstance, paramPath string) (value decl.Value, err error)

Gets the value of a parameter given by a path "comp1.comp2...compN.ParamName" starting at a given System and returns its Value

func (*Runtime) LoadFile

func (r *Runtime) LoadFile(filePath string) (*FileInstance, error)

Gets the initial run time environment for a File which would include its parameters and component creators

func (*Runtime) NewSystem

func (r *Runtime) NewSystem(systemName string) (sysInst *SystemInstance, err error)

Looks up all the files for the system maching the given name and initializes it

func (*Runtime) RegisterNativeMethod

func (r *Runtime) RegisterNativeMethod(name string, f NativeMethod)

func (*Runtime) SetParam

func (r *Runtime) SetParam(system *SystemInstance, paramPath string, newValue decl.Value) (oldValue decl.Value, err error)

Sets the value of a parameter given by a path "comp1.comp2...compN.ParamName" starting at a given System and sets its new value. Returns the oldValue (whether success or failure) and returns an error if setting failed

type RuntimeFlowStrategy

type RuntimeFlowStrategy struct{}

RuntimeFlowStrategy implements flow evaluation using the runtime-based approach

func (*RuntimeFlowStrategy) Evaluate

func (s *RuntimeFlowStrategy) Evaluate(system *SystemInstance, generators []GeneratorConfigAPI) (*FlowAnalysisResult, error)

Evaluate performs flow analysis using SolveSystemFlowsRuntime

func (*RuntimeFlowStrategy) GetInfo

func (s *RuntimeFlowStrategy) GetInfo() StrategyInfo

GetInfo returns metadata about this strategy

func (*RuntimeFlowStrategy) IsAvailable

func (s *RuntimeFlowStrategy) IsAvailable() bool

IsAvailable checks if this strategy can be used

type SampleExpr

type SampleExpr = decl.SampleExpr

type SetStmt

type SetStmt = decl.SetStmt

type SimpleEval

type SimpleEval struct {
	ErrorCollector

	RootFile *FileInstance
	Rand     *rand.Rand
	Tracer   Tracer
	Errors   []error
	// contains filtered or unexported fields
}

A simple evaluator

func NewSimpleEval

func NewSimpleEval(fi *FileInstance, tracer Tracer) *SimpleEval

func (*SimpleEval) Eval

func (s *SimpleEval) Eval(node Node, env *Env[Value], currTime *core.Duration) (result Value, returned bool)

The main Eval loop of an expression/statement

func (*SimpleEval) EvalInitSystem

func (s *SimpleEval) EvalInitSystem(sys *SystemInstance, env *Env[Value], currTime *core.Duration) (result Value, returned bool)

func (*SimpleEval) EvalStatements

func (s *SimpleEval) EvalStatements(stmts []Stmt, env *Env[Value]) (result []Value, returned bool, timeTaken core.Duration)

type SimpleIDGen

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

func (*SimpleIDGen) NextID

func (s *SimpleIDGen) NextID(class string) string

type Stmt

type Stmt = decl.Stmt

type StrategyInfo

type StrategyInfo struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Status      string   `json:"status"`
	Limitations []string `json:"limitations"`
	Recommended bool     `json:"recommended"`
}

StrategyInfo provides metadata about a flow strategy

type SwitchStmt

type SwitchStmt = decl.SwitchStmt

type SystemDecl

type SystemDecl = decl.SystemDecl

type SystemDeclBodyItem

type SystemDeclBodyItem = decl.SystemDeclBodyItem

type SystemInstance

type SystemInstance struct {
	// Where the system is defined
	File   *FileInstance
	System *SystemDecl

	// Holds the component instances and parameters
	Env *Env[Value]
}

func NewSystemInstance

func NewSystemInstance(file *FileInstance, system *SystemDecl) *SystemInstance

Initializes a new runtime System instance and its root environment

func (*SystemInstance) AllComponents

func (si *SystemInstance) AllComponents() []*ComponentInstance

AllComponents returns all component instances in the system

func (*SystemInstance) FindComponent

func (s *SystemInstance) FindComponent(fqn string) (out *ComponentInstance)

Finds a nested component a.b.c starting at the root of a system

func (*SystemInstance) GetSystemName

func (s *SystemInstance) GetSystemName() string

GetSystemName returns the name of the system

func (*SystemInstance) GetUninitializedComponents

func (s *SystemInstance) GetUninitializedComponents(env *Env[Value]) (items []*InitStmt)

Goes through all components and gets uninitialized components so user knows what/how to set them This is usually called after the Initializer expression is called but before any other expressions are called.

func (*SystemInstance) Initializer

func (s *SystemInstance) Initializer() (blockStmt *BlockStmt, err error)

A system declaration contains instantiations of components and other statemetns. Specifically in initializers it is important to not be bound by order. This method compiles the System into a set of statements that can be executed so that all components are intantiated first and then their properties/params are set.

func (*SystemInstance) RecomputeAllFlows

func (si *SystemInstance) RecomputeAllFlows(entryPoints map[string]float64) error

RecomputeAllFlows recalculates flows for all entry points in the system. Entry points are typically traffic generators or external interfaces.

func (*SystemInstance) RecomputeFlows

func (si *SystemInstance) RecomputeFlows(component, method string, inputRate float64) error

RecomputeFlows uses FlowEval to compute downstream traffic flows from a given entry point.

func (*SystemInstance) UpdateMethodArrivalRate

func (si *SystemInstance) UpdateMethodArrivalRate(componentName, methodName string, rate float64) error

UpdateMethodArrivalRate updates the arrival rate for a specific method on a component and triggers FlowEval to recompute downstream effects.

type TestNative

type TestNative struct {
	Name string
}

TestNative represents a hash-based index structure (e.g., static, extendible, linear)

func NewTestNative

func NewTestNative(name string) *TestNative

NewTestNative creates and initializes a new TestNative component.

func (*TestNative) Get

func (n *TestNative) Get(name string) (v decl.Value, ok bool)

func (*TestNative) Init

func (t *TestNative) Init() *TestNative

Init initializes the TestNative with defaults.

func (*TestNative) ReadBool

func (t *TestNative) ReadBool() (val Value)

func (*TestNative) ReadFloat32

func (t *TestNative) ReadFloat32() (val Value)

func (*TestNative) ReadFloat64

func (t *TestNative) ReadFloat64() (val Value)

func (*TestNative) ReadInt

func (t *TestNative) ReadInt() (val Value)

func (*TestNative) ReadInt32

func (t *TestNative) ReadInt32() (val Value)

func (*TestNative) ReadInt64

func (t *TestNative) ReadInt64() (val Value)

func (*TestNative) ReadOutcomes

func (t *TestNative) ReadOutcomes() *sc.Outcomes[sc.AccessResult]

This will test if AccessResult can be converted to a Value - and if so how

func (*TestNative) ReadOutcomesAsTupleValues

func (t *TestNative) ReadOutcomesAsTupleValues() *sc.Outcomes[Value]

func (*TestNative) ReadString

func (t *TestNative) ReadString() (val Value)

func (*TestNative) Set

func (n *TestNative) Set(name string, value decl.Value) error

type ThunkValue

type ThunkValue = decl.ThunkValue

type TraceData

type TraceData struct {
	System     string        `json:"system"`
	EntryPoint string        `json:"entry_point"`
	Events     []*TraceEvent `json:"events"`
}

TraceData is the top-level structure for a trace file.

type TraceEvent

type TraceEvent struct {
	Kind         TraceEventKind     `json:"kind"`
	ParentID     int64              `json:"parent_id,omitempty"`
	ID           int64              `json:"id"`
	Timestamp    core.Duration      `json:"ts"`            // Virtual time in simulation
	Duration     core.Duration      `json:"dur,omitempty"` // Duration in virtual time
	Component    *ComponentInstance `json:"-"`             // Component instance (nil for native/global methods)
	Method       *MethodDecl        `json:"-"`             // Method declaration
	Arguments    []string           `json:"args,omitempty"`
	ReturnValue  string             `json:"ret,omitempty"`
	ErrorMessage string             `json:"err,omitempty"`
	// Computed fields for JSON serialization
	ComponentName string `json:"component,omitempty"`
	MethodName    string `json:"method,omitempty"`
}

TraceEvent represents a single event in an execution trace.

func (*TraceEvent) GetComponentName

func (e *TraceEvent) GetComponentName() string

GetComponentName returns the component name for metrics/display

func (*TraceEvent) GetMethodName

func (e *TraceEvent) GetMethodName() string

GetMethodName returns the method name for metrics/display

func (*TraceEvent) Target

func (e *TraceEvent) Target() string

Target returns the target string for backward compatibility with viz package

type TraceEventKind

type TraceEventKind string

TraceEventKind defines the type of a trace event.

const (
	EventEnter TraceEventKind = "enter"
	EventExit  TraceEventKind = "exit"
	EventGo    TraceEventKind = "go"
	EventWait  TraceEventKind = "wait"
)

type TraceNode

type TraceNode struct {
	StartingTarget string      `json:"starting_target"`
	Edges          []Edge      `json:"edges"`
	Groups         []GroupInfo `json:"groups"`
}

TraceNode represents a single node in the execution tree (matches proto structure)

type Tracer

type Tracer interface {
	Enter(ts core.Duration, kind TraceEventKind, comp *ComponentInstance, method *MethodDecl, args ...string) int64
	Exit(ts core.Duration, duration core.Duration, comp *ComponentInstance, method *MethodDecl, retVal Value, err error)

	// PushParentID manually pushes a parent ID onto the stack.
	// Used by the aggregator to set the context for evaluating futures.
	PushParentID(id int64)

	// PopParent removes the most recent event ID from the stack.
	PopParent()
}

type TupleExpr

type TupleExpr = decl.TupleExpr

type Type

type Type = decl.Type

type TypeDecl

type TypeDecl = decl.TypeDecl

type UnaryExpr

type UnaryExpr = decl.UnaryExpr

type UsesDecl

type UsesDecl = decl.UsesDecl

type Value

type Value = decl.Value

func AccessResultToValue

func AccessResultToValue(ar sc.AccessResult) (val Value)

func InvokeMethod

func InvokeMethod(nativeValue any, methodName string, args []Value, env *Env[Value], currTime *core.Duration, rnd *rand.Rand, shouldSample bool) (val Value, err error)

func Native_delay

func Native_delay(eval *SimpleEval, env *Env[Value], currTime *core.Duration, args ...Value) (result Value, returned bool)

func Native_log

func Native_log(eval *SimpleEval, env *Env[Value], currTime *core.Duration, args ...Value) (result Value, returned bool)

type WaitAll

type WaitAll struct {
	TimeoutValue       core.Duration
	SuccessResultCodes []Value
}

func (*WaitAll) Eval

func (t *WaitAll) Eval(eval *SimpleEval, env *Env[Value], currTime *core.Duration, futures []Value) (result Value, returned bool)

type WaitAny

type WaitAny struct {
	TimeoutValue       core.Duration
	SuccessResultCodes []Value
}

func (*WaitAny) Eval

func (t *WaitAny) Eval(eval *SimpleEval, env *Env[Value], currTime *core.Duration, futures []Value) (result Value, returned bool)

type WaitExpr

type WaitExpr = decl.WaitExpr

Jump to

Keyboard shortcuts

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