metricstitch

    Bounded recoverable delta-to-cumulative metrics processing and event-time reordering

    opentelemetry
    metrics
    otlp
    checkpoint
    Download zip
    Author
    Version
    0.4.0
    License
    Apache-2.0
    Last updated
    3 hours ago
    Downloads
    2

    #MetricStitch

    A portable, bounded delta-to-cumulative processing library for MoonBit. Its consumers are telemetry gateways and offline OTLP replay tools.

    #Install

    From your own MoonBit module, add the registry dependency:

    moon add vivid-oi/metricstitch@0.4.0

    Import "vivid-oi/metricstitch" in moon.pkg. The separate integration/consumer module demonstrates public API use; the post-publication check moon run checks/registry.mbtx resolves this exact registry version in a fresh standalone module and runs it on Wasm, Wasm-GC and JavaScript.

    The core accumulates nonnegative Int64 and finite Double deltas with explicit interval continuity, last-point retry detection, checked overflow and atomic batches. State is immutable. Keep the returned state only after accepting the output. Older retries, gaps and overlaps raise StitchError and preserve the old state. New producer instances must have different series identities.

    Run moon run examples/counter to accumulate 7 and 5 into 12. Run moon test --target wasm for the public contract tests.

    #Complete local example

    The checked-in session adapts the pinned official OTLP example into two contiguous intervals. It includes a Double counter, Gauge and explicit histogram. Use new destination filenames for the following commands.

    moon update moon run --target wasm cli -- replay-to examples/session.json session-receipt.json moon run --target wasm cli -- inspect session-receipt.json moon run --target wasm cli -- export session-receipt.json session-otlp.json moon run checks/protocol.mbtx -- session-otlp.json

    The second interval has cumulative counter 7.5, histogram population 4 and Gauge 11. Inspection reports two active series because Gauge has no cumulative state. The exported file is a standard OTLP request suitable for an existing exporter or receiver. The last command independently decodes it with the community OpenTelemetry generated model and verifies JSON and Protobuf round trips. This is protocol-model interoperability validation. A separate Collector integration checks a real pinned receiver and file exporter, plus a separate consumer module. checks/replay.mbtx exercises these same commands in a temporary directory on Wasm and all three native CI operating systems. An independent accumulation comparison compares the shared profile against Collector Contrib's own delta-to-cumulative processor.

    Direct library callers provide series keys. State::checkpoint returns versioned JSON with exact decimal strings and sorted series. State::restore validates budgets, duplicate series, intervals and cumulative consistency before accepting state. Persistence and authenticity are the caller's responsibility. Unknown checkpoint fields and versions are rejected. Restored last-point retries remain idempotent.

    #OTLP file workflow

    process_otlp(state, request) accepts an OTLP/JSON ExportMetricsServiceRequest and returns a new state, cumulative request and duplicate count. The input JSON and original state remain intact on failure. parse_input(text) rejects duplicate decoded JSON object keys and limits nesting to 64 and text to 4M code units.

    The supported profile is DELTA monotonic Sum with exactly one nonnegative asInt decimal string or finite nonnegative asDouble number and positive strictly increasing nanosecond timestamps. Double accumulation uses ordered IEEE-754 addition with overflow rejection, so rounding follows Double arithmetic. State::apply_doubles exposes the typed floating-point entry point. A series cannot switch between Int64 and Double. The series budget is shared by both. Pure-integer checkpoints retain version 1, while states with floating-point series use version 2. Both versions can be restored. Attributes support strings, booleans, signed Int64 decimal strings, finite numeric doubles, base64 bytes, arrays and key-value lists. Each attribute set has a 4096-value budget and 16-level nesting limit. Attributes and nested key-value lists require unique keys. Identity preserves value kinds, canonicalizes integer/base64 representations and sorts key-value lists while retaining array order. Outgoing metadata preserves the original representation. Existing string-only series keys remain compatible. Resource and scope identity includes their attributes, scope name/version, both schema URLs, metric name/unit/description and point attributes. Attribute order does not affect identity. A description change deliberately creates a separate stream in this strict initial profile. Optional zero flags, empty exemplars and zero dropped-attribute counts are accepted. Other fields, metric kinds and values are refused with diagnostics. There is no numeric coercion or silent omission of unsupported data.

    moon update moon run checks/replay.mbtx -- moon wasm moon run --target wasm cli -- input.json moon run --target wasm cli -- next.json checkpoint.json moon run --target wasm cli -- apply-to input.json first.json moon run --target wasm cli -- apply-to next.json second.json first.json

    Success emits one JSON receipt containing request, checkpoint and duplicates. The consumer extracts request for its exporter and persists checkpoint for the next call. Persisting the whole receipt as one artifact keeps the output and its state together. This CLI reads regular UTF-8 files up to 4 MB, emits at most 4 MB, and exits 2 on failure with diagnostics on stderr and no result on stdout. apply-to writes the complete receipt to a new destination. It validates all input, writes and syncs a sibling temporary file, closes it and publishes with replacement disabled. Existing destinations, including input or previous-receipt paths, are refused. Success has empty stdout. Failed publication cleans up its temporary file. The optional previous receipt supplies its validated checkpoint directly, so file-based callers can resume without extracting JSON fields. Receipt files are trusted local state, with structural validation rather than authentication. Callers own delivery acknowledgement and single-writer ordering. Directory crash durability and hostile concurrent filesystem mutation are outside this publication contract.

    OtlpStep::receipt() produces the receipt envelope. decode_receipt(value) validates the envelope, checkpoint and supported Cumulative request profile. It accepts historical points from a multi-request replay without accumulating them a second time. Validation does not prove a relationship between a modified checkpoint and its output, and does not establish delivery acknowledgement. export RECEIPT.json OUTPUT.json validates a receipt and publishes only its OTLP request to a new file, retaining the full receipt as the recovery artifact. inspect RECEIPT.json validates and reports state capacity and duplicate count. File-based resumption uses the same receipt validation as inspection and export.

    Three intended uses are receiving integer deltas in a gateway, resuming a local agent after a checkpoint, and reproducing a faulty telemetry batch offline. The replay demonstrates all three using the official OTLP example. It first verifies refusal of the unmodified example's unsupported types, then derives an Int64-only two-interval counter from its real protocol structure, retains its resource/scope/attributes, accumulates 5 and 7 into 12 across a checkpoint and checks retry suppression, error recovery, whole-receipt resumption and refusal to overwrite existing files. The intervals and integer values are demonstration edits, not production telemetry. See SOURCES.md.

    The core supports wasm, wasm-gc, js and native. The async CLI supports wasm and native. CI runs core tests on the portable targets and native Linux/macOS/Windows, and executes the documented replay on Wasm and each native OS. See scale and reproducible benchmarks for the private series index, transaction copying costs and measured workload limitations.

    #Explicit histograms

    Exact coarsening can align compatible producer layouts without interpolation, including explicit migration of an existing typed state.

    Explicit-bucket Delta histograms are supported by State::apply_histograms and the OTLP workflow. Counts and population are nonnegative Int64 values, with checked addition, at most 1024 finite increasing bounds, and exactly bounds+1 buckets. Population must equal the bucket total. Arrays are copied at both API boundaries. Sum is optional and uses finite Double addition. Min/max are supplied together or omitted together, and empty populations omit extrema. Layout and sum availability must remain constant. Nonempty intervals must agree on extrema availability. Unsupported changes are refused. Histogram states use checkpoint version 3. Versions 1 and 2 remain readable and retain their existing output. The replay also exercises the pinned official histogram across two intervals and a saved receipt. Its times are edited to form contiguous positive intervals.

    #Validation

    Mixed requests may include Gauge metrics. Their finite signed Double or signed Int64 samples are validated and passed through unchanged. Gauge timestamps must be positive, and optional start times must not exceed the end. Gauge values do not accumulate, allocate series state or participate in retry suppression. Nonzero flags and nonempty exemplars are refused. A bad Gauge rejects the whole request, including earlier Sum or Histogram conversions. The replay verifies the official Counter/Gauge/Histogram examples together after adapting their times.

    validate_otlp(state, request) runs the complete conversion checks and returns the first Diagnostic or None. Its RFC 6901 pointer locates the nearest resource, scope, metric or data-point container, including array indices. process_otlp retains StitchError::Invalid and prefixes its message with the same location. Run moon run --target wasm cli -- check input.json checkpoint.json as a read-only CI gate. Valid input prints a JSON report and exits 0. Semantic errors print the diagnostic report and exit 2. JSON syntax and file errors use stderr and exit 2. The command checks the supplied state without publishing a converted receipt.

    diagnose_otlp(state, request) adds a stable IssueCode without changing the legacy diagnostic or StitchError::Invalid(String) API. The CLI check report includes diagnostic.code: invalid_input, unsupported_data, noncontiguous_interval, conflicting_retry, series_limit, numeric_overflow or kind_changed. Codes are assigned by validation, not by matching messages. Malformed numbers and shapes are invalid input; a valid but overflowing cumulative addition is numeric overflow. A retry with the last interval but different content is conflicting; older points, gaps and overlaps are noncontiguous. Messages can evolve; use the code and pointer for programmatic handling.

    #Recorded batch sequences

    For larger recordings, streaming NDJSON replay provides bounded UTF-8 framing, per-record checkpoints and atomic stream-to / stream-export files without a whole-recording 4 MB limit.

    Paired replay auditing recomputes original NDJSON against its receipts before export, checking complete output, state, progress and retries.

    process_sequence(state, requests) converts up to 1024 standard OTLP requests in order as one transaction. The result is a standard request retaining all emitted ResourceMetrics groups in order, a final checkpoint and total duplicate count. It does not coalesce groups. Failures identify /requests/N followed by the indexed input location. No partial state is returned.

    For cumulative exports, optional compact-to INPUT.json OUTPUT.json merges adjacent identical headers, conserving every point and its order while retaining empty containers. This does not change the default sequence/reorder output.

    For offline recordings, write {"requests":[REQUEST_1,REQUEST_2]} to sequence.json and run moon run --target wasm cli -- replay-to sequence.json receipt.json. An optional last argument accepts a previous receipt. The same input/output budgets, exclusive file publication and error cleanup as apply-to are used. The documented replay compares this workflow with sequential execution, including retries, restored state and a failed final request that publishes no receipt.

    #State lifecycle

    Checkpoint differences expose sorted added/removed/changed records and nested paths for recovery investigations without modifying state.

    State::summary() reports capacity, kind counts and oldest/newest last-point end times as exact decimal strings. State::partition_before(cutoff) explicitly partitions state at last.end < cutoff. Its retained and archived states keep the original capacity and can both be checkpointed and restored. The original state remains reusable. Persist the archive before adopting retained. Delayed points can continue through archived. Reintroducing an archived series into retained begins a new cumulative origin and loses its previous retry window. This operation is explicit, with no automatic eviction or system-clock access. Run moon run examples/archive to exercise archival and retry recovery. Use State::merge_disjoint or CLI merge-state to reattach a disjoint archive while preserving origins and refusing conflicts.

    #Roadmap

    Exponential histograms support both signs, zero counts, scale alignment, bounded downscaling and version 4 recovery. Run moon run examples/exponential. Zero-threshold changes are explicitly refused.

    The optional bounded reordering layer accepts typed Int64, Double and Histogram deltas with explicit watermarks, recoverable pending state, strict limits and no automatic eviction. Run moon run examples/reorder. The OTLP request API remains strict and does not reorder requests automatically. The opt-in OTLP reorder adapter retains complete pending metadata and exposes reorder-to file receipts, inspection and export. Run moon run checks/reorder.mbtx -- moon wasm for the documented 3,1,2 workflow.

    Network receivers and multi-writer coordination are planned capabilities. The current profile requires contiguous intervals. It remembers only the most recent delta per series and does not offer unbounded deduplication or an exactly-once delivery guarantee.

    The semantic reference is the OpenTelemetry metrics data model https://opentelemetry.io/docs/specs/otel/metrics/data-model/. The state-processing boundary complements instrumentation SDKs and exporters. Implementation and tests are authored for this project. The Apache-2.0 license text is shared with the owner's Apache-2.0 projects. The official OTLP example is included with its license. Processing code is authored for this project.

    BufferError

    pub suberror BufferError {
    ReorderInvalid(String)
    LatePoint(String)
    BufferFull
    WindowExceeded(String)
    ReorderConflict(String)
    MissingInterval(String)
    }

    StitchError

    pub suberror StitchError {
    Invalid(String)
    }

    BufferedPoint

    pub(all) enum BufferedPoint {
    Counter(Sample)
    DoubleCounter(DoubleSample)
    Histogram(HistogramSample)
    Exponential(ExponentialSample)
    } derive(Eq)

    Input points are deltas; emitted points carry cumulative origins and values.

    BufferedPoint::equal

    automatically derived

    BufferedPoint::not_equal

    fn BufferedPoint::not_equal(x : BufferedPoint, y : BufferedPoint) -> Bool
    automatically derived

    Diagnostic

    pub(all) struct Diagnostic {
    pointer : String
    message : String
    }

    pointer identifies the nearest resource, scope, metric or data-point container using RFC 6901 syntax. An empty pointer identifies the request root.

    DiagnosticDetail

    pub(all) struct DiagnosticDetail {
    code : IssueCode
    pointer : String
    message : String
    }

    DoubleSample

    pub(all) struct DoubleSample {
    series : String
    start : Int64
    end : Int64
    value : Double
    } derive(Eq)

    A nonnegative finite Double delta. Accumulation uses IEEE-754 addition.

    DoubleSample::equal

    automatically derived

    DoubleSample::not_equal

    fn DoubleSample::not_equal(x : DoubleSample, y : DoubleSample) -> Bool
    automatically derived

    DoubleStep

    pub(all) struct DoubleStep {
    state : State
    points : Array[DoubleSample]
    duplicates : Int
    }

    ExponentialBuckets

    pub(all) struct ExponentialBuckets {
    offset : Int
    counts : Array[Int64]
    } derive(Eq)

    Dense absolute-magnitude bucket indexes, shared by positive/negative sides.

    ExponentialBuckets::equal

    automatically derived

    ExponentialBuckets::not_equal

    automatically derived

    ExponentialSample

    pub(all) struct ExponentialSample {
    series : String
    start : Int64
    end : Int64
    scale : Int
    zero_count : Int64
    zero_threshold : Double
    positive : ExponentialBuckets
    negative : ExponentialBuckets
    count : Int64
    sum : Double?
    min : Double?
    max : Double?
    } derive(Eq)

    Bounded exponential Delta histogram. Scale -10..20; each side <=1024 bins. Zero threshold must remain constant within a stream. Negative populations require absent sum. Input and output bucket arrays are detached.

    ExponentialSample::equal

    automatically derived

    ExponentialSample::not_equal

    fn ExponentialSample::not_equal(x : ExponentialSample, y : ExponentialSample) -> Bool
    automatically derived

    ExponentialStep

    pub(all) struct ExponentialStep {
    state : State
    points : Array[ExponentialSample]
    duplicates : Int
    }

    HistogramSample

    pub(all) struct HistogramSample {
    series : String
    start : Int64
    end : Int64
    bounds : Array[Double]
    counts : Array[Int64]
    count : Int64
    sum : Double?
    min : Double?
    max : Double?
    } derive(Eq)

    Explicit buckets have upper-inclusive bounds. Counts and population fit Int64. sum is optional. min/max must be both present or both absent.

    HistogramSample::coarsen

    fn HistogramSample::coarsen(self : HistogramSample, bounds : Array[Double]) -> HistogramSample raise StitchError

    Combine explicit buckets exactly. Every target bound must occur in the source layout; splitting/interpolation is refused. Empty bounds produce one bucket. Population, sum, extrema, identity and interval are retained.

    test {
    let p : @metricstitch.HistogramSample = {
    series: "latency",
    start: 1L,
    end: 2L,
    bounds: [1.0, 2.0],
    counts: [1L, 2L, 3L],
    count: 6L,
    sum: None,
    min: None,
    max: None,
    }
    assert_eq(p.coarsen([2.0]).counts, [3L, 3L])
    }

    HistogramSample::equal

    automatically derived

    HistogramSample::not_equal

    fn HistogramSample::not_equal(x : HistogramSample, y : HistogramSample) -> Bool
    automatically derived

    HistogramStep

    pub(all) struct HistogramStep {
    state : State
    points : Array[HistogramSample]
    duplicates : Int
    }

    IssueCode

    pub(all) enum IssueCode {
    InvalidInput
    UnsupportedData
    NoncontiguousInterval
    ConflictingRetry
    SeriesLimit
    NumericOverflow
    KindChanged
    } derive(Eq)

    Stable programmatic categories. Messages remain descriptive, not an API.

    IssueCode::code

    fn IssueCode::code(self : IssueCode) -> String

    Stable snake_case representation used by the CLI JSON report.

    IssueCode::equal

    fn IssueCode::equal(IssueCode, IssueCode) -> Bool
    automatically derived

    IssueCode::not_equal

    fn IssueCode::not_equal(x : IssueCode, y : IssueCode) -> Bool
    automatically derived

    NdjsonDecoder

    pub struct NdjsonDecoder {
    // private fields
    }

    Immutable bounded UTF-8 line framing. A feed chunk is at most 64 KiB; records are at most max_record_bytes excluding LF, including an optional CR.

    NdjsonDecoder::feed

    fn NdjsonDecoder::feed(self : NdjsonDecoder, chunk : Bytes) -> NdjsonLines raise StitchError

    Delimit LF/CRLF without lossy decoding. Partial multibyte characters stay in the byte buffer until the complete record arrives. Failure preserves self.

    NdjsonDecoder::finish

    fn NdjsonDecoder::finish(self : NdjsonDecoder) -> String? raise StitchError

    Return the final unterminated record, or None after a terminal LF/empty file. Blank framed records are retained; the replay session will refuse them.

    NdjsonDecoder::new

    fn NdjsonDecoder::new(max_record_bytes? : Int) -> NdjsonDecoder raise StitchError

    NdjsonLines

    pub(all) struct NdjsonLines {
    decoder : NdjsonDecoder
    lines : Array[String]
    }

    OtlpReorderBuffer

    pub struct OtlpReorderBuffer {
    // private fields
    }

    Owns pending typed deltas together with complete validated OTLP envelopes.

    OtlpReorderBuffer::advance

    fn OtlpReorderBuffer::advance(self : OtlpReorderBuffer, watermark : Int64) -> OtlpReorderStep raise BufferError

    OtlpReorderBuffer::checkpoint

    Versioned checkpoint includes every pending payload and its typed binding.

    OtlpReorderBuffer::new

    fn OtlpReorderBuffer::new(state : State, watermark~ : Int64, max_pending? : Int, max_delay_ns~ : Int64) -> OtlpReorderBuffer raise BufferError

    Create an OTLP adapter with the same explicit event-time contract as ReorderBuffer. Requests and recoverable checkpoints are bounded to 4M JSON code units. Existing strict process_otlp behavior remains unchanged.

    test {
    let b = @metricstitch.OtlpReorderBuffer::new(
    @metricstitch.State::new(),
    watermark=1L,
    max_delay_ns=10L,
    )
    let step = b.push({ "resourceMetrics": [] }, watermark=2L)
    assert_eq(
    @metricstitch.decode_reorder_receipt(step.receipt()).buffer.pending_count(),
    0,
    )
    }

    OtlpReorderBuffer::pending_count

    fn OtlpReorderBuffer::pending_count(self : OtlpReorderBuffer) -> Int

    OtlpReorderBuffer::pending_report

    fn OtlpReorderBuffer::pending_report(self : OtlpReorderBuffer, target : Int64) ->
    Json
    raise BufferError

    Enrich typed gaps with the following point's original OTLP envelope, so an operator can identify its metric/resource/scope/attributes. Owned results are bounded to the same 4M JSON budget as checkpoints. canAdvance includes adapter envelope/output budget validation, not just the typed accumulator.

    OtlpReorderBuffer::push

    fn OtlpReorderBuffer::push(self : OtlpReorderBuffer, request :
    Json
    , watermark~ : Int64) -> OtlpReorderStep raise BufferError

    Atomically queue supported OTLP Delta points and emit ready cumulative points. Gauges pass through immediately, including repeated inputs. Original empty containers are retained; emitted points keep their original resource, scope, schema URLs, metric metadata and attributes. Groups are not coalesced.

    OtlpReorderBuffer::restore

    Validate each single-point envelope and its exact binding to pending state. Unknown fields, mismatched metadata/value/identity and extra payloads fail.

    OtlpReorderBuffer::state

    OtlpReorderStep

    pub(all) struct OtlpReorderStep {
    buffer : OtlpReorderBuffer
    request :
    Json

    duplicates : Int
    }

    OtlpReorderStep::receipt

    OtlpStep

    pub(all) struct OtlpStep {
    state : State
    request :
    Json

    duplicates : Int
    }

    OtlpStep::receipt

    Serialize conversion output and its matching next state as one receipt.

    Partition

    pub(all) struct Partition {
    retained : State
    archived : State
    }

    Both states retain the original capacity. Archive persistence and routing of delayed points are the caller's responsibility.

    PendingGap

    pub(all) struct PendingGap {
    series : String
    start : Int64
    end : Int64
    next_end : Int64
    blocks_target : Bool
    } derive(Eq)

    Missing half-open interval [start,end) before a queued point. A new stream's unknown origin is never invented. blocks_target refers to the following point's end; arithmetic/profile failures are reported separately.

    PendingGap::equal

    fn PendingGap::equal(PendingGap, PendingGap) -> Bool
    automatically derived

    PendingGap::not_equal

    fn PendingGap::not_equal(x : PendingGap, y : PendingGap) -> Bool
    automatically derived

    PendingReport

    pub(all) struct PendingReport {
    watermark : Int64
    target : Int64
    pending : Int
    ready : Int
    capacity : Int
    max_delay_ns : Int64
    oldest_end : Int64?
    newest_end : Int64?
    unanchored : Array[String]
    gaps : Array[PendingGap]
    advance_error : String?
    }

    PendingReport::to_json

    ReorderBuffer

    pub struct ReorderBuffer {
    // private fields
    }

    Explicit event-time watermark; no wall clock, timer, eviction or data loss.

    ReorderBuffer::advance

    fn ReorderBuffer::advance(self : ReorderBuffer, watermark : Int64) -> ReorderStep raise BufferError

    Advance without adding points. Failure never evicts a buffered interval.

    ReorderBuffer::checkpoint

    Detached, versioned JSON including committed state and every pending delta.

    ReorderBuffer::new

    fn ReorderBuffer::new(state : State, watermark~ : Int64, max_pending? : Int, max_delay_ns~ : Int64) -> ReorderBuffer raise BufferError

    watermark is the closed event-time boundary; later arrivals ending at or before it are refused except exact last-point retries. max_delay_ns bounds how far pending ends may lie ahead of the watermark, not processing latency.

    test {
    let b = @metricstitch.ReorderBuffer::new(
    @metricstitch.State::new(),
    watermark=1L,
    max_delay_ns=10L,
    )
    assert_eq(b.advance(2L).buffer.pending_count(), 0)
    }

    ReorderBuffer::pending_count

    fn ReorderBuffer::pending_count(self : ReorderBuffer) -> Int

    ReorderBuffer::pending_report

    fn ReorderBuffer::pending_report(self : ReorderBuffer, target : Int64) -> PendingReport raise BufferError

    Diagnose every queued gap and dry-run advance without consuming any point. Results follow deterministic end/series/start queue order. Success predicts only a typed advance with this exact buffer and target, not future arrivals.

    test {
    let b = @metricstitch.ReorderBuffer::new(
    @metricstitch.State::new(),
    watermark=1L,
    max_delay_ns=10L,
    )
    assert_eq(b.pending_report(2L).advance_error, None)
    assert_eq(b.pending_count(), 0)
    }

    ReorderBuffer::push

    fn ReorderBuffer::push(self : ReorderBuffer, batch : Array[BufferedPoint], watermark~ : Int64) -> ReorderStep raise BufferError

    Stage at most 4096 points and advance a nondecreasing watermark atomically. Ready points are ordered by end, series, start. Missing predecessors reject the whole call, leaving the old buffer available for correction and retry. A new stream begins at its earliest emitted interval; callers must establish its intended start by supplying all predecessors before advancing watermark.

    ReorderBuffer::restore

    Validate all state, limits, windows and pending conflicts. No unknown fields, versions, duplicate pending points or silent normalization of state accepted.

    ReorderBuffer::state

    fn ReorderBuffer::state(self : ReorderBuffer) -> State

    ReorderStep

    pub(all) struct ReorderStep {
    buffer : ReorderBuffer
    points : Array[BufferedPoint]
    duplicates : Int
    }

    ReplayRecord

    pub(all) struct ReplayRecord {
    session : ReplaySession
    request :
    Json

    duplicates : Int
    ordinal : Int64
    }

    ReplayRecord::receipt

    ReplaySession

    pub struct ReplaySession {
    // private fields
    }

    Serial ordered replay state. A restored session consumes a continuation, never an automatically skipped prefix of the original input file.

    ReplaySession::apply_line

    fn ReplaySession::apply_line(self : ReplaySession, line : String) -> ReplayRecord raise StitchError

    Apply one standard Delta OTLP JSON record atomically. Blank/malformed records are refused with a one-based ordinal; no record is silently skipped.

    test {
    let s = @metricstitch.ReplaySession::new(@metricstitch.State::new())
    let r = s.apply_line("{\"resourceMetrics\":[]}")
    assert_eq(r.ordinal, 1L)
    assert_eq(s.record_count(), 0L)
    }

    ReplaySession::checkpoint

    ReplaySession::new

    fn ReplaySession::new(state : State) -> ReplaySession raise StitchError

    ReplaySession::record_count

    fn ReplaySession::record_count(self : ReplaySession) -> Int64

    ReplaySession::restore

    ReplaySession::state

    fn ReplaySession::state(self : ReplaySession) -> State

    ReplaySession::verify_record

    fn ReplaySession::verify_record(self : ReplaySession, line : String, receipt :
    Json
    ) -> ReplaySession raise StitchError

    Recompute one receipt from its original Delta input and this trusted prior session. Compare progress, duplicates, complete output and complete logical checkpoint, including untouched streams and capacity. On mismatch no next session is returned. This proves correspondence to the supplied inputs, not their authenticity, downstream delivery, or an unprovided recording prefix.

    test {
    let s = @metricstitch.ReplaySession::new(@metricstitch.State::new())
    let line = "{\"resourceMetrics\":[]}"
    let record = s.apply_line(line)
    let verified = s.verify_record(line, record.receipt())
    assert_eq(verified.checkpoint(), record.session.checkpoint())
    assert_eq(s.record_count(), 0L)
    }

    Sample

    pub(all) struct Sample {
    series : String
    start : Int64
    end : Int64
    value : Int64
    } derive(Eq)

    A nonnegative Int64 delta over (start, end], with positive nanosecond times. Direct callers own the stable series identity. The OTLP adapter supplies it.

    Sample::equal

    fn Sample::equal(Sample, Sample) -> Bool
    automatically derived

    Sample::not_equal

    fn Sample::not_equal(x : Sample, y : Sample) -> Bool
    automatically derived

    State

    pub struct State {
    // private fields
    }

    State::apply

    fn State::apply(self : State, batch : Array[Sample]) -> Step raise StitchError

    Accumulate consecutive intervals atomically. Exact last-point retries emit nothing. Gaps, overlap, older retries and conflicting retries are rejected.

    test {
    let s = @metricstitch.State::new()
    let p : @metricstitch.Sample = {
    series: "requests",
    start: 1L,
    end: 2L,
    value: 7L,
    }
    let first = s.apply([p])
    assert_eq(first.state.apply([p]).duplicates, 1)
    }

    State::apply_doubles

    fn State::apply_doubles(self : State, batch : Array[DoubleSample]) -> DoubleStep raise StitchError

    Apply finite Double deltas with the same interval and retry rules as apply. Numeric-kind switches are rejected. State is committed only on success.

    test {
    let p : @metricstitch.DoubleSample = {
    series: "duration",
    start: 1L,
    end: 2L,
    value: 1.25,
    }
    let first = @metricstitch.State::new().apply_doubles([p])
    assert_eq(first.state.apply_doubles([p]).duplicates, 1)
    }

    State::apply_exponentials

    fn State::apply_exponentials(self : State, batch : Array[ExponentialSample]) -> ExponentialStep raise StitchError

    Accumulate contiguous exponential histograms, aligning to the coarser scale and lowering scale further when necessary to retain at most 1024 bins/side. All failures preserve the original state. Exact last-delta retries emit none.

    test {
    let p : @metricstitch.ExponentialSample = {
    series: "zeros",
    start: 1L,
    end: 2L,
    scale: 0,
    positive: { offset: 0, counts: [], },
    negative: { offset: 0, counts: [], },
    zero_count: 1L,
    zero_threshold: 0.0,
    count: 1L,
    sum: Some(0.0),
    min: None,
    max: None,
    }
    let state = @metricstitch.State::new().apply_exponentials([p]).state
    assert_eq(state.apply_exponentials([p]).duplicates, 1)
    }

    State::apply_histograms

    fn State::apply_histograms(self : State, batch : Array[HistogramSample]) -> HistogramStep raise StitchError

    Accumulate matching explicit-bucket histograms. Arrays are detached on entry and on return. A rejected batch leaves the old state reusable.

    test {
    let p : @metricstitch.HistogramSample = {
    series: "latency",
    start: 1L,
    end: 2L,
    bounds: [1.0],
    counts: [1L, 1L],
    count: 2L,
    sum: Some(2.0),
    min: Some(0.0),
    max: Some(2.0),
    }
    let first = @metricstitch.State::new().apply_histograms([p])
    assert_eq(first.state.apply_histograms([p]).duplicates, 1)
    }

    State::checkpoint

    fn State::checkpoint(self : State) ->
    Json

    Serialize exact decimal values in sorted series order, independent of arrival order.

    State::coarsen_histogram

    fn State::coarsen_histogram(self : State, series : String, bounds : Array[Double]) -> State raise StitchError

    Explicitly migrate one tracked histogram and its retry delta. Replay the coarsened last delta for retry detection after this migration. Other streams and the original State retain their previous layout and behavior.

    State::diff

    fn State::diff(self : State, other : State, max_changes? : Int, max_paths? : Int) -> StateDiff raise StitchError

    Compare logical records, independent of checkpoint version/arrival order. Sorted changes contain detached before/after values and RFC 6901 paths relative to each series view. This is a difference report, not a proof of lineage, valid accumulation, delivery, or a patch to apply to state.

    test {
    let a = @metricstitch.State::new()
    assert_eq(a.diff(a).changes.length(), 0)
    }

    State::merge_disjoint

    fn State::merge_disjoint(self : State, other : State) -> State raise StitchError

    Reattach disjoint archived/sharded states without adding their totals. The destination's capacity is authoritative. Any overlapping identity, including an identical record or a different kind, is refused atomically. Origins, most-recent deltas and checkpoint versions are preserved.

    test {
    let a : @metricstitch.Sample = { series: "a", start: 1L, end: 2L, value: 5L, }
    let b = { ..a, series: "b", }
    let left = @metricstitch.State::new().apply([a]).state
    let right = @metricstitch.State::new().apply([b]).state
    let joined = left.merge_disjoint(right)
    assert_eq(joined.apply([a, b]).duplicates, 2)
    }

    State::new

    fn State::new(max_series? : Int) -> State raise StitchError

    Create a bounded state. Applying batches returns a new state.

    State::partition_before

    fn State::partition_before(self : State, cutoff : Int64) -> Partition raise StitchError

    Partition by last.end < cutoff, expressed as positive Unix nanoseconds. No clock is read and no series is discarded. Reintroducing an archived series to retained starts a new cumulative origin. Route delayed points to archived when its previous cumulative history must continue.

    test {
    let p : @metricstitch.Sample = {
    series: "requests",
    start: 1L,
    end: 2L,
    value: 7L,
    }
    let state = @metricstitch.State::new().apply([p]).state
    let split = state.partition_before(3L)
    assert_eq(split.archived.checkpoint(), state.checkpoint())
    }

    State::restore

    Validate a versioned checkpoint before constructing state. This checks structural consistency, not authenticity of externally modified totals.

    State::summary

    Return a detached summary of capacity, kinds and most-recent end timestamps.

    StateChange

    pub(all) struct StateChange {
    series : String
    kind : StateChangeKind
    paths : Array[String]
    before :
    Json
    ?
    after :
    Json
    ?
    }

    StateChangeKind

    pub(all) enum StateChangeKind {
    Added
    Removed
    Changed
    } derive(Eq)

    StateChangeKind::code

    fn StateChangeKind::code(self : StateChangeKind) -> String

    StateChangeKind::equal

    automatically derived

    StateChangeKind::not_equal

    fn StateChangeKind::not_equal(x : StateChangeKind, y : StateChangeKind) -> Bool
    automatically derived

    StateDiff

    pub(all) struct StateDiff {
    before_capacity : Int
    after_capacity : Int
    unchanged : Int
    changes : Array[StateChange]
    }

    StateDiff::to_json

    Each call returns a detached JSON report, including detached nested arrays.

    Step

    pub(all) struct Step {
    state : State
    points : Array[Sample]
    duplicates : Int
    }

    coarsen_otlp_histograms

    fn coarsen_otlp_histograms(request :
    Json
    , bounds : Array[Double]) ->
    Json
    raise StitchError

    Coarsen supported Delta OTLP explicit Histograms without accumulating them. Other supported kinds and all metadata remain unchanged. Shape/profile validation is shared with the reorder adapter; no interval order is assumed.

    compact_otlp

    Coalesce adjacent equal headers in supported cumulative OTLP/JSON. Every point and its traversal order, exact values and metadata are preserved. Empty containers are barriers at their own level; no sorting, aggregation, schema guessing or removal of unsupported fields occurs. Input is detached.

    test {
    let empty : Json = { "resourceMetrics": [] }
    assert_eq(@metricstitch.compact_otlp(empty), empty)
    }

    decode_receipt

    fn decode_receipt(value :
    Json
    ) -> OtlpStep raise StitchError

    Validate trusted local receipt structure, checkpoint and cumulative request profile. Historical output points are validated independently. This does not authenticate a receipt or prove that its output was delivered.

    test {
    let step = @metricstitch.process_otlp(@metricstitch.State::new(), {
    "resourceMetrics": [],
    })
    let restored = @metricstitch.decode_receipt(step.receipt())
    assert_eq(restored.state.checkpoint(), step.state.checkpoint())
    }

    decode_reorder_receipt

    fn decode_reorder_receipt(value :
    Json
    ) -> OtlpReorderStep raise BufferError

    Structural validation for trusted local receipts, not authentication or a delivery acknowledgement. Output and checkpoint correspondence is not proven.

    decode_replay_record

    fn decode_replay_record(value :
    Json
    ) -> ReplayRecord raise StitchError

    Validate a trusted local record envelope, output profile and ordinal/session consistency. This is not authentication or proof of input-file identity.

    diagnose_otlp

    fn diagnose_otlp(state : State, request :
    Json
    ) -> DiagnosticDetail?

    Read-only classification produced at the failing check, without parsing error text. Existing Diagnostic and StitchError::Invalid remain unchanged.

    test {
    let d = @metricstitch.diagnose_otlp(@metricstitch.State::new(), {
    "unknown": 1,
    })
    assert_true(d is Some({ code: UnsupportedData, .. }))
    }

    parse_input

    fn parse_input(source : String) ->
    Json
    raise StitchError

    Parse bounded JSON with duplicate decoded object keys rejected. A Json value passed directly to process_otlp must already have unambiguous object keys.

    process_otlp

    fn process_otlp(state : State, request :
    Json
    ) -> OtlpStep raise StitchError

    Convert supported Delta metrics atomically. Errors retain the Invalid constructor and include the indexed input location in their message.

    process_sequence

    fn process_sequence(state : State, requests : Array[
    Json
    ]) -> OtlpStep raise StitchError

    Convert at most 1024 requests in order as one transaction. ResourceMetrics groups remain ordered and are not coalesced. A later error returns no partial receipt or state, and identifies its zero-based request index.

    test {
    let state = @metricstitch.State::new()
    let result = @metricstitch.process_sequence(state, [{ "resourceMetrics": [] }])
    assert_eq(result.state.checkpoint(), state.checkpoint())
    }

    validate_otlp

    fn validate_otlp(state : State, request :
    Json
    ) -> Diagnostic?

    Validate with the same conversion and state checks as process_otlp, returning the first diagnostic. Input and state remain available for correction/retry.

    test {
    let state = @metricstitch.State::new()
    assert_true(
    @metricstitch.validate_otlp(state, { "resourceMetrics": [] }) is None,
    )
    }