libo11y 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +170 -21
  3. data/README.md +77 -8
  4. data/lib/libo11y/{proc.rb → child_process.rb} +12 -2
  5. data/lib/libo11y/db.rb +22 -10
  6. data/lib/libo11y/detached.rb +241 -29
  7. data/lib/libo11y/http_client.rb +48 -15
  8. data/lib/libo11y/internal/bridges.rb +3553 -255
  9. data/lib/libo11y/internal/endpoint.rb +7 -1
  10. data/lib/libo11y/internal/env.rb +177 -59
  11. data/lib/libo11y/internal/error_type.rb +17 -0
  12. data/lib/libo11y/internal/histogram_buckets.rb +42 -0
  13. data/lib/libo11y/internal/http_common.rb +2 -0
  14. data/lib/libo11y/internal/identity.rb +10 -1
  15. data/lib/libo11y/internal/injected.rb +178 -0
  16. data/lib/libo11y/internal/logging_device.rb +141 -32
  17. data/lib/libo11y/internal/path_match.rb +148 -0
  18. data/lib/libo11y/internal/pii.rb +185 -65
  19. data/lib/libo11y/internal/pipeline.rb +141 -34
  20. data/lib/libo11y/internal/policy.rb +556 -52
  21. data/lib/libo11y/internal/propagators.rb +29 -6
  22. data/lib/libo11y/internal/quiet_inspect.rb +20 -0
  23. data/lib/libo11y/internal/resource.rb +187 -52
  24. data/lib/libo11y/internal/sdk_load.rb +64 -0
  25. data/lib/libo11y/internal/sql_text.rb +365 -67
  26. data/lib/libo11y/internal/summary.rb +2 -1
  27. data/lib/libo11y/options.rb +159 -1
  28. data/lib/libo11y/rack.rb +257 -44
  29. data/lib/libo11y/record.rb +70 -7
  30. data/lib/libo11y/redact.rb +87 -21
  31. data/lib/libo11y/signals.rb +70 -29
  32. data/lib/libo11y/spec/app_registry.rb +97 -61
  33. data/lib/libo11y/spec/yaml_v3.rb +179 -111
  34. data/lib/libo11y/telemetry.rb +315 -53
  35. data/lib/libo11y/testing.rb +31 -19
  36. data/lib/libo11y/version.rb +1 -1
  37. data/lib/libo11y.rb +1 -1
  38. metadata +94 -39
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9629b204a896f322453a963ce455749449dfba5b234a3af67cc5742e86e1be5a
4
- data.tar.gz: 837b04f3203878ce5128a40db7ac7bedc1e129a4764c128b235e379f7d32daca
3
+ metadata.gz: 79b1ed792c8b5c203dbae16c6dec730c7b8b072d17ee149bbed5e8e59fc0bc2c
4
+ data.tar.gz: 07e3d84f9b6c53a0686ed56cb197351230d4d9b8b7eb7f97df9f36cd891e83ce
5
5
  SHA512:
