bench

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CacheVersionInstanceID is the stable selector used by the benchmark CLI.
	CacheVersionInstanceID = "python-cache-version-v1"
	// CacheVersionRule is the treatment lesson's stable identity.
	CacheVersionRule = "bump-cached-response-version"
)
View Source
const (
	// ExportRegistryInstanceID is the stable selector used by the benchmark CLI.
	ExportRegistryInstanceID = "go-export-registry-v1"
	// ExportRegistryRule is the treatment lesson's stable identity.
	ExportRegistryRule = "register-async-export-format"
)
View Source
const (
	// HookDeliveryAlways repeats matching context on every edit.
	HookDeliveryAlways = reviews.HookDeliveryAlways
	// HookDeliveryOncePerContext suppresses a delivered lesson until compaction.
	HookDeliveryOncePerContext = reviews.HookDeliveryOncePerContext
)
View Source
const (
	// SchemaSyncInstanceID is the stable selector used by the benchmark CLI.
	SchemaSyncInstanceID = "python-ts-schema-sync-v1"
	// SchemaSyncRule is the treatment lesson's stable identity.
	SchemaSyncRule = "sync-generated-api-client"
)
View Source
const ResultSchemaVersion = 6

ResultSchemaVersion is the immutable contract emitted by the current harness and accepted by strict reporting. Version 6 adds explicit hook delivery intensity while strict reporting continues to accept frozen v5 evidence without rewriting it.

Variables

This section is empty.

Functions

func FileSHA256

func FileSHA256(path string) (string, error)

FileSHA256 returns the digest used to bind result rows to the exact Seamark executable that served their hooks.

func Fingerprint

func Fingerprint(cfg RunConfig) (string, error)

Fingerprint binds cost estimates and result pooling to one task, agent configuration, runtime, and Seamark binary. The command itself is hashed, never persisted, because custom adapters may carry sensitive arguments.

func GenerateSchemaSyncFixture

func GenerateSchemaSyncFixture(dir string) error

GenerateSchemaSyncFixture creates a small mixed-language monorepo whose git history contains one earlier backend-only schema change and its follow-up generated-client fix. The current checkout is healthy and carries no Seamark treatment files.

func InstanceIDs

func InstanceIDs() []string

InstanceIDs returns the stable CLI selectors in catalogue order.

func Preflight

func Preflight(ctx context.Context, cfg RunConfig) error

Preflight validates every invariant that can be checked without spending an agent call: deterministic generation, a clean and healthy base tree, a naive task-only solution the invariant judge must reject, a canonical passing solution, and uncontaminated arm wiring.

func PriorCostFor

func PriorCostFor(path, fingerprint string) (rows int, meanInput int64, meanCost float64, ok bool)

PriorCostFor only pools rows from the same immutable run fingerprint. An estimate made from another model, task, or runtime is worse than no estimate because it creates false confidence before a paid run.

func ValidateResultRow

func ValidateResultRow(row Row) error

ValidateResultRow enforces the semantic contract documented by the versioned schemas in bench/. It is intentionally stricter than ReadRows, whose best-effort behavior remains useful for historical cost estimation.

Types

type Arm

type Arm string

Arm is one experimental condition. The fixture itself carries no seamark artifacts; each arm installs exactly what it measures.

const (
	// ArmHookOff is the true baseline: no lesson anywhere, no hook.
	ArmHookOff Arm = "hook-off"
	// ArmFileOnly commits the real lesson to lessons.yaml but wires no
	// hook: delivery depends on the agent discovering the file. This
	// is the mechanism arm — a committed lessons.yaml is itself a
	// delivery channel, and the hook's claim is beating it.
	ArmFileOnly Arm = "file-only"
	// ArmPlacebo wires the hook with a same-size lesson that carries
	// no information about the mistake: the cost/attention control.
	ArmPlacebo Arm = "placebo"
	// ArmHookOn is the full treatment: real lesson, hook wired.
	ArmHookOn Arm = "hook-on"
)

type ArmReport

type ArmReport struct {
	Attempted        int
	Valid            int
	TaskDone         int
	InvariantPass    int
	ContextTokens    int64
	CostUSD          float64
	HookMatches      int
	HookInjections   int
	HookRepeated     int
	HookSuppressed   int
	HookContextBytes int
}

ArmReport aggregates valid and invalid attempts for one arm.

type BenchmarkReport

