runner API

用途

Luna-Flow/mare_mark/runner 负责测量循环。你描述一个基准测试用例,把它编译为经过验证的计划,然后用种子、环境快照、事件接收器和经过验证的协议 run 它。运行器在计时之前用判定器验证每个实现,校准批次大小,以平衡区组进行测量,并发出原始事件。每一步的理由见 runner 设计。

源码:src/runner/runner.mbt、src/runner/bench_spec.mbt。

导入

把这些包加入使用它们的那个包的 moon.pkg:

import {
  "Luna-Flow/mare_mark/model",
  "Luna-Flow/mare_mark/event",
  "Luna-Flow/mare_mark/runner",
  "Luna-Flow/mare_mark/fixture",
  "Luna-Flow/mare_mark/experiment",
  "moonbitlang/async",
}

本页的示例通过它们的默认别名(@model、@event、@runner、@fixture、@experiment、@async)调用它们;只有用 BenchSpec::advanced 构建用例时才需要 fixture 和 experiment。

异步与类型参数

run 和 execute_operation 是 async 的。请从 async fn main 或 async test 中调用它们;驱动它们的 moonbitlang/async 运行时可用于 native、JS 和 wasm 目标,但不可用于 wasm-gc。子进程工作者需要 native 目标。与每个 async 函数一样,run 可能抛出错误;它自身抛出的错误是 RunConfigError。

以下类型参数在整个包中反复出现:

参数含义
Scale数据集的规模参数,例如 Int
Input夹具为一个数据集物化出的值
Prepared实现运行所用的值,由夹具的 prepare 产生
Expected参考判定器计算出的值
Output实现返回的值
Context从一次操作传递到下一次操作的状态(无状态时为 Unit)
State, SinkValueOutputSink 的累加器和最终值

运行计划

run

run 执行一个已编译的计划并返回运行摘要。

pub async fn[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue] run(ValidatedBenchPlan[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue], RunContext) -> @model.RunSummary

在任何东西运行之前,run 会根据上下文的协议检查计划,当两者不相容时(例如多于一个数据集的 PerRun 夹具,见 BenchSpec::compile)抛出 RunConfigError;这种情况下不会发出任何事件。

对于每个规模,运行器按用例中的顺序依次处理该规模的数据集。协议的 experiment_design 决定数据集有多少个以及每个数据集由哪些区组测量。令 EE = exploratory_samples、CC = confirmatory_samples、rr = repeats_per_dataset,一个规模的区组编号为 b=0,…,E+C−1b = 0, \dots, E + C - 1(探索性区组在前),并且

experiment_design每个规模的数据集数 DD区组 bb 的数据集索引
FixedDatasetRepeatedMeasurements1100
MultipleDatasetsSingleMeasurementE+CE + Cbb
HierarchicalDatasetsAndRepeats(E+C)/r(E + C) / r⌊b/r⌋\lfloor b / r \rfloor

位置为 ss 的规模下,索引为 jj 的数据集具有 dataset_id =s⋅D+j= s \cdot D + j,在运行内唯一。对每个数据集,运行器物化输入;若 validation_coverage 要求,就用判定器验证各实现;若它是该规模的第一个数据集,则对每个实现进行预热和校准(所得批次大小随后适用于该规模的所有数据集);然后测量该数据集的区组:每个区组中每个实现一个批次,顺序由 balanced_order 决定。每次验证、失败、校准和观测都在发生时发送给接收器;摘要最后发送,接收器的 finish 返回的位置字符串成为返回的摘要中的 artifact_location。

返回的 RunSummary 具有 complete == true、各事件计数、验证统计(passed_count、failed_count、unsupported_count、expected_difference_count、measurement_validation_count)、环境、协议和种子。它的 run_id 为 @model.run_identity(case_id, protocol, seed, environment.provenance),因此只要环境来源信息中的 run_id 唯一,它就唯一(@env_detect.detect 会生成一个新的)。

