diff --git a/magefile.go b/magefile.go index cfcdc3103..3832fbd63 100644 --- a/magefile.go +++ b/magefile.go @@ -261,10 +261,29 @@ func Proto() error { // regenerate the telemetry conventions in otel/gen (needs weaver, see otel/README.md) func Otel() error { + // Snapshot otel/gen and restore it on any failure. generate.sh replaces otel/gen whole, and + // the Generate workflow commits whatever is left on disk, so a failed regeneration or a + // generated Go package that does not build or test must leave the previous otel/gen in place + // rather than a broken partial result. + backup, err := os.MkdirTemp("", "otel-gen-backup") + if err != nil { + return err + } + defer os.RemoveAll(backup) + if err := otelGenCopy("otel/gen", filepath.Join(backup, "gen")); err != nil { + return err + } + restore := func(cause error) error { + if err := otelGenCopy(filepath.Join(backup, "gen"), "otel/gen"); err != nil { + return fmt.Errorf("%w (and restoring otel/gen failed: %v)", cause, err) + } + return cause + } + cmd := exec.Command("otel/generate.sh") connectStd(cmd) if err := cmd.Run(); err != nil { - return err + return restore(err) } // Verify the generated Go package compiles and its alias invariants hold, so a model or @@ -276,12 +295,23 @@ func Otel() error { cmd := exec.Command("go", args...) connectStd(cmd) if err := cmd.Run(); err != nil { - return err + return restore(err) } } return nil } +// otelGenCopy replaces target with a fresh copy of source (a directory), used to snapshot and +// restore otel/gen around regeneration. +func otelGenCopy(source, target string) error { + if err := os.RemoveAll(target); err != nil { + return err + } + cmd := exec.Command("cp", "-R", source, target) + connectStd(cmd) + return cmd.Run() +} + // run tests func Test() error { cmd := exec.Command("go", "test", "-race", "./...") diff --git a/otel/README.md b/otel/README.md index 2c949012c..1c5f30203 100644 --- a/otel/README.md +++ b/otel/README.md @@ -44,14 +44,27 @@ The Go output, [`gen/go/semconv.go`](gen/go/semconv.go), is part of the protocol services import it directly: `semconv "github.com/livekit/protocol/otel/gen/go"`. It gives one constant per attribute key (`AttrLkRoomId`), enum value (`LkTrackSourceSourceCamera`), event (`EventLkRoomDisconnected`), span (`SpanLkConnect`), checkpoint and metric -(`MetricLkAgentsConnectionAcquireTime` and its `…Unit`), plus two alias maps built from the shared -keys' `renamed_from` annotations: -`RenamedKeys` (legacy key → canonical key) and `RenamedValues` (legacy key → legacy value → -canonical value, for the two enums whose values also changed). A consumer such as the collector -uses them to normalize an older capture to the canonical names. The legacy spellings are never -registered, so they appear only in these maps. `generate.sh` gofmts the file; `go tool mage otel`, -`.github/workflows/otel.yaml` and the Test workflow (`go test ./...`) build the package and run -`otel/gotest` to check the alias-map invariants. +(`MetricLkAgentsConnectionAcquireTime` and its `…Unit`), plus the legacy-key alias maps and reader +helpers built from the shared keys' `renamed_from` annotations: + +- `RenamedKeys` (legacy key → canonical key), covering the OTLP dotted rename and every + `renamed_from.aliases` entry (the pre-#7973 Agents span names and the Go logger / collector + spellings such as `roomID`, `room_id`). +- `RenamedValues` (legacy key → legacy value → canonical value, for the two enums whose values also + changed). +- `KeyAliases` (canonical key → its legacy spellings). +- `NormalizeKey(key) string` folds a legacy spelling onto its canonical key (or returns it + unchanged), `NormalizeValue(key, value) string` does the same for a renamed enum value, and + `AliasesFor(canonical) []string` expands a canonical key to `[canonical, …legacy]` for querying + historical data. The TypeScript output (`gen/ts/semconv.ts`, exported as + `@livekit/protocol/semconv`) mirrors these as `RENAMED_KEYS`, `RENAMED_VALUES`, `KEY_ALIASES`, + `normalizeKey`, `normalizeValue` and `aliasesFor`, so `livekit/web` uses the same source of truth. + +A consumer such as the collector uses them to normalize an older capture to the canonical names. +The legacy spellings are never registered, so they appear only in these maps. `generate.sh` gofmts +the file (with the go.mod toolchain's `gofmt`) and rejects a flat-namespace constant collision; +`go tool mage otel`, `.github/workflows/otel.yaml` and the Test workflow (`go test ./...`) build the +package and run `otel/gotest` to check the alias-map invariants. ## Ownership @@ -126,7 +139,7 @@ map, and its fields (such as `reason` in `outcome`) are payload, not attribute k | `unit_exception` | a reason | allows a `*_ms` key with `unit: ms` (the RTC stats keys: `lk.rtc.window_ms` as measured, the others converted from the W3C stats' seconds) | | `bindings` | map of producer/store → name | informational; live-check reads the Agents span name from `agents_otlp` | | `cardinality_exception` | `true`, on a metric | allows a high-cardinality ID as a metric dimension | - | `renamed_from` | `{key, values}`, on a shared key | the spelling it replaces, and for an enum a map of old value → member; the old key stays unregistered | + | `renamed_from` | `{key, aliases, values}`, on a shared key | the OTLP spelling it replaces (`key`), additional legacy spellings (`aliases`: the pre-#7973 Agents names and Go logger / collector spellings, any casing), and for an enum a map of old value → member; none of these are registered keys | | `pii_heuristic_exception` | a reason | documents a shipped key the PII heuristic would flag; it only takes effect for a key listed in `pii_heuristic_allowlist` in `policies/lib.rego` (today `lk.rpc.caller_identity`, `lk.rpc.destination_identity`), so a new key cannot opt out by annotating itself. The collector still does not redact them | Events and spans carry their own `annotations.livekit`, rendered in the docs; live-check @@ -151,6 +164,29 @@ map, and its fields (such as `reason` in `outcome`) are payload, not attribute k 5. Run `otel/check.sh`, then `go tool mage otel` (it runs `otel/generate.sh`), and commit `gen/` with the change. +## Migrating a key + +Renaming a telemetry key across the stack follows one lifecycle, with this registry as the single +source of truth for the legacy spellings. An emitter cannot rename a key in place, because readers +and historical data still carry the old one, so the spellings coexist for a while. + +1. **Declare.** Add the legacy spellings to the canonical key's `renamed_from` in `otel/model`: + `key` for the OTLP dotted rename (what live-check names) and `aliases` for the rest (Go logger / + collector spellings, pre-#7973 Agents names). Regenerate. The spellings never become registered + keys; they live only in the generated `RenamedKeys` / `KeyAliases` maps. +2. **Dual-emit.** The emitting service sends the canonical `lk.*` key alongside the legacy key + during rollout. It never renames in place. +3. **Ingest-normalize** (e.g. `cloud-observability`). On ingest, call `NormalizeKey` / + `normalizeKey` (and `NormalizeValue` / `normalizeValue` for renamed enum values) to fold legacy + keys onto canonical ones. When a record carries both during dual-emit, prefer the canonical key: + it is already canonical and `NormalizeKey` returns it unchanged. +4. **Query-expand** (e.g. `cloud-api-server`, `livekit/web`). To read historical ClickHouse / log + data or mixed payloads, call `AliasesFor` / `aliasesFor` to expand a canonical key to + `[canonical, …legacy]` and match any spelling. +5. **Retire.** Once no live data or query path carries a legacy spelling, drop it from + `renamed_from.aliases` (or the whole `renamed_from` when the OTLP rename is done too) and + regenerate. The spelling leaves the alias maps. + ## Versioning The registry is unversioned until a producer needs to emit `schema_url`. Weaver requires one, so @@ -186,7 +222,7 @@ otel/tests/negatives.sh # each negative fixture fails with its na go tool mage otel && git status otel/gen # regenerate (runs generate.sh, then go build + test); no diff expected otel/tests/live-check.sh # smoke and sparse samples clean, legacy keys flagged, wrapper exit status otel/tests/generate.sh # generate.sh replaces gen/ whole, and keeps it when a target fails -otel/tests/codegen.sh # a value with quotes, backslashes, newlines round-trips through rustc, tsc and python3 +otel/tests/codegen.sh # a value with quotes, backslashes, newlines round-trips through the Go toolchain, rustc, tsc and python3 rustc --edition 2021 --crate-type lib -D warnings -D missing_docs otel/gen/rust/semconv.rs --out-dir /tmp npx -p typescript@5.9.3 tsc --strict --noEmit --target es2020 otel/gen/ts/semconv.ts @@ -226,7 +262,9 @@ add to it: | `livekit_pii_marker` | yes | `sensitivity: pii` iff a `pii` key segment, except `chat.item`, which the collector drops by name (`pii_by_name` in `lib.rego`) | | `livekit_pii_heuristic` | yes | identity, email, phone, room/participant name outside `lk.pii.*`, unless the key is on the policy's `pii_heuristic_allowlist` and carries a `pii_heuristic_exception` reason | | `livekit_flat_identity` | yes | no `lk.room.sid`, `lk.participant.sid`, `lk.track.sid`, `lk.job.id`, and no `_sid` spelling (`lk.room_sid`, `lk.participant_sid`, `lk.track_sid`), deprecated or not (deprecated keys: resolved, both modes); pre-#7973 Agents names are historical bindings only | -| `livekit_shared_rename` | yes | no old spelling named in a `renamed_from` is defined, deprecated or not (resolved, both modes) | +| `livekit_shared_rename` | yes | no old spelling named in a `renamed_from` (the `key` or any `aliases` entry) is defined as a key, deprecated or not (resolved, both modes) | +| `livekit_alias_collision` | yes | no legacy spelling maps to more than one canonical key, so the reader helpers are unambiguous (resolved, both modes) | +| `livekit_alias_duplicate` | yes | a `renamed_from.aliases` entry does not repeat the key, `renamed_from.key` or another alias, which would be a duplicate key in the generated Go map and TypeScript object (resolved, both modes) | | `livekit_rename_value` | yes | every value a `renamed_from` maps to is a member of the shared key's enum | | `livekit_seconds`, `livekit_unit` | yes | seconds, unless `unit_exception` | | `livekit_metric_unit` | yes | metric units are not `ms` (resolved, so `definition/2` metrics and refinements count) | diff --git a/otel/gen/docs/semconv.md b/otel/gen/docs/semconv.md index f8ca07fa0..7a9738b30 100644 --- a/otel/gen/docs/semconv.md +++ b/otel/gen/docs/semconv.md @@ -838,7 +838,7 @@ Kind `client`. One LLM inference request, the OTel GenAI inference span. | Checkpoint | Requirement | Meaning | | --- | --- | --- | -| `gen_ai.client.inference.operation.details` | Best effort | OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced | +| `gen_ai.client.inference.operation.details` | Best effort | OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced, so it is named here). | No limits declared. @@ -1774,8 +1774,11 @@ historical names only: live-check does not exempt them from unregistered-attribu ## Old spellings Keys and values that producers sent before this registry, and the key and value to send instead. -Each row comes from `renamed_from` on the shared key. Live-check reports an old spelling as -`livekit_shared_rename` and names the replacement. +Each row comes from `renamed_from` on the shared key: the OTLP dotted rename (`key`) and any +`aliases` (the pre-#7973 Agents span names and the Go logger / collector spellings). The generated +reader helpers (`NormalizeKey`/`normalizeKey`, `AliasesFor`/`aliasesFor`) fold every spelling in +this table onto the canonical key; live-check reports only the dotted spelling as +`livekit_shared_rename`, since the alias spellings are not OTLP keys. | Old key | Old value | Key to send | Value to send | | --- | --- | --- | --- | @@ -1798,11 +1801,24 @@ Each row comes from `renamed_from` on the shared key. Live-check reports an old | `lk.disconnect.reason` | `user_rejected` | `lk.disconnect_reason` | `USER_REJECTED` | | `lk.disconnect.reason` | `user_unavailable` | `lk.disconnect_reason` | `USER_UNAVAILABLE` | | `lk.participant.sid` | any | `lk.participant_id` | unchanged | +| `lk.participant_sid` | any | `lk.participant_id` | unchanged | +| `participantID` | any | `lk.participant_id` | unchanged | +| `participant_id` | any | `lk.participant_id` | unchanged | | `lk.participant.identity` | any | `lk.pii.participant_identity` | unchanged | +| `participantIdentity` | any | `lk.pii.participant_identity` | unchanged | +| `participant_identity` | any | `lk.pii.participant_identity` | unchanged | | `lk.participant.remote_identity` | any | `lk.pii.remote_participant_identity` | unchanged | | `lk.room.name` | any | `lk.pii.room_name` | unchanged | +| `roomName` | any | `lk.pii.room_name` | unchanged | +| `room_name` | any | `lk.pii.room_name` | unchanged | | `lk.room.sid` | any | `lk.room_id` | unchanged | +| `lk.room_sid` | any | `lk.room_id` | unchanged | +| `roomID` | any | `lk.room_id` | unchanged | +| `room_id` | any | `lk.room_id` | unchanged | | `lk.track.sid` | any | `lk.track_id` | unchanged | +| `lk.track_sid` | any | `lk.track_id` | unchanged | +| `trackID` | any | `lk.track_id` | unchanged | +| `track_id` | any | `lk.track_id` | unchanged | | `lk.track.source` | `camera` | `lk.track_source` | `SOURCE_CAMERA` | | `lk.track.source` | `microphone` | `lk.track_source` | `SOURCE_MICROPHONE` | | `lk.track.source` | `screen_share` | `lk.track_source` | `SOURCE_SCREENSHARE` | diff --git a/otel/gen/go/semconv.go b/otel/gen/go/semconv.go index f86e5161d..7ef05140a 100644 --- a/otel/gen/go/semconv.go +++ b/otel/gen/go/semconv.go @@ -3,7 +3,8 @@ // Package semconv is the LiveKit telemetry semantic conventions as Go constants: the attribute // keys, enum values, event names, span names, checkpoints and metric names LiveKit producers send // over OTLP, and the legacy-key and legacy-value aliases a consumer uses to normalize an older -// capture to the canonical names (see RenamedKeys and RenamedValues). +// capture to the canonical names (see RenamedKeys, RenamedValues, KeyAliases and the NormalizeKey, +// AliasesFor and NormalizeValue helpers). package semconv // AttrAgentName is the "agent_name" attribute: The agent's name. @@ -1656,7 +1657,7 @@ const CheckpointFirstFrame = "first_frame" // CheckpointFirstMedia is the "first_media" checkpoint: The first inbound stats reading with bytes; the span ends ok here. const CheckpointFirstMedia = "first_media" -// CheckpointGenAiClientInferenceOperationDetails is the "gen_ai.client.inference.operation.details" checkpoint: OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced +// CheckpointGenAiClientInferenceOperationDetails is the "gen_ai.client.inference.operation.details" checkpoint: OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced, so it is named here). const CheckpointGenAiClientInferenceOperationDetails = "gen_ai.client.inference.operation.details" // CheckpointGeneration is the "generation" checkpoint: One generation started (the generation attributes). @@ -1799,49 +1800,49 @@ const MetricLkAgentsTurnTtsTtfb = "lk.agents.turn.tts_ttfb" // MetricLkAgentsTurnTtsTtfbUnit is the unit of MetricLkAgentsTurnTtsTtfb, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsTurnTtsTtfbUnit = "s" -// MetricLkAgentsUsageInterruptionNumRequests is the "lk.agents.usage.interruption_num_requests" metric: Interruption-detector requests. Instrument: counter, unit: “. +// MetricLkAgentsUsageInterruptionNumRequests is the "lk.agents.usage.interruption_num_requests" metric: Interruption-detector requests. Instrument: counter. const MetricLkAgentsUsageInterruptionNumRequests = "lk.agents.usage.interruption_num_requests" // MetricLkAgentsUsageInterruptionNumRequestsUnit is the unit of MetricLkAgentsUsageInterruptionNumRequests, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageInterruptionNumRequestsUnit = "" -// MetricLkAgentsUsageLlmInputAudioTokens is the "lk.agents.usage.llm_input_audio_tokens" metric: Realtime-model audio input tokens. Instrument: counter, unit: “. +// MetricLkAgentsUsageLlmInputAudioTokens is the "lk.agents.usage.llm_input_audio_tokens" metric: Realtime-model audio input tokens. Instrument: counter. const MetricLkAgentsUsageLlmInputAudioTokens = "lk.agents.usage.llm_input_audio_tokens" // MetricLkAgentsUsageLlmInputAudioTokensUnit is the unit of MetricLkAgentsUsageLlmInputAudioTokens, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageLlmInputAudioTokensUnit = "" -// MetricLkAgentsUsageLlmInputCachedTokens is the "lk.agents.usage.llm_input_cached_tokens" metric: LLM cached input tokens. Instrument: counter, unit: “. +// MetricLkAgentsUsageLlmInputCachedTokens is the "lk.agents.usage.llm_input_cached_tokens" metric: LLM cached input tokens. Instrument: counter. const MetricLkAgentsUsageLlmInputCachedTokens = "lk.agents.usage.llm_input_cached_tokens" // MetricLkAgentsUsageLlmInputCachedTokensUnit is the unit of MetricLkAgentsUsageLlmInputCachedTokens, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageLlmInputCachedTokensUnit = "" -// MetricLkAgentsUsageLlmInputTextTokens is the "lk.agents.usage.llm_input_text_tokens" metric: Realtime-model text input tokens. Instrument: counter, unit: “. +// MetricLkAgentsUsageLlmInputTextTokens is the "lk.agents.usage.llm_input_text_tokens" metric: Realtime-model text input tokens. Instrument: counter. const MetricLkAgentsUsageLlmInputTextTokens = "lk.agents.usage.llm_input_text_tokens" // MetricLkAgentsUsageLlmInputTextTokensUnit is the unit of MetricLkAgentsUsageLlmInputTextTokens, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageLlmInputTextTokensUnit = "" -// MetricLkAgentsUsageLlmInputTokens is the "lk.agents.usage.llm_input_tokens" metric: LLM input tokens. Instrument: counter, unit: “. +// MetricLkAgentsUsageLlmInputTokens is the "lk.agents.usage.llm_input_tokens" metric: LLM input tokens. Instrument: counter. const MetricLkAgentsUsageLlmInputTokens = "lk.agents.usage.llm_input_tokens" // MetricLkAgentsUsageLlmInputTokensUnit is the unit of MetricLkAgentsUsageLlmInputTokens, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageLlmInputTokensUnit = "" -// MetricLkAgentsUsageLlmOutputAudioTokens is the "lk.agents.usage.llm_output_audio_tokens" metric: Realtime-model audio output tokens. Instrument: counter, unit: “. +// MetricLkAgentsUsageLlmOutputAudioTokens is the "lk.agents.usage.llm_output_audio_tokens" metric: Realtime-model audio output tokens. Instrument: counter. const MetricLkAgentsUsageLlmOutputAudioTokens = "lk.agents.usage.llm_output_audio_tokens" // MetricLkAgentsUsageLlmOutputAudioTokensUnit is the unit of MetricLkAgentsUsageLlmOutputAudioTokens, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageLlmOutputAudioTokensUnit = "" -// MetricLkAgentsUsageLlmOutputTextTokens is the "lk.agents.usage.llm_output_text_tokens" metric: Realtime-model text output tokens. Instrument: counter, unit: “. +// MetricLkAgentsUsageLlmOutputTextTokens is the "lk.agents.usage.llm_output_text_tokens" metric: Realtime-model text output tokens. Instrument: counter. const MetricLkAgentsUsageLlmOutputTextTokens = "lk.agents.usage.llm_output_text_tokens" // MetricLkAgentsUsageLlmOutputTextTokensUnit is the unit of MetricLkAgentsUsageLlmOutputTextTokens, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageLlmOutputTextTokensUnit = "" -// MetricLkAgentsUsageLlmOutputTokens is the "lk.agents.usage.llm_output_tokens" metric: LLM output tokens. Instrument: counter, unit: “. +// MetricLkAgentsUsageLlmOutputTokens is the "lk.agents.usage.llm_output_tokens" metric: LLM output tokens. Instrument: counter. const MetricLkAgentsUsageLlmOutputTokens = "lk.agents.usage.llm_output_tokens" // MetricLkAgentsUsageLlmOutputTokensUnit is the unit of MetricLkAgentsUsageLlmOutputTokens, exactly as the producer creates the instrument (empty = none). @@ -1865,27 +1866,84 @@ const MetricLkAgentsUsageTtsAudioDuration = "lk.agents.usage.tts_audio_duration" // MetricLkAgentsUsageTtsAudioDurationUnit is the unit of MetricLkAgentsUsageTtsAudioDuration, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageTtsAudioDurationUnit = "s" -// MetricLkAgentsUsageTtsCharacters is the "lk.agents.usage.tts_characters" metric: Characters synthesized. Instrument: counter, unit: “. +// MetricLkAgentsUsageTtsCharacters is the "lk.agents.usage.tts_characters" metric: Characters synthesized. Instrument: counter. const MetricLkAgentsUsageTtsCharacters = "lk.agents.usage.tts_characters" // MetricLkAgentsUsageTtsCharactersUnit is the unit of MetricLkAgentsUsageTtsCharacters, exactly as the producer creates the instrument (empty = none). const MetricLkAgentsUsageTtsCharactersUnit = "" // RenamedKeys maps a legacy attribute key to the canonical key that replaces it, from the -// `renamed_from` annotations on the shared keys. A consumer (such as the collector) uses it to -// normalize a legacy key read from an older capture to the key this registry defines. The legacy -// keys are never registered, so they appear only here. +// `renamed_from` annotations on the shared keys: the OTLP dotted rename and every `aliases` entry +// (the pre-#7973 Agents span names and the Go logger / collector spellings). A consumer (such as +// the collector) uses it, via NormalizeKey, to fold a legacy key read from an older capture onto +// the key this registry defines. The legacy keys are never registered, so they appear only here. var RenamedKeys = map[string]string{ "lk.disconnect.reason": "lk.disconnect_reason", "lk.participant.sid": "lk.participant_id", + "lk.participant_sid": "lk.participant_id", + "participantID": "lk.participant_id", + "participant_id": "lk.participant_id", "lk.participant.identity": "lk.pii.participant_identity", + "participantIdentity": "lk.pii.participant_identity", + "participant_identity": "lk.pii.participant_identity", "lk.participant.remote_identity": "lk.pii.remote_participant_identity", "lk.room.name": "lk.pii.room_name", + "roomName": "lk.pii.room_name", + "room_name": "lk.pii.room_name", "lk.room.sid": "lk.room_id", + "lk.room_sid": "lk.room_id", + "roomID": "lk.room_id", + "room_id": "lk.room_id", "lk.track.sid": "lk.track_id", + "lk.track_sid": "lk.track_id", + "trackID": "lk.track_id", + "track_id": "lk.track_id", "lk.track.source": "lk.track_source", } +// KeyAliases maps a canonical key to its legacy spellings, the OTLP dotted rename first and then +// the `aliases`. AliasesFor reads it to expand a canonical key to every spelling older captures +// used, for querying historical ClickHouse/log data or reading mixed payloads. +var KeyAliases = map[string][]string{ + "lk.disconnect_reason": { + "lk.disconnect.reason", + }, + "lk.participant_id": { + "lk.participant.sid", + "lk.participant_sid", + "participantID", + "participant_id", + }, + "lk.pii.participant_identity": { + "lk.participant.identity", + "participantIdentity", + "participant_identity", + }, + "lk.pii.remote_participant_identity": { + "lk.participant.remote_identity", + }, + "lk.pii.room_name": { + "lk.room.name", + "roomName", + "room_name", + }, + "lk.room_id": { + "lk.room.sid", + "lk.room_sid", + "roomID", + "room_id", + }, + "lk.track_id": { + "lk.track.sid", + "lk.track_sid", + "trackID", + "track_id", + }, + "lk.track_source": { + "lk.track.source", + }, +} + // RenamedValues maps a legacy attribute key to its legacy-value -> canonical-value mapping, for the // shared keys whose enum values were also renamed. A renamed key whose values did not change is // absent here; look it up in RenamedKeys only. @@ -1918,3 +1976,35 @@ var RenamedValues = map[string]map[string]string{ "unknown": "SOURCE_UNKNOWN", }, } + +// NormalizeKey returns the canonical key for a legacy spelling, or key unchanged when it is not a +// known legacy spelling. A reader calls it on ingest to fold legacy keys onto canonical ones. +// During dual-emit a record may carry both: the canonical key is already canonical and returns +// unchanged, so prefer it over the result of normalizing the legacy key. +func NormalizeKey(key string) string { + if canonical, ok := RenamedKeys[key]; ok { + return canonical + } + return key +} + +// AliasesFor returns the canonical key followed by its legacy spellings, for querying historical +// data that may carry either. A key with no recorded legacy spelling yields just itself. +func AliasesFor(canonical string) []string { + aliases := KeyAliases[canonical] + out := make([]string, 0, 1+len(aliases)) + out = append(out, canonical) + return append(out, aliases...) +} + +// NormalizeValue returns the canonical value for a legacy value under a legacy key, or value +// unchanged. Pass the legacy key as read from the capture, not the canonical key; only the shared +// keys whose enum values were renamed have value mappings. +func NormalizeValue(key, value string) string { + if values, ok := RenamedValues[key]; ok { + if canonical, ok := values[value]; ok { + return canonical + } + } + return value +} diff --git a/otel/gen/python/semconv.py b/otel/gen/python/semconv.py index 76a8fc1c1..b5798ee18 100644 --- a/otel/gen/python/semconv.py +++ b/otel/gen/python/semconv.py @@ -1566,7 +1566,7 @@ class TelemetrySdkLanguage: CHECKPOINT_FIRST_FRAME = "first_frame" #: The first inbound stats reading with bytes; the span ends ok here. CHECKPOINT_FIRST_MEDIA = "first_media" -#: OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced +#: OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced, so it is named here). CHECKPOINT_GEN_AI_CLIENT_INFERENCE_OPERATION_DETAILS = "gen_ai.client.inference.operation.details" #: One generation started (the generation attributes). CHECKPOINT_GENERATION = "generation" diff --git a/otel/gen/rust/semconv.rs b/otel/gen/rust/semconv.rs index 7ad3e3420..1433b292d 100644 --- a/otel/gen/rust/semconv.rs +++ b/otel/gen/rust/semconv.rs @@ -1466,7 +1466,7 @@ pub mod checkpoint { pub const FIRST_FRAME: &str = "first_frame"; /// The first inbound stats reading with bytes; the span ends ok here. pub const FIRST_MEDIA: &str = "first_media"; - /// OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced + /// OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced, so it is named here). pub const GEN_AI_CLIENT_INFERENCE_OPERATION_DETAILS: &str = "gen_ai.client.inference.operation.details"; /// One generation started (the generation attributes). pub const GENERATION: &str = "generation"; diff --git a/otel/gen/ts/semconv.ts b/otel/gen/ts/semconv.ts index 46450539c..9e99e513c 100644 --- a/otel/gen/ts/semconv.ts +++ b/otel/gen/ts/semconv.ts @@ -1174,7 +1174,7 @@ export const CHECKPOINT_EXCEPTION = "exception" as const; export const CHECKPOINT_FIRST_FRAME = "first_frame" as const; /** Checkpoint (span event): The first inbound stats reading with bytes; the span ends ok here. */ export const CHECKPOINT_FIRST_MEDIA = "first_media" as const; -/** Checkpoint (span event): OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced */ +/** Checkpoint (span event): OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced, so it is named here). */ export const CHECKPOINT_GEN_AI_CLIENT_INFERENCE_OPERATION_DETAILS = "gen_ai.client.inference.operation.details" as const; /** Checkpoint (span event): One generation started (the generation attributes). */ export const CHECKPOINT_GENERATION = "generation" as const; @@ -1299,3 +1299,116 @@ export const METRIC_LK_AGENTS_USAGE_TTS_AUDIO_DURATION = "lk.agents.usage.tts_au /** Characters synthesized. Instrument: counter, unit: ``. */ export const METRIC_LK_AGENTS_USAGE_TTS_CHARACTERS = "lk.agents.usage.tts_characters" as const; + +/** + * Maps a legacy attribute key to the canonical key that replaces it, from the `renamed_from` + * annotations on the shared keys: the OTLP dotted rename and every `aliases` entry. The same source + * of truth as the Go semconv's RenamedKeys. Use {@link normalizeKey} to fold a legacy key read from + * an older capture onto the key this registry defines. + */ +export const RENAMED_KEYS: Record = { + "lk.disconnect.reason": "lk.disconnect_reason", + "lk.participant.sid": "lk.participant_id", + "lk.participant_sid": "lk.participant_id", + "participantID": "lk.participant_id", + "participant_id": "lk.participant_id", + "lk.participant.identity": "lk.pii.participant_identity", + "participantIdentity": "lk.pii.participant_identity", + "participant_identity": "lk.pii.participant_identity", + "lk.participant.remote_identity": "lk.pii.remote_participant_identity", + "lk.room.name": "lk.pii.room_name", + "roomName": "lk.pii.room_name", + "room_name": "lk.pii.room_name", + "lk.room.sid": "lk.room_id", + "lk.room_sid": "lk.room_id", + "roomID": "lk.room_id", + "room_id": "lk.room_id", + "lk.track.sid": "lk.track_id", + "lk.track_sid": "lk.track_id", + "trackID": "lk.track_id", + "track_id": "lk.track_id", + "lk.track.source": "lk.track_source", +}; + +/** + * Maps a legacy attribute key to its legacy-value -> canonical-value mapping, for the shared keys + * whose enum values were also renamed. A renamed key whose values did not change is absent here. + */ +export const RENAMED_VALUES: Record> = { + "lk.disconnect.reason": { + "agent_error": "AGENT_ERROR", + "client_initiated": "CLIENT_INITIATED", + "connection_timeout": "CONNECTION_TIMEOUT", + "duplicate_identity": "DUPLICATE_IDENTITY", + "join_failure": "JOIN_FAILURE", + "media_failure": "MEDIA_FAILURE", + "migration": "MIGRATION", + "participant_removed": "PARTICIPANT_REMOVED", + "reconnect_failed": "RECONNECT_FAILED", + "room_closed": "ROOM_CLOSED", + "room_deleted": "ROOM_DELETED", + "server_shutdown": "SERVER_SHUTDOWN", + "signal_close": "SIGNAL_CLOSE", + "sip_trunk_failure": "SIP_TRUNK_FAILURE", + "state_mismatch": "STATE_MISMATCH", + "unknown": "UNKNOWN_REASON", + "user_rejected": "USER_REJECTED", + "user_unavailable": "USER_UNAVAILABLE", + }, + "lk.track.source": { + "camera": "SOURCE_CAMERA", + "microphone": "SOURCE_MICROPHONE", + "screen_share": "SOURCE_SCREENSHARE", + "screen_share_audio": "SOURCE_SCREENSHARE_AUDIO", + "unknown": "SOURCE_UNKNOWN", + }, +}; + +/** + * Maps a canonical key to its legacy spellings, the OTLP dotted rename first and then the + * `aliases`. {@link aliasesFor} reads it to expand a canonical key for querying historical data. + */ +export const KEY_ALIASES: Record = { + "lk.disconnect_reason": ["lk.disconnect.reason"], + "lk.participant_id": ["lk.participant.sid", "lk.participant_sid", "participantID", "participant_id"], + "lk.pii.participant_identity": ["lk.participant.identity", "participantIdentity", "participant_identity"], + "lk.pii.remote_participant_identity": ["lk.participant.remote_identity"], + "lk.pii.room_name": ["lk.room.name", "roomName", "room_name"], + "lk.room_id": ["lk.room.sid", "lk.room_sid", "roomID", "room_id"], + "lk.track_id": ["lk.track.sid", "lk.track_sid", "trackID", "track_id"], + "lk.track_source": ["lk.track.source"], +}; + +/** + * Own-property lookup, so a key such as `constructor` or `toString` read from a capture never + * resolves to an Object.prototype member of the alias maps. + */ +function own(map: Record, key: string): T | undefined { + return Object.prototype.hasOwnProperty.call(map, key) ? map[key] : undefined; +} + +/** + * Returns the canonical key for a legacy spelling, or `key` unchanged when it is not a known legacy + * spelling. During dual-emit a record may carry both; the canonical key is already canonical and + * returns unchanged, so prefer it over the result of normalizing the legacy key. + */ +export function normalizeKey(key: string): string { + return own(RENAMED_KEYS, key) ?? key; +} + +/** + * Returns the canonical key followed by its legacy spellings, for querying historical data that may + * carry either. A key with no recorded legacy spelling yields just itself. + */ +export function aliasesFor(canonical: string): string[] { + return [canonical, ...(own(KEY_ALIASES, canonical) ?? [])]; +} + +/** + * Returns the canonical value for a legacy value under a legacy key, or `value` unchanged. Pass the + * legacy key as read from the capture, not the canonical key. + */ +export function normalizeValue(key: string, value: string): string { + const values = own(RENAMED_VALUES, key); + return (values && own(values, value)) ?? value; +} \ No newline at end of file diff --git a/otel/generate.sh b/otel/generate.sh index 8e5d0d28f..782e89eed 100755 --- a/otel/generate.sh +++ b/otel/generate.sh @@ -13,5 +13,17 @@ done # The Go output is gofmt-canonical, so the committed file matches `gofmt`/`go fmt` and stays # diff-stable. weaver emits unaligned const and map literals that gofmt would otherwise rewrite; # the other targets need no such pass. gofmt fails loudly on a template that emits invalid Go. -gofmt -w "$tmp/gen/go" +# Use the go.mod toolchain's gofmt (`$(go env GOROOT)/bin/gofmt`), not whatever bare gofmt is on +# PATH, so formatting matches the Go version CI builds and tests the generated package with. +"$(go env GOROOT)/bin/gofmt" -w "$tmp/gen/go" +# Go has no namespaces: every attribute key, enum value, event, span, checkpoint and metric becomes +# a top-level constant, where Rust and Python keep them apart in modules and classes. Two that +# generate the same identifier are a redeclaration; `go build` rejects it, but catch it here with +# the offending name, so a model addition cannot slip a silent flat-namespace collision past review. +dupes=$(grep -hoE '^const [A-Za-z0-9_]+' "$tmp/gen/go/semconv.go" | awk '{print $2}' | sort | uniq -d || true) +if [[ -n $dupes ]]; then + echo "generate.sh: generated Go has duplicate top-level constants (flat-namespace collision):" >&2 + echo "$dupes" >&2 + exit 1 +fi rm -rf gen && mv "$tmp/gen" gen diff --git a/otel/gotest/semconv_test.go b/otel/gotest/semconv_test.go index 36bb5aead..e2b276d6f 100644 --- a/otel/gotest/semconv_test.go +++ b/otel/gotest/semconv_test.go @@ -55,9 +55,11 @@ func TestConstants(t *testing.T) { } } -// TestRenamedKeys checks the legacy-key alias map against the eight documented client renames, and -// its structural invariants: a legacy key is never empty, maps to a non-empty canonical key, and is -// never equal to its own canonical key (a rename changes the spelling). +// TestRenamedKeys checks the legacy-key alias map against the eight documented OTLP client renames +// as a subset (the map now also carries the pre-#7973 Agents span names and the Go logger / +// collector spellings as aliases), and its structural invariants: a legacy key is never empty, maps +// to a non-empty canonical key, and is never equal to its own canonical key (a rename changes the +// spelling). func TestRenamedKeys(t *testing.T) { want := map[string]string{ "lk.room.sid": semconv.AttrLkRoomId, @@ -69,9 +71,6 @@ func TestRenamedKeys(t *testing.T) { "lk.track.source": semconv.AttrLkTrackSource, "lk.disconnect.reason": semconv.AttrLkDisconnectReason, } - if len(semconv.RenamedKeys) != len(want) { - t.Fatalf("RenamedKeys has %d entries, want %d: %v", len(semconv.RenamedKeys), len(want), semconv.RenamedKeys) - } for legacy, canonical := range want { got, ok := semconv.RenamedKeys[legacy] if !ok { @@ -92,6 +91,86 @@ func TestRenamedKeys(t *testing.T) { } } +// TestKeyAliases checks the canonical-to-aliases map and its cross-map invariants: every canonical +// key is a registered attribute, every alias maps back to that canonical in RenamedKeys, an alias +// is never a canonical key itself, and the two maps agree (RenamedKeys has one entry per alias +// across all KeyAliases lists). +func TestKeyAliases(t *testing.T) { + registered := map[string]bool{ + semconv.AttrLkRoomId: true, + semconv.AttrLkParticipantId: true, + semconv.AttrLkTrackId: true, + semconv.AttrLkPiiRoomName: true, + semconv.AttrLkPiiParticipantIdentity: true, + semconv.AttrLkPiiRemoteParticipantIdentity: true, + semconv.AttrLkTrackSource: true, + semconv.AttrLkDisconnectReason: true, + } + aliasCount := 0 + for canonical, aliases := range semconv.KeyAliases { + if !registered[canonical] { + t.Errorf("KeyAliases has canonical key %q that is not a registered attribute", canonical) + } + for _, alias := range aliases { + aliasCount++ + if alias == canonical { + t.Errorf("KeyAliases[%q] lists the canonical key as its own alias", canonical) + } + if got := semconv.RenamedKeys[alias]; got != canonical { + t.Errorf("KeyAliases[%q] has alias %q, but RenamedKeys[%q] = %q", canonical, alias, alias, got) + } + if _, ok := semconv.KeyAliases[alias]; ok { + t.Errorf("alias %q is also a canonical key in KeyAliases", alias) + } + } + } + if aliasCount != len(semconv.RenamedKeys) { + t.Errorf("KeyAliases lists %d aliases, RenamedKeys has %d entries; they must match", aliasCount, len(semconv.RenamedKeys)) + } +} + +// TestNormalizeKey checks that a legacy spelling folds onto its canonical key, an unknown key is +// returned unchanged, and a canonical key is already canonical. +func TestNormalizeKey(t *testing.T) { + cases := map[string]string{ + "roomID": semconv.AttrLkRoomId, + "room_id": semconv.AttrLkRoomId, + "lk.room.sid": semconv.AttrLkRoomId, + "participantID": semconv.AttrLkParticipantId, + semconv.AttrLkRoomId: semconv.AttrLkRoomId, + "app.custom.key": "app.custom.key", + } + for key, want := range cases { + if got := semconv.NormalizeKey(key); got != want { + t.Errorf("NormalizeKey(%q) = %q, want %q", key, got, want) + } + } +} + +// TestAliasesFor checks that the canonical key comes first, its aliases follow, and a key with no +// recorded legacy spelling yields just itself. +func TestAliasesFor(t *testing.T) { + got := semconv.AliasesFor(semconv.AttrLkRoomId) + if len(got) == 0 || got[0] != semconv.AttrLkRoomId { + t.Fatalf("AliasesFor(%q) = %v, want canonical first", semconv.AttrLkRoomId, got) + } + found := false + for _, a := range got[1:] { + if a == "roomID" { + found = true + } + if a == semconv.AttrLkRoomId { + t.Errorf("AliasesFor(%q) repeats the canonical key", semconv.AttrLkRoomId) + } + } + if !found { + t.Errorf("AliasesFor(%q) = %v, missing alias roomID", semconv.AttrLkRoomId, got) + } + if got := semconv.AliasesFor("app.custom.key"); len(got) != 1 || got[0] != "app.custom.key" { + t.Errorf("AliasesFor(%q) = %v, want just itself", "app.custom.key", got) + } +} + // TestRenamedValues checks the two enums whose values were also renamed, and that every key in // RenamedValues is also in RenamedKeys (a value remapping implies a key remapping). func TestRenamedValues(t *testing.T) { @@ -110,3 +189,20 @@ func TestRenamedValues(t *testing.T) { } } } + +// TestNormalizeValue checks that a legacy value under a legacy key folds onto its canonical value, +// and an unmapped key or value is returned unchanged. +func TestNormalizeValue(t *testing.T) { + if got := semconv.NormalizeValue("lk.track.source", "camera"); got != semconv.LkTrackSourceSourceCamera { + t.Errorf("NormalizeValue(track.source, camera) = %q, want %q", got, semconv.LkTrackSourceSourceCamera) + } + if got := semconv.NormalizeValue("lk.disconnect.reason", "client_initiated"); got != semconv.LkDisconnectReasonClientInitiated { + t.Errorf("NormalizeValue(disconnect.reason, client_initiated) = %q, want %q", got, semconv.LkDisconnectReasonClientInitiated) + } + if got := semconv.NormalizeValue("lk.track.source", "SOURCE_CAMERA"); got != "SOURCE_CAMERA" { + t.Errorf("NormalizeValue of an already-canonical value = %q, want unchanged", got) + } + if got := semconv.NormalizeValue("lk.room.sid", "RM_abc"); got != "RM_abc" { + t.Errorf("NormalizeValue of a key with no value map = %q, want unchanged", got) + } +} diff --git a/otel/model/agents/signals.yaml b/otel/model/agents/signals.yaml index 3386b0541..2db96984e 100644 --- a/otel/model/agents/signals.yaml +++ b/otel/model/agents/signals.yaml @@ -600,7 +600,7 @@ groups: annotations: livekit: checkpoints: - - {name: gen_ai.client.inference.operation.details, requirement: best_effort, brief: OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced, so it is named here).} + - {name: gen_ai.client.inference.operation.details, requirement: best_effort, brief: "OTel GenAI inference details event (the GenAI registry defines it; events cannot be referenced, so it is named here)."} attributes: - ref: lk.retry_count requirement_level: recommended diff --git a/otel/model/shared/registry.yaml b/otel/model/shared/registry.yaml index db03e2fa7..d48527bcd 100644 --- a/otel/model/shared/registry.yaml +++ b/otel/model/shared/registry.yaml @@ -24,7 +24,11 @@ groups: owner: shared sensitivity: none authority: cloud - renamed_from: {key: lk.room.sid} + renamed_from: + key: lk.room.sid + # Legacy spellings beyond the OTLP rename above, normalized to lk.room_id by the + # reader helpers: the pre-#7973 Agents span name and the Go logger / collector names. + aliases: [lk.room_sid, roomID, room_id] # Physical name per producer/store. Weaver carries these; nothing validates them. bindings: agents_otlp: lk.room_id # canonical-only after livekit/agents#7973, all signals @@ -41,7 +45,14 @@ groups: never a default metric dimension. examples: ["PA_9kLm2NpQ4rTs"] annotations: - livekit: {owner: shared, sensitivity: none, authority: cloud, renamed_from: {key: lk.participant.sid}, bindings: {event_logs: participantID}} + livekit: + owner: shared + sensitivity: none + authority: cloud + renamed_from: + key: lk.participant.sid + aliases: [lk.participant_sid, participantID, participant_id] + bindings: {event_logs: participantID} - id: lk.track_id type: string stability: development @@ -55,7 +66,9 @@ groups: owner: shared sensitivity: none authority: cloud - renamed_from: {key: lk.track.sid} + renamed_from: + key: lk.track.sid + aliases: [lk.track_sid, trackID, track_id] bindings: agents_otlp: lk.track_id # canonical-only after livekit/agents#7973 agents_otlp_before_7973: lk.track_sid # historical spans @@ -95,7 +108,7 @@ groups: On every record and span of a session once the client has joined. examples: ["my-room"] annotations: - livekit: {owner: shared, sensitivity: pii, renamed_from: {key: lk.room.name}} + livekit: {owner: shared, sensitivity: pii, renamed_from: {key: lk.room.name, aliases: [roomName, room_name]}} - id: lk.pii.participant_identity type: string stability: development @@ -104,7 +117,7 @@ groups: On every record and span of a session once the client has joined. examples: ["identity-0"] annotations: - livekit: {owner: shared, sensitivity: pii, renamed_from: {key: lk.participant.identity}} + livekit: {owner: shared, sensitivity: pii, renamed_from: {key: lk.participant.identity, aliases: [participantIdentity, participant_identity]}} - id: lk.pii.remote_participant_identity type: string stability: development diff --git a/otel/policies/resolved.rego b/otel/policies/resolved.rego index 0b2f24218..5a0db0b10 100644 --- a/otel/policies/resolved.rego +++ b/otel/policies/resolved.rego @@ -25,16 +25,51 @@ attributes contains {"key": a.key, "attr": a} if { some a in object.get(input, ["registry", "attributes"], []) } -renamed_to[old] := a.key if { +# Every legacy spelling a shared key replaces, paired with its canonical key: the OTLP dotted +# `renamed_from.key` and each `renamed_from.aliases` entry (the pre-#7973 Agents span names and the +# Go logger / collector spellings). A set of pairs, not a map, so a spelling claimed by two keys is +# a reportable collision rather than a Rego object-key conflict. +renamed_pairs contains {"old": a.attr.annotations.livekit.renamed_from.key, "new": a.key} if { some a in attributes - old := data.livekit.lib.lk(a.attr, "renamed_from").key + data.livekit.lib.lk(a.attr, "renamed_from") != null } -# An old spelling stays unregistered, deprecated or not: the rename lives on the shared key. +renamed_pairs contains {"old": old, "new": a.key} if { + some a in attributes + some old in object.get(a.attr, ["annotations", "livekit", "renamed_from", "aliases"], []) +} + +# An old spelling stays unregistered, deprecated or not: the rename lives on the shared key. This +# covers the dotted rename and every alias. deny contains data.livekit.lib.finding("livekit_shared_rename", msg) if { some a in attributes - new := renamed_to[a.key] - msg := sprintf("%s: renamed to %s (renamed_from on %s); the old spelling may not be defined, deprecated or not", [a.key, new, new]) + some p in renamed_pairs + a.key == p.old + msg := sprintf("%s: renamed to %s (renamed_from on %s); the old spelling may not be defined, deprecated or not", [a.key, p.new, p.new]) +} + +# A legacy spelling must normalize to exactly one canonical key, so the reader helpers are +# unambiguous. Two shared keys claiming the same old spelling is a hard error. +deny contains data.livekit.lib.finding("livekit_alias_collision", msg) if { + some p in renamed_pairs + some q in renamed_pairs + p.old == q.old + p.new < q.new + msg := sprintf("%s: legacy spelling maps to both %s and %s; a legacy key normalizes to one canonical key", [p.old, p.new, q.new]) +} + +# Each spelling in a key's `renamed_from` appears once: an alias that repeats `renamed_from.key`, +# repeats another alias or is the key itself would be a duplicate key in the generated Go map and +# TypeScript object literals (a compile error in both), and the set of pairs above hides it. +deny contains data.livekit.lib.finding("livekit_alias_duplicate", msg) if { + some a in attributes + from := data.livekit.lib.lk(a.attr, "renamed_from") + from != null + aliases := object.get(from, "aliases", []) + spellings := array.concat([a.key, from.key], aliases) + some alias in aliases + count([s | some s in spellings; s == alias]) > 1 + msg := sprintf("%s: renamed_from alias %s repeats the key, renamed_from.key or another alias", [a.key, alias]) } # The attribute rules skip deprecated keys, but a spelling the flat-identity rule forbids (a dotted diff --git a/otel/templates/registry/go/semconv.go.j2 b/otel/templates/registry/go/semconv.go.j2 index b1cae56f2..251b66fde 100644 --- a/otel/templates/registry/go/semconv.go.j2 +++ b/otel/templates/registry/go/semconv.go.j2 @@ -29,7 +29,8 @@ const {{ a.key | pascal_case }}{{ v.id | pascal_case }} = {{ lit(v.value) }} // Package semconv is the LiveKit telemetry semantic conventions as Go constants: the attribute // keys, enum values, event names, span names, checkpoints and metric names LiveKit producers send // over OTLP, and the legacy-key and legacy-value aliases a consumer uses to normalize an older -// capture to the canonical names (see RenamedKeys and RenamedValues). +// capture to the canonical names (see RenamedKeys, RenamedValues, KeyAliases and the NormalizeKey, +// AliasesFor and NormalizeValue helpers). package semconv {% for a in ctx.attributes %} @@ -40,7 +41,7 @@ package semconv {{ attr(a) }}{% endfor %}{% if ctx.upstream_metrics %} // Upstream metrics that LiveKit producers create, imported from the registry's dependencies. {% for m in ctx.upstream_metrics %} -// Metric{{ m.name | pascal_case }} is the {{ lit(m.name) }} metric: {{ line(m.brief) }} Instrument: {{ m.instrument }}, unit: `{{ line(m.unit or "") }}`. +// Metric{{ m.name | pascal_case }} is the {{ lit(m.name) }} metric: {{ line(m.brief) }} Instrument: {{ m.instrument }}{% if m.unit %}, unit: `{{ line(m.unit) }}`{% endif %}. const Metric{{ m.name | pascal_case }} = {{ lit(m.name) }} // Metric{{ m.name | pascal_case }}Unit is the unit of Metric{{ m.name | pascal_case }}, as the upstream definition gives it (empty = none). @@ -64,18 +65,30 @@ const Checkpoint{{ c.name | pascal_case }} = {{ lit(c.name) }} {% endfor %}{% if ctx.metrics %} // Metric names. {% for m in ctx.metrics %} -// Metric{{ m.name | pascal_case }} is the {{ lit(m.name) }} metric: {{ line(m.brief) }} Instrument: {{ m.instrument }}, unit: `{{ line(m.unit or "") }}`. +// Metric{{ m.name | pascal_case }} is the {{ lit(m.name) }} metric: {{ line(m.brief) }} Instrument: {{ m.instrument }}{% if m.unit %}, unit: `{{ line(m.unit) }}`{% endif %}. const Metric{{ m.name | pascal_case }} = {{ lit(m.name) }} // Metric{{ m.name | pascal_case }}Unit is the unit of Metric{{ m.name | pascal_case }}, exactly as the producer creates the instrument (empty = none). const Metric{{ m.name | pascal_case }}Unit = {{ lit(m.unit or "") }} {% endfor %}{% endif %} // RenamedKeys maps a legacy attribute key to the canonical key that replaces it, from the -// `renamed_from` annotations on the shared keys. A consumer (such as the collector) uses it to -// normalize a legacy key read from an older capture to the key this registry defines. The legacy -// keys are never registered, so they appear only here. +// `renamed_from` annotations on the shared keys: the OTLP dotted rename and every `aliases` entry +// (the pre-#7973 Agents span names and the Go logger / collector spellings). A consumer (such as +// the collector) uses it, via NormalizeKey, to fold a legacy key read from an older capture onto +// the key this registry defines. The legacy keys are never registered, so they appear only here. var RenamedKeys = map[string]string{ {% for a in ctx.attributes %}{% set from = a.annotations.livekit.renamed_from %}{% if from %} {{ lit(from.key) }}: {{ lit(a.key) }}, +{% for alias in from.aliases or [] %} {{ lit(alias) }}: {{ lit(a.key) }}, +{% endfor %}{% endif %}{% endfor %}} + +// KeyAliases maps a canonical key to its legacy spellings, the OTLP dotted rename first and then +// the `aliases`. AliasesFor reads it to expand a canonical key to every spelling older captures +// used, for querying historical ClickHouse/log data or reading mixed payloads. +var KeyAliases = map[string][]string{ +{% for a in ctx.attributes %}{% set from = a.annotations.livekit.renamed_from %}{% if from %} {{ lit(a.key) }}: { + {{ lit(from.key) }}, +{% for alias in from.aliases or [] %} {{ lit(alias) }}, +{% endfor %} }, {% endif %}{% endfor %}} // RenamedValues maps a legacy attribute key to its legacy-value -> canonical-value mapping, for the @@ -86,3 +99,35 @@ var RenamedValues = map[string]map[string]string{ {% for old, new in from["values"] | items %} {{ lit(old) }}: {{ lit(new) }}, {% endfor %} }, {% endif %}{% endfor %}} + +// NormalizeKey returns the canonical key for a legacy spelling, or key unchanged when it is not a +// known legacy spelling. A reader calls it on ingest to fold legacy keys onto canonical ones. +// During dual-emit a record may carry both: the canonical key is already canonical and returns +// unchanged, so prefer it over the result of normalizing the legacy key. +func NormalizeKey(key string) string { + if canonical, ok := RenamedKeys[key]; ok { + return canonical + } + return key +} + +// AliasesFor returns the canonical key followed by its legacy spellings, for querying historical +// data that may carry either. A key with no recorded legacy spelling yields just itself. +func AliasesFor(canonical string) []string { + aliases := KeyAliases[canonical] + out := make([]string, 0, 1+len(aliases)) + out = append(out, canonical) + return append(out, aliases...) +} + +// NormalizeValue returns the canonical value for a legacy value under a legacy key, or value +// unchanged. Pass the legacy key as read from the capture, not the canonical key; only the shared +// keys whose enum values were renamed have value mappings. +func NormalizeValue(key, value string) string { + if values, ok := RenamedValues[key]; ok { + if canonical, ok := values[value]; ok { + return canonical + } + } + return value +} diff --git a/otel/templates/registry/markdown/semconv.md.j2 b/otel/templates/registry/markdown/semconv.md.j2 index c39897fce..08c29468a 100644 --- a/otel/templates/registry/markdown/semconv.md.j2 +++ b/otel/templates/registry/markdown/semconv.md.j2 @@ -205,11 +205,15 @@ historical names only: live-check does not exempt them from unregistered-attribu ## Old spellings Keys and values that producers sent before this registry, and the key and value to send instead. -Each row comes from `renamed_from` on the shared key. Live-check reports an old spelling as -`livekit_shared_rename` and names the replacement. +Each row comes from `renamed_from` on the shared key: the OTLP dotted rename (`key`) and any +`aliases` (the pre-#7973 Agents span names and the Go logger / collector spellings). The generated +reader helpers (`NormalizeKey`/`normalizeKey`, `AliasesFor`/`aliasesFor`) fold every spelling in +this table onto the canonical key; live-check reports only the dotted spelling as +`livekit_shared_rename`, since the alias spellings are not OTLP keys. | Old key | Old value | Key to send | Value to send | | --- | --- | --- | --- | {% for a in ctx.attributes %}{% set from = a.annotations.livekit.renamed_from %}{% if from %}{% if from["values"] %}{% for old, new in from["values"] | items %}| `{{ from.key }}` | `{{ old }}` | `{{ a.key }}` | `{{ new }}` | {% endfor %}{% else %}| `{{ from.key }}` | any | `{{ a.key }}` | unchanged | -{% endif %}{% endif %}{% endfor %} +{% endif %}{% for alias in from.aliases or [] %}| `{{ alias }}` | any | `{{ a.key }}` | unchanged | +{% endfor %}{% endif %}{% endfor %} diff --git a/otel/templates/registry/typescript/semconv.ts.j2 b/otel/templates/registry/typescript/semconv.ts.j2 index 9d0d0a732..033c7e029 100644 --- a/otel/templates/registry/typescript/semconv.ts.j2 +++ b/otel/templates/registry/typescript/semconv.ts.j2 @@ -30,3 +30,65 @@ export const CHECKPOINT_{{ c.name | screaming_snake_case }} = {{ c.name | tojson /** {{ line(m.brief) }} Instrument: {{ m.instrument }}, unit: `{{ line(m.unit) }}`. */ export const METRIC_{{ m.name | screaming_snake_case }} = {{ m.name | tojson }} as const; {% endfor %} +/** + * Maps a legacy attribute key to the canonical key that replaces it, from the `renamed_from` + * annotations on the shared keys: the OTLP dotted rename and every `aliases` entry. The same source + * of truth as the Go semconv's RenamedKeys. Use {@link normalizeKey} to fold a legacy key read from + * an older capture onto the key this registry defines. + */ +export const RENAMED_KEYS: Record = { +{% for a in ctx.attributes %}{% set from = a.annotations.livekit.renamed_from %}{% if from %} {{ from.key | tojson }}: {{ a.key | tojson }}, +{% for alias in from.aliases or [] %} {{ alias | tojson }}: {{ a.key | tojson }}, +{% endfor %}{% endif %}{% endfor %}}; + +/** + * Maps a legacy attribute key to its legacy-value -> canonical-value mapping, for the shared keys + * whose enum values were also renamed. A renamed key whose values did not change is absent here. + */ +export const RENAMED_VALUES: Record> = { +{% for a in ctx.attributes %}{% set from = a.annotations.livekit.renamed_from %}{% if from and from["values"] %} {{ from.key | tojson }}: { +{% for old, new in from["values"] | items %} {{ old | tojson }}: {{ new | tojson }}, +{% endfor %} }, +{% endif %}{% endfor %}}; + +/** + * Maps a canonical key to its legacy spellings, the OTLP dotted rename first and then the + * `aliases`. {@link aliasesFor} reads it to expand a canonical key for querying historical data. + */ +export const KEY_ALIASES: Record = { +{% for a in ctx.attributes %}{% set from = a.annotations.livekit.renamed_from %}{% if from %} {{ a.key | tojson }}: [{{ from.key | tojson }}{% for alias in from.aliases or [] %}, {{ alias | tojson }}{% endfor %}], +{% endif %}{% endfor %}}; + +/** + * Own-property lookup, so a key such as `constructor` or `toString` read from a capture never + * resolves to an Object.prototype member of the alias maps. + */ +function own(map: Record, key: string): T | undefined { + return Object.prototype.hasOwnProperty.call(map, key) ? map[key] : undefined; +} + +/** + * Returns the canonical key for a legacy spelling, or `key` unchanged when it is not a known legacy + * spelling. During dual-emit a record may carry both; the canonical key is already canonical and + * returns unchanged, so prefer it over the result of normalizing the legacy key. + */ +export function normalizeKey(key: string): string { + return own(RENAMED_KEYS, key) ?? key; +} + +/** + * Returns the canonical key followed by its legacy spellings, for querying historical data that may + * carry either. A key with no recorded legacy spelling yields just itself. + */ +export function aliasesFor(canonical: string): string[] { + return [canonical, ...(own(KEY_ALIASES, canonical) ?? [])]; +} + +/** + * Returns the canonical value for a legacy value under a legacy key, or `value` unchanged. Pass the + * legacy key as read from the capture, not the canonical key. + */ +export function normalizeValue(key: string, value: string): string { + const values = own(RENAMED_VALUES, key); + return (values && own(values, value)) ?? value; +} diff --git a/otel/tests/codegen.sh b/otel/tests/codegen.sh index b9b94f5de..7e8a766c2 100755 --- a/otel/tests/codegen.sh +++ b/otel/tests/codegen.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# Generates Rust, TypeScript and Python from otel/model plus tests/codegen/escape.yaml, compiles -# them, and checks the tricky enum value comes back byte for byte from rustc, tsc + node and python3. +# Generates Go, Rust, TypeScript and Python from otel/model plus tests/codegen/escape.yaml, compiles +# them, and checks the tricky enum value comes back byte for byte from the Go toolchain, rustc, +# tsc + node and python3. set -euo pipefail cd "$(dirname "$0")/.." W=${WEAVER:-weaver} @@ -8,11 +9,20 @@ tmp=$(mktemp -d) && trap 'rm -rf "$tmp"' EXIT want=$'a "quoted" back\\slash, \'single\', & */ tab\tnew\nline' cp -R model "$tmp/model" && cp tests/codegen/escape.yaml "$tmp/model/" -for target in rust typescript python; do +for target in go rust typescript python; do "$W" registry generate --v2 -r "$tmp/model" -t templates "$target" "$tmp/$target" > "$tmp/gen.log" 2>&1 || { cat "$tmp/gen.log"; echo "FAIL weaver could not generate $target" >&2; exit 1; } done +# Go: build a throwaway module around the generated package and print the constant. Uses the +# go.mod toolchain, the same one that builds otel/gen/go in CI. +mkdir -p "$tmp/gomod/semconv" +cp "$tmp/go/semconv.go" "$tmp/gomod/semconv/semconv.go" +printf 'module codegentest\n\ngo 1.21\n' > "$tmp/gomod/go.mod" +printf 'package main\n\nimport (\n\t"fmt"\n\n\t"codegentest/semconv"\n)\n\nfunc main() { fmt.Print(semconv.LkTestEscapeTricky) }\n' > "$tmp/gomod/main.go" +got=$( (cd "$tmp/gomod" && GOFLAGS=-mod=mod go run .); printf . ) +[[ $got == "$want." ]] || { echo "FAIL Go literal does not round-trip" >&2; exit 1; } + rustc --edition 2021 --crate-type lib -D warnings -D missing_docs "$tmp/rust/semconv.rs" --out-dir "$tmp" printf '#[allow(dead_code)]\n#[path = "%s"]\nmod semconv;\nfn main() { print!("{}", semconv::lk_test_escape::TRICKY); }\n' \ "$tmp/rust/semconv.rs" > "$tmp/main.rs" @@ -24,4 +34,4 @@ got=$(node -e 'process.stdout.write(require(process.argv[1]).LkTestEscape.TRICKY [[ $got == "$want." ]] || { echo "FAIL TypeScript literal does not round-trip" >&2; exit 1; } got=$(python3 -I -c 'import sys, importlib.util; s = importlib.util.spec_from_file_location("semconv", sys.argv[1]); m = importlib.util.module_from_spec(s); s.loader.exec_module(m); sys.stdout.write(m.LkTestEscape.TRICKY)' "$tmp/python/semconv.py"; printf .) [[ $got == "$want." ]] || { echo "FAIL Python literal does not round-trip" >&2; exit 1; } -echo "PASS codegen: escaped literals round-trip through rustc, tsc and python3" +echo "PASS codegen: escaped literals round-trip through the Go toolchain, rustc, tsc and python3" diff --git a/otel/tests/negatives/alias-collision.yaml b/otel/tests/negatives/alias-collision.yaml new file mode 100644 index 000000000..59d081b29 --- /dev/null +++ b/otel/tests/negatives/alias-collision.yaml @@ -0,0 +1,26 @@ +# expect: livekit_alias_collision +groups: + - id: registry.lk.negative + type: attribute_group + brief: Negative fixture. + attributes: + - id: lk.negative_one + type: string + stability: development + brief: Claims the legacy alias collide_me. + examples: ["x"] + annotations: + livekit: + owner: shared + sensitivity: none + renamed_from: {key: lk.negative.one, aliases: [collide_me]} + - id: lk.negative_two + type: string + stability: development + brief: Also claims the legacy alias collide_me, so one spelling has two canonical keys. + examples: ["x"] + annotations: + livekit: + owner: shared + sensitivity: none + renamed_from: {key: lk.negative.two, aliases: [collide_me]} diff --git a/otel/tests/negatives/alias-defined.yaml b/otel/tests/negatives/alias-defined.yaml new file mode 100644 index 000000000..860503c71 --- /dev/null +++ b/otel/tests/negatives/alias-defined.yaml @@ -0,0 +1,22 @@ +# expect: livekit_shared_rename +groups: + - id: registry.lk.negative + type: attribute_group + brief: Negative fixture. + attributes: + - id: lk.negative_id + type: string + stability: development + brief: A shared key whose legacy alias is wrongly defined as a key below. + examples: ["x"] + annotations: + livekit: + owner: shared + sensitivity: none + renamed_from: {key: lk.negative.id, aliases: [negativeID]} + - id: negativeID + type: string + stability: development + brief: The legacy alias, defined as a key, which the rename forbids. + examples: ["x"] + annotations: {livekit: {owner: client, sensitivity: none}} diff --git a/otel/tests/negatives/alias-duplicate.yaml b/otel/tests/negatives/alias-duplicate.yaml new file mode 100644 index 000000000..2464ed2f7 --- /dev/null +++ b/otel/tests/negatives/alias-duplicate.yaml @@ -0,0 +1,16 @@ +# expect: livekit_alias_duplicate +groups: + - id: registry.lk.negative + type: attribute_group + brief: Negative fixture. + attributes: + - id: lk.negative_id + type: string + stability: development + brief: Lists its dotted rename again as an alias, a duplicate map key in the generated Go and TypeScript. + examples: ["x"] + annotations: + livekit: + owner: shared + sensitivity: none + renamed_from: {key: lk.negative.id, aliases: [lk.negative.id, negativeID]} diff --git a/packages/javascript/package.json b/packages/javascript/package.json index 51fc9fe01..e6b515105 100644 --- a/packages/javascript/package.json +++ b/packages/javascript/package.json @@ -32,6 +32,11 @@ }, "main": "./dist/index.mjs", "types": "./dist/index.d.mts", + "typesVersions": { + "*": { + "semconv": ["./dist/semconv.d.ts"] + } + }, "scripts": { "generate:proto": "mkdir -p src/gen && protoc --es_out src/gen --es_opt target=dts+js -I=../../protobufs ../../protobufs/livekit_*.proto ../../protobufs/agent/livekit_*.proto", "generate:semconv": "mkdir -p src/gen && cp ../../otel/gen/ts/semconv.ts src/gen/semconv.ts",