type BenchmarkReport struct {
	ResultSchemaVersion int
	ClaimSchemaVersion  int
	EvidenceFrom        string
	EvidenceTo          string
	Inputs              []ReportInput
	Cohorts             []CohortReport
	Assessments         []ClaimAssessment
}

BenchmarkReport is a deterministic summary of explicit raw inputs.

func BuildBenchmarkReport

func BuildBenchmarkReport(paths []string, registry ClaimRegistry) (BenchmarkReport, error)

BuildBenchmarkReport strictly reads the requested JSONL files. Malformed or semantically invalid rows fail the report instead of disappearing.

func (BenchmarkReport) Markdown

func (r BenchmarkReport) Markdown() string

Markdown renders a deterministic, reviewable report. Percentages are point estimates; the paired discordance counts remain visible so tiny samples do not look conclusive.

type CheckResult

type CheckResult struct {
	Command  string `json:"command"`
	Pass     bool   `json:"pass"`
	TimedOut bool   `json:"timed_out,omitempty"`
	Output   string `json:"output,omitempty"`
}

CheckResult is the persisted result of one validation command.

type Claim

type Claim struct {
	ID                           string   `yaml:"id"`
	Claim                        string   `yaml:"claim"`
	PrimaryMetric                string   `yaml:"primary_metric"`
	Comparison                   string   `yaml:"comparison"`
	Direction                    string   `yaml:"direction"`
	RequiredModel                string   `yaml:"required_model"`
	RequiredEffort               string   `yaml:"required_effort"`
	RequireCleanSeamark          bool     `yaml:"require_clean_seamark"`
	MinimumEffect                float64  `yaml:"minimum_effect"`
	MinimumInstanceEffect        float64  `yaml:"minimum_instance_effect"`
	MaximumHarmfulInterference   float64  `yaml:"maximum_harmful_interference"`
	MinimumInstances             int      `yaml:"minimum_instances"`
	MinimumValidPairsPerInstance int      `yaml:"minimum_valid_pairs_per_instance"`
	Instances                    []string `yaml:"instances"`
}

Claim defines one falsifiable product claim and its evidence floor.

type ClaimAssessment

type ClaimAssessment struct {
	ID                  string
	Definition          Claim
	Status              string
	Reason              string
	QualifyingInstances int
	MeanEffect          float64
	WorstInstanceEffect float64
	HarmfulInterference float64
}

ClaimAssessment says whether the supplied evidence has reached the frozen floor. A positive effect with too few independent instances stays insufficient rather than being promoted to a pass.

type ClaimRegistry

type ClaimRegistry struct {
	SchemaVersion int     `yaml:"schema_version"`
	Claims        []Claim `yaml:"claims"`
}

ClaimRegistry is the versioned set of thresholds frozen before expanding a benchmark corpus.

func LoadClaimRegistry

func LoadClaimRegistry(path string) (ClaimRegistry, error)

LoadClaimRegistry parses and validates the committed claim thresholds.

func (ClaimRegistry) Validate

func (r ClaimRegistry) Validate() error

Validate rejects claim files that could silently weaken or ambiguously define the evidence threshold.

type CohortReport

type CohortReport struct {
	Instance         string
	Fingerprint      string
	Task             string
	TaskSHA          string
	Pin              string
	Fixture          string
	RequestedModel   string
	Model            string
	SeamarkVersion   string
	SeamarkSHA       string
	AgentVersion     string
	Effort           string
	HookDelivery     HookDeliveryMode
	RuntimeID        string
	MaxBudgetUSD     float64
	Rows             int
	ValidPairs       int
	FavorablePairs   int
	UnfavorablePairs int
	TiedPairs        int
	HarmfulPairs     int
	HookOn           ArmReport
	HookOff          ArmReport
}

CohortReport is one immutable experiment fingerprint. Different harness, fixture, model, or runtime identities are never pooled.

func (CohortReport) Effect

func (c CohortReport) Effect() (float64, bool)

Effect returns the hook-on minus hook-off invariant-pass rate, conditional on completing the visible task in each arm.

func (CohortReport) EffectInterval95

func (c CohortReport) EffectInterval95() (low, high float64, ok bool)

EffectInterval95 returns a conservative Newcombe-style 95% Wilson score interval for the difference between the two conditional proportions. Paired direction counts are reported separately because they preserve information this interval does not model.

type Command