验证失败不会中止测量:该实现仍然会被计时,失败也会被报告,这样报告就能把不匹配显示在它所否定的系列旁边。

fn environment() -> @model.EnvironmentSnapshot {
  @model.EnvironmentSnapshot::new(
    @model.SemanticEnvironment::new(@model.ExecutionTarget::Native, "moonc 0.10", "", "i32"),
    @model.PerformanceEnvironment::new("native", "laptop", "default", 1, "monotonic"),
    @model.ProvenanceEnvironment::new("macos", "host", "2026-10-08T00:00:00Z", "HEAD", "run-1"),
  )
}

async test "run a plan" {
  let square = @runner.Implementation::stateless("square", "1", (x : Int) => {
    @model.OperationResult::completed(x * x, ())
  })
  let plan = @runner.single_step("square", [2, 3])
    .with_immutable_input(context => context.dataset_key.scale, x => x.to_string())
    .compare([square])
    .against_equal(x => x * x, (expected, actual) => expected == actual)
    .compile()
    .unwrap()
  let memory = @event.InMemorySink::new()
  let summary = @runner.run(
    plan,
    @runner.RunContext::new(
      environment(),
      memory.as_sink(),
      42UL,
      @runner.ProtocolPreset::QuickCheck.validated(),
    ),
  )
  inspect(summary.run_id, content="square|mmkp_2:a8272a0d9e84b872|42|run-1|2026-10-08T00:00:00Z")
  inspect(summary.passed_count, content="2")
  inspect(summary.observation_count, content="8")
  debug_inspect(summary.seed, content="Some(42)")
  inspect(summary.artifact_location.unwrap(), content="memory://run/square|mmkp_2:a8272a0d9e84b872|42|run-1|2026-10-08T00:00:00Z")
}

使用 QuickCheck 时,每个规模有一个探索性区组和三个验证性区组,因此两个规模和一个实现会产生八个观测。该示例手写了环境,使运行 id 每次都相同;真实的运行会使用 @env_detect.detect。

RunContext

RunContext 携带一次运行除计划以外所需的一切。

pub struct RunContext {
  seed : UInt64
  environment : @model.EnvironmentSnapshot
  sink : @event.ObservationSink
  protocol : ValidatedProtocol
}
pub fn RunContext::new(@model.EnvironmentSnapshot, @event.ObservationSink, UInt64, ValidatedProtocol) -> Self

注意 RunContext::new 的参数顺序:环境、接收器、种子、协议。种子通过 GenerationContext.seed 原样传给夹具,混入区组顺序(参见 balanced_order),并记录在 RunSummary.seed 和运行 id 中。

balanced_order

balanced_order 返回某个区组所用的实现索引的循环轮换。

pub fn balanced_order(Int, Int) -> Array[Int]

balanced_order(k, b) 为 [(0+b) mod k,(1+b) mod k,…,(k−1+b) mod k][(0 + b) \bmod k, (1 + b) \bmod k, \dots, (k-1+b) \bmod k]。在 OrderPolicy::BalancedBlocks(order_seed) 下,运行器使用区组偏移 b+ob + o,其中 o=(order_seed⊕run_seed) mod ko = (\text{order\_seed} \oplus \text{run\_seed}) \bmod k;在 FixedOrder 下使用恒等排列。在任意 kk 个连续区组中,每个实现恰好在每个位置出现一次。

test "rotated block order" {
  debug_inspect(@runner.balanced_order(3, 0), content="[0, 1, 2]")
  debug_inspect(@runner.balanced_order(3, 1), content="[1, 2, 0]")
  debug_inspect(@runner.balanced_order(3, 5), content="[2, 0, 1]")
}

协议

ValidatedProtocol

ValidatedProtocol 是通过了 validate_protocol 的 RunProtocol。

pub struct ValidatedProtocol {
  protocol : @model.RunProtocol
}

它只能从 validate_protocol 或 ProtocolPreset 获得,因此计划永远不会以负的样本数或空的迭代范围运行。

