event API
目的
Luna-Flow/mare_mark/event は runner のイベントを受け取ります。ObservationSink は 5 個の callback の record です。メモリー内、バッファ付き JSONL、ストリーミング JSONL の sink と fan-out を提供します。JSONL は report と replay の監査記録であり、protocol_json と protocol_from_json が記録内の protocol を読み書きします。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 は protocol preset、moonbitlang/core/json は 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 はすべてのイベントを 1 行の 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 は要約を含め、イベントごとに 1 行を追加します。その 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
第 1 引数は改行を含まない各行を受け取り、第 2 引数は 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 はすべてのイベントを 2 つのシンクに送ります。
pub fn tee(ObservationSink, ObservationSink) -> ObservationSink
イベントはまず左のシンクに送られます。finish は両方を呼び出し、右のシンクのロケーションを返します。
Protocol オブジェクト
protocol_json
protocol_json は run protocol の全欄を JSON オブジェクトに符号化します。
pub fn protocol_json(@model.RunProtocol) -> Json
これは JSONL summary 行の protocol オブジェクトです。キーは RunProtocol の欄名と、calibration 内の CalibrationProtocol の欄名です。enum は text() のタグ、未指定の warmup_time_us は null、order_policy は {"kind":"fixed_order"} または {"kind":"balanced_blocks","seed":"<decimal>"} です。seed はすべての UInt64 を JSON 数値で表せないため文字列にします。非有限 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 オブジェクトを 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 | フィールド |
|---|---|
observation | case、implementation、implementation_version、dataset_id、repetition_id、block_id、phase、elapsed_us、iterations、batch_sink、setup_timing、valid。記録された場合は setup_frequency、workspace_scope、空でない尺度テキストがある場合は scale。 |
validation | status、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(10 進文字列)、original_fingerprint、minimal_fingerprint、shrink_path、minimal_input |
calibration | implementation, dataset_id, batch_iterations, elapsed_us, target_elapsed_us, retries |
summary | run_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 があれば protocol_identity と protocol、run seed があれば十進文字列 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 は同じ dataset の検証と共通の尺度テキストです。
runner は全欄を埋めます。mmka_1 内で reason と setup_timing(issue #8)、summary の protocol_identity、protocol、seed(issue #3)、setup と測定検証の欄および measurement_validation_count(issue #4)、observation の 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")
}