type Command struct {
	Name    string
	Args    []string
	Timeout time.Duration
}

Command is a deterministic repository-local validation command. Hidden task/invariant judges stay in Go; these commands answer whether the tree the agent left behind still builds and passes its public checks.

func (Command) String

func (c Command) String() string

type HookDeliveryMode

type HookDeliveryMode = reviews.HookDeliveryMode

HookDeliveryMode is the lessons hook policy measured by a benchmark cohort.

type Instance

type Instance struct {
	ID          string
	Rule        string
	Task        string
	LessonYAML  string
	PlaceboYAML string

	Generate  func(string) error
	Judge     func(string) (Verdict, error)
	ApplyGold func(string) error
	// ApplyNaive installs a task-complete solution that deliberately omits the
	// owner invariant. Preflight uses it to prove that the two judges actually
	// discriminate the failure mode the experiment claims to measure.
	ApplyNaive func(string) error
	// JudgeVersion must change whenever verdict semantics change. It binds
	// persisted rows to the exact interpretation used by this instance.
	JudgeVersion string
	Checks       []Command

	// ExploreFiles are repository-relative paths whose appearance in an
	// assistant message is useful diagnostic evidence. They do not affect the
	// verdict.
	ExploreFiles []string
	// contains filtered or unexported fields
}

Instance is one immutable benchmark problem. The runner deliberately knows nothing about the fixture's language or mistake class: generation, judging, and verification all live here so additional instances do not fork the experimental harness.

func CacheVersionInstance

func CacheVersionInstance() Instance

CacheVersionInstance models an owner-only compatibility rule: changing a cached response shape requires a namespace bump even though the presenter and its public tests pass without one.

func ExportRegistryInstance

func ExportRegistryInstance() Instance

ExportRegistryInstance models a split synchronous/asynchronous ownership rule: the visible preview API and its tests do not exercise the worker's separately maintained formatter registry.

func InstanceByID

func InstanceByID(id string) (Instance, error)

InstanceByID resolves one CLI-facing benchmark instance. An empty selector retains the schema-sync instance as the backwards-compatible default.

func Instances

func Instances() []Instance

Instances returns the stable benchmark catalogue. Values are constructed on demand so callers can safely customize them without mutating shared state. Catalogue membership is intentionally outside the execution fingerprint: adding an unrelated fixture must not invalidate an existing cohort.

func SchemaSyncInstance

func SchemaSyncInstance() Instance

SchemaSyncInstance models a recurring owner-only contract: backend API changes require an explicit generated-client refresh that ordinary backend tests do not enforce. The repository is synthetic and deterministic, but the workflow is the same one used by mixed Python/TypeScript monorepos.

func (Instance) TaskSHA

func (i Instance) TaskSHA() string

TaskSHA identifies the exact problem statement without copying it into every result row.

func (Instance) Validate

func (i Instance) Validate() error

Validate rejects incomplete instances before they can spend an agent call.

type ModelUsage

type ModelUsage struct {
	InputTokens         int64   `json:"input_tokens,omitempty"`
	CacheReadTokens     int64   `json:"cache_read_input_tokens,omitempty"`
	CacheCreationTokens int64   `json:"cache_creation_input_tokens,omitempty"`
	OutputTokens        int64   `json:"output_tokens,omitempty"`
	CostUSD             float64 `json:"cost_usd,omitempty"`
}

ModelUsage preserves provider-reported usage for every model involved in a session. Helper-model calls must never be mistaken for the primary model.

type ReportInput

type ReportInput struct {
	Path   string
	SHA256 string
	Rows   int
}

ReportInput identifies one raw input exactly.

type Row