validate_protocol

validate_protocol 检查协议,返回一个 ValidatedProtocol 或发现的全部违规。

pub fn validate_protocol(@model.RunProtocol) -> Result[ValidatedProtocol, Array[ProtocolConfigError]]
规则错误
warmup_iterations >= 0InvalidInteger("warmup_iterations", n)
warmup_time_us(若设置)有限且 >= 0InvalidDuration("warmup_time_us", t)
exploratory_samples >= 0InvalidInteger("exploratory_samples", n)
confirmatory_samples > 0InvalidInteger("confirmatory_samples", n)
target_batch_time_us 有限且 > 0InvalidDuration("target_batch_time_us", t)
max_sample_time_us 有限且 > 0InvalidDuration("max_sample_time_us", t)
target_batch_time_us <= max_sample_time_usInvalidDuration("target_batch_time_us", t)
0 < min_batch_iterations <= max_batch_iterationsInvalidIterationRange(min, max)
practical_delta_pct 有限且 >= 0InvalidPracticalDelta(pct)
repeats_per_dataset >= 1InvalidInteger("repeats_per_dataset", r)
在 HierarchicalDatasetsAndRepeats 下,rr 整除 exploratory_samplesIndivisibleSamples("exploratory_samples", n, r)
在 HierarchicalDatasetsAndRepeats 下,rr 整除 confirmatory_samplesIndivisibleSamples("confirmatory_samples", n, r)
在其他设计下,repeats_per_dataset == 1UnusedRepeatsPerDataset(r)

所有规则都会被检查;错误按此顺序一并返回。只有当 repeats_per_dataset >= 1 时才检查整除规则。这些规则使层次设计中的每个数据集恰好属于一个阶段:rr 整除 EE 时,区组 0,…,E−10, \dots, E-1 恰好填满整数个数据集,因此不会有数据集一部分由探索性区组测量、一部分由验证性区组测量。

“有限”排除了 NaN 和正负无穷大。如果没有这个要求,NaN 会通过所有规则,因为与 NaN 的任何比较都为假:NaN 的 target_batch_time_us 会关闭校准,NaN 的 practical_delta_pct 会使之后的每次比较都失去意义。阈值 0.0 是有效的;此时 stats.compare_paired 把每个非零相对差值报告为 Faster 或 Slower,把完全持平报告为 Equivalent。

test "protocol validation reports every problem" {
  let protocol = @model.RunProtocol::new(
    @model.ExperimentDesign::FixedDatasetRepeatedMeasurements,
    -1,
    None,
    @model.CalibrationProtocol::new(1000.0, 10, 5, 10000.0, @model.BatchPolicy::PerImplementation),
    1.0,
    @model.OrderPolicy::BalancedBlocks(7UL),
    @model.OutlierPolicy::ReportOnly,
    @model.ValidationCoverage::EveryDataset,
    2,
    0,
  )
  guard @runner.validate_protocol(protocol) is Err(errors) else { fail("expected errors") }
  inspect(errors.length(), content="3")
  inspect(errors[0] is InvalidInteger("warmup_iterations", -1), content="true")
  inspect(errors[1] is InvalidInteger("confirmatory_samples", 0), content="true")
  inspect(errors[2] is InvalidIterationRange(10, 5), content="true")
}

test "repeats per dataset must fit the design" {
  let hierarchical = @model.RunProtocol::new(
    @model.ExperimentDesign::HierarchicalDatasetsAndRepeats,
    1,
    None,
    @model.CalibrationProtocol::new(1000.0, 1, 1000, 100000.0, @model.BatchPolicy::PerImplementation),
    1.0,
    @model.OrderPolicy::BalancedBlocks(1UL),
    @model.OutlierPolicy::ReportOnly,
    @model.ValidationCoverage::EveryDataset,
    3,
    10,
    repeats_per_dataset=2,
  )
  guard @runner.validate_protocol(hierarchical) is Err(errors) else { fail("expected errors") }
  inspect(errors is [IndivisibleSamples("exploratory_samples", 3, 2)], content="true")
}

