event API

用途

Luna-Flow/mare_mark/event 接收运行器发出的内容。ObservationSink 是由五个回调组成的记录;该包提供内存接收器、带缓冲的 JSONL 接收器、流式 JSONL 接收器以及一个扇出组合子。JSONL 格式是报告和重放所读取的审计记录;protocol_json 和 protocol_from_json 负责写出和读取其中包含的运行协议。参见 event 设计。

源码:src/event/event.mbt、src/event/protocol.mbt。

导入

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

import {
  "Luna-Flow/mare_mark/model",
  "Luna-Flow/mare_mark/event",
  "Luna-Flow/mare_mark/runner",
  "moonbitlang/core/json",
}

本页的示例通过它们的默认别名(@model、@event、@runner、@json)调用它们;只有协议预设才需要 runner,只有解析 JSON 文本才需要 moonbitlang/core/json。

接收器

ObservationSink

ObservationSink 是运行器与存储之间的接口。

pub struct ObservationSink {
  emit_observation : (@model.Observation) -> Unit
  emit_validation : (@model.Validation) -> Unit
  emit_failure : (@model.ValidationFailure) -> Unit
  emit_calibration : (@model.CalibrationEvent) -> Unit
  finish : (@model.RunSummary) -> String
}
pub fn ObservationSink::new((@model.Observation) -> Unit, (@model.Validation) -> Unit, (@model.CalibrationEvent) -> Unit, (@model.RunSummary) -> String, emit_failure? : (@model.ValidationFailure) -> Unit) -> Self

finish 在结束时接收一次运行摘要,并返回一个位置字符串,运行器将其存入 RunSummary.artifact_location。注意 new 的参数顺序:观测、验证、校准、结束,以及可选的失败回调(默认忽略失败)。

test "a counting sink" {
  let count = Ref(0)
  let sink = @event.ObservationSink::new(
    _ => count.val += 1,
    _ => (),
    _ => (),
    summary => "counted://" + summary.run_id,
  )
  (sink.emit_observation)(
    @model.Observation::new("c", "a", "1", 0, 0, 0, Confirmatory, 1.5, 10, Kept, ExcludedFromMeasurement, true),
  )
  inspect(count.val, content="1")
  inspect((sink.finish)(@model.RunSummary::new("r", 1, 0, 0, true, None)), content="counted://r")
}

InMemorySink

InMemorySink 把每个事件保存在数组中。

pub struct InMemorySink {
  observations : Array[@model.Observation]
  validations : Array[@model.Validation]
  failures : Array[@model.ValidationFailure]
  calibrations : Array[@model.CalibrationEvent]
}
pub fn InMemorySink::new() -> Self
pub fn InMemorySink::as_sink(Self) -> ObservationSink

as_sink 向数组追加;它的 finish 返回 "memory://run/" + run_id,且不保存摘要。

JsonlSink

JsonlSink 把每个事件保存为一行 JSON。

pub struct JsonlSink {
  lines : Array[String]
}
pub fn JsonlSink::new() -> Self
pub fn JsonlSink::as_sink(Self) -> ObservationSink
pub fn JsonlSink::to_jsonl(Self) -> String

as_sink 为每个事件(包括摘要)追加一行;它的 finish 返回 "jsonl://memory/" + run_id。to_jsonl 用 "\n" 连接各行,末尾不带换行符。

test "JSONL lines" {
  let jsonl = @event.JsonlSink::new()
  let sink = jsonl.as_sink()
  (sink.emit_calibration)(@model.CalibrationEvent::new("a", 0, 64, 1012.5, 1000.0, 1))
  inspect(
    jsonl.to_jsonl(),
    content="{\"artifact_version\":\"mmka_1\",\"type\":\"calibration\",\"implementation\":\"a\",\"dataset_id\":0,\"batch_iterations\":64,\"elapsed_us\":1012.5,\"target_elapsed_us\":1000,\"retries\":1}",
  )
}

streaming_jsonl

streaming_jsonl 返回一个立即写出每个事件行的接收器。

pub fn streaming_jsonl((String) -> Unit, String) -> ObservationSink

第一个参数接收不带换行符的每一行;第二个参数是 finish 返回的位置。可用它在运行过程中向文件或管道追加内容,这样即使崩溃,也会留下流的一个有效前缀。

test "stream lines as they happen" {
  let written : Array[String] = []
  let sink = @event.streaming_jsonl(line => written.push(line), "file://events.jsonl")
  let location = (sink.finish)(@model.RunSummary::new("r", 0, 0, 0, true, None))
  inspect(location, content="file://events.jsonl")
  inspect(written[0].contains("\"type\":\"summary\""), content="true")
}

tee

tee 把每个事件发送到两个接收器。

pub fn tee(ObservationSink, ObservationSink) -> ObservationSink

事件先发往左侧接收器。finish 调用两者,并返回右侧接收器的位置。

协议对象

protocol_json

protocol_json 把运行协议的每个字段编码为一个 JSON 对象。

pub fn protocol_json(@model.RunProtocol) -> Json

