Skip to content

Observability

A failure event says what failed. For logs and traces it also needs to say where: which system, which operation, which run. dataexcept keeps those two apart, as the Python package does. The envelope describes the failure, and an operation context describes where it happened. The two are joined in a failure event, and projected onto OpenTelemetry spans.

Operation context

context <- operation_context(
  system = "batch",
  component = "billing",
  operation = "settle_invoices",
  job_id = "job-42",
  correlation_id = "corr-9"
)

The fields fall into two groups:

Fields What they are Use them for
system, component, operation Low-cardinality labels: a route template such as "POST /users/{id}", a job name, a workflow step Filtering and grouping
request_id, job_id, correlation_id, trace_id, span_id Identifiers of one run Finding one specific execution; never as metric dimensions or indexed tags

operation_index_fields(context) returns only the labels. Every field is optional: a missing identifier stays missing rather than being invented. URLs in any field lose their credentials and their path. The fields and rules are those of the Python package's OperationContext.

Failure events

condition_to_event() pairs a condition's envelope with its operation context:

err <- tryCatch(
  stop(missing_column_error("customer_id", dataframe = "orders")),
  error = identity
)
cat(condition_to_event_json(err, operation_context = context, pretty = TRUE))
{
  "event": "exception",
  "exception": {
    "type": "MissingColumnError",
    "module": "dataexcept",
    "message": "Missing required column 'customer_id' in data frame 'orders'",
    "failure": {
      "kind": "unknown",
      "retryable": null,
      "retry_after_seconds": null
    },
    "attributes": {
      "column": "customer_id",
      "dataframe": "orders"
    }
  },
  "operation": {
    "system": "batch",
    "component": "billing",
    "operation": "settle_invoices",
    "job_id": "job-42",
    "correlation_id": "corr-9"
  }
}

The envelope is exactly what condition_to_json() writes. The context stays under its own key rather than being flattened into the failure, so a log pipeline can index the labels and keep the identifiers for correlation. With no context there is no operation key.

This is the event format of the Python package's exception_to_observability_event(). The test suite checks the two agree on events generated by the Python package.

Logging a job's failures

condition_to_event_json() writes an event as one line of JSON, which is what most log collectors expect:

run_job <- function(context) {
  withCallingHandlers(
    settle_invoices(),
    dataexcept_error = function(e) {
      cat(condition_to_event_json(e, operation_context = context), "\n",
        file = stderr(), sep = ""
      )
    }
  )
}

A calling handler logs the failure and lets it carry on, so the job still fails as it would have.

OpenTelemetry

dataexcept works with the r-lib otel package, which it suggests but does not require.

Recording a failure on a span

settle_invoices <- function() {
  otel::start_local_active_span("settle_invoices")
  tryCatch(
    charge_customers(),
    dataexcept_error = function(e) {
      record_otel_exception(e, operation_context = context)
      stop(e)
    }
  )
}

With no span argument, record_otel_exception() records on otel's active span, and sets the span's status to "error". It is fail-open, because it runs while a failure is being handled. If otel is not installed, tracing is off, or recording fails, it returns FALSE and the failure carries on unchanged.

When the handler recovers and the operation goes on to succeed, record the failure without failing the span:

tryCatch(
  fetch_rates(),
  dataexcept_error = function(e) {
    record_otel_exception(e, set_status = FALSE)
    cached_rates()
  }
)

The exception event carries these attributes, named as in the Python package:

Attribute Value
exception.type The envelope's module and type: dataexcept.MissingColumnError, base.simpleError, or for a failure read from a Python envelope, the Python class's qualified name
exception.message The envelope's message, redacted
exception.stacktrace The rlang backtrace if the condition has one, otherwise its call; redacted. Absent when there is neither
dataexcept.failure.kind, .retryable, .retry_after_seconds The failure metadata, flat and typed, present only for the values the failure record carries
dataexcept.operation.* The context's labels and run identifiers. trace_id and span_id are left out: the span already carries them
dataexcept.envelope, dataexcept.envelope.schema With include_envelope = TRUE: the whole envelope as compact JSON, and its schema id

condition_to_otel_attributes() returns the same attributes without recording them, and it is strict: invalid input is an error.

Keeping credentials out of traces

The otel SDK builds an exception event's message by printing the condition, and its stack trace from the condition's call, with no redaction. An error with a credential-bearing URL in its message or call puts the credential in the trace:

err <- simpleError(
  "GET https://user:pw@api.example.com/private failed",
  call = quote(download("https://user:pw@api.example.com/private"))
)

span$record_exception(err)          # exception.message contains user:pw
record_otel_exception(err, span)    # https://***:***@api.example.com/*** instead

record_otel_exception() passes redacted exception.message, exception.type and exception.stacktrace attributes, which the SDK uses in place of its own.

The same applies to errors that escape a span. When an error escapes a span that otel ends automatically (one from otel::start_local_active_span(), otel::with_active_span() or otel::local_active_span()), the SDK records it itself, unredacted, unless the span's status has already been set. Because record_otel_exception() sets the status, the pattern in Recording a failure on a span records the failure once, redacted, even though the error then escapes. The test suite checks this against the real SDK.

Unhandled errors are still the SDK's

An error that escapes a span without passing through record_otel_exception() is recorded by the SDK as it is. Handle the failures that can carry credentials, such as those from HTTP and database calls, inside the span, and keep credentials out of messages you write yourself.

Correlating logs with traces

operation_context_from_otel() fills a context's trace_id and span_id from the active span, so the failure events written to logs carry the trace's identifiers:

otel::start_local_active_span("settle_invoices")
context <- operation_context_from_otel(
  operation_context(system = "batch", operation = "settle_invoices")
)

With tracing off or no valid active span, the context comes back unchanged. An identifier the context already has must agree with the span's: a conflict is an error, because silently replacing provenance is worse than omitting it.

Design rules

These are the Python package's rules, kept in R:

  1. No fake provenance. Missing identifiers stay missing.
  2. Low-cardinality operations. Route templates, job names and workflow steps identify the operation; payloads and run identifiers do not.
  3. Redaction stays central. Events and span attributes come from the same redacted envelope as everything else.
  4. Correlation is separate from indexing. Run identifiers stay available without becoming labels.
  5. Emission is fail-open, conversion is strict. record_otel_exception() never replaces the failure being handled; condition_to_event() and condition_to_otel_attributes() report mistakes as errors.

One difference from Python is deliberate: record_otel_exception() sets the span's status, which the Python helper leaves alone. The R SDK records any error that escapes an automatically ended span unless the status is set, so setting it is what keeps a recorded failure from being recorded a second time, unredacted.