ProtocolConfigError

ProtocolConfigError 指明一条被违反的协议规则。

pub(all) enum ProtocolConfigError {
  InvalidInteger(String, Int)
  InvalidDuration(String, Double)
  InvalidIterationRange(Int, Int)
  InvalidPracticalDelta(Double)
  IndivisibleSamples(String, Int, Int)
  UnusedRepeatsPerDataset(Int)
}

String 载荷是字段名;数字是被拒绝的值。IndivisibleSamples(field, samples, repeats) 携带样本数以及不能整除它的 repeats_per_dataset;UnusedRepeatsPerDataset(r) 携带一个在不使用它的设计下不等于 1 的 repeats_per_dataset。

ProtocolPreset

ProtocolPreset 指明一个现成的协议。

pub(all) enum ProtocolPreset {
  QuickCheck
  Development
  RegressionGate
  Custom(ValidatedProtocol)
}
pub fn ProtocolPreset::validated(Self) -> ValidatedProtocol

validated 返回预设的协议(对于 Custom,返回其包装的协议)。预设包括:

字段QuickCheckDevelopmentRegressionGate
experiment_designFixedDatasetRepeatedMeasurementsFixedDatasetRepeatedMeasurementsHierarchicalDatasetsAndRepeats
warmup_iterations1310
warmup_time_usNoneSome(5000.0)Some(10000.0)
target_batch_time_us1000500010000
批次迭代次数1 到 10001 到 100005 到 10000
max_sample_time_us1000002500001000000
batch_policyPerImplementationPerImplementationPerImplementation
practical_delta_pct1.01.00.5
order_policyBalancedBlocks(1)BalancedBlocks(1)BalancedBlocks(1)
outlier_policyReportOnlyReportOnlyTukeyFence
validation_coverageConfirmatoryOnlyEveryDatasetEveryMeasurement
exploratory_samples135
confirmatory_samples31020
repeats_per_dataset115
每个规模的数据集数115(1 个探索性,4 个验证性)

运行器会使用除 outlier_policy 和 practical_delta_pct 之外的每个字段,这两个是分析设置:它们记录在摘要中,report.document_from_jsonl 在比较实现时应用它们。RegressionGate 每个规模测量五个数据集,每个数据集五个连续区组,并验证每个被测批次;它的第一个数据集只由探索性区组测量。

实现

Implementation

Implementation 是基准测试中的一个参赛者。

pub struct Implementation[Prepared, Output, Context] {
  id : String
  version : String
  initial_context : () -> Context
  execution : ExecutionMode[Prepared, Output, Context]
  synchronize : () -> Unit
}

id 在事件中为它命名,在一个用例内必须唯一且非空;version 会被复制到每个观测和验证中。initial_context 作为每个验证序列和每个测量批次的起点。synchronize 在时钟启动前和停止后立即调用;可用它等待排队中的异步工作(GPU 流、线程池)。

Implementation::stateless

Implementation::stateless 包装一个作用于准备好的输入、不需要上下文的函数。

pub fn[Prepared, Output] Implementation::stateless(String, String, (Prepared) -> @model.OperationResult[Output, Unit]) -> Self[Prepared, Output, Unit]

函数结果中的 next_context 会被忽略并替换为 Some(()),因此无状态操作永远不会提前结束序列。

Implementation::in_process

Implementation::in_process 构建一个在当前进程中运行并传递上下文的实现。

pub fn[Prepared, Output, Context] Implementation::in_process(String, String, () -> Context, (Prepared, Context) -> @model.OperationResult[Output, Context], synchronize? : () -> Unit) -> Self[Prepared, Output, Context]

返回 next_context = Some(c) 以继续使用 c;返回 None 以结束序列(在计时批次中,这会把该观测标记为无效)。

