kuilt-otel
Offline-first OpenTelemetry for Kotlin Multiplatform.
Record traces, metrics, and logs on any platform — JVM, Android, iOS, macOS, or browser (wasm) — and have them automatically reconcile across all your users' devices when connectivity returns. Syncing the same saved state twice never counts it twice; retrying a failed export is another matter, covered below.
Why this is different
Standard OpenTelemetry exporters POST spans to a collector and fail if the network is down. kuilt-otel turns that around: export() succeeds the moment the data is durably written to local storage. Delivery to a backend happens whenever the network allows, possibly hours later. Reconnecting devices exchange only the missing deltas — not a full queue replay — so a brief reconnection is kind to a flaky link.
Every signal is stored as a CRDT. Spans are full SpanRecord values in an ORSet, including their causal stamps; span id alone does not determine equality. Metrics are mergeable counters. Logs are an ordered append-only sequence. Merging the same saved snapshot again is idempotent: it does not add another copy.
Retrying export() is different from merging a snapshot. A span shows in snapshot() only once its writes have landed, so a peer never holds a span the store might lack. A failed or cancelled export shows nothing and leaves nothing in memory, stamped or not, so the caller's retry is the span's only copy. (Earlier versions kept a failed export's unstamped or explicitly stamped span in memory, and the next write saved it.) A span write may still land after the call failed or was cancelled. After a restart, recovery can read it, and retrying the original unstamped span then mints a new stamp and adds another value with the same span id. Retrying a metric increment adds it again; a log record whose id was already exported is skipped.
Quick start
val telemetry = WarpTelemetry(
replica = ReplicaId("device-uuid-abc123"),
store = InMemoryDurableStore(),
)
// Load any spans and log records buffered during a previous session.
telemetry.recover()
// Span ids are raw bytes (OTLP wire format): 16 bytes for trace id, 8 for span id.
val span = SpanRecord(
traceId = ByteString(ByteArray(16) { it.toByte() }),
spanId = ByteString(ByteArray(8) { it.toByte() }),
parentSpanId = null,
name = "purchase",
kind = SpanKind.SERVER,
startEpochNanos = 1_000_000_000L,
endEpochNanos = 1_500_000_000L,
attributes = mapOf("item.id" to "widget-42"),
status = SpanStatus.Ok,
)
// export() returns the moment the data is durably written locally —
// not when it reaches a backend. Delivery is the fabric's job.
val spanResult = telemetry.spans.export(span)
check(spanResult == ExportResult.Success) { "export failed: $spanResult" }
val logRecord = LogRecord(
recordId = ByteString(ByteArray(8) { it.toByte() }),
body = "purchase completed",
severityNumber = 9, // INFO
traceId = ByteString(ByteArray(16) { it.toByte() }),
spanId = ByteString(ByteArray(8) { it.toByte() }),
)
val logResult = telemetry.logs.export(logRecord)
check(logResult == ExportResult.Success) { "log export failed: $logResult" }Is the device saving anything?
Read WarpTelemetry.health to see whether each buffer is making progress. Logs keep record counts (ExporterHealth); spans and metrics expose PersistenceHealth through observable health flows. Its acknowledged counter advances once a complete local persistence turn succeeds, even if that turn needs several store calls. Reads and calls that do no store IO do not advance it. For metrics a turn is one metric kind's write, so a WarpMetricExporter.record batch counts one turn per kind it touched. A batch the store partly refuses moves both acknowledged and failed.
failed counts failed turns. outstandingFailures stays nonzero until the same work succeeds: a healthy sum write cannot hide a failing histogram, and a successful metric clear cannot prove writes work. A failed read or decode of saved state sets recoveryFailed for the instance's lifetime, whether it failed in recover() or when a later turn retried a refused read; lastFailure retains the latest cause after recovery. Bad bytes start the log and span buffers fresh. A store that refuses the read instead makes every log or span turn fail, and write nothing, until a later read succeeds. That keeps the records and spans on disk the read would have found. Log turns retry the read on a window that doubles up to 63 turns, so a long outage costs one store read per 64 log turns; recover() always reads. Span turns (export, merge and clear) retry on the same window, so a long outage reads the whole span blob once per 64 turns. A span turn that read stops, or that skips the read inside the window, counts in failed, and the first span write that lands resolves it. Metrics do the same for each metric kind on its own: a refused read of the histograms fails the histogram turns, and a batch's sums still write. Each kind retries its read on the same doubling window as the logs, counted in that kind's own turns, so a refused histogram read backs off the histograms alone and a turn that writes only sums spends none of it. A batch refused for an overflow spends one as well, since it would have read the kind; it still counts no turn on health. A skipped turn fails exactly as a refused read does. A metric exporter nobody recovered reads each kind before its first write.
The span clock is counted as its own work. While the store refuses the clock's read, a span turn still saves its span, without a causal stamp, and skips the clock. Its turns retry the clock's read on the same doubling window, and a turn inside the window skips the read and counts as a refused one would. That turn counts twice: acknowledged for the span and failed for the clock. A clock refused forever therefore keeps outstandingFailures above zero however many spans land. The first turn that writes the clock clears those failures, unless that turn wanted a stamp the clock could not give. A clock with no stamps left (ClockTick.Exhausted) is that case: each export that wanted a stamp saves its span without one and counts a clock failure, though the clock's write lands. A clear, or a span that carries its own stamp, wants no stamp, so it is not counted, and its clock write clears those failures. A refused clock write fails the whole turn, since the span write comes after it and is never made. A failed turn may still have saved its data, and a cancelled turn counts as neither acknowledged nor failed; a cancelled metric batch keeps the turns of the kinds it had already written. "Cancelled" means the caller was cancelled. When the store cancels its own call instead, say on its own timeout, a log turn counts as failed. These are local persistence signals, not confirmation of delivery to a backend. The combined getter reads each exporter in turn, so it is not an atomic snapshot across signals during concurrent activity.
When an app suddenly has a lot to say
Saving one log line used to cost a full round of bookkeeping and two writes to the device's storage — every single time. Hand over a handful of lines at once and that cost is paid once for the lot, so an app that gets chatty for a moment doesn't have to pay for each line separately.
Nothing is delayed to make that happen. A batch is only ever what the caller already had in hand, and it is on disk before the call returns — a lone line on a quiet app is written just as promptly as before.
WarpLogRecordExporter.export takes either a single record or a list of them. The list overload admits the whole run to the Rga, encodes the active segment once and writes it once, rather than repeating that per record; a run too large for one segment is split across turns, so a failure means "stop", not "none of it landed" (#2194). Dedup and the buffer cap remain per-record decisions. Its KDoc carries a worked example.
Where the bytes actually land
Every exporter here writes through a DurableStore — a small "keep these bytes safe" interface with a crash-safe implementation per platform. It lives in its own module, kuilt-store, because a durable key→bytes store has nothing to do with telemetry; see that module's documentation for the durability contract and the four backends.
kuilt-otel on a server
On a phone, kuilt-otel is the safety net for a train tunnel. A server rarely loses its network. It does crash, restart and get redeployed, and a deploy can take the last few seconds of metrics with it. On a server kuilt-otel plays a smaller part: a copy of your metrics on disk, kept beside the OpenTelemetry SDK you already run. That copy survives the restart and reaches the collector later.
It is not where a busy server should count each request. The SDK already does that in memory, cheaply. Let the SDK add up the numbers, and let kuilt keep what the SDK hands over. KuiltMetricExporter, in kuilt-otel-sdk, is the bridge between the two.
The promise, and what it costs
WarpMetricExporter returns MetricExportResult.Success only once the update is durably written to its DurableStore. That is the whole contract. It says nothing about the collector, which hears about the update on a later drain.
The result says what a retry may send. A Refused is an overflow: the whole call was refused before anything was applied, and the same call may be refused again until that series is cleared or evicted. A Partial lists in uncounted exactly the updates of a metric kind the store would not let it read. Those were not applied, so recording just that list again counts each once. Every other update of a Partial was counted. A refused write means "not yet on disk", not "not counted": the change stays in memory and the next successful write of that kind carries it, so retrying it counts it twice.
A merge* call or clear() returns a plain MetricWriteResult, Success or Failure(cause). A merge is a join and a clear a delete, so calling either again is always safe.
The promise has a price. Each write re-encodes every series of its kind. A single call such as incrementSum is one write. Hand many changes over at once with WarpMetricExporter.record, a list of MetricUpdates, and you pay one write per metric kind the list touches, under the same promise (#3284). KuiltMetricExporter records each SDK export that way, so an export of N counter points is one write of the sums, not N. Every UpDownCounter series is still in every export, moved or not. That is why kuilt-otel belongs behind the SDK's periodic reader, which hands it one batch every few seconds, and not in a request's hot path.
What a collector receives
A number can travel two ways: as a running total since the start, or as the change since the last report. OpenTelemetry calls this choice temporality, and the two values are cumulative and delta. kuilt takes counter deltas in and sends totals out.
Going in, KuiltMetricExporter asks the SDK for delta temporality on counters, because incrementSum adds what it is given; a running total would be added again on every collection. It asks for cumulative on UpDownCounters, which become gauges: a gauge holds a level, and a delta would store the change since the last collection instead. Gauges and histograms stay delta. A sum that arrives the other way, from a reader that picks its own temporality, is dropped with a warning. The SDK sets temporality per reader, so registering the bridge on a reader of its own leaves your existing OTLP exporter as it was.
Going out, WarpOtlpBridge.drain renders each series from its CRDT, and the OTLP encoders in kuilt-otel-otlp (JSON and protobuf alike) put it on the wire like this:
MetricKind | Stored as | OTLP point | Temporality |
|---|---|---|---|
SUM, incrementSum | GCounter | monotonic Sum, integer | cumulative |
SUM, incrementSumDouble | GCounterDouble | monotonic Sum, double | cumulative |
GAUGE | LWWRegister<Double> | Gauge | none — a level |
CARDINALITY | HyperLogLog | Gauge, the integer estimate | none — a level |
EXPONENTIAL_HISTOGRAM | DDSketch | ExponentialHistogram | cumulative |
A collector should expect four things of those points:
The start time is zero. Sums and histograms carry
startTimeUnixNano = 0, OTLP's "unknown start", so nothing on the wire marks where a series began.The time is the drain's, not the update's. Every point is stamped with the bridge's clock when the drain runs.
An unchanged series is not re-sent. A drain sends a series only when its value differs from the last one the edge recorded for it. A steady total produces no new points, and a gap between points does not mean a gap in counting.
A total already includes every peer it has merged. A
GCounteradds up each replica's own slot, so two replicas that gossip their metrics and drain the same series both send the combined total. Adding their totals together counts the shared increments twice.
If you implement OtlpEdge yourself, the same rules apply: MetricPoint.Sum, MetricPoint.DoubleSum and MetricPoint.ExponentialHistogram are running totals, so send them as cumulative.
What's here
| Type | What it does |
|---|---|
WarpSpanExporter | Span buffer of full SpanRecord values (ORSet). Snapshot merge is idempotent; export retries can mint another causal stamp. |
WarpMetricExporter | CRDT-backed metric buffer: sums (GCounter, GCounterDouble), gauges (LWWRegister), cardinality (HyperLogLog), exponential histograms (DDSketch). Success means durably written. |
WarpLogRecordExporter | CRDT-backed log buffer (Rga). Ordered, idempotent export + merge. |
WarpTelemetry | Facade that composes all exporters under one surface. |
WarpTelemetry.clear | The supported reset: empties every signal's buffer and its persisted state on a live instance — no restart, no per-platform directory delete. Logs and spans suppress what they drop, so a peer cannot re-merge it back; metrics forget only locally (a monotonic join has no merge-safe forget). |
WarpOtlpBridge | Drains converged CRDTs to an OTLP edge, reconciling by digest. |
OtlpEdge | Interface your backend implements to receive spans. |
SpanDigest | Compact set of span ids the edge already holds; drives delta computation. |
DrainResult | Typed result of WarpOtlpBridge.drain: Success with per-signal counts, Partial (counts plus the signals that failed), or Failure (every attempted signal failed). Each failure is a SignalFailure naming its OtlpSignal and the edge's own exception. |
SpanRecord | OTLP-shaped span data model. |
LogRecord | OTLP-shaped log-record data model with optional trace correlation. |
MetricKey | Identity of one metric time series (name + kind + label set). |
MetricKind | SUM / GAUGE / CARDINALITY / EXPONENTIAL_HISTOGRAM. |
ExportResult | Typed result of span/log export() / merge(). |
MetricExportResult | Typed result of record and the single-point metric mutators: Success, Refused (an overflow; nothing applied), or Partial, whose uncounted is exactly the updates a retry may send again. |
MetricWriteResult | Typed result of the idempotent merge* calls and metric clear(): Success or Failure(cause). |
BufferPolicy | Span/log bounded-buffer eviction strategy (spans log each drop; log records count them on ExporterHealth). |
MetricBufferPolicy | Metric bounded-buffer eviction strategy (always logs what it drops). |
Honest limits
Clock skew. Timestamps are the producer's local clock. Long-offline devices may have skewed clocks; an HLC offset could be estimated on reconnect but is not yet implemented. Gauge values from a device with a slow clock may be silently overwritten by a peer with a faster clock even if the slow-clock value is "newer" in wall time.
Late traces. A trace straddling an offline and an online producer only assembles when the offline half syncs. Collectors accept late spans within a configurable assembly window.
Bounded buffer. The span and log buffers are capped (
DEFAULT_MAX_SPANS,DEFAULT_MAX_LOG_RECORDS); the metric buffer atDEFAULT_MAX_METRICSdistinct series. Eviction is never silent, but it is reported differently by rate: spans and metrics log each drop; log records are counted exactly onExporterHealth.dropped/ExporterHealth.refusedwith one rate-limited summary line, because atDEFAULT_MAX_LOG_RECORDSevery exported record evicts one and a per-record line would narrate the cap doing its job. Counters are O(1) regardless of offline duration (a counter compresses losslessly).For logs, the total settles on the export path and still grows on the gossip path.
WarpLogRecordExporterpersists its op-log in segments ofDEFAULT_LOG_SEGMENT_OPSoperations, so one export rewrites one segment rather than the whole log (the exception follows a refused merge, below); it then periodically drops everything outside the retained window from memory and deletes any sealed segment that durably written suppression state fully covers. A device fed only by its ownWarpLogRecordExporter.exportcalls therefore holds O(DEFAULT_MAX_LOG_RECORDS) ops and a flat number of keys however long it runs, and startup reads that many keys rather than one per segment ever written (#2127). That is one arm of the claim, not the whole of it — and the other arm costs whole records, not a small note. A record that arrived from a peer throughWarpLogRecordExporter.mergecannot fold into the per-author floor — raising another author's floor would annihilate records it has not written yet — so each one windowed away is suppressed by an explicit compaction record instead. In memory that is one bodiless(id -> id)pair per element. On disk it is not bodiless at all: nothing prunes a compaction record, so a segment carrying one is pinned, and a pinned segment is retained entire — every record it holds, bodies included, permanently. Three shapes reach it. A sealed segment that happened to be active when a pass minted one keeps its fullDEFAULT_LOG_SEGMENT_OPSoperations (~123 KB at the defaults) forever. AndWarpLogRecordExporter.mergepersists the remote's op-log verbatim under a key of its own, so merging from a peer that has itself windowed a foreign author's records — which is any peer in a steady-state mesh — pins that peer's whole log: megabytes per merge at the defaultDEFAULT_MAX_LOG_RECORDS. And the first merge after a failed one persists this replica's whole merged log instead of the remote's, so the stranded ops reach disk. Until that merge lands, a local export of one of the stranded records persists the same whole log first, pinned on the same terms. So the gossip path is growth, not a bound, and a replica that gossips accumulates it for as long as the process lives. Bounding it needs the same causal-stability argument tombstone collection does; consolidation — rewriting a pinned segment's compaction record forward so the segment can go — was considered and declined, and nothing implements it. The span and metric exporters still rewrite their whole state per export.Cardinality estimation. HyperLogLog gives ~0.81% relative error at default precision (
p=14). Small cardinalities (< ~5 distinct elements) have higher relative error; the linear-counting correction reduces but does not eliminate this. Precision is fixed per metric; changing it after production data exists is wire-breaking.Trust. On-device telemetry and peer-relayed telemetry need auth/encryption to prevent forgery. Deferred to a later PR.