type Row struct {
	SchemaVersion int    `json:"schema_version"`
	TS            string `json:"ts"`
	RunID         string `json:"run_id"`
	Instance      string `json:"instance"`
	TaskSHA       string `json:"task_sha256"`
	Pin           string `json:"pin"`
	Arm           Arm    `json:"arm"`
	Trial         int    `json:"trial"`
	TaskDone      bool   `json:"task_pass"`
	Avoided       bool   `json:"invariant_pass"`
	Notes         string `json:"notes,omitempty"`

	// Valid says the agent session and treatment were actually delivered.
	// PairValid additionally says every requested arm in this trial number was
	// valid. Only rows satisfying both enter effect tallies.
	Valid                 bool   `json:"valid"`
	PairValid             bool   `json:"pair_valid"`
	InvalidReason         string `json:"invalid_reason,omitempty"`
	InfrastructureFailure bool   `json:"infrastructure_failure,omitempty"`
	// Fixture is the generated repo's full HEAD commit. Generation
	// is deterministic, so this identifies the exact fixture content a
	// row was measured against — rows from different fixture versions
	// must never be pooled as one series.
	Fixture string `json:"fixture,omitempty"`
	// HookFirings is how many firing records the trial repo's own
	// audit log holds after the run (hook-on arm only). Zero means the
	// injection never reached the agent and the arms were effectively
	// identical — the row proves its treatment happened instead of
	// assuming it.
	HookFirings int `json:"hook_firings,omitempty"`
	// HookAuditRows records every audit row, including unrelated or malformed
	// firings. HookFirings counts only rows proving that the selected lesson
	// reached an in-region edit through the expected hook surface.
	HookAuditRows int `json:"hook_audit_rows,omitempty"`
	// Schema v6 delivery intensity. Matches counts matching edit-hook
	// invocations; each match either injected context or was fully suppressed.
	HookMatches      int `json:"hook_matches"`
	HookInjections   int `json:"hook_injections"`
	HookRepeated     int `json:"hook_repeated_injections"`
	HookSuppressed   int `json:"hook_suppressed"`
	HookContextBytes int `json:"hook_context_bytes"`
	// Transcript is where this trial's raw agent output was saved;
	// StderrLog and Patch keep the rest of the audit record, so a
	// verdict stays checkable after the trial dir is deleted.
	Transcript    string `json:"transcript,omitempty"`
	TranscriptSHA string `json:"transcript_sha256,omitempty"`
	StderrLog     string `json:"stderr,omitempty"`
	StderrSHA     string `json:"stderr_sha256,omitempty"`
	Patch         string `json:"patch,omitempty"`
	PatchSHA      string `json:"patch_sha256,omitempty"`
	// Checks are public repository-local validation commands. Hidden task and
	// invariant judges are represented by TaskDone and Avoided above.
	ChecksPass bool          `json:"checks_pass"`
	Checks     []CheckResult `json:"checks,omitempty"`
	// LessonFileRead: the agent named .seamark/lessons.yaml in its own
	// messages. In arms without a lesson file this must be false; in a
	// control arm it would mean contamination.
	LessonFileRead bool `json:"lesson_file_read,omitempty"`
	// Explored lists instance-selected files the agent named in its own
	// messages and tool calls, in first-mention order. It is diagnostic
	// evidence only and never affects a verdict.
	Explored            []string              `json:"explored,omitempty"`
	RequestedModel      string                `json:"requested_model,omitempty"`
	Model               string                `json:"model,omitempty"`
	ModelUsage          map[string]ModelUsage `json:"model_usage,omitempty"`
	InputTokens         int64                 `json:"input_tokens,omitempty"`
	CacheReadTokens     int64                 `json:"cache_read_input_tokens,omitempty"`
	CacheCreationTokens int64                 `json:"cache_creation_input_tokens,omitempty"`
	ContextTokens       int64                 `json:"context_tokens,omitempty"`
	OutputTokens        int64                 `json:"output_tokens,omitempty"`
	Turns               int                   `json:"turns,omitempty"`
	PermissionDenials   int                   `json:"permission_denials,omitempty"`
	CostUSD             float64               `json:"cost_usd,omitempty"`
	DurationMS          int64                 `json:"duration_ms,omitempty"`
	AgentExit           int                   `json:"agent_exit"`
	TimedOut            bool                  `json:"timed_out,omitempty"`
	AgentError          bool                  `json:"agent_error,omitempty"`
	InitSeen            bool                  `json:"init_seen,omitempty"`
	ResultSeen          bool                  `json:"result_seen,omitempty"`
	Tools               []string              `json:"tools,omitempty"`
	Plugins             []string              `json:"plugins,omitempty"`
	MCPServers          []string              `json:"mcp_servers,omitempty"`
	SeamarkVersion      string                `json:"seamark_version,omitempty"`
	SeamarkSHA          string                `json:"seamark_sha256,omitempty"`
	AgentVersion        string                `json:"agent_version,omitempty"`
	Effort              string                `json:"effort,omitempty"`
	HookDelivery        HookDeliveryMode      `json:"hook_delivery,omitempty"`
	MaxBudgetUSD        float64               `json:"max_budget_usd,omitempty"`
	RuntimeID           string                `json:"runtime_id,omitempty"`
	Fingerprint         string                `json:"fingerprint,omitempty"`
}