test "a stateful implementation" {
  let counter = @runner.Implementation::in_process("counter", "1", () => 0, (step : Int, total : Int) => {
    @model.OperationResult::completed(total + step, total + step)
  })
  inspect(counter.id, content="counter")
  inspect((counter.initial_context)(), content="0")
}

Implementation::worker

Implementation::worker 构建一个在单独进程中运行每次操作的实现。

pub fn[Prepared, Output, Context] Implementation::worker(String, String, () -> Context, WorkerSpec[Prepared, Output, Context], synchronize? : () -> Unit) -> Self[Prepared, Output, Context]

把它用于可能崩溃、挂起或破坏内存的代码。崩溃会变成 Aborted 结果,而不会终止基准测试。

ExecutionMode

ExecutionMode 表示操作在哪里运行。

pub enum ExecutionMode[Prepared, Output, Context] {
  InProcess((Prepared, Context) -> @model.OperationResult[Output, Context])
  Subprocess(WorkerSpec[Prepared, Output, Context])
}

它在包外是只读的;请通过 Implementation 的构造函数构建它。

WorkerSpec

WorkerSpec 描述如何以子进程方式运行一次操作。

pub struct WorkerSpec[Prepared, Output, Context] {
  command : String
  build_arguments : (Prepared, Context) -> Array[String]
  decode : (String) -> @model.OperationResult[Output, Context]
  timeout_ms : Int
  cwd : String?
}
pub fn[Prepared, Output, Context] WorkerSpec::new(String, (Prepared, Context) -> Array[String], (String) -> @model.OperationResult[Output, Context], timeout_ms? : Int, cwd? : String) -> Self[Prepared, Output, Context]

build_arguments 生成参数向量,decode 把工作进程的 stdout 转换为结果,timeout_ms 默认为 5000,cwd 默认为当前目录。

fn echo_worker() -> @runner.Implementation[Int, String, Unit] {
  @runner.Implementation::worker(
    "echo",
    "1",
    () => (),
    @runner.WorkerSpec::new(
      "sh",
      (n, _) => ["-c", "echo " + n.to_string()],
      stdout => @model.OperationResult::completed(stdout.trim().to_owned(), ()),
      timeout_ms=1000,
    ),
  )
}

test "a worker is described, not started" {
  inspect(echo_worker().id, content="echo")
}

execute_operation

execute_operation 运行实现的一次操作。

pub async fn[Prepared, Output, Context] execute_operation(Implementation[Prepared, Output, Context], Prepared, Context) -> @model.OperationResult[Output, Context]

对于 InProcess,它调用该函数。对于 Subprocess,它启动命令,捕获 stdout 和 stderr,并按如下方式映射结果:

工作进程结果结果
退出码为 0decode(stdout) 返回的结果和上下文,并附上 stdout、stderr 和退出码
退出码 ≠0\ne 0Aborted(code, stderr),没有下一个上下文
在 timeout_ms 内未退出Timeout(timeout_ms, "worker exceeded timeout");进程被终止
进程无法启动ParseFailure(error text)
不在 native 目标上Aborted(-1, "subprocess workers require the native target")

OutputSink

OutputSink 折叠一个批次的输出,使编译器无法丢弃这些工作。

pub struct OutputSink[Output, State, SinkValue] {
  initial : () -> State
  fold : (State, Output) -> State
  finish : (State) -> SinkValue
}
pub fn[Output, State, SinkValue] OutputSink::new(() -> State, (State, Output) -> State, (State) -> SinkValue) -> Self[Output, State, SinkValue]
pub fn[Output] OutputSink::keep_last() -> Self[Output, Output?, Output?]

fold 在计时区域内、每次操作之后运行;finish 在时钟停止后运行,其值被传给 @bench.Bench::keep。keep_last 保留最后一个输出。当输出必须被消费时,请配合一个廉价的校验和使用 OutputSink::new:

