- an explicit, callback-based
TelemetryContext/TelemetrySpancontract; - a shared
NOOP_TELEMETRY_CONTEXT; - opaque cross-process propagation and span links;
- counters, up-down counters, histograms, and typed metric schemas;
- a reference
InMemoryTelemetryContextimplementation; - serializable schema definitions with inferred TypeScript types;
- no exporter, global current-span state, or dependency on a telemetry backend.
Installation
Telemetry Concepts
Telemetry describes what a program did while it was running. This package models that work using spans, attributes, events, statuses, and explicit context:
For example, loading an account could produce this telemetry:
Core Context API
ATelemetryContext starts a span around a callback. The callback receives a TelemetrySpan, which is also the explicit parent context for child spans. Contexts optionally expose their adapter’s metrics?: TelemetryMetrics and propagation?: TelemetryPropagation capabilities; child spans and extracted parents carry the same capabilities. A TelemetryContext adapter starts root spans; hosts retain this adapter. Invocation contexts and @bastani/atomic-ai request options carry a TelemetrySpan, never the adapter. A tracing adapter that only implements startSpan() is still valid.
end() method. startSpan() owns settlement and keeps the span open until the callback’s value or promise settles. For an expected failure represented by a normal return value, set the status explicitly:
Adapter Contract
An adapter implementsTelemetryContext and bridges the generic API to its backend. Typed inputs are trusted; malformed inputs have unspecified behavior. Adapters are not required to validate inputs or suppress adapter/backend failures.
The callback and recording contract is:
- create a child span and invoke the callback synchronously, exactly once;
- expose optional metric and propagation capabilities on its contexts, child spans, and extracted parents, including inert fallback spans;
- preserve the callback’s returned value and rejection value, returning a promise rejected with the same value after a synchronous throw;
- keep the native span open until a returned promise settles;
- treat normal completion as
okand throws/rejections as errors unless an explicit status was set; - make repeated
setStatus()calls last-write-wins; - merge
setAttributes()calls, with later defined values replacing earlier values andundefinedignored; - make recording methods synchronous;
- ignore calls made after settlement.
TelemetryContext arguments. Exporter buffering, flushing, sampling, backend IDs, and backend-specific context objects belong to the adapter. Use the adapter conformance suite to check these observable semantics.
Propagation and Span Links
An adapter may also implementTelemetryPropagation. Expose it through context.propagation so code can inject or extract using the context it already has. The root, spans, and extracted parents share the adapter’s capability object:
traceparent and tracestate fit without requiring them. Transport code sends only the carrier, never a context or span:
undefined for roots, no-op contexts, and unsupported contexts. Extraction returns a receiver-owned parent. Absent or unknown carriers fall back to the adapter’s root. Extraction checks only that required carrier keys contain strings; identifiers are opaque and need no format validation. Both methods are synchronous. Trace metadata is diagnostics, never authorization. Transport boundaries own carrier size limits.
A link relates work without changing its parent. Use SpanOptions.links when the target is known at creation, or span.addLink() after the span has started:
TelemetryContext handles, including spans and extracted remote parents. For a remote link, first call adapter.extract(carrier). A settled target remains linkable and injectable; a settled source ignores addLink(). Links append in order, copy attributes, and ignore root, no-op, or unsupported contexts. The typed span starter’s callback also supports addLink(); initial links use the low-level startSpan() API.
NOOP_TELEMETRY_PROPAGATION ignores its arguments: injection returns undefined, extraction returns NOOP_TELEMETRY_CONTEXT.
Metrics
An adapter may implementTelemetryMetrics alongside TelemetryContext and TelemetryPropagation. Applications configure one adapter, not separate backends for each capability. Expose the shared capability through context.metrics; child spans retain it, so nested model calls can record metrics without a separate configuration option. The in-memory adapter also implements the factory methods directly:
InstrumentOptions (description, unit). Histograms additionally accept HistogramOptions.boundaries: callers supply finite, strictly increasing bucket hints. Backends own aggregation and may translate these hints. Callers are responsible for finite measurements and non-negative counter increments; up-down counters and histograms may use signed values. Histogram record(value, attributes?, context?) optionally correlates a measurement with a span, called an exemplar. Counter add(value, attributes?) has no context argument.
Factories and recording methods are synchronous and trust typed inputs. Adapters need not validate measurement values, metadata, attributes, or boundaries; malformed inputs have unspecified behavior. NOOP_TELEMETRY_METRICS returns shared frozen instruments that discard measurements. Record only values already available to business code; do not serialize or measure extra data for telemetry.
Use only low-cardinality attributes: bounded values such as direction or method, not request IDs, user IDs, prompts, or arbitrary paths. The low-level attribute bag remains open; instrumentation owns this policy, not backend-specific heuristics.
Typed metric schemas
TelemetrySchemaDefinition.metrics optionally declares instrument names, kinds, metadata, and required/optional attributes. createTypedMetrics() combines one or more schemas and rejects duplicate metric names, incorrect instrument kinds, unknown attributes, and missing required attributes at compile time:
kind: 'counter' | 'upDownCounter' | 'histogram'; only histograms may declare boundaries. Metric attributes use the same scalar/array definitions as spans, but reject cardinality: 'high'. Omitting the cardinality annotation does not waive the low-cardinality policy. Unlike the typed span starter, the metric helper reads and retains schema instrument metadata at runtime. It performs no runtime attribute validation.
InMemoryTelemetryContext.getMetrics() returns ordered, detached RecordedTelemetryMeasurement snapshots: kind, name, optional description/unit/boundaries, value, copied attributes, and a carrier-shaped exemplar context or null. This is a measurement log, not aggregated counters or buckets; storage is unbounded. Measurement times are retained privately for store queries, not exposed in these snapshots.
No-op Context
UseNOOP_TELEMETRY_CONTEXT when telemetry is optional:
- invokes callbacks synchronously;
- preserves returned values and asynchronous rejections, and converts a synchronous throw to a promise rejected with the same value;
- uses one shared frozen inert span, including for nested spans;
- exposes
NOOP_TELEMETRY_METRICSandNOOP_TELEMETRY_PROPAGATIONon its root and spans; - does not inspect or retain names, attributes, events, or statuses.
In-Memory Reference Adapter
InMemoryTelemetryContext is the backend-neutral reference implementation. It is useful for tests, local diagnostics, and applications that intentionally want process-local capture without an exporter:
getSpans() returns detached snapshots in span-start order. Each RecordedTelemetrySpan contains a deterministic numeric ID, local parent ID, carrier-shaped context and parentContext snapshots, ordered links, merged attributes, ordered events, final status, settlement state, and deterministic end sequence. These normalized snapshots expose no timestamps. A remote parent has parentId: null but a non-null parentContext; a root has both null. A RecordedTelemetryLink contains a target carrier and copied attributes.
The adapter implements TelemetryPropagation with its own small carrier codec: a unique recorder scope, a deterministic numeric span ID, and an inherited trace ID. The carrier survives JSON round trips and works across independent processes without a shared registry. Its keys are an implementation detail, not a public wire format for other adapters.
The adapter is safe to use as an ordinary TelemetryContext, but storage is unbounded and process-local. Create a fresh instance to isolate tests or recording scopes, and do not capture sensitive attributes unless the caller’s data policy allows them.
Stored Telemetry
TelemetryStore separates querying from recording. InMemoryTelemetryContext implements it, and a persistent adapter can implement it too:
findTraces(query?)returns complete locally stored traces, newest trace start first. Filters include the earliest stored span’sname, inclusivestartMin/startMax,errors: true, and scalarattributes. All requested attributes must match one span, anywhere in the trace. Pages default to 20 traces; pass the returned opaquecursorwith the same filters to continue. Equal start times are ordered by trace ID.getTrace(traceId)returns a trace orundefined.findMetrics({ name, startMin?, startMax?, attributes? })returns metric rows with count, sum, minimum, and maximum. Time bounds are inclusive interval-start times. The in-memory adapter maps each raw measurement to a count-one row in its ten-second interval; SQLite aggregates measurements per series and interval.
<recorder UUID>:<counter>) and propagates with the parent identity. Stores return the spans available locally: remote or expired parents can be absent, and a child can appear before its parent settles. Pagination is not a snapshot across requests; late settlements and retention can change a trace’s earliest stored span. SQLite reads committed rows without implicitly flushing.
StoredSpan includes epoch-millisecond startedMs/endedMs, event offsets in timeMs, and links carrying both target traceId and spanId. Duration uses a monotonic clock; wall clocks across processes may disagree. Merge spans from several stores by trace ID; parent relationships, not timestamp containment, define the tree.
Rendering is a separate subpath, kept out of the root entry graph:
renderTrace() accepts stored spans, deduplicates IDs, treats absent parents as roots, and prints attributes, durations, statuses, event offsets, and cross-trace links. It never follows links or queries a store.
Adapter Conformance
@bastani/atomic-telemetry/testing exports a runner-independent conformance suite modeled as grouped cases. A fixture supplies a fresh context and converts its backend’s finished spans into normalized RecordedTelemetrySpan snapshots:
propagation to additionally check JSON round trips, multiple adapter hops, and root fallback for absent or unknown carriers. Fixtures may also supply metrics and getMetrics() to check ordered measurements, histogram exemplars, and input copying. It does not test malformed inputs or require suppression of adapter/backend failures. getSpans() may flush an asynchronous exporter before returning. The testing subpath uses Node’s assertion APIs; the root telemetry package remains runtime-neutral.
Typed Schemas
The low-level span API intentionally accepts open names and attribute bags so adapters remain generic. Domain packages can define closed, serializable schemas and infer exact TypeScript types from them.Start and Completion Attributes
startAttributes and endAttributes describe when an attribute is normally known, not separate runtime storage:
Both sets become ordinary attributes on the same backend span. There is no separate end-attribute payload or end callback. In the preceding example,
example.resource is known when example.read starts, while example.item_count is known only after readAccounts() returns:
setAttributes() zero times is valid. This matters for early failures, cancellation, and provider-specific data that may not exist on every path.
Repeated setAttributes() calls merge into the same attribute bag. A later defined value replaces an earlier value for the same key, while undefined is ignored. The schema-scoped method accepts only the current span’s declared end attributes.
Attributes do not end the span. Returning, resolving, throwing, or rejecting from the callback controls settlement; startSpan() performs the actual end operation. Adapter calls made after settlement are inert.
A starter can compose multiple independently versioned schemas, each defined with defineTelemetrySchema():
as const. Literal duplicate span names across the array are rejected at compile time; schemas are not merged, inspected, or retained at runtime.
Schema-derived types reject missing required attributes, unknown keys, invalid closed-set values, undeclared events, and attributes on empty schemas. End attributes are always optional enrichment; the type system does not require setAttributes() to be called.
defineTelemetrySchema() is a typed identity function. It returns ordinary JSON-serializable data and performs no runtime validation or parent-rule enforcement.
Schema Metadata
Supported attribute types are:string,number, andboolean;string[],number[], andboolean[].
values: a closed set for scalar values;elementValues: a closed set for array elements;examples: documentation examples;sensitive: marks data requiring special handling;cardinality: records expectedloworhighcardinality.
required. End attributes do not; see Start and Completion Attributes.
Parent metadata is descriptive schema data:
{ kind: 'any' }: root or any caller span;{ kind: 'root_or_external' }: root or a caller-owned span outside the schema;{ kind: 'spans', spans: [...] }: only the listed schema spans.
Atomic Package Integration
Package ownership is intentionally split:@bastani/atomic-telemetryowns the vendor-neutral contract, no-op and in-memory reference contexts, schema utilities, and adapter conformance suite;@bastani/atomic-aiaccepts a parentTelemetryContextthroughtelemetryContextin its request options.
Security and Portability
Telemetry is diagnostics, not durable application state. Do not persist aTelemetryContext, TelemetrySpan, or backend-native trace object in records, messages, snapshots, or deferred handles. An injected TelemetryCarrier may cross a transport or be stored as optional diagnostic correlation data. Changing adapters may lose correlation; carriers are not application state.
Attribute values are intentionally limited to primitive scalars and arrays. Domain instrumentation should avoid prompts, completions, tool arguments or output, file contents, provider payloads, headers, credentials, and free-form error details unless its schema and data policy explicitly allow them.
The package does not use AsyncLocalStorage or another runtime-specific ambient context API. It is suitable for Node.js, Bun, browsers, and workers; backend adapters remain responsible for their own runtime compatibility.