Row is one trial's result as appended to the JSONL file. Rows are self-contained: pin, arm, verdict, and cost travel together so the file stays meaningful across runs and versions.

func ReadRows

func ReadRows(path string) ([]Row, error)

ReadRows reads a results JSONL file back, skipping unparseable lines. A missing file is an empty history, not an error.

type RunConfig

type RunConfig struct {
	Trials     int           // trials per arm
	Arms       []Arm         // arms to run; nil means both
	Instance   Instance      // zero value selects SchemaSyncInstance
	AgentArgv  []string      // agent command; the task prompt is appended as the last argument
	SeamarkBin string        // absolute path to the seamark binary (hook command + index)
	Timeout    time.Duration // per-trial agent timeout; 0 means 10 minutes
	Out        string        // results JSONL path, appended one row per trial
	WorkDir    string        // parent for trial dirs; "" means a fresh temp dir
	Keep       bool          // keep trial dirs after judging, for inspection
	// TranscriptDir saves each trial's raw agent stdout (the full
	// stream-json transcript when the agent emits one) for reading WHY
	// a verdict came out the way it did. Empty disables saving.
	TranscriptDir string
	// PrepareIndex runs `seamark index` in hook-on trials so the hook
	// has a store to read. Hermetic tests turn it off.
	PrepareIndex bool
	Version      string // seamark version stamped into rows
	SeamarkSHA   string // exact binary digest stamped into rows
	AgentVersion string // agent CLI version stamped into rows
	Model        string // exact requested primary model; empty for custom agents
	Effort       string // requested effort level
	MaxBudgetUSD float64
	RuntimeID    string // sandbox/toolchain identity
	Fingerprint  string // immutable instance + runtime configuration hash
	// RunID groups rows and makes transcript names unique across concurrent
	// invocations. Empty asks Run to generate a cryptographically random ID.
	RunID string
	// HookDelivery selects the edit-hook repeat policy. Empty means always.
	HookDelivery HookDeliveryMode

	// RequireStructuredResult and RequireCleanInit are true for the
	// default Claude adapter. Stub/custom adapters may leave them false.
	RequireStructuredResult bool
	RequireCleanInit        bool
	Log                     func(string, ...any) // progress lines; nil silences
}

RunConfig configures one benchmark run.

type Summary

type Summary struct {
	Rows          []Row
	ByArm         map[Arm]Tally
	RunID         string
	Instance      string
	Rule          string
	StoppedReason string
}

Summary is the whole run's outcome, per arm.

func Run

func Run(ctx context.Context, cfg RunConfig) (Summary, error)

Run executes the experiment: Trials fresh fixture repos per arm, alternating arms so slow model drift within the run spreads evenly, each judged mechanically. A pair is finalized and appended before the next pair starts; graceful cancellation also flushes a completed arm from a partially executed pair.

Cancelling ctx stops the run cleanly between (or during) trials and returns the partial summary with a nil error, so an interrupted run still reports what it measured.

func (Summary) Lines

func (s Summary) Lines() []string

Lines renders the summary the way the RFC reports results: raw counts per arm, no statistics theater, plus the measured token cost of the injection when both arms reported usage.

type Tally

type Tally struct {
	Attempted    int
	Ran          int
	Invalid      int
	Completed    int // trials where the task was done at all
	Avoided      int // completed trials where the owner invariant passed
	Firings      int // hook firing records across the arm's trials
	Matches      int
	Injections   int
	Repeated     int
	Suppressed   int
	ContextBytes int
	MeanInput    int64
}

Tally is one arm's aggregate.

type Verdict

type Verdict struct {
	// TaskDone means the agent completed the visible task.
	TaskDone bool
	// Avoided means a task-complete solution also preserved the owner invariant.
	Avoided bool
	// Notes concisely explains the deterministic judgment.
	Notes string
}

Verdict is one trial's deterministic judgment, read from the code the agent left behind rather than inferred from its transcript.

func JudgeSchemaSync

func JudgeSchemaSync(dir string) (Verdict, error)

JudgeSchemaSync first verifies the requested backend behavior, then derives the expected TypeScript client independently of the agent-editable generator.

Jump to

Keyboard shortcuts

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