test "a checksum sink" {
  let sink : @runner.OutputSink[Int, Int, Int] = @runner.OutputSink::new(
    () => 0,
    (state, output) => state ^ output,
    state => state,
  )
  let folded = [3, 5, 6].fold(init=(sink.initial)(), (state, x) => (sink.fold)(state, x))
  inspect((sink.finish)(folded), content="0")
}

描述用例

single_step

single_step 为每个输入只有一次操作的用例启动简短构建器。

pub fn[Scale] single_step(String, Array[Scale]) -> SingleStepCase[Scale]

构建器链为 single_step(id, scales) .with_immutable_input(generate, fingerprint) .compare(implementations) .against_equal(reference, comparator) .compile()。每一步都会复制它接收到的数组。

Case

Case 是构建器入口点的命名空间。

pub(all) enum Case {
  Case
}
pub fn[Scale] Case::single_step(String, Array[Scale]) -> SingleStepCase[Scale]

Case::single_step(id, scales) 与 single_step(id, scales) 相同。

SingleStepCase

SingleStepCase 是一个已有 id 和规模、但还没有输入的用例。

pub struct SingleStepCase[Scale] {
  id : String
  scales : Array[Scale]
}
pub fn[Scale] SingleStepCase::compile(Self[Scale]) -> Result[Unit, Array[BenchConfigError]]
pub fn[Scale, Input] SingleStepCase::with_immutable_input(Self[Scale], (@model.GenerationContext[Scale]) -> Input, (Input) -> String) -> ImmutableSingleStepCase[Scale, Input]

compile 在这一阶段总是失败,并列出缺少的内容(MissingFixture、EmptyImplementations、MissingOracle、MissingOutputSink,适用时还有 EmptyCaseId 和 EmptyScales)。with_immutable_input 添加一个名为 id + "-fixture"、版本为 "1"、用 @fixture.Fixture::immutable 构建的不可变夹具。

ImmutableSingleStepCase

ImmutableSingleStepCase 是带有不可变输入的用例。

pub struct ImmutableSingleStepCase[Scale, Input] {
  id : String
  scales : Array[Scale]
  fixture : @fixture.Fixture[Scale, Input, Input]
}
pub fn[Scale, Input, Output] ImmutableSingleStepCase::compare(Self[Scale, Input], Array[Implementation[Input, Output, Unit]]) -> ComparedSingleStepCase[Scale, Input, Output]

compare 添加要比较的无状态实现。

ComparedSingleStepCase

ComparedSingleStepCase 是带有输入和实现的用例。

pub struct ComparedSingleStepCase[Scale, Input, Output] {
  id : String
  scales : Array[Scale]
  fixture : @fixture.Fixture[Scale, Input, Input]
  implementations : Array[Implementation[Input, Output, Unit]]
}
pub fn[Scale, Input, Expected, Output] ComparedSingleStepCase::against_equal(Self[Scale, Input, Output], (Input) -> Expected, (Expected, Output) -> Bool) -> BenchSpec[Scale, Input, Input, Expected, Output, Unit, Output?, Output?]

against_equal(reference, comparator) 添加一个名为 id + "-reference"、用 @experiment.ReferenceOracle::equal 构建的参考判定器,一个 OutputSink::keep_last 接收器,序列长度 1,空的规模文本,以及输入和输出的占位文本("<input>"、"<output>")。它的重放规格带有空命令,唯一参数是实现 id。规模文本为空时,验证携带 "scale":"",观测不带 scale,因此报告按 dataset_id 摆放这类运行。当你需要在事件和重放产物中使用真实文本(尤其是规模)时,请使用 BenchSpec::advanced。

BenchSpec

BenchSpec 是一份完整但尚未验证的用例描述。

pub struct BenchSpec[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue] {
  case : DifferentialCase[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue]
}

BenchSpec::advanced

BenchSpec::advanced 由用例的全部组成部分构建用例。