6
- metadata.gz: 55fe7e3c7a4fed853d04aa645bd061bb372e925dfc948254bc74c3b702a9bd585ab7b0711b76edbc2c67c63f859a820b1e93283bc1418798e86acf6a248b7a5b
7
- data.tar.gz: 6c6bb641fb3b9a715bdc767e057faba067f5762cc1e733593fe64956a146b58ea15c9418b3051e4be85be1482226fbe802c9c1b024746b041d4aaa5b9eecbeae
6
+ metadata.gz: 0033443414f08ee64440ec39d41e152e849f82e510c9034c2f7b0b85335a5d92420de6d5912ebdd6bd78b59aff0e484760217183c2ac353a010c4331e78f489a
7
+ data.tar.gz: 245cffea96c707fcf4174e2fb149fc98d1d0cd5adad2bf9db65aaebf28fa5de05b2a6fa17eef6312660fbb12ca59749f15bcec07b02e71bb5c6351a49bc08d19
data/CHANGELOG.md CHANGED
@@ -7,6 +7,171 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.3.0] - 2026-11-29
11
+
12
+ This release ships the Ruby council hardening fixes from Rounds 2 through 30, including breaking renames (`Libo11y::Proc` -> `Libo11y::ChildProcess`, removal of `sdk_provider`) and strict sensitivity, encoding, ownership, and shutdown guarantees across all three OTLP signals.
13
+
14
+ ### Changed
15
+
16
+ - `Telemetry#tracer` takes `version:` and `attributes:` as keywords, as `Telemetry#meter` does and as the OpenTelemetry API now asks, and `#meter` takes `attributes:` too. The version as a second positional argument still works. 0.2.0 took keywords given to `tracer` for the version.
17
+ - A span processor or a log record processor added to the handle's providers after the shutdown is refused with a warning, as the SDK's providers refuse it. It used to join a group that was already shut down, without a word.
18
+ - `Telemetry#shutdown(timeout:)` holds to its deadline in every case. A caller that waits on a shutdown another thread started gets a report at its own deadline, with the error "shutdown is still in progress". Writing the `o11y.telemetry.dropped` events is bounded too, so a console or extra sink that blocks no longer holds shutdown open.
19
+ - `Libo11y.shutdown_on_signals` gives `before_shutdown` and the shutdown one shared deadline. A callback that outlives it is left behind, and a callback that raises still gets the shutdown, then its error.
20
+ - An OTLP endpoint that is not an absolute `http` or `https` URL with a host fails `setup` and `init` with `Libo11y::ExporterError`. The message names the variable and never the value. 0.2.0 let `URI::InvalidURIError` or an exporter's own error through.
21
+ - `Testing::Recorder` raises `ArgumentError` for `env`, `span_exporter`, `metric_reader`, `log_exporter` and `console_writer`, which it sets itself. 0.2.0 accepted them, and the recorder then read sinks that held nothing.
22
+ - `Rack::Middleware` matches `ignore_paths` as Go's `path.Match` does: `*` and `?` stop at a slash, `**` has no recursive meaning, and a malformed pattern matches nothing. 0.2.0 used `File.fnmatch`, whose `**` and escapes differ.
23
+ - `DB::Client` records no `db.query.text` for a statement it cannot read with certainty, as `go/o11ysql` now does: a backslash before a quote in a plain PostgreSQL or MySQL string, whose end depends on `standard_conforming_strings`, `NO_BACKSLASH_ESCAPES` or `ANSI_QUOTES`, and a MySQL or MariaDB versioned comment. 0.2.0 chose one reading, and under the other a part of a value stayed in the text. The operation and table are still recorded. A list of tables with aliases names no single table, and SQLite's `[name]` is read as a table name.
24
+ - `OTEL_RUBY_EXPORTER_OTLP_SSL_VERIFY_NONE` turns certificate verification off only when it is `true`. In 0.2.0 any value turned it off, `false` included, as in the upstream trace and metric exporters.
25
+ - A shutdown writes the `o11y.telemetry.dropped` events inside its deadline. The providers get the time less a reserve of at most 100 ms, as in Go. 0.2.0 could run 50 ms past the deadline.
26
+ - `Rack::Middleware` with `public_endpoint: true` keeps the caller's baggage beside the new trace and the link, as the Go and Python middleware do. 0.2.0 dropped the whole inbound context.
27
+ - An invalid `pii_mode` and a `pii_hash_key` that is not a String raise `ArgumentError`, as other bad options do. 0.2.0 raised `Libo11y::Error` for the first and `NoMethodError` for the second.
28
+ - A client certificate or key file that cannot be read or parsed fails `setup` and `init` with `Libo11y::ExporterError` that names the signal. 0.2.0 let `Errno::ENOENT` or an OpenSSL error through.
29
+ - `Libo11y.shutdown_on_signals` raises `ArgumentError` for an empty list of signals, which it used to wait on for ever, and reads `timeout:` as `Telemetry#shutdown` does.
30
+ - `Testing::Recorder#assert_correlated!` and `#assert_triangle!` no longer ask for a console record from a recorder built with `console_enabled: false`.
31
+ - `Rack::Middleware` ends the span, the duration and the canonical line when the server closes the response body, for a body that is not an Array. The time a streamed body takes counts, and an error it raises is recorded with `error.type`. 0.2.0 ended them when the application returned, before a streamed body was produced. An Array body is complete at that point and ends the request there, as before.
32
+ - An `OTEL_TRACES_SAMPLER` that names no sampler, an `OTEL_TRACES_SAMPLER_ARG` that is not a ratio from 0 to 1 and an `OTEL_METRICS_EXEMPLAR_FILTER` that names no filter give the default with a warning, as in Go and Python. 0.2.0 failed the start with `ExporterError`. The summary reports the sampler that runs.
33
+ - `nil` for an option means the option's default. In 0.2.0 `strict_identity: nil` turned the identity check off.
34
+ - `Testing::Recorder#metrics` returns the current collection, each metric once. 0.2.0 returned every collection made so far, so a look at the metrics could hide a later violation from `assert_conforms!`. `Recorder#exemplars` still returns the exemplars of every collection.
35
+ - The fiber-local keys (`FORCE_EMIT_FIBER_KEY`, `REENTRY_FIBER_KEY`, `RECORD_FIBER_KEY`, `Rack::ROUTE_FIBER_KEY`) are private constants.
36
+ - The derived `service.instance.id` is one random UUID for every handle of a process, as the specification says and as Go now does. A forked child draws its own. 0.2.0 drew one for each handle.
37
+ - `error.type` on `o11y.telemetry.dropped` names the error that failed the signal, as in Go: `Timeout::Error` for a signal or an export that ran out of time, the class of an error an exporter or a processor raised, and `Libo11y::ExporterError` for an export the collector refused. The error in the `ShutdownReport` is still a `Libo11y::ExporterError`, with the other error as its `cause`.
38
+ - `Libo11y::Proc` is now `Libo11y::ChildProcess`, in `libo11y/child_process`. Inside the `Libo11y` namespace the old name hid Ruby's own `Proc`.
39
+ - `Logger::UNKNOWN` is written as severity 21 with the text `ANY`. 0.2.0 wrote it as `INFO`, below a warning, although Ruby ranks it above `FATAL`.
40
+ - An entry of the `views` option must name an `:aggregation`, and raises `ArgumentError` without one. The OpenTelemetry Ruby SDK records nothing through a view that names none and writes an empty stream for it.
41
+ - Injected parts that no provider takes are shut down by the handle, once, concurrently under one deadline: under `OTEL_SDK_DISABLED=true`, where 0.2.0 never shut them down, and after a start that fails before a provider is built around them. Sharing one injected exporter, processor, or reader across different signals, passing the same object as both exporter and processor for a signal, or injecting or adding a metric reader registered on an active meter provider as a span or log part all raise `ArgumentError`.
42
+ - A span opened before `Telemetry#shutdown` and finished after shutdown no longer reaches injected span processors or exporters.
43
+ - Under `strict_identity: false`, an explicit non-String `service.name` in `resource_attributes` (such as `42`) is preserved rather than rewritten to `"unknown_service"`, matching Go.
44
+ - `HttpClient` sends a method given as a String as it is written, since a method token is case-sensitive, and a Symbol in upper case. 0.2.0 upper-cased both.
45
+ - `HttpClient` never sends a `traceparent`, `tracestate` or `baggage` header the caller passed as it came. To a destination `propagate_fn` refuses none is sent, and to any other only what the propagator writes, which for baggage is what the egress filter lets out.
46
+ - A record on the OpenTelemetry log API takes its trace and span ids from the context, as the specification reserves them. 0.2.0 exported ids a caller passed to `on_emit`.
47
+ - `Telemetry#logger` writes what `<<` is given, as a record at INFO. 0.2.0 discarded it, so `Rack::CommonLogger` logged nothing through it.
48
+ - Under `OTEL_SDK_DISABLED=true` a metric reader or a log processor added to the handle's providers after the start is not registered.
49
+ - `add_view` on the handle's meter provider raises `ArgumentError` for a view without one of the SDK's aggregations, as the `views` option does.
50
+ - The gemspec holds the OTLP exporters (including `opentelemetry-exporter-otlp-common` 0.4), the metrics SDK and the logs SDK to the minor versions the suite runs against (`opentelemetry-metrics-sdk` 0.22, `opentelemetry-exporter-otlp` 0.37 and so on). libo11y uses parts of those 0.x gems that they call internal, so a newer minor version needs a libo11y release. 0.2.0 allowed any later 0.x.
51
+ - `add_view` on the handle's meter provider raises `ArgumentError` for a view that selects a histogram libo11y has registered a view for. The SDK cannot take a view back and would write the histogram as two streams. Give such a view in the `views` option.
52
+ - `Detached::Carrier.new` enforces the 32 KiB encoded carrier size limit and raises `Libo11y::InvalidCarrier` when exceeded, matching `Detached.capture` and `Detached::Carrier.unmarshal_text`. `Detached::Carrier.unmarshal_text` and `Detached.restore_baggage` align with Go's W3C baggage parsing: valid headers within the 64-member and 8192-byte limits keep their serialized text verbatim, while invalid or oversized headers drop bad or excess members identically on direct restore and text round-trip.
53
+ - `inspect` and `pp` on the handle's logger, its providers, a meter, an instrument, the HTTP client, the DB client and the Rack middleware show the class only. Ruby's own `inspect` followed their instance variables to the OTLP exporters and printed their headers. `Options#inspect` shows a Hash, an Array and any other object by its size or class, so an `env` with OTLP headers is not printed.
54
+ - `sdk_provider` on the handle's meter provider is gone. It handed out the SDK's own provider, whose meters are not classified.
55
+ - `url.path` on a Rack request's span and summary is the decoded path, as Go and Python record it and as `ignore_paths` already matched it. 0.2.0 recorded the percent-encoded `PATH_INFO`.
56
+ - Two views that may select one instrument raise `ArgumentError` when either has `attribute_keys`, from the `views` option and from `add_view`. The SDK adds a view's attributes to the measurement itself, so the second view's stream got the first one's labels.
57
+ - An injected log processor owns the log export path, as an injected span processor owns the trace export path. With `log_processors` set, no OTLP log exporter is built from the environment, and the summary reports `o11y.config.logs=injected`.
58
+ - A view in the `views` option that names one of libo11y's duration histograms replaces the built-in view. 0.2.0 kept both, so the histogram was written as two streams.
59
+ - `shutdown_timeout` must be a finite number of seconds above 0, and `exemplar_filter` one of the three filters. Both raise `ArgumentError` at `setup` and `init`. A `timeout:` that is infinite or not a number raises `ArgumentError` from `shutdown` and `force_flush`.
60
+ - `Testing::Recorder#assert_conforms!` also fails for a secret key of an application registry that reached a sink in the clear. 0.2.0 looked for the specification's secret keys only.
61
+ - Adding an already-stopped `PeriodicMetricReader` to a handle's meter provider raises `ArgumentError` instead of registering a reader whose background export loop is dead.
62
+ - `DB::Client` SQL query summarization treats form feed (`\f`) as whitespace and compares qualified table names by their unquoted identifier component boundaries, accepting optional SQL whitespace around `.`.
63
+
64
+ ### Fixed
65
+
66
+ - `url.path` is valid UTF-8 for a path that does not percent-decode when the server gives it as binary, which Rack servers do. The bytes that are not UTF-8 were kept, and one such value fails a whole OTLP export.
67
+ - A blank `service.version` in `OTEL_RESOURCE_ATTRIBUTES` or `resource_attributes` no longer keeps the build info from giving the version.
68
+ - A global `setup` that fails while it lists the injected parts frees the global claim.
69
+ - `Telemetry#inspect`, `Options#inspect` and the sensitivity policy's `inspect` printed the `pii_hash_key`. They now print the effective-config line, the options with the key filtered, and the PII mode.
70
+ - An injected span processor could read the unredacted span: 0.2.0 handed it a view that kept the SDK span reachable. It now gets a finished span that holds the classified data only. With several injected processors each violation is counted once, where 0.2.0 counted it once per processor.
71
+ - A meter taken from `OpenTelemetry.meter_provider` before `Libo11y.setup` raised `ArgumentError` on its first instrument after setup, because the wrapped meter did not take the options the OpenTelemetry API passes on. A `setup` that fails while it installs the globals now puts back the ones it had replaced.
72
+ - `HttpClient` recorded `http.client.request.duration` after the client span had left the context, so the measurement's exemplar named the caller's span. It is recorded inside the client span.
73
+ - `Telemetry#logger` did not answer `Logger#log`, which Ruby defines as an alias of `add`, so `logger.log(Logger::INFO, "x")` wrote to the base logger's nil device and nothing reached a sink.
74
+ - A log attribute holding a list of hashes or lists with a `NaN` or infinite float raised inside the logger on its way to OTLP, and the record was lost. Such a float is written as `"NaN"`, `"+Inf"` or `"-Inf"`, as it already was on the console.
75
+ - The registry YAML reader read a quoted scalar that follows a tag or an anchor, such as `!!str "a\x41"`, as a plain scalar, so an escape `yaml.v3` rejects was accepted.
76
+ - `Rack::Middleware` added `Server-Timing` to any response whose content type began with `text/html`, such as `text/html5`. The media type must be `text/html`.
77
+ - The `CHANGELOG.md` in the 0.2.0 gem repeated the 0.1.0 section inside the 0.2.0 one, which also cut the 0.2.0 release notes short. The file is repaired, and the release check refuses a changelog with a version heading twice.
78
+ - An attribute replacer could remove or rename the `event.name` of an event, the startup summary and the dropped-telemetry events included. The name is written after the replacer has run, as in Go.
79
+ - The logging methods of `Telemetry#logger` and `Telemetry#event` return `true`, as `Logger` does. 0.2.0 returned the list of extra sinks. `unknown` takes attributes as the other level methods do.
80
+ - `OTEL_TRACES_SAMPLER=traceidratio` and `parentbased_traceidratio` with no `OTEL_TRACES_SAMPLER_ARG` sample everything, as the OpenTelemetry SDKs do. 0.2.0 failed the start.
81
+ - `Detached::Carrier` reads baggage as Go does: of the members that share a key the last is kept, a value over 8192 bytes is dropped whole, members past the 64th are dropped, and a member with a malformed property or percent escape is dropped. 0.2.0 kept the first of a repeated key and had no limits.
82
+ - `Libo11y.shutdown_on_signals` puts back the handlers it had replaced when a later signal name is refused.
83
+ - A start that is interrupted by an `Interrupt` or another non-`StandardError` stops the providers it built and frees the global claim. 0.2.0 left `Libo11y.setup` refusing every later call.
84
+ - A resource attribute that is a list of numbers or booleans keeps its type. 0.2.0 turned every list into strings. `build_info` takes a `Pathname`, ignores a file that holds no JSON object, and ignores blank values.
85
+ - `require "libo11y/options"` works by itself.
86
+ - The error for a malformed OTLP endpoint kept the URL parser's error as its cause, and that error's message quotes the value. The error has no cause now.
87
+ - The general OTLP endpoint gets a signal's path after its own path when it has a query, and a signal's own endpoint with no path is sent to `/`.
88
+ - A setup that fails before the providers are installed leaves a tracer, meter or logger taken from OpenTelemetry's global proxies free for the setup that succeeds. The propagator is installed first, since a proxy binds to the first provider for good.
89
+ - `Libo11y.shutdown_on_signals` refuses a timeout that is infinite or not above 0 before it waits, installs one handler for a signal named twice, and gives a shutdown no fresh time when `before_shutdown` has used the deadline.
90
+ - The registry YAML reader checks the escapes of a quoted scalar whose tag or anchor follows a flow indicator, as in `[!!str "a\/b"]`.
91
+ - An event with more attributes than the limit kept its `event.name` on the console and lost it on OTLP. It is the last attribute the SDK would drop now.
92
+ - `Telemetry#logger` writes the `progname` when a call gives no message, as `Logger` does.
93
+ - `build_info` writes `o11y.build.modified` as a boolean, and not at all for a blank or other value.
94
+ - `pp` printed the fields of a Struct that includes `Redact::Fields` in the clear, because `pp` prints a Struct member by member and does not call `inspect`. `Redact::Fields`, `Redact::Secret` and `Redact::Masked` define `pretty_print`.
95
+ - A log attribute holding a list of several kinds, or a list with a `nil`, was refused by the OpenTelemetry SDK, which then stopped checking the record's remaining attributes. Such a list is written as strings.
96
+ - An attribute group that flattens to `event.name`, such as `"event" => { "name" => ... }`, replaced an event's name on OTLP.
97
+ - A block scalar whose header follows a tag or an anchor, as in `brief: !!str |`, was read as quoted text, so its content could be refused for an escape.
98
+ - `Detached::Carrier` trims only a space or a tab around a baggage member, so a member with a newline is dropped, and refuses a bad escape in a repeated field.
99
+ - `OTEL_BSP_MAX_QUEUE_SIZE` or `OTEL_BLRP_MAX_QUEUE_SIZE` below the batch size failed the start with a bare `ArgumentError`. The batch size is capped at the queue size. An export timeout that is not finite is ignored.
100
+ - An injected span processor's `on_finishing` was never called. It is forwarded with the live span, as `on_start` is.
101
+ - A view whose name is a pattern, such as `http.server.*`, replaces the built-in view of a duration histogram it matches.
102
+ - `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION` is read from the `env` given and no longer from the process environment under `HERMETIC` or an explicit `env`.
103
+ - `Libo11y.shutdown_on_signals` takes one signal name as well as a list.
104
+ - A view's `attribute_keys`, which the SDK adds to every measurement after the meter has classified it, could put a secret or PII key on a data point. They are classified, from the `views` option and from `add_view` on the handle's meter provider.
105
+ - A view replaces the built-in view of a duration histogram only when it selects that histogram by the SDK's own rules: name, kind, unit, and the meter's name and version. A view scoped to another meter no longer removed the built-in boundaries.
106
+ - A Rack response body that is produced while it is sent runs in the request's context: its logs name the server span, and it sees the caller's baggage and the request's `Libo11y.current_record`.
107
+ - A Rack response body's `close` or `to_ary` that raises marks the span and the measurement, and a route the body sets with `Rack.set_route` is the request's route.
108
+ - A shutdown that starts with little of its deadline left, as after a long `before_shutdown`, gives the signals what is left. It failed all three at once when less than the 50 ms reserve remained.
109
+ - `Libo11y.shutdown_on_signals` raises `ArgumentError` for a `before_shutdown` that cannot be called, and `env:` for a value that is neither a Hash nor `HERMETIC`. Both raised `NoMethodError`. `Testing::Recorder` reads `nil` for `console_enabled` and `runtime_metrics` as its own defaults.
110
+ - `Rack::Middleware` removes the `(.:format)` that Rails appends to a route pattern from `http.route` and the span name.
111
+ - A view's `attribute_keys` given as an object that converts to a Hash were not classified. They are converted first, and anything else raises `ArgumentError`.
112
+ - A shutdown makes the last metric collection itself. The SDK's periodic reader makes it only when its worker is already waiting, so a shutdown soon after the start could report success and export no metrics.
113
+ - A log exporter whose shutdown raises no longer keeps the injected log processors from being shut down. An injected metric reader whose `shutdown` takes no timeout, such as the SDK's in-memory pull exporter, no longer fails the shutdown. A part listed twice under `OTEL_SDK_DISABLED` is shut down once. A part or a processor that answers with the SDK's timeout code is reported with a `Timeout::Error`.
114
+ - An `o11y.telemetry.dropped` event no longer enters the log pipeline that is shutting down, and is not written to a console that was busy until the deadline had passed.
115
+ - The built-in view of a duration histogram selects it by libo11y's meter too, so a histogram of the same name in the caller's own meter keeps the caller's view alone.
116
+ - A Rack response body's `to_path` runs in the request's context, and an error it raises is recorded.
117
+ - The registry YAML reader parses the text once, however many `\'` escapes it holds, and reports a second document before anything a third one holds, as Go does.
118
+ - A signal's OTLP header replaces the general header of the same name in another case. 0.2.0 kept both, and they went out as one header with both values.
119
+ - `create_instrument`, which the SDK's meter makes public, returned an instrument whose measurements were not classified. It is wrapped as a factory's result is.
120
+ - `error.type` is the nearest named class for an error whose class has no name, such as one made with `Class.new`. 0.2.0 wrote `nil` there, which left a failed Rack request unmarked.
121
+ - An injected part whose `shutdown` takes its timeout by position is called without a keyword.
122
+ - The registry YAML reader no longer takes a quote in a comment between a tag or an anchor and its scalar for the scalar.
123
+ - The Ruby generator also refuses a registry name that would generate a constant of `tables.rb` or `goprint.rb`, such as a metric named `o11y.resource.labels` and `METRIC_RESOURCE_LABELS`.
124
+ - The gem could not be loaded in a process whose environment held an attribute limit the OpenTelemetry Ruby SDK refuses, such as `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT=0`: the SDK raises for it while it loads. libo11y loads the SDK without such a variable, puts it back, and warns.
125
+ - A span processor added to the handle's tracer provider after the start got the unclassified span. It joins the group of injected processors behind the policy, and a span's violations are still counted once.
126
+ - A metric flush that raises during a shutdown no longer keeps the reader from being shut down. Every step of a signal's shutdown runs, and the first error is reported.
127
+ - In a registry with a `\'` escape, a double-quoted value that spelled the reader's stand-in through other escapes, such as `"\x5c\x75\x45\x30\x30\x30"`, was changed. A double-quoted value is no longer searched for the stand-in's text.
128
+ - A failed start no longer waits for an injected part that ignores its shutdown timeout. A processor listed twice in the options is registered once.
129
+ - `add_view` on the handle's meter provider with a `nil` name is checked as the SDK reads it, as a view that selects by its other fields. A view of another kind may be added for a name in `histogram_buckets`.
130
+ - The canonical line of a Rack request carries `http.request.method_original` when the method was not a standard one, as the Go and Python summaries do.
131
+ - `container.id` was not detected under cgroup v2 with a cgroup namespace, which is what current Docker, containerd, Podman and Kubernetes run, and a run of 64 hex digits anywhere in a cgroup line was taken for one. The cgroup path is read segment by segment, and the mount of `/etc/hostname` in `/proc/self/mountinfo` is read when the cgroup file names no container, as the Python implementation does.
132
+ - A span exporter whose shutdown or flush raises no longer keeps the injected span processors from being shut down.
133
+ - A Rack response with no body, or one whose connection the application hijacks, ends the request when the application returns. The middleware wrapped it and waited for a close that never comes. A wrapped body no longer answers `to_str`.
134
+ - `Record#max` raises `ArgumentError` for a `Complex`. Of two OTLP headers in one variable that differ in case only, the later stays.
135
+ - A propagator that raises no longer fails the request, the outbound call or `Telemetry#inject` and `#extract`. It is reported to OpenTelemetry's error handler and skipped, as OpenTelemetry's own composite propagator does.
136
+ - A span the policy changes keeps every other member of its data, also one a later SDK release adds. The data was rebuilt from a fixed list of members.
137
+ - After a failed start each provider and the injected parts no provider took are stopped on their own thread, so one that blocks keeps none of the others from stopping. `Libo11y.setup` also shuts down unowned injected parts when it raises `AlreadySetup`.
138
+ - Every active injected part (exporters, processors, and metric readers, including late registrations on the handle's providers) is tracked by identity across handles and plain SDK `MeterProvider` instances in both registration orders, keeping same-provider duplicates idempotent and shutting down an unowned reader whose registration raises a non-ownership `ArgumentError`.
139
+ - A log record processor or a metric reader added to the handle's providers after the start is isolated as the ones from the options are, so one that raises in a shutdown or a flush no longer keeps the next from being called, and `add_view` records a view only after the SDK accepts it.
140
+ - Attribute keys in non-UTF-8 encodings (including UTF-16LE, BINARY, and non-convertible encodings such as UTF-7 and ISO-2022-JP-2) are normalized to valid UTF-8 before sensitivity classification across resources, logs, spans, and metrics; `attr_replacer` receives independent copies of the group path strings and returned keys are frozen so in-place mutations cannot alter policy lookup.
141
+ - Capture-time redaction applies `:mask` before `attr_replacer` runs (using a mutable, single-pass, bounded, cycle-safe capture-redacted copy that re-checks within depth and node bounds when a parent callback mutates a child composite in place, and rescues replacer errors or malformed return values via `OpenTelemetry.handle_error` without exposing raw exception messages) and resets the floor after unwrapping `Redact::Secret` so a secret under `:mask` emits and hashes `"REDACTED"` instead of `"XXXXXXXX"`; lazy `PIIMode::HASH` masking on `Redact::Fields` also masks scalar values before float canonicalization or binary base64 encoding.
142
+ - Injected `BatchLogRecordProcessor` instances (and subclasses that inspect or assign `LogRecord` fields including `Time` timestamps) receive deep-copied, bounded, cycle-free, UTF-8-scrubbed `LogRecordData` snapshots with detached binary trace/span IDs and copied `instrumentation_scope`; direct OpenTelemetry Logs API records (scrubbing `severity_text` before required-field normalization, bounding deep or DAG log bodies to 16 nesting levels and 2048 nodes so `google-protobuf`'s 100-frame limit is never exceeded, and normalizing mixed attribute arrays), exported spans, metric attributes (`Redact.render` bounded to 32 levels and 2048 nodes, and `OtelSafe` bounded to 16 levels and a single shared 2048-node budget including pre-budget prefixes, snapshotting mutable Strings, Arrays, and Hashes, keeping distinct mixed-type arrays separate, and avoiding clean-path allocations), instrumentation scopes (snapshotting scope names, versions, and attributes without merging distinct mixed-type arrays and encoding them on OTLP trace, metric, and log exports), instrument names/units/descriptions, and resources (snapshotting mutable resource strings and array elements, trimming identity strings with Go Unicode whitespace rules while preserving explicit `resource_attributes` values and untrimmed `k8s.*` attributes, normalizing `deployment.environment.name` and `extra_environments` to valid UTF-8, and treating non-String identity attributes as missing, matching Go) scrub invalid UTF-8 strings and convert attribute integers outside signed `int64` range to decimal strings while all three signals (trace, metric, and log providers, injected processors, `ObservedExporter`, `SafeShutdownExporter`, `ObservedPeriodicReader`, and `InjectedParts`) share the caller's single monotonic deadline across concurrent processor/reader `force_flush` and `shutdown` (skipping expired queued flushes and keeping blocked processors from starving healthy siblings, preserving custom `#collect` arguments and zero-argument `PeriodicMetricReader#force_flush`/`shutdown` overrides even behind prepended modules, keeping periodic workers alive past transient exporter exceptions, always running exporter `shutdown` even if exporter `force_flush` raises on base or subclass periodic readers, catching `nil` returned on non-empty periodic exports with latched collection tracking, normalizing lifecycle return values consistently across all signals to reject floats, `false`, and negative integers while accepting `0`/`nil`/`true`, and propagating injected `PeriodicMetricReader` export failures to `force_flush` and `shutdown`) and require `Array` `histogram_buckets` and `views` explicit histogram boundaries (rejecting non-`Array` values such as `nil`, numbers, or ranges) and validate boundaries and exponential `zero_threshold` as finite, strictly increasing floats before recording (ignoring invalid advisory boundaries on `create_histogram` and `create_instrument` via `OpenTelemetry.handle_error` and guarding non-Hash `advisory:` options) and promote overflowing integers, `BigDecimal`, `Rational`, and float-colliding explicit bounds on metric data points, histogram summaries, `zero_threshold`, and exemplars to `double` so malformed or overflowing values do not drop OTLP batches, and console/OTLP JSON encoding disables Ruby's 100-level default nesting cap.
143
+ - Failed late metric reader registration preserves upstream `register_meter_provider` ordering, normalizes meter scope versions and attributes to match upstream `MeterProvider`, retains ownership if the SDK appended the reader before raising, atomically claims unowned injected parts before discarding or shutting them down so another handle cannot acquire a part while a timed-out shutdown or failed-start discard thread is still running, sanitizes partial collections immediately, prunes rejected streams from instruments on pre-acceptance failures, and tracks accepted streams within a bounded two-tier FIFO scan tracking minimum discovery depth per node (depth 16, 512 nodes, 4096 entries per collection) across SDK `MetricStore` subclasses (checking `@metric_streams` directly), wrapped SDK `MetricStore` delegators (including `Struct`/`Data` wrappers, treating reachable SDK stores authoritatively over audit arrays and checking direct container `MetricStore` members before expanding element lists), and pure custom stores (scanning collection entries and 1-level `Struct`/`Data`/object wrappers directly without spending BFS nodes on scalars or existing streams) so retrying attaches only missing instruments (including internal `o11y.schema.violations`). `AppRegistry::Decoder` decodes YAML `<<` merges and alias chains iteratively without overflowing the Ruby stack; `SqlText.summarize` tracks top-level `JOIN`s and flat column lists for `MERGE`/`DELETE ... USING (...)`, matching `go/o11ysql`; `Env.parse_exporter_choice` rejects comma-separated multi-exporter lists with `UnsupportedProtocol`; and `Endpoint.sanitize` falls back to raw bytes on non-UTF-8 `ASCII-8BIT` endpoints.
144
+ - `Detached::Carrier` baggage parsing matches Go's `baggage.Parse` and `validBaggage` at the 64-member and 8192 re-encoded byte limits, accepts literally empty property segments (`k=v;`, `k=v;;p`) while rejecting whitespace-only segments (`a=1; `), preserves raw property spacing during wire filtering while normalizing property whitespace and percent-encoding on restore, keeps original first-matching duplicate order when filtering invalid members, rejects malformed percent escapes in property values, and replaces each invalid UTF-8 byte individually with U+FFFD on restore.
145
+ - A Rack application that takes the connection over through `env["rack.hijack"]` ends the request when it returns. The response it returns is ignored by the server, and the middleware waited for its body to be closed. The request is recorded with the status 101, as in Go, whatever the application returns or raises, without inspecting a discarded tuple or adding `Server-Timing` to it. A hijack that raises leaves the request with the status of the response and wraps streaming bodies as usual, and `env["rack.hijack"]` is restored when the call finishes. A `route` callable that raises no longer replaces the application's own error.
146
+ - `Rack::Middleware`, `HttpClient`, and `DB::Client` refresh their cached duration histogram when the global `OpenTelemetry.meter_provider` is replaced between `setup`/`shutdown` lifecycles.
147
+ - A propagator whose `fields`, `inject`, or `extract` raises, including a custom global `OpenTelemetry.propagation`, no longer fails the start, an outbound call, a Rack request, `Detached.capture`, or `ChildProcess` frame helpers; partial writes from a propagator that raises mid-`inject` are discarded.
148
+ - `HttpClient` always strips `traceparent`, `tracestate`, and `baggage` case-insensitively before applying `propagate_fn`, even when a custom propagator reports no `fields`.
149
+ - `Detached::Carrier.unmarshal_text` extracts the span context before checking the re-encoded size, so a valid carrier under 32 KiB whose unescaped `tracestate` expands past 32 KiB drops `tracestate` to fit instead of failing.
150
+ - Top-level self-referential attribute hashes keep their original caller identity across `Telemetry#logger`, `Telemetry#event`, `Record#set_all`/`Record#emit_event`, `Rack::Middleware` canonical request summaries, `Redact::Fields` wrappers, and the OpenTelemetry Logs API without attaching raw attributes or classification markers to `OpenTelemetry::Context` or failing when `context: nil` is passed. `Record` tracks hash origins per key so non-cyclic nested hashes are preserved, and classification enables identity comparison before inserting the root hash so a value whose `#hash` raises cannot abort logging before it is dropped.
151
+ - The OTLP log export processor receives a detached snapshot of each record at handoff, so a later application log processor that mutates `attributes` or nested values cannot alter records already queued for OTLP export.
152
+ - `Redact::Fields` wrappers are traversed lazily under the shared 16-depth and 2048-node walk budget on both log classification and `PIIMode::HASH`, stopping before invoking getters past the limit.
153
+ - Unclassified invalid UTF-8 or binary strings on `Telemetry#logger` are scrubbed to valid UTF-8 after sensitivity classification before console JSON and OTLP serialization, so one malformed string neither drops its console line nor poisons an OTLP batch.
154
+ - `DB::Client` SQL query summarization handles SQLite `INDEXED BY` / `NOT INDEXED` hints and `?` double-quoted table aliases, MySQL index hints, `TABLESAMPLE`, and `DELETE`/`MERGE USING`, matching `go/o11ysql`.
155
+ - Under `PIIMode::HASH`, scalar strings with invalid UTF-8 bytes hash their raw bytes, while strings and map keys inside nested arrays or hashes sort by UTF-8 bytes and escape each invalid UTF-8 byte as `\ufffd` (keeping valid U+FFFD literal) to match Go's `encoding/json` tokens; nested `Redact::Fields` values under a PII key are rendered lazily inside the bounded hash walk so logs and spans produce identical tokens while preserving `"truncated"` cycle handling and the 2048-node budget. Emitting on the OpenTelemetry Logs API with `attributes: nil` preserves `nil` instead of coercing it to `{}`.
156
+ - A record on the OpenTelemetry log API that brings no timestamp, body, or severity gets the time it was observed, an empty string body, and `INFO`, since every exported record must carry them. Out-of-range severity numbers (outside `1..24`) and blank text count as none. Sub-level severity numbers format as OpenTelemetry short names (`INFO2`, `ERROR2`, and so on) matching Go, and text without a number maps recognized level names (`WARNING` and sub-levels included) to their severity numbers. The provider copies caller attribute hashes before SDK record construction so active limits do not mutate reusable hashes or raise `FrozenError` on frozen hashes.
157
+ - A sink invoked from a handle's `o11y.telemetry.dropped` writer thread that calls `shutdown` on the same handle returns an in-progress report immediately instead of waiting for the shutdown deadline.
158
+ - Duplicate OTLP headers that differ in case resolve in input order so the last occurrence wins (`X-Label=one,x-label=two,X-Label=three` keeps `three`).
159
+ - The hygiene script finds `Kernel.p`, and no longer takes `def self.print` for a call.
160
+ - One injected log processor whose shutdown raises no longer keeps the processors after it from being shut down. Each processor of a shutdown or a flush gets the time that is left, and its error is in the report.
161
+ - An `o11y.telemetry.dropped` event is not handed to a further sink once the shutdown's deadline has passed. 0.2.0 went on to the remaining sinks after `shutdown` had returned.
162
+ - The registry YAML reader takes libyaml's own word for what is a double-quoted scalar, so a quote after a comma or a bracket inside a plain scalar is plain text. A problem in the first document is reported before a later document that does not parse, as the conformance contract says.
163
+ - The Ruby generator refuses a registry name that would generate one of its own constants, such as an event named `o11y.name_key` and `EVENT_NAME_KEY`.
164
+ - One injected span processor that raises no longer keeps the others from seeing the span. An `Interrupt` while the globals are installed puts back the ones already replaced.
165
+
166
+ ### Added
167
+
168
+ - A warning at the start for each limit variable that holds a value the OpenTelemetry Ruby SDK refuses, which says what applies in its place: the default of 128 for a count limit, and no limit for a value length limit under 32. The warning the gem writes when it loads names the same effect.
169
+ - A warning at the start under `PIIMode::HASH` for a value length limit that changes the tokens. On spans, span events and OpenTelemetry Logs API records any value length limit gives a longer value a token of what the SDK left of it, which differs from `Telemetry#logger` and console output. On log records (both `Telemetry#logger` and the OpenTelemetry Logs API) a limit under the 44 characters of a token also cuts the tokens themselves. The warning names the variable that was read.
170
+ - `Record#max` keeps the larger of the value under a key and a new one, by the rule of Go's `Record.Max`: a Float under the key that is at least as large stays, and anything else under the key is replaced. NaN is ignored.
171
+ - A "Wide events" section in the README shows `Libo11y.start_record`, `Record#set`, `add`, `max` and `emit_event`, and the record of a Rack request.
172
+ - Every option is documented: in YARD on `Libo11y::Options` and in an "Options" table in the README, with its type, its default and the error it raises.
173
+ - The release check asserts the specification's schema URL on the resource of each signal and a metric exemplar that names the span, on the installed gem over OTLP.
174
+
10
175
  ## [0.2.0] - 2026-11-28
11
176
 
12
177
  This release fixes most of what the first review of 0.1.0 found. It changes an option name, a return type and the text form of a carrier, so read the "Changed" list before upgrading.
@@ -51,24 +216,7 @@ This release fixes most of what the first review of 0.1.0 found. It changes an o
51
216
  - The `views` option is applied. It takes Hashes of `MeterProvider#add_view` arguments with a `:name`. In 0.1.0 it did nothing.
52
217
  - With `env: Libo11y::HERMETIC` or an explicit `env`, the span and log record limits, the batch processors' worker switch, and the exporters' certificate files and certificate verification no longer come from the process environment.
53
218
  - Two registries that declare one namespace are refused also when they are given as compiled registries.
54
- - The registry parser checks the escapes of a double-quoted scalar that follows an apostrophe in a plain or block scalar. It used to treat the apostrophe as an open quote, so `"a \/ b"` was accepted there and `"it the log record and the exemplar were on different traces. It requires one trace with a span, a log record and an exemplar, and takes a metric name to look at one metric's exemplars.
55
- - `Recorder#assert_conforms!` passed after the code under test emitted a secret, because the secret had been redacted. It now fails on any counted redaction of a secret, as Go's `AssertConforms` does, looks at metric data points too, and lists every problem it finds.
56
-
57
- ## [0.1.0] - 2026-11-28
58
-
59
- ### Added
60
-
61
- - Core Ruby SDK (`Libo11y.setup`, `Libo11y.init`, `Options`, typed `Libo11y::Error` hierarchy, idempotent bounded concurrent shutdown, `shutdown_on_signals`).
62
- - Generated spec constants, tables, and `GoPrint` ranges (`Libo11y::Spec`, spec 1.3.0) and strict `yaml.v3`-compatible application attribute registry validator passing all 46 shared conformance cases, plus `exe/libo11y registry check`.
63
- - Single `SensitivityPolicy` across resource, spans, metrics (PII always dropped), and structured logs, matching all shared PII hash, instance ID, and endpoint sanitization conformance vectors. An injected span processor sees the redacted span through `attributes`, `events`, `links` and `to_span_data`. Observable instruments classify the attributes given to `add_attributes` and `observe`. A log record is classified once, so one PII value has one token on the console, on OTLP and on spans, and one violation is counted per record. The walk over nested log values drops what its depth bound, its budget of 2048 nodes or a cycle kept it from examining.
64
- - Capture-time redaction (`Libo11y::Redact::Secret`, `Masked`, `Fields`), where the strictest protection wins through nesting and a subclass keeps its parent's field rules, wide events (`Record`), `force_emit`, detached propagation (`Libo11y::Detached`), child-process propagation (`Libo11y::Proc`), and zero-dependency Ruby/process runtime metrics.
65
- - Integrations: `Libo11y::Rack::Middleware`, `Libo11y::HttpClient`, and `Libo11y::DB::Client`. The DB client removes literals and comments with the same dialect-aware lexer as `go/o11ysql` (PostgreSQL dollar quoting, escape strings and nested comments, MySQL backslash escapes, double-quoted strings, `#` and versioned comments, SQLite parameters), records `db.query.text` only for `postgresql`, `sqlite`, `mysql` and `mariadb`, capped at 4096 bytes, names the span after the operation and table, and never records a driver's error message.
66
- - Hermetic test harness (`Libo11y::Testing::Recorder` and `OtlpHttpReceiver`). `OtlpHttpReceiver` serves through WEBrick, which the gem does not depend on. A consumer adds `gem "webrick"` to its test group.
67
-
68
- [Unreleased]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.2.0...HEAD
69
- [0.2.0]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.1.0...ruby/v0.2.0
70
- [0.1.0]: https://github.com/jamesainslie/libo11y/releases/tag/ruby/v0.1.0
71
- s"` was refused.
219
+ - The registry parser checks the escapes of a double-quoted scalar that follows an apostrophe in a plain or block scalar. It used to treat the apostrophe as an open quote, so `"a \/ b"` was accepted there and `"it's"` was refused.
72
220
  - `exe/libo11y` prints its usage on standard output and exits 0 for `-h`, `--help` and `help`, as the Go command does.
73
221
  - Resident memory is computed with the system's page size, not a fixed 4 KiB.
74
222
  - `OtlpHttpReceiver` returns copies of what it has received, taken under its lock.
@@ -87,6 +235,7 @@ s"` was refused.
87
235
  - Integrations: `Libo11y::Rack::Middleware`, `Libo11y::HttpClient`, and `Libo11y::DB::Client`. The DB client removes literals and comments with the same dialect-aware lexer as `go/o11ysql` (PostgreSQL dollar quoting, escape strings and nested comments, MySQL backslash escapes, double-quoted strings, `#` and versioned comments, SQLite parameters), records `db.query.text` only for `postgresql`, `sqlite`, `mysql` and `mariadb`, capped at 4096 bytes, names the span after the operation and table, and never records a driver's error message.
88
236
  - Hermetic test harness (`Libo11y::Testing::Recorder` and `OtlpHttpReceiver`). `OtlpHttpReceiver` serves through WEBrick, which the gem does not depend on. A consumer adds `gem "webrick"` to its test group.
89
237
 
90
- [Unreleased]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.2.0...HEAD
91
- [0.2.0]: https://github.com/jamesainslie/libo11y/compare/ruby/v0.1.0...ruby/v0.2.0
92
- [0.1.0]: https://github.com/jamesainslie/libo11y/releases/tag/ruby/v0.1.0
238
+ [Unreleased]: https://github.com/libo11y/libo11y/compare/ruby/v0.3.0...HEAD
239
+ [0.3.0]: https://github.com/libo11y/libo11y/compare/ruby/v0.2.0...ruby/v0.3.0
240
+ [0.2.0]: https://github.com/libo11y/libo11y/compare/ruby/v0.1.0...ruby/v0.2.0
241
+ [0.1.0]: https://github.com/libo11y/libo11y/releases/tag/ruby/v0.1.0
data/README.md CHANGED
@@ -27,7 +27,7 @@ Libo11y.setup(
27
27
  end
28
28
  ```
29
29
 
30
- `Libo11y.setup` installs the global tracer, meter, and logger providers, installs the W3C TraceContext + Baggage propagator wrapped in the baggage egress filter, and runs the startup canary (`o11y.telemetry.configured`). Passing a block guarantees bounded concurrent shutdown across all three signals when the block exits.
30
+ `Libo11y.setup` installs the global tracer, meter, and logger providers, installs the W3C TraceContext + Baggage propagator wrapped in the baggage egress filter, and runs the startup canary (`o11y.telemetry.configured`). The canary fails setup when a sink rejects the event as it is emitted. The default OTLP log processor batches, so setup does not wait for a collector to accept the event, and a collector that is down shows up in the shutdown report. Passing a block guarantees bounded concurrent shutdown across all three signals when the block exits.
31
31
 
32
32
  `tel.shutdown(timeout: 5)` runs once and returns a `ShutdownReport`. `report.ok?` is false, and `report.errors` names the signal, when a signal fails, misses the deadline, or has its final export rejected by the collector. Each such signal also gets an `o11y.telemetry.dropped` event on the console and the extra sinks. `tel.force_flush` returns `false` on the same failures.
33
33
 
@@ -51,17 +51,86 @@ bundle exec libo11y registry check o11y-registry.yaml
51
51
  |---|---|
52
52
  | `Libo11y::Rack::Middleware` | Rack 3 middleware (Rails, Sinatra, Hanami); route templates (`set_route`, Sinatra/Rails keys), `http.server.request.duration` with exemplars, `public_endpoint`, `ignore_paths`, `filter`, `server_timing` (HTML responses), `canonical_line` (needs `telemetry:`). A method outside the standard set is recorded as `_OTHER` |
53
53
  | `Libo11y::HttpClient` | Instrumented `Net::HTTP` client (no global monkey-patching); W3C injection, URL credential stripping, `propagate_fn`, `peer_service`, `http.client.request.duration` with exemplars |
54
- | `Libo11y::DB::Client` | Parent-gated DB client spans named after the operation and table, `db.client.operation.duration` with exemplars, and sanitized `db.query.text` for `postgresql`, `sqlite`, `mysql` and `mariadb` only, capped at 4096 bytes (`query_text: false` turns it off). A failed call sets `error.type` to the SQLSTATE or the error class and never records the driver's message |
54
+ | `Libo11y::DB::Client` | Parent-gated DB client spans named after the operation and table, `db.client.operation.duration` with exemplars, and sanitized `db.query.text` for `postgresql`, `sqlite`, `mysql` and `mariadb` only, capped at 4096 bytes (`query_text: false` turns it off). A statement whose literal or comment boundaries depend on a server setting or version gets no text: a backslash before a quote in a plain PostgreSQL or MySQL string, or a MySQL or MariaDB versioned comment. A failed call sets `error.type` to the SQLSTATE or the error class and never records the driver's message |
55
55
  | `Libo11y::Detached` | `Carrier` with the URL-encoded text form every libo11y implementation reads (at most 32 KiB, the trace state and then the baggage dropped to fit), egress-filtered baggage, `capture`, `restore_baggage`, and `start_linked`, which starts a linked root span and merges the carrier's baggage into the caller's |
56
- | `Libo11y::Proc` | `TRACEPARENT`/`TRACESTATE` env carriers (never baggage) and framed map `inject_frame`/`extract_frame`. Pass `Libo11y::Proc.child_env` as the environment argument of `Process.spawn`: it adds the current trace and removes a stale one the child would inherit |
56
+ | `Libo11y::ChildProcess` | `TRACEPARENT`/`TRACESTATE` env carriers (never baggage) and framed map `inject_frame`/`extract_frame`. Pass `Libo11y::ChildProcess.child_env` as the environment argument of `Process.spawn`: it adds the current trace and removes a stale one the child would inherit |
57
57
  | `Libo11y::Redact` | `Secret`, `Masked`, and `Fields` mixin (`mask`, `redact`, `omit`, `confidential`, `secret`) |
58
58
  | `Libo11y::Testing` | Hermetic `Recorder` (`assert_conforms!`, `assert_correlated!`, `assert_triangle!`) and in-process `OtlpHttpReceiver`. The receiver serves through WEBrick, which the gem does not depend on, so add `gem "webrick"` to your test group to use it |
59
59
 
60
+ ## Wide events
61
+
62
+ A wide event is one log record that carries everything a unit of work learned about itself. `Libo11y.start_record` opens a `Libo11y::Record` for the block, and `Libo11y.current_record` returns it from anywhere inside.
63
+
64
+ ```ruby
65
+ Libo11y.start_record do |record|
66
+ record.set("order.id", order.id) # a value
67
+ record.add("db.queries", 1) # a count that adds up
68
+ record.max("db.slowest_seconds", elapsed) # the largest value seen
69
+ record.emit_event(tel, "order.placed") # one event with all of it
70
+ end
71
+ ```
72
+
73
+ The Rack middleware opens a record for each request. With `canonical_line: true` it writes the record as the `o11y.request.summary` event when the request ends, beside the method, the route, the status and the duration:
74
+
75
+ ```ruby
76
+ use Libo11y::Rack::Middleware, telemetry: tel, canonical_line: true
77
+
78
+ # anywhere in the request
79
+ Libo11y.current_record&.set("tenant.plan", plan)
80
+ ```
81
+
82
+ The record's attributes are classified as any log attributes are.
83
+
84
+ ## Options
85
+
86
+ Every option is a keyword of `Libo11y.setup` and `Libo11y.init`, and a member of `Libo11y::Options`. `nil` for an option means its default. A keyword that is not an option raises `ArgumentError`.
87
+
88
+ | Option | Type | Default | Notes |
89
+ |---|---|---|---|
90
+ | `service_name` | String | none | Required, here or in `OTEL_SERVICE_NAME`. Missing raises `NoServiceName` |
91
+ | `version` | String | `build_info`, else `0.0.0-unknown` | `service.version` |
92
+ | `environment` | String | none | `production`, `staging`, `development`, `test` or one of `extra_environments`. Missing raises `NoEnvironment`, another value `InvalidEnvironment` |
93
+ | `service_namespace` | String | none | `service.namespace` |
94
+ | `service_instance_id` | String | Kubernetes pod, else one random UUID per process | `service.instance.id` |
95
+ | `extra_environments` | Array of String | `[]` | Environment names allowed beside the four |
96
+ | `strict_identity` | Boolean | `true` | `false` starts without a name or an allowed environment and counts a violation for each |
97
+ | `resource_attributes` | Hash | `{}` | Beat `OTEL_RESOURCE_ATTRIBUTES`, lose to the named options |
98
+ | `build_info` | Hash, String or Pathname | none | `version`, `vcs_revision`, `build_time`, `build_modified`, or the path of a JSON file with them |
99
+ | `build_info_enabled` | Boolean | `true` | `false` ignores `build_info` |
100
+ | `env` | Hash or `Libo11y::HERMETIC` | the process environment | Where `OTEL_*` settings come from. Under `HERMETIC` a signal with nothing injected is off |
101
+ | `pii_mode` | `PIIMode::DROP`, `HASH`, `ALLOW` | `DROP` | `DROP` removes PII from the resource, spans, logs and metrics. `HASH` puts an HMAC token in its place on the resource, spans and logs, and removes it from metrics. `ALLOW` keeps it on all four. Secrets are removed whatever the mode |
102
+ | `pii_hash_key` | String of 32 bytes or more | none | Required for `HASH`. Too short raises `PIIHashKey` |
103
+ | `app_registries` | Array of YAML text, path or compiled registry | none | A bad one raises `InvalidAppRegistry` |
104
+ | `attr_replacer` | callable `(groups, key, value)` | none | Runs on log attributes before the policy. Returns `[key, value]`, or `nil` to drop |
105
+ | `propagators` | propagator or Array | W3C TraceContext and Baggage | `OTEL_PROPAGATORS` is not read |
106
+ | `baggage_egress_allow` | callable `(key)` | all members leave | Only members it returns true for leave the process |
107
+ | `sampler` | OpenTelemetry sampler | `OTEL_TRACES_SAMPLER`, else parent-based always-on | |
108
+ | `exemplar_filter` | `ExemplarFilter::TRACE_BASED`, `ALWAYS_ON`, `ALWAYS_OFF` | `OTEL_METRICS_EXEMPLAR_FILTER`, else `TRACE_BASED` | |
109
+ | `histogram_buckets` | Hash of name to boundaries | libo11y's latency boundaries | An entry for a duration histogram replaces its boundaries |
110
+ | `views` | Array of Hash | none | The arguments of the SDK's `add_view` with a `:name`. Each needs an `:aggregation` of the SDK. One that selects a libo11y duration histogram replaces its built-in view. Its `:attribute_keys` are classified. Two views that may select one instrument are refused when either has `:attribute_keys` |
111
+ | `runtime_metrics` | Boolean | `true` | Ruby runtime metrics |
112
+ | `console_writer` | responds to `write` | `$stdout` | Where the JSON console lines go |
113
+ | `console_enabled` | Boolean | `true` | |
114
+ | `log_level` | `Logger` constant or name | `INFO` | The level of `Telemetry#logger`. Gates every sink |
115
+ | `extra_log_sinks` | Array of callables | `[]` | Each gets the classified record |
116
+ | `span_exporter` | span exporter | none | With one, traces are not exported from the environment's settings |
117
+ | `span_processors` | Array | `[]` | Get classified finished spans, and own the trace export path |
118
+ | `metric_reader` | metric reader | none | With one, metrics are not exported from the environment's settings |
119
+ | `log_exporter` | log record exporter | none | With one, logs are not exported from the environment's settings |
120
+ | `log_processors` | Array | `[]` | See classified records, and own the log export path |
121
+ | `shutdown_timeout` | Numeric, seconds | `5` | For `shutdown` and `force_flush` called without a timeout |
122
+
123
+ libo11y owns an injected exporter, processor or reader from the start and shuts it down once, also under `OTEL_SDK_DISABLED=true` and after a start that fails.
124
+
125
+ ### Upstream internals
126
+
127
+ libo11y uses several parts of the OpenTelemetry Ruby gems that those gems call internal: the OTLP exporters' private `send_bytes` method, where it adds the resource schema URL and instrumentation scope attributes; `opentelemetry-exporter-otlp-common` 0.4's encoders and utilities; the metrics SDK's view selector, `ExplicitBucketHistogram` `@boundaries`, and `ExponentialBucketHistogram` `@zero_threshold`, with which it normalizes bucket boundaries to IEEE 754 floats and decides whether a view replaces a built-in one; `MeterProvider::READER_OWNERS` / `READER_OWNERS_MUTEX`, `MeterProvider.reader_config`, `MeterProvider` `@stopped` / `@mutex`, `Meter` `@instrument_descriptors` / `@mutex`, `MetricReader` `@meter_provider`, `register_with_new_metric_store`, `MetricStore` `@metric_streams` / `@mutex`, `AsynchronousInstrument#init_callback`, `AsynchronousMetricStream` `@callback` / `@mutex`, and instrument `@metric_streams`, with which it enforces single-provider metric reader ownership, concurrent multi-reader shutdown, rollback on failed instrument creation, and duplicate-free partial retries; and `PeriodicMetricReader`'s private `export` method and `@exporter`, with which it observes injected periodic reader export failures without terminating the background worker thread or skipping exporter shutdown. So the gemspec holds the OTLP exporters (including `opentelemetry-exporter-otlp-common`), the metrics SDK and the logs SDK to the minor versions the suite runs against. A newer minor version needs a libo11y release.
128
+
60
129
  ## Per-signal guarantees and caveats
61
130
 
62
- - **Traces:** `PolicySpanExporter` and `PolicySpanProcessor` classify span, event, and link attributes before leaving the process. An injected span processor receives a redacted view at `on_finish` (`attributes`, `events`, `links`, `to_span_data`) and the live span at `on_start`.
63
- - **Metrics:** `PolicyMeterProvider` classifies the attributes of synchronous measurements and of observable instruments (`add_attributes`, `observe`) before SDK recording (covering derived Views and exemplars). PII is always dropped on metrics even in `PIIMode::HASH`. Trace-based exemplars are on by default.
64
- - **Logs:** `tel.logger` is a `::Logger`. Its `level`, first set by the `log_level` option (`Logger::INFO` by default), gates the console, OTLP and the extra sinks alike. `Libo11y.force_emit { ... }` and `tel.event` pass it. `StructuredLogger` applies capture-time redaction, user `attr_replacer`, and `SensitivityPolicy` once per record, and writes the same classified attributes to console JSON, OTLP logs, and extra sinks. Nested values are walked to a depth of 16 within a budget of 2048 nodes, and what the walk did not examine, a cycle included, is dropped. A record from the OpenTelemetry Logs API is classified by the first processor on the logger provider, before any injected processor sees it.
65
- - **Policy scope (shared across all languages):** Key-based classification does not inspect log message bodies, span names, span status descriptions, instrumentation scope attributes, map-valued span/metric members, attributes read at `on_start`, or baggage. Use `Libo11y::Redact` for values under unclassified keys.
66
- - **Environment:** With `env: Libo11y::HERMETIC` or an explicit `env`, libo11y passes every setting it can to the SDK, so the process environment does not set limits, batch settings or certificate verification. Two variables remain that the upstream metrics SDK reads directly: `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` and `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION`.
131
+ - **Traces:** Span, event, and link attributes are classified before they leave the process, on the export path and for injected processors, also for one added to the handle's tracer provider after the start. An injected span processor receives a redacted view at `on_finish` (`attributes`, `events`, `links`, `to_span_data`) and the live span at `on_start` and `on_finishing`.
132
+ - **Metrics:** The handle's meter provider classifies the attributes of synchronous measurements and of observable instruments (`add_attributes`, `observe`) before SDK recording (covering derived Views and exemplars). PII is dropped on metrics under `PIIMode::DROP` and `HASH`, and kept under `ALLOW`. Trace-based exemplars are on by default.
133
+ - **Logs:** `tel.logger` is a `::Logger`. Its `level`, first set by the `log_level` option (`Logger::INFO` by default), gates the console, OTLP and the extra sinks alike. `Libo11y.force_emit { ... }` and `tel.event` pass it. The logger applies capture-time redaction, user `attr_replacer`, and the sensitivity policy once per record, and writes the same classified attributes to console JSON, OTLP logs, and extra sinks. Nested values are walked to a depth of 16 within a budget of 2048 nodes, and what the walk did not examine, a cycle included, is dropped. A record from the OpenTelemetry Logs API is classified by the first processor on the logger provider, before any injected processor sees it.
134
+ - **Policy scope (shared across all languages):** Key-based classification does not inspect log message bodies, span names, span status descriptions, span event names, instrumentation scope attributes, map-valued span/metric members, attributes read at `on_start`, or baggage. A measurement made on a meter taken from the SDK's own `MeterProvider`, and not from the handle, is not classified. Use `Libo11y::Redact` for values under unclassified keys.
135
+ - **Environment:** With `env: Libo11y::HERMETIC` or an explicit `env`, libo11y passes every setting it can to the SDK, so the process environment does not set limits, batch settings or certificate verification. One variable remains that the upstream metrics SDK reads directly: `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`. An `OTEL_TRACES_SAMPLER`, `OTEL_TRACES_SAMPLER_ARG` or `OTEL_METRICS_EXEMPLAR_FILTER` that is not valid gives the default with a warning and does not stop the service. `OTEL_RUBY_EXPORTER_OTLP_SSL_VERIFY_NONE` turns certificate verification off only when it is `true`. The OpenTelemetry Ruby SDK accepts no count limit under 1 and no value length limit under 32. For such a count limit the default of 128 applies. For such a length limit no limit applies, where Go and Python cut the value. libo11y warns of each at the start. The SDK also refuses such a variable while it loads, so libo11y loads the SDK without it and puts it back. Under `PIIMode::HASH` a value length limit changes the tokens, and libo11y warns of it at the start. On spans, span events and OpenTelemetry Logs API records the SDK cuts a longer value first and libo11y hashes what is left, as Go does on spans. The Ruby SDK ends a cut value in `...`, so that token differs from `Telemetry#logger`, console output, and Go. On log records (both `Telemetry#logger` and the OpenTelemetry Logs API) a limit under 44 characters also cuts the 44-character token itself when the SDK writes the record's attributes. A collector that answers an export with HTTP 200 and a partial success is not reported as a failure: the upstream trace and metric exporters ignore the response body, and the upstream logs exporter reports positive `rejected_log_records` through `OpenTelemetry.handle_error` before returning `SUCCESS`. Under `OTEL_SDK_DISABLED=true` a reader or a log processor added to the handle's providers later is not registered. The query of an OTLP endpoint URL is not sent: the upstream exporters request the URL's path only, as the OpenTelemetry Go exporters do.
67
136
  - **Protocol support:** OTLP over `http/protobuf` is supported (gRPC and Prometheus exporters raise `Libo11y::UnsupportedProtocol`).
@@ -4,7 +4,9 @@ require "opentelemetry"
4
4
 
5
5
  module Libo11y
6
6
  # Child-process environment and framed-map propagation (TRACEPARENT/TRACESTATE only; never baggage).
7
- module Proc
7
+ # Go names its package o11yproc. The Ruby name is not Proc, which inside
8
+ # this namespace would hide Ruby's own Proc.
9
+ module ChildProcess
8
10
  TRACEPARENT_ENV = "TRACEPARENT"
9
11
  TRACESTATE_ENV = "TRACESTATE"
10
12
 
@@ -38,13 +40,21 @@ module Libo11y
38
40
 
39
41
  def inject_frame(frame = {}, telemetry: nil, context: OpenTelemetry::Context.current)
40
42
  propagator = telemetry ? telemetry.propagator : OpenTelemetry.propagation
41
- propagator.inject(frame, context: context)
43
+ staged = {}
44
+ propagator.inject(staged, context: context)
45
+ staged.each { |key, value| frame[key] = value }
46
+ frame
47
+ rescue StandardError => e
48
+ OpenTelemetry.handle_error(exception: e, message: "libo11y: #{propagator.class} raised in inject")
42
49
  frame
43
50
  end
44
51
 
45
52
  def extract_frame(frame, telemetry: nil, context: OpenTelemetry::Context.current)
46
53
  propagator = telemetry ? telemetry.propagator : OpenTelemetry.propagation
47
54
  propagator.extract(frame, context: context)
55
+ rescue StandardError => e
56
+ OpenTelemetry.handle_error(exception: e, message: "libo11y: #{propagator.class} raised in extract")
57
+ context
48
58
  end
49
59
  end
50
60
  end
data/lib/libo11y/db.rb CHANGED
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "opentelemetry"
4
+ require_relative "internal/error_type"
5
+ require_relative "internal/quiet_inspect"
4
6
  require_relative "internal/histogram_buckets"
5
7
  require_relative "internal/sql_text"
6
8
 
@@ -12,7 +14,7 @@ module Libo11y
12
14
  # statement values.
13
15
  module DB
14
16
  DB_DURATION_BUCKETS = Internal::HistogramBuckets::DB
15
- SCOPE_NAME = "libo11y.db"
17
+ SCOPE_NAME = Internal::HistogramBuckets::DB_SCOPE
16
18
 
17
19
  # The lexer for a db.system.name value, and whether that lexer is known to
18
20
  # find every literal the database reads. An unknown system gets the
@@ -35,17 +37,22 @@ module Libo11y
35
37
  state = error.sqlstate if error.respond_to?(:sqlstate)
36
38
  return state if state.is_a?(String) && !state.empty?
37
39
 
38
- error.class.name || error.class.to_s
40
+ Internal::ErrorType.of(error)
39
41
  end
40
42
 
41
43
  # Wraps database calls. One client describes one database, so it is safe
42
44
  # to share between threads.
43
45
  class Client
46
+ include Internal::QuietInspect
47
+
44
48
  # @param db_system [String] the db.system.name value, such as "postgresql"
45
49
  # @param db_namespace [String, nil] the database name
46
50
  # @param query_text [Boolean] record the sanitized statement as
47
51
  # db.query.text. It is recorded only for postgresql, sqlite, mysql and
48
- # mariadb, whose literals the sanitizer knows.
52
+ # mariadb, whose literals the sanitizer knows, and not for a statement
53
+ # whose literal or comment boundaries depend on a server setting or
54
+ # version: a backslash before a quote in a plain PostgreSQL or MySQL
55
+ # string, or a MySQL or MariaDB versioned comment.
49
56
  # @param telemetry [Libo11y::Telemetry, nil] the handle to record
50
57
  # through. Without one the client uses the global providers.
51
58
  def initialize(db_system:, db_namespace: nil, server_address: nil, server_port: nil, query_text: true, telemetry: nil)
@@ -58,6 +65,7 @@ module Libo11y
58
65
  @query_text = query_text && known
59
66
  @mutex = Mutex.new
60
67
  @duration = nil
68
+ @duration_provider = nil
61
69
  end
62
70
 
63
71
  # Runs the block as one database call and returns its value.
@@ -110,13 +118,15 @@ module Libo11y
110
118
  unless sql.nil?
111
119
  # OTLP sends attribute values as protobuf strings, which must be
112
120
  # valid UTF-8, and one invalid value fails the whole export batch.
113
- sanitized = Internal::SqlText.sanitize(sql.to_s, @dialect).dup.force_encoding(Encoding::UTF_8).scrub("�")
114
- found_operation, found_collection = Internal::SqlText.summarize(sanitized)
121
+ raw, safe = Internal::SqlText.sanitize(sql.to_s, @dialect)
122
+ sanitized = Internal::SqlText.to_valid_utf8(raw)
123
+ found_operation, found_collection = Internal::SqlText.summarize(sanitized, @dialect)
115
124
  if operation.nil?
116
125
  operation = found_operation
117
126
  collection ||= found_collection
118
127
  end
119
- text = Internal::SqlText.truncate(sanitized) if @query_text
128
+ # No text for a statement the lexer could not read with certainty.
129
+ text = Internal::SqlText.truncate(sanitized) if @query_text && safe
120
130
  end
121
131
  name, attrs = named(operation.to_s, collection.to_s)
122
132
  [name, attrs, text]
@@ -141,19 +151,21 @@ module Libo11y
141
151
 
142
152
  def tracer
143
153
  provider = @telemetry ? @telemetry.tracer_provider : OpenTelemetry.tracer_provider
144
- provider.tracer(SCOPE_NAME, Libo11y::VERSION)
154
+ provider.tracer(name: SCOPE_NAME, version: Libo11y::VERSION)
145
155
  end
146
156
 
147
157
  def duration
158
+ provider = @telemetry ? @telemetry.meter_provider : OpenTelemetry.meter_provider
148
159
  @mutex.synchronize do
149
- @duration ||= begin
150
- provider = @telemetry ? @telemetry.meter_provider : OpenTelemetry.meter_provider
151
- provider.meter(SCOPE_NAME, version: Libo11y::VERSION).create_histogram(
160
+ unless @duration_provider.equal?(provider)
161
+ @duration = provider.meter(SCOPE_NAME, version: Libo11y::VERSION).create_histogram(
152
162
  "db.client.operation.duration",
153
163
  unit: "s",
154
164
  description: "Duration of database client operations."
155
165
  )
166
+ @duration_provider = provider
156
167
  end
168
+ @duration
157
169
  end
158
170
  end
159
171
  end