这就是 JSONL summary 行中的 protocol 对象。键是 RunProtocol 的字段名,以及嵌套在 calibration 之下的 CalibrationProtocol 的字段名。枚举写作其 text() 标签,warmup_time_us 缺省时为 null,order_policy 为 {"kind":"fixed_order"} 或 {"kind":"balanced_blocks","seed":"<decimal>"};种子写成字符串,因为 JSON 数值无法容纳每一个 UInt64。非有限的 double 写作字符串 "NaN"、"Infinity" 或 "-Infinity",-0.0 写作 -0,因此该对象能精确保留每一个值。

test "protocol as JSON" {
  let protocol = @runner.ProtocolPreset::RegressionGate.validated().protocol
  let json = @event.protocol_json(protocol).stringify()
  inspect(json.contains("\"experiment_design\":\"hierarchical_datasets_and_repeats\""), content="true")
  inspect(json.contains("\"order_policy\":{\"kind\":\"balanced_blocks\",\"seed\":\"1\"}"), content="true")
  inspect(json.contains("\"repeats_per_dataset\":5"), content="true")
}

protocol_from_json

protocol_from_json 把 protocol 对象解码回协议。

pub fn protocol_from_json(Json) -> Result[@model.RunProtocol, String]

它保留有限值(包括带符号的零)、无穷大和规范 NaN,因此这些协议保持其 @model.protocol_identity。非规范 NaN 载荷会被序列化为 "NaN" 且不会保留,因此其 identity 可能改变。除 repeats_per_dataset 外每个字段都必需;未知键会被忽略。

test "protocol round trip" {
  let protocol = @runner.ProtocolPreset::Development.validated().protocol
  let decoded = @event.protocol_from_json(@event.protocol_json(protocol)).unwrap()
  inspect(@model.protocol_identity(decoded) == @model.protocol_identity(protocol), content="true")
  let broken = @json.parse("{\"experiment_design\":\"sometimes\"}")
  inspect(@event.protocol_from_json(broken) is Err("protocol.calibration: missing"), content="true")
}

JSONL 记录

每一行都是一个带有 "artifact_version": "mmka_1" 和 "type" 的对象:

type字段
observationcase、implementation、implementation_version、dataset_id、repetition_id、block_id、phase、elapsed_us、iterations、batch_sink、setup_timing、valid;记录了时还有 setup_frequency 和 workspace_scope;规模文本非空时还有 scale
validationstatus、reason(除 valid 外的每种状态)、implementation、oracle、scale;对测量验证还有 validation_scope("measurement")、repetition_id 和 block_id;带有证据时还有 case、dataset_id、step_id、operation、operands、context、rounding、expected、actual、expected_kind、actual_kind、expected_flags、actual_flags、trap、stderr、exit_code(存在时)、fingerprint、implementation_version、replay_command、replay_arguments、replay_timeout_ms(不带证据的测量验证自身携带 dataset_id)
validation_failure验证的全部字段,外加 seed(十进制字符串)、original_fingerprint、minimal_fingerprint、shrink_path、minimal_input
calibrationimplementation, dataset_id, batch_iterations, elapsed_us, target_elapsed_us, retries
summaryrun_id、observation_count、validation_count、calibration_count、complete、passed_count、failed_count、unsupported_count、expected_difference_count、measurement_validation_count;已知时带有 semantic、performance 和 provenance 对象的 environment;协议已知时有 protocol_identity 和 protocol(见 protocol_json);运行种子已知时有 seed(十进制字符串)

status 是 valid、invalid、skipped、expected_difference、unsupported、infrastructure_failure 之一;reason 是该状态携带的字符串。phase 为 exploratory 或 confirmatory;batch_sink 为 kept 或 discarded:<reason>;setup_timing 为 excluded_from_measurement 或 included_in_measurement;setup_frequency 为 per_run、per_dataset、per_implementation、per_sample、per_batch 或 per_iteration;workspace_scope 为 run_workspace、dataset_workspace、implementation_workspace、sample_workspace、batch_workspace 或 operation_workspace。scale 是数据集规模的文本,与该数据集的验证所携带的文本相同。

运行器会填写每个字段。这些字段是在 mmka_1 之内陆续加入的:reason 和 setup_timing(issue #8),摘要的 protocol_identity、protocol 和 seed(issue #3),准备与测量验证相关字段以及 measurement_validation_count(issue #4),以及观测的 scale(issue #7)。较旧的流中没有这些字段,读取方不得要求它们存在。

test "an observation line with its scale and setup" {
  let observation = @model.Observation::new(
    "sum", "loop", "1", 3, 0, 2, Confirmatory, 1.25, 64, Kept, ExcludedFromMeasurement, true,
    setup_frequency=PerDataset, workspace_scope=DatasetWorkspace, scale_text="1024",
  )
  let jsonl = @event.JsonlSink::new()
  (jsonl.as_sink().emit_observation)(observation)
  inspect(jsonl.to_jsonl().contains("\"setup_frequency\":\"per_dataset\""), content="true")
  inspect(jsonl.to_jsonl().contains("\"scale\":\"1024\""), content="true")
}