pub fn[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue] BenchSpec::advanced(String, @fixture.Fixture[Scale, Input, Prepared], Array[Implementation[Prepared, Output, Context]], OutputSink[Output, State, SinkValue], @experiment.OracleSpec[Input, Expected, Output, Context], Array[Scale], (Scale) -> String, Int, (Input, Int) -> @model.CaseDescriptor, (Input) -> String, (Output) -> String, (Context) -> String, (Input, String) -> @model.ReplaySpec, shrinker? : @experiment.Shrinker[Input]) -> Self[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue]
参数作用
id用例 id,复制到每个事件中
fixture物化、克隆、准备和重置输入
implementations参赛者(数组会被复制)
output_sink在计时批次内折叠输出
oracle参考验证和/或关系验证
scales每个规模一个数据集,按此顺序(会被复制)
scale_text验证事件和观测事件中规模的文本;报告的 x 轴
sequence_length每个实现和数据集验证的操作次数
describe第 ii 步的操作、操作数、上下文和舍入方式,用于证据
input_text, output_text, context_text证据和失败产物中使用的文本形式
replay复现输入和实现 id 的命令
shrinker可选;最小化失败的输入

BenchSpec::with_sequence_length

with_sequence_length 返回规格的一个副本,带有另一个序列长度。

pub fn[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue] BenchSpec::with_sequence_length(Self[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue], Int) -> Self[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue]

BenchSpec::compile

compile 验证规格,返回一个计划或全部配置错误。

pub fn[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue] BenchSpec::compile(Self[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue], protocol? : ValidatedProtocol) -> Result[ValidatedBenchPlan[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue], Array[BenchConfigError]]

它依次检查:用例 id 非空、至少一个规模、至少一个实现、序列长度为正、实现 id 非空且唯一,以及 SetupFrequency::PerRun 的夹具只服务于单个数据集。没有 protocol 时,每个规模算作一个数据集,这是任何设计所物化的最少数量;有它时,按该协议的设计所物化的数据集计数。run 会用其上下文的协议重复这项准备检查,因此不带协议编译的计划同样无法在多个数据集上运行 PerRun 夹具。

test "compile collects every configuration error" {
  let anonymous = @runner.Implementation::stateless("", "1", (x : Int) => {
    @model.OperationResult::completed(x, ())
  })
  let result = @runner.single_step("", ([] : Array[Int]))
    .with_immutable_input(context => context.dataset_key.scale, x => x.to_string())
    .compare([anonymous])
    .against_equal(x => x, (expected, actual) => expected == actual)
    .compile()
  guard result is Err(errors) else { fail("expected errors") }
  inspect(errors.length(), content="3")
  inspect(errors[0] is EmptyCaseId, content="true")
  inspect(errors[1] is EmptyScales, content="true")
  inspect(errors[2] is EmptyImplementationId(0), content="true")
}

BenchConfigError

BenchConfigError 指明用例描述中的一个问题。

pub(all) enum BenchConfigError {
  MissingFixture
  MissingOracle
  MissingOutputSink
  MissingSerializer(String)
  EmptyCaseId
  EmptyImplementations
  EmptyScales
  EmptyImplementationId(Int)
  DuplicateImplementationId(String)
  InvalidSequenceLength(Int)
  InvalidOracleSequenceLength(Int)
  OracleSequenceLengthMismatch(Int, Int)
  PerRunSetupWithMultipleDatasets(Int)
}

EmptyImplementationId 携带实现索引,DuplicateImplementationId 携带重复 id,InvalidSequenceLength 携带被拒绝的用例长度。InvalidOracleSequenceLength 携带参考判定器返回的非正长度;OracleSequenceLengthMismatch 依次携带配置长度和判定器长度。PerRunSetupWithMultipleDatasets 携带运行的数据集数。PerRun 为整次运行准备一个值,而准备值来自一个数据集的输入,不能用于多个数据集;应改用 PerDataset。Missing* 构造器来自 SingleStepCase::compile;MissingSerializer 是保留项,当前代码不会产生它。

RunConfigError

当计划与运行上下文的协议不相容时,run 抛出 RunConfigError。

