The API contracts enforced by the span, span event, and annotation implementations, shared by the C++ API (instrument.md) and the C API (instrument_c.md) — see the name mapping for the C spellings.
Most violations are detected at runtime and degrade to a logged no-op rather than a crash — but they distort traces, and the threading and lifetime rules below are hard requirements that can crash the process if broken. Treat the warning messages quoted here as instrumentation bugs when they appear in the agent log.
A Span instance — including every SpanEvent it hands out — must be used by one thread only for its entire lifetime. Nothing inside a span is locked (the event stack, string fields, annotation lists), so concurrent calls on the same span are undefined behavior and can corrupt memory or crash.
- The agent binds a span to the first thread that calls
NewSpanEvent()and logs an error (plus anassertin debug builds) when another thread touches it afterwards:span accessed from another thread.GetSpanEvent()is checked and binds the same way — it reads the same event stack. The binding-oriented overloadsRecordSpanEvent()and the three-argumentNewAsyncSpan(operation, async_id, async_sequence)are not checked: they exist for language bindings that manage span events outside this library and serialize every crossing into the span themselves, so a binding ending a shared span from another thread degrades per its own contract instead of tripping the assert. - Because binding is lazy, a complete handoff is allowed — but only before the span records anything: the owning thread is fixed by the first
NewSpanEvent()/RecordSpanEvent()call, so create the span on thread A, pass theSpanPtrto thread B before any event is created, and never touch it from A again (the thread examples in instrument.md §10 rely on this). Once the first event exists, the span belongs to that thread for good; handing it on afterwards logsspan accessed from another thread. - To trace work that runs concurrently with the parent, do not share the span. Call
NewAsyncSpan()on the span's owning thread and hand the returned child span to the worker; the child follows the same single-thread rule on its own thread.
EndSpan() and EndEvent() are terminal:
- A duplicate
EndSpan()/EndEvent()logsspan (event) is already finishedand does nothing. - After the end call, every recording method on that object becomes a warning no-op: property setters,
SetError,RecordHeader,SetSqlQuery,InjectContext, andSetAnnotation(). The data may already be in flight on the agent's gRPC worker thread, so nothing can be added afterwards. Record status codes, errors, and annotations before callingEndSpan()/EndEvent(). - A span released without
EndSpan()is never sent — its data is lost. The destructor only cleans up internal bookkeeping; it does not submit the span. RecordSpanEvent()(batch replay, for wrappers that time their events themselves) returns an open event even though the call already supplies both timestamps: annotations, SQL, errors,SetDestination(),SetEndPoint()andSetNextSpanId()are applied to the returned handle, so it must be closed withEndEvent()before the nextRecordSpanEvent()orEndSpan(). Skipping that end holds one depth slot untilEndSpan()auto-closes it (§3), which walks a long-lived span towardMaxEventDepthoverflow.
This is why RAII guards are the recommended pattern:
helper::ScopedSpanEvent for events (see
instrument.md §4), and for spans a guard
of your own:
class SpanGuard {
public:
explicit SpanGuard(pinpoint::SpanPtr span) : span_(std::move(span)) {}
~SpanGuard() { if (span_) span_->EndSpan(); }
private:
pinpoint::SpanPtr span_;
};
void handleRequest() {
auto agent = pinpoint::GlobalAgent();
auto span = agent->NewSpan("Service", "/endpoint");
SpanGuard guard(span);
// Even if an exception is thrown, the span is ended
processRequest();
}Span events form a stack. Calling EndEvent() on an outer event while an inner event is still open implicitly finishes every event nested above it and logs span event ended out of order. Likewise, EndSpan() force-finishes all still-open events and logs N span event(s) not ended by user code. The trace survives, but implicitly finished events get the wrong end time — their duration silently stretches to the enclosing end call.
Unbalanced end policy. An EndSpan() that arrives with events still on the stack is not treated as a fatal inconsistency: every open event is auto-closed at the EndSpan() timestamp, kept in the final chunk, and the span is sent as usual, with the unbalanced events' durations stretched to the span end. Treat the N span event(s) not ended by user code warning as an instrumentation bug to fix, not as a lost span. An async child span is the one legitimate case: its root event stays open until EndSpan() by design and is excluded from that count.
SpanEventPtr is a raw pointer whose object is owned by the parent span's internal data:
- It stays valid only while you hold the parent
SpanPtr. Calling into an already-ended event while the span is alive is a safe warning no-op. - Do not cache these pointers in long-lived structures. Obtain them, use them, and let them go within the span's scope. Once the last
SpanPtris released, everySpanEventPtrit handed out is dangling — including the shared disabled event of §5 and an unsampled span's event (§11), both of which have exactly the same lifetime as a real event's. - A call that does slip past the span's release is handled defensively rather than crashing when the event object itself is still alive (the agent keeps ended events alive while a chunk is in flight): it logs
span event outlived its spanand records nothing, andInjectContext()falls back to writing onlyPinpoint-Sampled: s0— no valid trace context can be built without the span, so the downstream service is told not to trace instead of continuing a broken one. This is a backstop for a contract violation, not a supported pattern: the release order is not yours to observe, so treat a danglingSpanEventPtras a use-after-free.
Per span, event nesting depth is capped by Span.MaxEventDepth (default 64) and the total event count by Span.MaxEventSequence (default 5000). Depth is 1-based, and the allowance is MaxEventDepth + 1 nesting levels — with MaxEventDepth: 3 the events at depth 1, 2, 3 and 4 are recorded and the fifth nesting level overflows. The off-by-one is deliberate: the limit is compared against the events already on the stack, so the push landing at depth maxDepth + 1 is still admitted. The sequence cap has no such offset — exactly MaxEventSequence events are recorded. When either cap is exceeded, NewSpanEvent() logs span event maximum depth/sequence exceeded and returns a shared disabled event instead:
- It records nothing — operation name, timings, SQL, error strings, exception call stacks and annotations are all discarded.
SetError()on it is the one exception: nothing about the error is recorded, but it still fails the transaction (§9) — the depth limit bounds what is recorded, not whether the transaction failed.InjectContext()still writes the full trace context, so downstream services continue the distributed trace. Overflow limits profiling detail; it is not a sampling decision.- You must still call
EndEvent()exactly once for each overflowedNewSpanEvent()call — the span balances an internal overflow counter with it. - The disabled event is a single shared object per span, so
SetDestination()values from interleaved overflowed calls can bleed into each other'sPinpoint-Hostheader. Concretely: with two nested overflowed events, the inner one'sSetDestination("db:3306")is what the outer one's laterInjectContext()writes asPinpoint-Host. It affects only that header on calls made past the depth limit — nothing is recorded at that depth either way — so if it matters, raiseSpan.MaxEventDepthrather than working around it. - Its lifetime and its post-span behavior match a real span event's exactly (§4): it is owned by the same span data, not by the span object, and after the span is gone
EndEvent()is a no-op andInjectContext()writes onlyPinpoint-Sampled: s0. NewAsyncSpan()called while the span is overflowed returns a no-op span.
If the overflow warning appears regularly, create fewer, coarser span events per transaction or raise the limits in the configuration.
GetSpanEvent() returns the top of the event stack: the most recently created event that has not ended. It never returns null — a span with no active event returns a shared no-op event and logs abnormal span - has no event; a finished span returns the same no-op event but logs span is already finished; an overflowed span returns the disabled event without logging. Do not assume it refers to a specific event you created earlier; in helper functions, prefer passing the SpanEventPtr returned by NewSpanEvent() explicitly.
- The annotation list is sealed when its owner ends (
EndEvent()/EndSpan()). A laterSetAnnotation()logs a warning and does nothing. - String views are consumed and copied during the call and do not need to outlive it. No annotation payload string is materialized for a no-op, unsampled, or already-ended span/event.
SetAnnotation()never throws; on allocation failure the annotation is dropped with an error log.- There is no key de-duplication: recording the same key twice records two annotations.
- One span's (or one event's) annotation list keeps at most 1024 entries, every internal annotation (status code, recorded headers, SQL) included. Later appends are dropped with a throttled
annotation limit (1024) reachedwarning. A span's own list is sent only with its final chunk, so a long-lived span that annotates per message should record on short-lived events instead. - Every annotation byte is copied into the span and shipped to the collector — keep annotations small and sanitized (see instrument.md §5).
The operation passed to NewSpan()/NewSpanEvent()/NewAsyncSpan()/SpanEvent::SetOperationName() and the error_name passed to SetError() are interned in bounded LRU caches, and every new unique string enqueues a metadata message to the collector. Per-request unique names churn the cache and flood the collector with metadata:
// DON'T: unique operation name per request
auto se = span->NewSpanEvent("getUser-" + user_id);
// DO: fixed operation name, variable data as an annotation
auto se = span->NewSpanEvent("getUser");
se->SetAnnotation(CUSTOM_USER_ID, user_id);The rpc_point argument of NewSpan() is not interned — it may safely carry the actual request path.
MarkError(name, message)is the verdict-only counterpart toSetError()for language bindings that detect event overflow before native event creation. It appliesSpan.IgnoreErrorsand the exception category mask to the trace root (or to an unsampled span's URL-stat failure flag) but creates no error string,exceptionInfo, exception metadata, call stack or event. Application instrumentation should normally useSetError();MarkErrorexists to preserveDisabledSpanEvent::SetErrorsemantics across a batched binding.SetError()on the span marks the whole transaction as failed.SetError()on a span event records the error on that step and also marks the transaction as failed (PSpan.err, URL stat failed histogram).PSpan.erris a mask of error causes, not a boolean: an exception sets bit2, a failing status code bit4, aSql.ErrorCountoverflow bit8, and they accumulate.Span.ErrorMark/Span.ErrorMarkExcludedecide which causes are allowed to fail the transaction (see config.md). An error on an async child span fails the trace root, not just that child: only the root'sPSpancarrieserron the wire, so the flag is shared down the whole async chain. The one case it cannot reach is a child that ends after the root already sent its final chunk — thePSpanis serialized once, at root end. There is no way to record a step error without failing the transaction; use an annotation for informational failures.- Every path into
SetError()on a span fails the transaction, including the ones that record nothing else: an overflowed span event (§5) marks the trace root without keeping the error, and an unsampled span (§11) marks its URL stat entry as failed. The paths that record nothing at all areSetError()on an unsampled span's event, which is dropped, matching Java's no-opDisableSpanEventRecorder.recordException, and any error on an unsampled span's async child (§11). Record a step failure you need reflected in the URL statistics on the span itself. Span.IgnoreErrorsis applied on all of them, so an excluded error never fails a transaction regardless of which path recorded it.- The call-stack overload
SetError(name, message, CallStackReader&)exists only onSpanEvent, and records frames only whenEnableCallstackTrace: trueis set in the configuration (defaultfalse). - The error message is abbreviated to 256 bytes: a longer message is cut at the last whole UTF-8 character within 256 bytes and gains a
...(<original length>)suffix. Put anything longer (a full SQL statement, a response body) in its own annotation, not in the error message. - At most 100 exceptions with call stacks are buffered per span; further ones are dropped, counted, and reported once at
EndSpan()(a throttled warning naming the operation and the number of dropped entries). The buffer does not shrink beforeEndSpan(), so once it is full every later exception on the span is dropped. Buffered exceptions are transmitted only atEndSpan()— a span kept open for a very long time delays them and grows memory. There is no per-chain depth cap: every chain is one entry, so the span cap is the only bound. - Every call-stack
SetError()is its own exception chain of one entry. Each call buffers one exception with a freshexceptionIdatPException.exceptionDepth0 and stampsANNOTATION_EXCEPTION_IDon the event that recorded it. Telling a cause from an unrelated exception would need throwable identity, which this agent has none of, so it neither joins calls into one chain nor numbers them — two entries under one id at the same depth would leave the collector no way to order them. The cost: the same exception recorded on a nested event and again on the event that catches it is two chains, each asking theCallstackTraceNewThroughputlimiter. A call stack the limiter refused is a plain error (exceptionInfo, failed transaction) without its frames; the next call asks again. - On the wire,
PException.exceptionClassNameis thenameargument ofSetError(name, message, ...); only a call stack recorded without a name falls back to the top frame's module.PException.startTimeis the span event's start time (including one overridden withSetStartTime()), not the moment the frames were collected.
Elapsed times travel as int32 milliseconds on the wire. If you override timestamps with SetStartTime():
- Only pass values derived from
std::chrono::system_clock::now()taken at the actual start of the operation. - A start time more than ~24.8 days in the past overflows the elapsed field; a start time in the future is clamped to an elapsed of 0 at end time, but inter-event offsets within a chunk can still wrap.
- A fabricated
time_point(e.g. built from epoch seconds interpreted as milliseconds) produces wrapped, meaningless timings.
The C API's start_time_ms arguments take milliseconds since the Unix epoch. Passing seconds (e.g. time(NULL)) is not validated: the computed deltas overflow int32 and silently corrupt the trace timeline.
NewSpan() never returns null. When the agent is disabled, not started or not yet registered with the collector (registration is retried indefinitely and tracing stays off — with no statistics collected either — until it succeeds; see Verifying Agent Startup), the URL/method is excluded by filters, or sampling rejects the transaction, you receive a no-op or unsampled span on which every call succeeds and records nothing:
IsSampled()returnsfalse,GetTraceId()returns an empty string, andGetSpanId()returns 0 for no-op spans and for the async children of unsampled spans (an unsampled span itself does carry a real span id).- An unsampled span is never sent, but it still feeds the response-time and URL statistics.
SetError()on the span marks that URL stat entry as failed; nothing else about the error is kept.SetError()on its span event records nothing at all, as Java'sDisableSpanEventRecorderand the Go agent's unsampled event do — a step failure that should show in the URL statistics has to be recorded on the span. - The injected header set is conditional.
InjectContext()writes a header only when it has a value, so aTraceContextWritermust tolerate any subset.Pinpoint-pServiceNameappears only foruid.version=v4,Pinpoint-Hostonly when the event has a destination,Pinpoint-pAppNamespaceonly whenClusterNamespaceis set (never empty — an empty one makes a receiver that has a cluster namespace configured restart the trace instead of continuing it), and a dead-span or unsampled event writes onlyPinpoint-Sampled: s0. - Use
IsSampled()to skip expensive data collection only — do not skip creating span events and callingInjectContext()on outbound calls. An unsampled span's event still writesPinpoint-Sampled: s0, which tells downstream services not to trace the request. Skipping the injection makes downstream agents treat the call as a brand-new transaction and sample it, producing broken partial traces. NewAsyncSpan()on an unsampled span returns an unsampled async child, not the no-op span, from both overloads. Its events writePinpoint-Sampled: s0like the parent's, and so do the events of its own async children, so a call made from background work is not traced downstream either. The same holds for the eventRecordSpanEvent()returns on an unsampled span. The child is not a transaction: it does not count as an active request, records no URL statistics or response time, and an error set on it is dropped. It does not fail the parent's URL stat entry, which the parent has usually sent at its ownEndSpan()by then (a sampled async child's error fails the trace root instead, §9). The child is stateless and shared, one instance process-wide like the no-op span: it holds nothing of the parent, reports span id 0, and so may outlive the parent and be used and ended on another thread. ItsEndSpan()is a cheap no-op and safe to repeat.- A no-op span's async child is the no-op span again, and its events write nothing. That is correct for a disabled agent or an excluded URL: a proxy then passes the inbound Pinpoint headers on untouched instead of overriding them.
NewSpan() continues an inbound distributed trace only when all three of
these are true:
Pinpoint-TraceIDis present and parses asagentId^startTime^sequence.Pinpoint-SpanIDis present.Pinpoint-pSpanIDis present.
Anything else — a missing or blank trace id, a trace id that does not parse,
or either id header absent — starts a new transaction: a locally generated
trace id, a generated span id, no parent span id, and the new-trace sampler
(plus Sampling.NewThroughput) deciding it. Nothing is dropped and nothing is
guessed; the request simply becomes the root of its own trace.
With ClusterNamespace set, a fourth condition applies, as in the Java agent:
a Pinpoint-pAppNamespace that is present and differs from it (an empty one
included) also starts a new transaction. An absent one does not.
Only the presence of the two id headers is checked, not their contents: a
present-but-unparseable Pinpoint-SpanID still describes a hop, so the trace
is continued and only that one id is regenerated (a warning is logged,
throttled). A missing header is a different thing — a hop that was never
described at all.
Two consequences for a TraceContextReader implementation:
- A carrier that forwards only
Pinpoint-TraceIDbreaks the trace. Some proxies, gateways and hand-written clients strip the rest. Such a request is recorded as its own transaction, so the call appears as two traces in the UI rather than one — nothing is lost, but the link is.InjectContext()always writes all three, so an all-Pinpoint call chain is unaffected. Pinpoint-Sampled: s0is checked before any of this and short-circuits everything (unsampled span, no sampler consulted).Pinpoint-Flagstakes part in no decision and defaults to0when absent.
NewSpan(operation, rpc_point, method, const std::map<std::string, std::string>&)
wraps the map in the agent's own TraceContextReader, and that adapter keeps
the contract tracer.h places on HTTP-backed readers:
- Keys are matched case-insensitively. The canonical names
(
Pinpoint-TraceID,HEADER_TRACE_ID, ...) are the fast path — an exact map lookup. Any other spelling, including the all-lowercase form HTTP/2 and HTTP/3 deliver (pinpoint-traceid), falls back to a linear scan of the map compared case-insensitively. A binding layer may therefore dump the request headers as received; it does not have to re-case them. - Values are taken verbatim. Only the key comparison ignores case.
- A non-empty map with no trace id under any spelling starts a fresh
transaction exactly as an empty map does, and additionally logs a throttled
warning,
Pinpoint headers present but unrecognized, so a binding bug that turns every request into its own trace is visible in the agent log. - The three-header rule above applies unchanged; case-insensitive matching changes how a header is found, not which headers are required.
Not a span rule, but a lifetime rule of the same kind, about the agent itself:
what the host log sink (AgentOptions::log_sink,
pt_agent_options_set_log_sink()) may do, and when it may be torn down.
The full callback contract is on pinpoint::LogSink in tracer.h and on
pt_log_sink_fn in tracer_c.h.
- The sink must not start, stop or reload the agent. Never call
StartAgent(),Shutdown()(including by destroying aScopedAgent) orReloadAgentConfig()from it, norpt_start_agent(),pt_agent_shutdown()orpt_reload_agent_config(). The agent can call the sink while it holds a lock those calls need, or while a shutdown or replacement waits for that very sink call to return, so such a call can deadlock or stall shutdown until its deadline. To restart or stop the agent in reaction to a log line, hand the work to another thread. Other API calls from the sink are safe; a line the agent would log from inside the sink is dropped. - Once
Shutdown()returns, no call into the sink is in flight on any thread, so the host may free the sink's state. That holds for everyShutdown()of the agent, not only the one that runs the teardown: a second call — from a host thread, whileStartAgent()is replacing the same agent, say — returns only once the first call's teardown has released the sink. In the C API the same holds forpt_agent_shutdown(), including through a handle that already acts as the disabled agent because its agent was shut down or replaced. A failedStartAgent()/pt_start_agent()releases the sink it installed before it returns. - A restart logs like a first start. The lines a new
StartAgent()writes before it applies its own log settings — a typo in the new config, the notice that it replaces a failed agent — go to the previousLog.FilePathwhen one was configured, and to stdout otherwise, rather than being dropped because the previous agent's shutdown closed the log.