pub(all) suberror RunConfigError {
  RunConfigError(Array[BenchConfigError])
}

错误载荷包括 PerRunSetupWithMultipleDatasets、InvalidOracleSequenceLength 和 OracleSequenceLengthMismatch。设置不兼容会在发出任何事件前被拒绝。每个选中用于参考验证的数据集都会在候选验证或测量开始前检查判定器长度。

fn per_run_spec(scales : Array[Int]) -> @runner.BenchSpec[Int, Int, Int, Int, Int, Unit, Int?, Int?] {
  let fixture = @fixture.Fixture::new(
    "shared",
    "1",
    (context : @model.GenerationContext[Int]) => context.dataset_key.scale,
    x => x.to_string(),
    x => x,
    (x, _, _) => x,
    (_, _) => (),
    @model.SetupPolicy::new(PerRun, ExcludedFromMeasurement, RunWorkspace),
  )
  @runner.BenchSpec::advanced(
    "per-run",
    fixture,
    [@runner.Implementation::stateless("id", "1", x => @model.OperationResult::completed(x, ()))],
    @runner.OutputSink::keep_last(),
    @experiment.OracleSpec::Reference(@experiment.ReferenceOracle::equal("id", x => x, (e, a) => e == a)),
    scales,
    n => n.to_string(),
    1,
    (x, _) => @model.CaseDescriptor::new("id", [x.to_string()], "", ""),
    x => x.to_string(),
    x => x.to_string(),
    _ => "",
    (x, id) => @model.ReplaySpec::new("", [id, x.to_string()]),
  )
}

async test "a per-run setup serves one dataset" {
  let two_scales = per_run_spec([1, 2]).compile()
  inspect(two_scales is Err([PerRunSetupWithMultipleDatasets(2)]), content="true")
  let gate = @runner.ProtocolPreset::RegressionGate.validated()
  let one_scale = per_run_spec([1]).compile(protocol=gate)
  inspect(one_scale is Err([PerRunSetupWithMultipleDatasets(5)]), content="true")
  let plan = per_run_spec([1]).compile().unwrap()
  let environment = @model.EnvironmentSnapshot::new(
    @model.SemanticEnvironment::new(@model.ExecutionTarget::Native, "moonc 0.10", "", "i32"),
    @model.PerformanceEnvironment::new("native", "laptop", "rc", 1, "monotonic"),
    @model.ProvenanceEnvironment::new("macos", "host", "2026-10-08T00:00:00Z", "HEAD", "run-2"),
  )
  let raised = try {
    ignore(@runner.run(plan, @runner.RunContext::new(environment, @event.InMemorySink::new().as_sink(), 1UL, gate)))
    false
  } catch {
    @runner.RunConfigError(_) => true
    _ => false
  }
  inspect(raised, content="true")
}

DifferentialCase

DifferentialCase 是规格或计划背后的记录。

pub struct DifferentialCase[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue] {
  id : String
  fixture : @fixture.Fixture[Scale, Input, Prepared]
  implementations : Array[Implementation[Prepared, Output, Context]]
  output_sink : OutputSink[Output, State, SinkValue]
  oracle : @experiment.OracleSpec[Input, Expected, Output, Context]
  scales : Array[Scale]
  scale_text : (Scale) -> String
  sequence_length : Int
  describe : (Input, Int) -> @model.CaseDescriptor
  input_text : (Input) -> String
  output_text : (Output) -> String
  context_text : (Context) -> String
  shrinker : @experiment.Shrinker[Input]?
  replay : (Input, String) -> @model.ReplaySpec
}

它的字段与 BenchSpec::advanced 的参数一一对应。

ValidatedBenchPlan

ValidatedBenchPlan 是通过了 BenchSpec::compile 的用例。

pub struct ValidatedBenchPlan[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue] {
  case : DifferentialCase[Scale, Input, Prepared, Expected, Output, Context, State, SinkValue]
}

它只能由 compile 创建,而 run 只接受它。